Files
Sharang ParnerkarandClaude Opus 5.5 38b9a72eda
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Successful in 6m51s
ci / image (pull_request) Skipped
feat(erp): restrict for late payment only after a mahnung
AGB § 10 allows restricting access only "trotz Mahnung und angemessener
Nachfrist". The ladder counted from the due date (restricted after 14,
halted after 30 days overdue) and escalated any warning after 14 days.

Now an overdue invoice alone means warning. The reconcile pass reads the
customer's submitted, unresolved ERPNext Dunnings; the earliest one that
names a still-open invoice sets the clock: restricted 14 days after its
posting date, halted a further 14 days after the restriction. A Mahnung
never halts directly, so a late-seen one errs in the customer's favour.
A failed Dunning read keeps the tenant on warning and is reported.

ERP_HALT_AFTER_DAYS defaults to 28 (was 30), so an expired trial is
read-only for 14 days instead of 16 before it is halted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:04:11 +01:00

363 lines
12 KiB
Go

// Package erp is the ERPNext (Frappe REST) client the registry uses for the
// always-on customer ⇄ ERP link (ERP/02, decision 3 + 12): Customer upsert on
// tenant creation, Subscription reads for the reconcile job, Usage Record
// pushes from the outbox and CRM leads from catalog requests. On staging the
// endpoint is cmd/erpmock (decision 18); prod talks to erp.breakpilot.com.
//
// Authentication is Frappe's `Authorization: token <key>:<secret>`.
package erp
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
// The image is distroless: carry the zone database for Europe/Berlin.
_ "time/tzdata"
)
// Doctypes. LeadDoctype is ERPNext v15's "Lead"; the Frappe CRM app names it
// "CRM Lead" — configurable via Config.LeadDoctype.
const (
CustomerDoctype = "Customer"
SubscriptionDoctype = "Subscription"
UsageRecordDoctype = "Usage Record"
SalesInvoiceDoctype = "Sales Invoice"
DefaultLeadDoctype = "Lead"
)
// ErrUnavailable wraps transport / 5xx failures so the outbox retries them.
var ErrUnavailable = errors.New("erp: unavailable")
// ErrNotFound — a GET by name returned 404.
var ErrNotFound = errors.New("erp: not found")
type Config struct {
BaseURL string
APIKey string
APISecret string
LeadDoctype string
Timeout time.Duration
}
type Client struct {
cfg Config
http *http.Client
}
// New returns a client; Enabled() is false when BaseURL is empty.
func New(cfg Config) *Client {
if cfg.Timeout <= 0 {
cfg.Timeout = 10 * time.Second
}
if cfg.LeadDoctype == "" {
cfg.LeadDoctype = DefaultLeadDoctype
}
cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/")
return &Client{cfg: cfg, http: &http.Client{Timeout: cfg.Timeout}}
}
func (c *Client) Enabled() bool { return c != nil && c.cfg.BaseURL != "" }
// Customer — the ERPNext Customer doc subset we read/write. TenantID is the
// custom field `tenant_id` (ERP/03 live configuration).
type Customer struct {
Name string `json:"name,omitempty"`
CustomerName string `json:"customer_name"`
CustomerType string `json:"customer_type,omitempty"`
CustomerGroup string `json:"customer_group,omitempty"`
Territory string `json:"territory,omitempty"`
TenantID string `json:"tenant_id"`
TenantSlug string `json:"tenant_slug,omitempty"`
}
// Subscription — Subscription doc subset. Plans carry the SKU (Subscription
// Plan name == Item code == platform SKU) and the quantity (seats/runners).
type Subscription struct {
Name string `json:"name"`
Party string `json:"party"`
Status string `json:"status"` // Trialling | Active | Past Due Date | Unpaid | Cancelled | Completed
SalesOrder string `json:"sales_order,omitempty"`
StartDate string `json:"start_date,omitempty"`
EndDate string `json:"end_date,omitempty"`
Plans []SubscriptionPlan `json:"plans"`
}
type SubscriptionPlan struct {
Plan string `json:"plan"`
Qty float64 `json:"qty"`
}
// UsageRecord — one metered fact (custom doctype, ERP/02 §usage).
type UsageRecord struct {
Customer string `json:"customer"`
TenantID string `json:"tenant_id"`
Product string `json:"product"`
Metric string `json:"metric"`
Qty float64 `json:"qty"`
OccurredAt string `json:"occurred_at"`
IdempotencyKey string `json:"idempotency_key"`
}
// Lead — a CRM lead from a catalog request.
type Lead struct {
LeadName string `json:"lead_name"`
CompanyName string `json:"company_name,omitempty"`
EmailID string `json:"email_id,omitempty"`
Source string `json:"source,omitempty"`
Notes string `json:"notes,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
Product string `json:"requested_product,omitempty"`
}
// FindCustomerByTenant returns the Customer whose tenant_id equals tenantID
// ("" when none).
func (c *Client) FindCustomerByTenant(ctx context.Context, tenantID string) (*Customer, error) {
filters := fmt.Sprintf(`[["tenant_id","=",%q]]`, tenantID)
var out struct {
Data []Customer `json:"data"`
}
q := url.Values{"filters": {filters}, "fields": {`["name","customer_name","tenant_id","tenant_slug"]`}, "limit_page_length": {"1"}}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(CustomerDoctype)+"?"+q.Encode(), nil, &out); err != nil {
return nil, err
}
if len(out.Data) == 0 {
return nil, nil
}
return &out.Data[0], nil
}
// UpsertCustomer creates the Customer for a tenant unless one already carries
// its tenant_id. Returns the ERP customer name (the id the registry stores).
func (c *Client) UpsertCustomer(ctx context.Context, in Customer) (string, error) {
if in.TenantID == "" {
return "", errors.New("erp: tenant_id required")
}
if existing, err := c.FindCustomerByTenant(ctx, in.TenantID); err != nil {
return "", err
} else if existing != nil {
return existing.Name, nil
}
if in.CustomerType == "" {
in.CustomerType = "Company"
}
if in.CustomerGroup == "" {
in.CustomerGroup = "Commercial"
}
if in.Territory == "" {
in.Territory = "All Territories"
}
var out struct {
Data Customer `json:"data"`
}
if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(CustomerDoctype), in, &out); err != nil {
return "", err
}
return out.Data.Name, nil
}
// ListSubscriptions returns every Subscription of the customer (any status).
func (c *Client) ListSubscriptions(ctx context.Context, customer string) ([]Subscription, error) {
filters := fmt.Sprintf(`[["party","=",%q]]`, customer)
var names struct {
Data []struct {
Name string `json:"name"`
} `json:"data"`
}
q := url.Values{"filters": {filters}, "fields": {`["name"]`}, "limit_page_length": {"200"}}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(SubscriptionDoctype)+"?"+q.Encode(), nil, &names); err != nil {
return nil, err
}
out := make([]Subscription, 0, len(names.Data))
for _, n := range names.Data {
var doc struct {
Data Subscription `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(SubscriptionDoctype)+"/"+url.PathEscape(n.Name), nil, &doc); err != nil {
return nil, err
}
out = append(out, doc.Data)
}
return out, nil
}
// Invoice — an open, overdue Sales Invoice.
type Invoice struct {
Name string `json:"name"`
DueDate string `json:"due_date"` // YYYY-MM-DD
OutstandingAmount float64 `json:"outstanding_amount"`
}
// ListOverdueInvoices returns the customer's submitted invoices with an open
// amount whose due date is before today (YYYY-MM-DD, company time zone).
// ERPNext sets the Overdue status in a nightly bulk update that fires no
// document event, so the registry asks instead of waiting for a webhook.
func (c *Client) ListOverdueInvoices(ctx context.Context, customer, today string) ([]Invoice, error) {
filters := fmt.Sprintf(`[["customer","=",%q],["docstatus","=",1],["outstanding_amount",">",0],["due_date","<",%q]]`, customer, today)
var out struct {
Data []Invoice `json:"data"`
}
q := url.Values{"filters": {filters}, "fields": {`["name","due_date","outstanding_amount"]`}, "order_by": {"due_date asc"}, "limit_page_length": {"200"}}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape("Sales Invoice")+"?"+q.Encode(), nil, &out); err != nil {
return nil, err
}
return out.Data, nil
}
// DunningDoctype is ERPNext's Mahnung.
const DunningDoctype = "Dunning"
// Dunning — a submitted Mahnung that is not resolved yet, with the invoices
// it names (child table overdue_payments).
type Dunning struct {
Name string `json:"name"`
PostingDate string `json:"posting_date"` // YYYY-MM-DD
Invoices []string `json:"-"`
}
// ListOpenDunnings returns the customer's submitted, unresolved Dunnings
// (Mahnungen). AGB § 10: access is restricted only after a Mahnung and a
// Nachfrist, so the registry counts from the Mahnung, not from the due date.
func (c *Client) ListOpenDunnings(ctx context.Context, customer string) ([]Dunning, error) {
filters := fmt.Sprintf(`[["customer","=",%q],["docstatus","=",1],["status","!=","Resolved"]]`, customer)
var names struct {
Data []struct {
Name string `json:"name"`
} `json:"data"`
}
q := url.Values{"filters": {filters}, "fields": {`["name"]`}, "limit_page_length": {"200"}}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(DunningDoctype)+"?"+q.Encode(), nil, &names); err != nil {
return nil, err
}
out := make([]Dunning, 0, len(names.Data))
for _, n := range names.Data {
var doc struct {
Data struct {
Name string `json:"name"`
PostingDate string `json:"posting_date"`
OverduePayments []struct {
SalesInvoice string `json:"sales_invoice"`
} `json:"overdue_payments"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(DunningDoctype)+"/"+url.PathEscape(n.Name), nil, &doc); err != nil {
return nil, err
}
d := Dunning{Name: doc.Data.Name, PostingDate: doc.Data.PostingDate}
for _, op := range doc.Data.OverduePayments {
if op.SalesInvoice != "" {
d.Invoices = append(d.Invoices, op.SalesInvoice)
}
}
out = append(out, d)
}
return out, nil
}
// CreateUsageRecord pushes one usage record (idempotency is the registry's
// job: it only sends each event once, via the outbox).
func (c *Client) CreateUsageRecord(ctx context.Context, rec UsageRecord) (string, error) {
rec.OccurredAt = FrappeDatetime(rec.OccurredAt)
var out struct {
Data struct {
Name string `json:"name"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(UsageRecordDoctype), rec, &out); err != nil {
return "", err
}
return out.Data.Name, nil
}
// CreateLead files a CRM lead.
func (c *Client) CreateLead(ctx context.Context, lead Lead) (string, error) {
var out struct {
Data struct {
Name string `json:"name"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(c.cfg.LeadDoctype), lead, &out); err != nil {
return "", err
}
return out.Data.Name, nil
}
func (c *Client) do(ctx context.Context, method, path string, body any, into any) error {
if !c.Enabled() {
return fmt.Errorf("%w: ERP_BASE_URL not configured", ErrUnavailable)
}
var reader io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return err
}
reader = bytes.NewReader(buf)
}
req, err := http.NewRequestWithContext(ctx, method, c.cfg.BaseURL+path, reader)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.cfg.APIKey != "" {
req.Header.Set("Authorization", "token "+c.cfg.APIKey+":"+c.cfg.APISecret)
}
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("%w: %v", ErrUnavailable, err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
switch {
case resp.StatusCode == http.StatusNotFound:
return ErrNotFound
case resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests:
return fmt.Errorf("%w: %s %s → %d %s", ErrUnavailable, method, path, resp.StatusCode, truncate(raw))
case resp.StatusCode/100 != 2:
return fmt.Errorf("erp: %s %s → %d %s", method, path, resp.StatusCode, truncate(raw))
}
if into != nil && len(raw) > 0 {
if err := json.Unmarshal(raw, into); err != nil {
return fmt.Errorf("erp: decode %s %s: %w", method, path, err)
}
}
return nil
}
func truncate(b []byte) string {
s := strings.TrimSpace(string(b))
if len(s) > 200 {
return s[:200] + "…"
}
return s
}
// frappeZone is the ERPNext system time zone; Datetime fields are stored as
// naive local times in it.
var frappeZone = func() *time.Location {
if loc, err := time.LoadLocation("Europe/Berlin"); err == nil {
return loc
}
return time.UTC
}()
// FrappeDatetime turns an RFC 3339 time into the "YYYY-MM-DD HH:MM:SS" form a
// Frappe Datetime field accepts (MariaDB refuses "2026-09-30T06:03:53Z"),
// in the ERP's time zone. Anything else is passed through unchanged.
func FrappeDatetime(s string) string {
t, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
return s
}
return t.In(frappeZone).Format("2006-01-02 15:04:05")
}