feat(erp): restrict for late payment only after a mahnung
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Successful in 6m51s
ci / image (pull_request) Skipped

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>
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-17 09:04:11 +01:00
1 parent 8a72469e18
commit 38b9a72eda
7 files changed
+280 -70

No files matched your search

+18 -7
View File
@@ -57,7 +57,7 @@ Env vars (override at the shell):
| `ERP_LEAD_DOCTYPE` | `Lead` | `CRM Lead` when the Frappe CRM app is used |
| `ERP_WEBHOOK_SECRET` | empty (receiver disabled) | HMAC secret for `POST /v1/internal/erp/webhook` |
| `ERP_OUTBOX_INTERVAL` / `ERP_RECONCILE_INTERVAL` | `15s` / `15m` | Worker cadence |
| `ERP_RESTRICT_AFTER_DAYS` / `ERP_HALT_AFTER_DAYS` / `ERP_EXPORT_WINDOW_DAYS` | `14` / `30` / `30` | Ladder timing |
| `ERP_RESTRICT_AFTER_DAYS` / `ERP_HALT_AFTER_DAYS` / `ERP_EXPORT_WINDOW_DAYS` | `14` / `28` / `30` | Ladder timing: days after the Mahnung until read-only / halted; export window |
| `LICENCE_SIGNING_KEY` / `LICENCE_ISSUER` / `LICENCE_TTL_DAYS` | empty (ephemeral) / `tenant-registry` / `30` | CLI licence signer (base64 Ed25519 seed) |
| `SECRETS_ENCRYPTION_KEY` | empty | base64, 32 bytes (`openssl rand -base64 32`). Seals the LiteLLM key of a Werkpilot CI licence so the reused licence hands it out again (ADR 0001 §5). Empty: a reused CI licence comes without the key (warning `llm_key_not_repeatable`). |
| `LITELLM_BASE_URL` | `https://llm.breakpilot.com` | LiteLLM proxy root; returned to Werkpilot as `llm_base_url` |
@@ -118,14 +118,25 @@ on the ladder (`ERP/02 Billing and Entitlements`):
- **Webhooks** (`POST /v1/internal/erp/webhook`, HMAC `ERP_WEBHOOK_SECRET`):
`sales_order.submit` → subscriptions + `tenant_products` (SKU → product,
`-STD/-BUS/-ENT` → plan, add-on SKUs → limit, e.g. `runners`) + `active`;
`sales_invoice.overdue` → `warning`, `restricted` from
`ERP_RESTRICT_AFTER_DAYS` (14), `halted` from `ERP_HALT_AFTER_DAYS` (30);
`sales_invoice.overdue` → `warning` (never more: see below);
`payment_entry.submit` → `active`; `subscription.cancel` → `halted`.
- **Late payment needs a Mahnung** (AGB § 10: restriction only "trotz
Mahnung und angemessener Nachfrist"). 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` (read-only) `ERP_RESTRICT_AFTER_DAYS` (14)
after its posting date, `halted` a further 14 days after the restriction
(so `ERP_HALT_AFTER_DAYS`, 28, after a Mahnung seen on time). A tenant is
always read-only before it is halted.
A Mahnung for paid invoices does not count. The ERP API user needs read
access to Dunning.
- **Reconcile** every `ERP_RECONCILE_INTERVAL` (15 min): re-reads ERP
Subscriptions per customer (safety net for lost webhooks) and applies the
time-based steps — trial expiry → `restricted`, `warning` → `restricted`
after 14 d, `restricted` → `halted` after 30 d total, `halted` →
`archived` after `ERP_EXPORT_WINDOW_DAYS` (30).
Subscriptions and overdue invoices + Dunnings per customer (safety net for
lost webhooks) and applies the time-based steps: trial expiry →
`restricted`, `restricted` → `halted` after a further 14 d
(`ERP_HALT_AFTER_DAYS` − `ERP_RESTRICT_AFTER_DAYS`), `halted` → `archived`
after `ERP_EXPORT_WINDOW_DAYS` (30). A `warning` never escalates by time
alone.
- Every status change syncs the coarse `tenant_status` claim to Keycloak.
**Staging uses the mock** (`cmd/erpmock`, decision 18): the Frappe REST
+7 -3
View File
@@ -54,8 +54,12 @@ type Config struct {
ErpWebhookSecret string // HMAC for POST /v1/internal/erp/webhook; empty ⇒ receiver disabled
ErpOutboxInterval time.Duration
ErpReconcileEvery time.Duration
// Ladder timing (days): warning → restricted, restricted → halted,
// halted → archived (export window).
// Ladder timing (days). Non-payment counts from the Mahnung (ERPNext
// Dunning), not the due date (AGB § 10): restricted RestrictAfterDays
// after the Mahnung, halted HaltAfterDays-RestrictAfterDays after the
// restriction (so HaltAfterDays after a Mahnung seen on time). An
// expired trial is read-only for the same spacing, then halted. Halted →
// archived after ExportWindowDays.
RestrictAfterDays int
HaltAfterDays int
ExportWindowDays int
@@ -146,7 +150,7 @@ func Load() (*Config, error) {
ErpOutboxInterval: getduration("ERP_OUTBOX_INTERVAL", 15*time.Second),
ErpReconcileEvery: getduration("ERP_RECONCILE_INTERVAL", 15*time.Minute),
RestrictAfterDays: getint("ERP_RESTRICT_AFTER_DAYS", 14),
HaltAfterDays: getint("ERP_HALT_AFTER_DAYS", 30),
HaltAfterDays: getint("ERP_HALT_AFTER_DAYS", 28),
ExportWindowDays: getint("ERP_EXPORT_WINDOW_DAYS", 30),
LicenceSigningKey: os.Getenv("LICENCE_SIGNING_KEY"),
+50
View File
@@ -210,6 +210,56 @@ func (c *Client) ListOverdueInvoices(ctx context.Context, customer, today string
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) {
+86 -31
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"math"
"net/http"
"sort"
"strings"
@@ -23,8 +24,11 @@ import (
// ERPNext is the commercial authority (Sales Orders / Subscriptions /
// Invoices / Payments); the registry mirrors what it hears into
// subscriptions + tenant_products and moves the tenant on the ladder
// (ERP/02): active → warning (invoice overdue) → restricted (grace over,
// read-only) → halted (cancelled / hard stop) → archived (export window over).
// (ERP/02): active → warning (invoice overdue) → restricted (read-only,
// RestrictAfterDays after a Mahnung) → halted (a further
// HaltAfterDays-RestrictAfterDays later, or cancelled) → archived (export window over). AGB § 10 allows
// restricting access only "trotz Mahnung und angemessener Nachfrist", so an
// overdue invoice alone never goes past warning.
// erpWebhook is POST /v1/internal/erp/webhook (PUBLIC_EXPLICIT, HMAC).
func (s *Server) erpWebhook(w http.ResponseWriter, r *http.Request) {
@@ -135,7 +139,9 @@ 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:
next, ok := s.overdueStep(t, ev.DaysOverdue)
// days_overdue counts from the due date: warning only. Restriction
// needs a Mahnung, which the reconcile pass reads from ERPNext.
next, ok := s.overdueStep(t, false, 0)
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
@@ -436,49 +442,73 @@ 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) {
// overdueStep is the ladder rung for an overdue invoice. Without a Mahnung
// (dunned false) it is warning. With one, restricted from RestrictAfterDays
// after the Mahnung (sinceMahnung in calendar days). It never returns halted:
// a tenant is always read-only first, and escalation() halts it a further
// HaltAfterDays-RestrictAfterDays after the restriction, so a Mahnung seen
// late (back-dated, or ERPNext unreachable for a while) errs in the
// customer's favour. 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, dunned bool, sinceMahnung 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() {
if dunned && sinceMahnung >= 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
// applyOverdueInvoices is the reconcile half of the dunning ladder. Any open
// overdue invoice means warning; the earliest open Mahnung (Dunning) that
// names one of them decides restricted and halted. A Mahnung whose invoices
// are all paid does not count. When no invoice 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) {
func (s *Server) applyOverdueInvoices(ctx context.Context, t *store.Tenant, invs []erp.Invoice, dunnings []erp.Dunning, now time.Time) (*store.Tenant, string, error) {
if len(invs) > 0 {
open := make(map[string]bool, len(invs))
oldest := invs[0]
for _, inv := range invs[1:] {
for _, inv := range invs {
open[inv.Name] = true
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)
var mahnung time.Time
mahnungName := ""
for _, d := range dunnings {
if !namesOpenInvoice(d, open) {
continue
}
at, err := time.ParseInLocation("2006-01-02", d.PostingDate, erpZone)
if err != nil {
return t, "", fmt.Errorf("dunning %s: posting date %q: %w", d.Name, d.PostingDate, err)
}
if mahnungName == "" || at.Before(mahnung) {
mahnung, mahnungName = at, d.Name
}
}
days := int(berlinDate(now).Sub(due).Hours() / 24)
next, ok := s.overdueStep(t, days)
dunned := mahnungName != ""
days := 0
if dunned {
days = calendarDays(mahnung, berlinDate(now))
}
next, ok := s.overdueStep(t, dunned, days)
if !ok {
return t, "", nil
}
t2, err := s.transition(ctx, nil, t, next, "reconcile:invoice_overdue:"+oldest.Name)
source := "reconcile:invoice_overdue:" + oldest.Name
if dunned && next != store.StatusWarning {
source += ":dunning:" + mahnungName
}
t2, err := s.transition(ctx, nil, t, next, source)
return t2, next, err
}
if t.Status != store.StatusWarning && t.Status != store.StatusRestricted && t.Status != store.StatusFrozen {
@@ -495,6 +525,23 @@ func (s *Server) applyOverdueInvoices(ctx context.Context, t *store.Tenant, invs
return t2, store.StatusActive, err
}
// namesOpenInvoice reports whether the Mahnung names an invoice that is still
// open and overdue.
func namesOpenInvoice(d erp.Dunning, open map[string]bool) bool {
for _, inv := range d.Invoices {
if open[inv] {
return true
}
}
return false
}
// calendarDays is the number of calendar days from one ERP-zone midnight to
// another (rounded, so a DST switch in between does not lose a day).
func calendarDays(from, to time.Time) int {
return int(math.Round(to.Sub(from).Hours() / 24))
}
// 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.
@@ -555,7 +602,7 @@ func (s *Server) haltAfterDays() int {
if d := s.cfg().HaltAfterDays; d > 0 {
return d
}
return 30
return 28
}
func (s *Server) exportWindowDays() int {
@@ -612,9 +659,18 @@ 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"))
var dunnings []erp.Dunning
if err == nil && len(invs) > 0 {
// Without the Mahnungen the tenant can still get a warning,
// never more, so a failed read is reported and not fatal.
if dunnings, err = s.ERP.ListOpenDunnings(ctx, t.ErpCustomerID); err != nil {
rep.Errors = append(rep.Errors, t.Slug+": erp dunnings: "+err.Error())
dunnings, err = nil, nil
}
}
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 {
} else if t2, moved, err := s.applyOverdueInvoices(ctx, t, invs, dunnings, now); err != nil {
rep.Errors = append(rep.Errors, t.Slug+": invoices: "+err.Error())
} else {
if moved != "" {
@@ -648,13 +704,12 @@ func (s *Server) escalation(t *store.Tenant, now time.Time) (string, string) {
if t.TrialEndsAt != nil && now.After(*t.TrialEndsAt) {
return store.StatusRestricted, "trial_expired"
}
case store.StatusWarning:
if age >= time.Duration(s.restrictAfterDays())*day {
return store.StatusRestricted, "grace_over"
}
case store.StatusRestricted, store.StatusFrozen:
// non-payment and expired trials alike: read-only for the rest of the
// grace window, then halted (no access), then the export window.
// non-payment and expired trials alike: read-only for
// HaltAfterDays-RestrictAfterDays (14 days by default), then halted
// (no access), then the export window. For non-payment that is
// HaltAfterDays after the Mahnung when it was seen on time. A warning
// never escalates by time alone: that needs a Mahnung (AGB § 10).
if age >= time.Duration(s.haltAfterDays()-s.restrictAfterDays())*day {
return store.StatusHalted, "hard_stop"
}
+98 -17
View File
@@ -105,7 +105,7 @@ func TestErpWebhook_ladder(t *testing.T) {
t.Fatalf("duplicate: %d %s", resp.StatusCode, raw)
}
// overdue 3 days → warning; 20 days → restricted (read-only)
// overdue 3 days → warning; 20 days without a Mahnung → still warning
if resp, raw := h.webhook(t, erp.WebhookEvent{Event: erp.EventInvoiceOverdue, Doctype: "Sales Invoice", Name: "INV-1", Customer: "CUST-00001", DaysOverdue: 3}, "evt-2"); resp.StatusCode != 200 {
t.Fatalf("overdue: %d %s", resp.StatusCode, raw)
}
@@ -113,13 +113,14 @@ func TestErpWebhook_ladder(t *testing.T) {
t.Fatalf("after overdue 3d: %s", got.Status)
}
h.webhook(t, erp.WebhookEvent{Event: erp.EventInvoiceOverdue, Doctype: "Sales Invoice", Name: "INV-1", Customer: "CUST-00001", DaysOverdue: 20}, "evt-3")
if got = getTenant(t, h, tn.ID); got.Status != "restricted" {
t.Fatalf("after overdue 20d: %s", got.Status)
if got = getTenant(t, h, tn.ID); got.Status != "warning" {
t.Fatalf("after overdue 20d without a Mahnung: %s", got.Status)
}
if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); !chk.Allowed || !chk.ReadOnly {
t.Fatalf("restricted must be read-only: %+v", chk)
if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); !chk.Allowed || chk.ReadOnly {
t.Fatalf("warning keeps full access: %+v", chk)
}
// a later, shorter overdue never moves the tenant back up
// an overdue event never moves a restricted tenant back up
h.do("POST", "/v1/tenants/"+tn.ID+"/status", map[string]any{"status": "restricted", "reason": "test"})
h.webhook(t, erp.WebhookEvent{Event: erp.EventInvoiceOverdue, Doctype: "Sales Invoice", Name: "INV-2", Customer: "CUST-00001", DaysOverdue: 1}, "evt-4")
if got = getTenant(t, h, tn.ID); got.Status != "restricted" {
t.Fatalf("overdue must not lift restriction: %s", got.Status)
@@ -421,23 +422,37 @@ func TestReconcile_ladderEscalation(t *testing.T) {
if !bytes.Contains(raw, []byte(`"escalated":[]`)) {
t.Fatalf("day 1: %s", raw)
}
// +15 days: warning → restricted, trial expired → restricted
// +15 days: trial expired → restricted; a warning does not escalate
// by time alone (that needs a Mahnung, AGB § 10)
h.app.Now = func() time.Time { return time.Now().Add(15 * 24 * time.Hour) }
_, raw = h.do("POST", "/v1/internal/erp/reconcile", nil)
if getTenant(t, h, warn.ID).Status != "restricted" || getTenant(t, h, trial.ID).Status != "restricted" {
if getTenant(t, h, warn.ID).Status != "warning" || getTenant(t, h, trial.ID).Status != "restricted" {
t.Fatalf("day 15: %s", raw)
}
// +31 days: halted → archived (export window); restricted (ex-warning) → halted
// the store stamps status changes with the real clock: 13 days after
// the restriction the trial is still read-only, after 14 it is halted
h.app.Now = func() time.Time { return time.Now().Add(13 * 24 * time.Hour) }
_, raw = h.do("POST", "/v1/internal/erp/reconcile", nil)
if getTenant(t, h, trial.ID).Status != "restricted" {
t.Fatalf("13 days read-only: %s", raw)
}
h.app.Now = func() time.Time { return time.Now().Add(14*24*time.Hour + time.Hour) }
_, raw = h.do("POST", "/v1/internal/erp/reconcile", nil)
if getTenant(t, h, trial.ID).Status != "halted" {
t.Fatalf("14 days read-only: %s", raw)
}
// +31 days: halted → archived (export window); the warning stays
h.app.Now = func() time.Time { return time.Now().Add(31 * 24 * time.Hour) }
_, raw = h.do("POST", "/v1/internal/erp/reconcile", nil)
if getTenant(t, h, halted.ID).Status != "archived" {
t.Fatalf("day 31 halted: %s", raw)
}
if getTenant(t, h, warn.ID).Status != "halted" {
t.Fatalf("day 31 restricted: %s", raw)
if getTenant(t, h, warn.ID).Status != "warning" {
t.Fatalf("day 31 warning: %s", raw)
}
// expired trial walks the same ladder: restricted → halted
if getTenant(t, h, trial.ID).Status != "halted" {
// the trial, halted above (stamped on the real clock), is past its
// export window by now as well
if getTenant(t, h, trial.ID).Status != "archived" {
t.Fatalf("expired trial: %s", getTenant(t, h, trial.ID).Status)
}
h.app.Now = nil
@@ -500,11 +515,36 @@ func TestReconcile_overdueInvoicesDriveTheLadder(t *testing.T) {
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)})
// 40 days overdue but no Mahnung → still warning (AGB § 10); a
// cancelled (docstatus 2) invoice does not count
invName := inv["name"].(string)
mockDo("PUT", "/api/resource/Sales Invoice/"+invName, map[string]any{"due_date": day(-40)})
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)
if raw := reconcile(); getTenant(t, h, tn.ID).Status != "warning" {
t.Fatalf("40 days, no Mahnung: %s", raw)
}
// Mahnungen that don't count: a draft, a resolved one, one for a paid invoice
dunning := func(posted string, docstatus int, status string, invoice string) map[string]any {
return mockDo("POST", "/api/resource/Dunning", map[string]any{"customer": cust, "docstatus": docstatus, "status": status, "posting_date": posted,
"overdue_payments": []map[string]any{{"sales_invoice": invoice}}})
}
dunning(day(-20), 0, "Draft", invName)
dunning(day(-20), 1, "Resolved", invName)
dunning(day(-20), 1, "Unresolved", paid["name"].(string))
if raw := reconcile(); getTenant(t, h, tn.ID).Status != "warning" {
t.Fatalf("no counting Mahnung: %s", raw)
}
// a Mahnung 13 days ago → warning; 14 days ago → restricted (read-only)
mahnung := dunning(day(-13), 1, "Unresolved", invName)
if raw := reconcile(); getTenant(t, h, tn.ID).Status != "warning" {
t.Fatalf("Mahnung 13 days: %s", raw)
}
mockDo("PUT", "/api/resource/Dunning/"+mahnung["name"].(string), map[string]any{"posting_date": day(-14)})
if raw := reconcile(); getTenant(t, h, tn.ID).Status != "restricted" || !strings.Contains(raw, "dunning-co→restricted") {
t.Fatalf("Mahnung 14 days: %s", raw)
}
if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); !chk.ReadOnly {
t.Fatalf("restricted must be read-only: %+v", chk)
}
// paid via Zahlungsabgleich (no payment event) → active again
mockDo("PUT", "/api/resource/Sales Invoice/"+inv["name"].(string), map[string]any{"outstanding_amount": 0})
@@ -520,6 +560,47 @@ func TestReconcile_overdueInvoicesDriveTheLadder(t *testing.T) {
})
}
// A Mahnung that cannot be read never restricts: the tenant stays on warning
// and the reconcile report names the error.
func TestReconcile_dunningReadFailureStaysWarning(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(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/resource/Dunning") {
http.Error(w, `{"exc_type":"PermissionError"}`, http.StatusForbidden)
return
}
mock.ServeHTTP(w, r)
}))
defer ms.Close()
h.app.ERP = erp.New(erp.Config{BaseURL: ms.URL, APIKey: "k", APISecret: "s"})
tn := newTenant(t, h, "dunning-403")
if _, err := h.app.DrainOutbox(t.Context()); err != nil {
t.Fatal(err)
}
cust := getTenant(t, h, tn.ID).ErpCustomerID
post := func(path string, body map[string]any) {
buf, _ := json.Marshal(body)
req, _ := http.NewRequest("POST", 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 POST %s: %v %v", path, err, resp)
}
_ = resp.Body.Close()
}
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}}})
berlin, _ := time.LoadLocation("Europe/Berlin")
due := time.Now().In(berlin).AddDate(0, 0, -40).Format("2006-01-02")
post("/api/resource/Sales Invoice", map[string]any{"customer": cust, "docstatus": 1, "due_date": due, "outstanding_amount": 10})
_, raw := h.do("POST", "/v1/internal/erp/reconcile", nil)
if getTenant(t, h, tn.ID).Status != "warning" || !strings.Contains(string(raw), "dunning-403: erp dunnings:") {
t.Fatalf("dunning read failure: %s", raw)
}
})
}
// TestOutbox_deadLettersAfterMaxAttempts: an item that keeps failing is
// retried with backoff, then given up after server.MaxOutboxAttempts (kept, with
// "dead letter: " in last_error) instead of being retried forever.
+17 -10
View File
@@ -10,22 +10,29 @@ func TestOverdueStep(t *testing.T) {
s := &Server{}
for _, c := range []struct {
status string
dunned bool
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},
{"active", false, 0, "warning", true},
{"trial", false, 0, "warning", true},
// no Mahnung: never past warning, however long overdue (AGB § 10)
{"warning", false, 90, "", false},
{"active", true, 13, "warning", true},
{"active", true, 14, "restricted", true},
{"warning", true, 14, "restricted", true},
// a Mahnung never halts directly: read-only first, the timer halts
{"restricted", true, 40, "", false},
{"active", true, 40, "restricted", true},
{"warning", true, 40, "restricted", true},
{"warning", true, 2, "", false},
{"demo", true, 40, "", false},
{"halted", true, 40, "", false},
} {
next, ok := s.overdueStep(&store.Tenant{Status: c.status}, c.days)
next, ok := s.overdueStep(&store.Tenant{Status: c.status}, c.dunned, 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)
t.Errorf("%s dunned=%v %d days: %q %v, want %q %v", c.status, c.dunned, c.days, next, ok, c.next, c.ok)
}
}
}
+4 -2
View File
@@ -2079,8 +2079,10 @@ paths:
X-Hub-Signature-256 = sha256=hex). Idempotent by X-Frappe-Event-Id
(fallback: hash of event+name+modified+body). Events:
sales_order.submit → subscriptions + entitlements + active;
sales_invoice.overdue → warning / restricted (days_overdue ≥
ERP_RESTRICT_AFTER_DAYS) / halted; payment_entry.submit → active;
sales_invoice.overdue → warning only (restricted and halted need a
Mahnung: the reconcile pass reads open ERPNext Dunnings and counts
ERP_RESTRICT_AFTER_DAYS / ERP_HALT_AFTER_DAYS from the Mahnung date,
AGB § 10); payment_entry.submit → active;
subscription.cancel → halted. Unknown customers are acknowledged (202).
requestBody:
required: true