From 145b79ad221e13130ed5c242c29abbb356ab4197 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 30 Sep 2026 12:41:47 +0200 Subject: [PATCH] feat(erp): overdue invoices drive the ladder from the reconcile pass Live ERPNext marks invoices Overdue in a nightly bulk update that fires no document event, so the sales_invoice.overdue webhook never arrives. Every reconcile (15 min) now lists the customer's submitted invoices with an open amount and a due date before today (Europe/Berlin); the oldest one sets the rung (warning, restricted after 14 days, halted after 30), with the same rules as the webhook (shared overdueStep). When no invoice is open any more and the status came from the ladder, the tenant goes back to active, which covers payments matched by Zahlungsabgleich (no event). A status set by staff is left alone. The erpmock list understands < and > filters. Fixes #50 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- internal/erp/erp.go | 23 +++++ internal/erpmock/server.go | 21 ++++ internal/server/erp.go | 121 ++++++++++++++++++++--- internal/server/erp_test.go | 75 ++++++++++++++ internal/server/overdue_internal_test.go | 31 ++++++ 5 files changed, 260 insertions(+), 11 deletions(-) create mode 100644 internal/server/overdue_internal_test.go diff --git a/internal/erp/erp.go b/internal/erp/erp.go index 68a2e36..aa3d660 100644 --- a/internal/erp/erp.go +++ b/internal/erp/erp.go @@ -187,6 +187,29 @@ func (c *Client) ListSubscriptions(ctx context.Context, customer string) ([]Subs 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 +} + // 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) { diff --git a/internal/erpmock/server.go b/internal/erpmock/server.go index 3e29edd..bd92602 100644 --- a/internal/erpmock/server.go +++ b/internal/erpmock/server.go @@ -10,6 +10,7 @@ import ( "io" "net/http" "sort" + "strconv" "strings" "sync" "time" @@ -208,6 +209,10 @@ func matches(d Doc, fs []filter) bool { if got == want { return false } + case "<", ">": + if !compare(got, want, f.Op) { + return false + } case "like": if !strings.Contains(strings.ToLower(got), strings.ToLower(strings.Trim(want, "%"))) { return false @@ -400,3 +405,19 @@ func writeJSON(w http.ResponseWriter, code int, body any) { w.WriteHeader(code) _ = json.NewEncoder(w).Encode(body) } + +// compare orders numbers numerically and anything else (dates) as strings. +func compare(got, want, op string) bool { + g, err1 := strconv.ParseFloat(got, 64) + w, err2 := strconv.ParseFloat(want, 64) + if err1 == nil && err2 == nil { + if op == "<" { + return g < w + } + return g > w + } + if op == "<" { + return got < want + } + return got > want +} diff --git a/internal/server/erp.go b/internal/server/erp.go index 8ce99b2..6104eec 100644 --- a/internal/server/erp.go +++ b/internal/server/erp.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "encoding/json" "errors" + "fmt" "io" "net/http" "sort" @@ -134,17 +135,11 @@ func (s *Server) applyErpEvent(ctx context.Context, r *http.Request, t *store.Te return map[string]any{"status": "applied", "tenant_status": t2.Status}, nil case erp.EventInvoiceOverdue: - if t.Status == store.StatusDemo || t.Status == store.StatusArchived || t.Status == store.StatusHalted { - return map[string]any{"status": "ignored", "tenant_status": t.Status}, nil - } - next := store.StatusWarning - if ev.DaysOverdue >= s.restrictAfterDays() { - next = store.StatusRestricted - } - if ev.DaysOverdue >= s.haltAfterDays() { - next = store.StatusHalted - } - if rank(next) <= rank(t.Status) && t.Status != store.StatusTrial && t.Status != store.StatusActive { + next, ok := s.overdueStep(t, ev.DaysOverdue) + if !ok { + if t.Status == store.StatusDemo || t.Status == store.StatusArchived || t.Status == store.StatusHalted { + return map[string]any{"status": "ignored", "tenant_status": t.Status}, nil + } return map[string]any{"status": "unchanged", "tenant_status": t.Status}, nil } t2, err := s.transition(ctx, r, t, next, "erp:invoice_overdue:"+ev.Name) @@ -441,6 +436,97 @@ func rankPlan(p string) int { return 0 } +// overdueStep is the ladder rung for an invoice `days` overdue: warning, then +// restricted and halted after the grace days. ok is false when the tenant +// is not billed (demo), already gone (halted, archived) or already on that +// rung or a higher one; the ladder never moves backwards on overdue. +func (s *Server) overdueStep(t *store.Tenant, days int) (string, bool) { + if t.Status == store.StatusDemo || t.Status == store.StatusArchived || t.Status == store.StatusHalted { + return "", false + } + next := store.StatusWarning + if days >= s.restrictAfterDays() { + next = store.StatusRestricted + } + if days >= s.haltAfterDays() { + next = store.StatusHalted + } + if rank(next) <= rank(t.Status) && t.Status != store.StatusTrial && t.Status != store.StatusActive { + return "", false + } + return next, true +} + +// applyOverdueInvoices is the reconcile half of the dunning ladder: the +// oldest open invoice decides the rung. When none is left and the tenant was +// put on the ladder by an overdue invoice, it goes back to active (a payment +// matched by Zahlungsabgleich fires no event). +func (s *Server) applyOverdueInvoices(ctx context.Context, t *store.Tenant, invs []erp.Invoice, now time.Time) (*store.Tenant, string, error) { + if len(invs) > 0 { + oldest := invs[0] + for _, inv := range invs[1:] { + if inv.DueDate < oldest.DueDate { + oldest = inv + } + } + due, err := time.ParseInLocation("2006-01-02", oldest.DueDate, erpZone) + if err != nil { + return t, "", fmt.Errorf("invoice %s: due date %q: %w", oldest.Name, oldest.DueDate, err) + } + days := int(berlinDate(now).Sub(due).Hours() / 24) + next, ok := s.overdueStep(t, days) + if !ok { + return t, "", nil + } + t2, err := s.transition(ctx, nil, t, next, "reconcile:invoice_overdue:"+oldest.Name) + return t2, next, err + } + if t.Status != store.StatusWarning && t.Status != store.StatusRestricted && t.Status != store.StatusFrozen { + return t, "", nil + } + subs, err := s.Store.ListSubscriptions(ctx, t.ID) + if err != nil || !hasActive(subs) { + return t, "", err + } + if !s.onLadderForInvoices(ctx, t) { + return t, "", nil + } + t2, err := s.transition(ctx, nil, t, store.StatusActive, "reconcile:invoices_settled") + return t2, store.StatusActive, err +} + +// onLadderForInvoices reports whether the tenant's current status was set by +// the dunning ladder (not by staff or an expired trial), from the audit event +// that set it. +func (s *Server) onLadderForInvoices(ctx context.Context, t *store.Tenant) bool { + since := t.StatusChangedAt.Add(-time.Minute) + evs, _, err := s.Store.ListAudit(ctx, store.AuditFilter{TenantID: t.ID, Action: "tenant.status_changed", Since: &since, Limit: 50}) + if err != nil || len(evs) == 0 { + return false + } + src, _ := evs[len(evs)-1].Metadata["source"].(string) + for _, p := range []string{"erp:invoice_overdue:", "reconcile:invoice_overdue:", "reconcile:grace_over"} { + if strings.HasPrefix(src, p) { + return true + } + } + return false +} + +// erpZone is the ERPNext company time zone; due dates are calendar days there. +var erpZone = func() *time.Location { + if l, err := time.LoadLocation("Europe/Berlin"); err == nil { + return l + } + return time.UTC +}() + +// berlinDate is midnight of t's calendar day in the ERP time zone. +func berlinDate(t time.Time) time.Time { + y, m, d := t.In(erpZone).Date() + return time.Date(y, m, d, 0, 0, 0, 0, erpZone) +} + // rank orders the ladder for "never move backwards on overdue" checks. func rank(status string) int { switch status { @@ -524,6 +610,19 @@ func (s *Server) Reconcile(ctx context.Context) ReconcileReport { } } } + if s.ERP.Enabled() && t.ErpCustomerID != "" { + invs, err := s.ERP.ListOverdueInvoices(ctx, t.ErpCustomerID, berlinDate(now).Format("2006-01-02")) + if err != nil { + rep.Errors = append(rep.Errors, t.Slug+": erp invoices: "+err.Error()) + } else if t2, moved, err := s.applyOverdueInvoices(ctx, t, invs, now); err != nil { + rep.Errors = append(rep.Errors, t.Slug+": invoices: "+err.Error()) + } else { + if moved != "" { + rep.Escalated = append(rep.Escalated, t.Slug+"→"+moved) + } + t = t2 + } + } if next, why := s.escalation(t, now); next != "" { if _, err := s.transition(ctx, nil, t, next, "reconcile:"+why); err != nil { rep.Errors = append(rep.Errors, t.Slug+": escalate: "+err.Error()) diff --git a/internal/server/erp_test.go b/internal/server/erp_test.go index 650b24f..e9544a1 100644 --- a/internal/server/erp_test.go +++ b/internal/server/erp_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -370,3 +371,77 @@ func TestReconcile_ladderEscalation(t *testing.T) { } func ptr(s string) *string { return &s } + +// Live ERPNext sets invoices Overdue without firing a webhook (#50): the +// reconcile pass reads the open invoices itself. +func TestReconcile_overdueInvoicesDriveTheLadder(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + mock := erpmock.New(erpmock.Config{APIKey: "k", APISecret: "s", WebhookURL: h.srv.URL + "/v1/internal/erp/webhook", WebhookSecret: testWebhookSecret}) + ms := httptest.NewServer(mock) + defer ms.Close() + h.app.ERP = erp.New(erp.Config{BaseURL: ms.URL, APIKey: "k", APISecret: "s"}) + + tn := newTenant(t, h, "dunning-co") + if _, err := h.app.DrainOutbox(t.Context()); err != nil { + t.Fatal(err) + } + cust := getTenant(t, h, tn.ID).ErpCustomerID + mockDo := func(method, path string, body map[string]any) map[string]any { + buf, _ := json.Marshal(body) + req, _ := http.NewRequest(method, ms.URL+path, bytes.NewReader(buf)) + req.Header.Set("Authorization", "token k:s") + resp, err := http.DefaultClient.Do(req) + if err != nil || resp.StatusCode != 200 { + t.Fatalf("mock %s %s: %v %v", method, path, err, resp) + } + defer func() { _ = resp.Body.Close() }() + var out struct { + Data map[string]any `json:"data"` + } + _ = json.NewDecoder(resp.Body).Decode(&out) + return out.Data + } + mockDo("POST", "/_mock/fire/sales-order-submit", map[string]any{"tenant_id": tn.ID, "items": []map[string]any{{"item_code": "CRA-CSA-CLD-STD", "qty": 1}}}) + if got := getTenant(t, h, tn.ID); got.Status != "active" { + t.Fatalf("after SO: %s", got.Status) + } + berlin, _ := time.LoadLocation("Europe/Berlin") + day := func(offset int) string { return time.Now().In(berlin).AddDate(0, 0, offset).Format("2006-01-02") } + reconcile := func() string { + _, raw := h.do("POST", "/v1/internal/erp/reconcile", nil) + return string(raw) + } + + // an invoice due tomorrow and a paid one are not overdue + mockDo("POST", "/api/resource/Sales Invoice", map[string]any{"customer": cust, "docstatus": 1, "due_date": day(1), "outstanding_amount": 100}) + paid := mockDo("POST", "/api/resource/Sales Invoice", map[string]any{"customer": cust, "docstatus": 1, "due_date": day(-40), "outstanding_amount": 0}) + if raw := reconcile(); getTenant(t, h, tn.ID).Status != "active" { + t.Fatalf("not overdue: %s", raw) + } + // 3 days overdue (no webhook) → warning; again → unchanged + inv := mockDo("POST", "/api/resource/Sales Invoice", map[string]any{"customer": cust, "docstatus": 1, "due_date": day(-3), "outstanding_amount": 2118.2}) + if raw := reconcile(); getTenant(t, h, tn.ID).Status != "warning" || !strings.Contains(raw, "dunning-co→warning") { + t.Fatalf("3 days: %s", raw) + } + if raw := reconcile(); getTenant(t, h, tn.ID).Status != "warning" || strings.Contains(raw, "dunning-co→") { + t.Fatalf("second pass: %s", raw) + } + // 20 days → restricted; a cancelled (docstatus 2) invoice does not count + mockDo("PUT", "/api/resource/Sales Invoice/"+inv["name"].(string), map[string]any{"due_date": day(-20)}) + mockDo("POST", "/api/resource/Sales Invoice", map[string]any{"customer": cust, "docstatus": 2, "due_date": day(-60), "outstanding_amount": 50}) + if raw := reconcile(); getTenant(t, h, tn.ID).Status != "restricted" { + t.Fatalf("20 days: %s", raw) + } + // paid via Zahlungsabgleich (no payment event) → active again + mockDo("PUT", "/api/resource/Sales Invoice/"+inv["name"].(string), map[string]any{"outstanding_amount": 0}) + if raw := reconcile(); getTenant(t, h, tn.ID).Status != "active" { + t.Fatalf("settled: %s", raw) + } + // a status set by staff is left alone when no invoice is open + h.do("POST", "/v1/tenants/"+tn.ID+"/status", map[string]any{"status": "warning", "reason": "manual"}) + if raw := reconcile(); getTenant(t, h, tn.ID).Status != "warning" { + t.Fatalf("staff warning undone: %s", raw) + } + _ = paid + }) +} diff --git a/internal/server/overdue_internal_test.go b/internal/server/overdue_internal_test.go new file mode 100644 index 0000000..560ca52 --- /dev/null +++ b/internal/server/overdue_internal_test.go @@ -0,0 +1,31 @@ +package server + +import ( + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +func TestOverdueStep(t *testing.T) { + s := &Server{} + for _, c := range []struct { + status string + days int + next string + ok bool + }{ + {"active", 1, "warning", true}, + {"trial", 1, "warning", true}, + {"active", 14, "restricted", true}, + {"warning", 30, "halted", true}, + {"warning", 2, "", false}, + {"restricted", 5, "", false}, + {"demo", 40, "", false}, + {"halted", 40, "", false}, + } { + next, ok := s.overdueStep(&store.Tenant{Status: c.status}, c.days) + if next != c.next || ok != c.ok { + t.Errorf("%s %d days: %q %v, want %q %v", c.status, c.days, next, ok, c.next, c.ok) + } + } +} -- 2.54.1