Files
tenant-registry/internal/server/erp_test.go
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

642 lines
30 KiB
Go

package server_test
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/erp"
"git.breakpilot.com/platform/tenant-registry/internal/erpmock"
"git.breakpilot.com/platform/tenant-registry/internal/server"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// webhook posts a signed ERP event to the registry.
func (h *testHarness) webhook(t *testing.T, ev erp.WebhookEvent, eventID string) (*http.Response, []byte) {
t.Helper()
body, _ := json.Marshal(ev)
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/internal/erp/webhook", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set(erp.HeaderSignature, erp.Sign(testWebhookSecret, body))
if eventID != "" {
req.Header.Set(erp.HeaderEventID, eventID)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
var buf bytes.Buffer
_, _ = buf.ReadFrom(resp.Body)
return resp, buf.Bytes()
}
func newTenant(t *testing.T, h *testHarness, slug string) *store.Tenant {
t.Helper()
resp, raw := h.do("POST", "/v1/tenants", map[string]any{"slug": slug, "name": slug + " GmbH"})
if resp.StatusCode != 201 {
t.Fatalf("create %s: %d %s", slug, resp.StatusCode, raw)
}
return decode[struct {
Tenant *store.Tenant `json:"tenant"`
}](t, raw).Tenant
}
func getTenant(t *testing.T, h *testHarness, id string) store.Tenant {
t.Helper()
_, raw := h.do("GET", "/v1/tenants/"+id, nil)
return decode[store.Tenant](t, raw)
}
func TestErpWebhook_ladder(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
tn := newTenant(t, h, "erp-co")
// link the ERP customer as the outbox worker would
if _, err := h.store.UpdateTenant(t.Context(), tn.ID, store.TenantUpdate{ErpCustomerID: ptr("CUST-00001")}); err != nil {
t.Fatal(err)
}
// unsigned → 401
body, _ := json.Marshal(erp.WebhookEvent{Event: erp.EventSalesOrderSubmit})
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/internal/erp/webhook", bytes.NewReader(body))
if resp, _ := http.DefaultClient.Do(req); resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("unsigned: %d", resp.StatusCode)
}
// sales order: Prüfwerk business + 2 Werkbank runners + Firmwerk std → active, entitlements from ERP
so := erp.WebhookEvent{Event: erp.EventSalesOrderSubmit, Doctype: "Sales Order", Name: "SAL-ORD-00001", Customer: "CUST-00001",
Subscription: "SUB-00001",
Items: []erp.WebhookItem{{ItemCode: "CRA-CSA-CLD-BUS", Qty: 5}, {ItemCode: "CRA-WBK-CLD-BUS", Qty: 2}, {ItemCode: "DEV-FWK-CLD-STD", Qty: 3}, {ItemCode: "PLT-CORE-CLD-BUS", Qty: 1}}}
resp, raw := h.webhook(t, so, "evt-1")
if resp.StatusCode != 200 {
t.Fatalf("sales order: %d %s", resp.StatusCode, raw)
}
got := getTenant(t, h, tn.ID)
if got.Status != "active" || got.Plan != "business" {
t.Fatalf("after SO: status=%s plan=%s", got.Status, got.Plan)
}
if h.kcMock.Status["erp-co"] != "active" {
t.Fatalf("keycloak not synced: %q", h.kcMock.Status["erp-co"])
}
chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk", "addon": "werkbank"})
if !chk.Allowed || toF(chk.Limits["runners"]) != 2 || toF(chk.Limits["seats"]) != 5 {
t.Fatalf("pruefwerk entitlement: %+v", chk)
}
if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "firmwerk"}); !chk.Allowed || toF(chk.Limits["seats"]) != 3 {
t.Fatalf("firmwerk entitlement: %+v", chk)
}
if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "werkpilot"}); chk.Allowed {
t.Fatalf("werkpilot must not be entitled: %+v", chk)
}
_, raw = h.do("GET", "/v1/subscriptions?tenant_id="+tn.ID, nil)
subs := decode[struct {
Items []store.Subscription `json:"items"`
}](t, raw).Items
if len(subs) != 3 { // PLT-CORE has no product → not mirrored
t.Fatalf("subscriptions = %d: %+v", len(subs), subs)
}
// duplicate delivery is a no-op
if resp, raw := h.webhook(t, so, "evt-1"); resp.StatusCode != 200 || !bytes.Contains(raw, []byte(`"duplicate"`)) {
t.Fatalf("duplicate: %d %s", resp.StatusCode, raw)
}
// 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)
}
if got = getTenant(t, h, tn.ID); got.Status != "warning" {
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 != "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("warning keeps full access: %+v", chk)
}
// 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)
}
// payment → active again
h.webhook(t, erp.WebhookEvent{Event: erp.EventPaymentEntrySubmit, Doctype: "Payment Entry", Name: "PAY-1", Customer: "CUST-00001", Invoice: "INV-1"}, "evt-5")
if got = getTenant(t, h, tn.ID); got.Status != "active" {
t.Fatalf("after payment: %s", got.Status)
}
// cancel the subscription → halted, ERP-sourced entitlements disabled
h.webhook(t, erp.WebhookEvent{Event: erp.EventSubscriptionCancel, Doctype: "Subscription", Name: "SUB-00001", Customer: "CUST-00001", Subscription: "SUB-00001"}, "evt-6")
if got = getTenant(t, h, tn.ID); got.Status != "halted" {
t.Fatalf("after cancel: %s", got.Status)
}
if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); chk.Allowed || chk.Reason != "tenant_halted" {
t.Fatalf("halted: %+v", chk)
}
// payment after cancel does not reactivate (no active subscription)
h.webhook(t, erp.WebhookEvent{Event: erp.EventPaymentEntrySubmit, Doctype: "Payment Entry", Name: "PAY-2", Customer: "CUST-00001"}, "evt-7")
if got = getTenant(t, h, tn.ID); got.Status != "halted" {
t.Fatalf("payment without subscription: %s", got.Status)
}
// unknown customer → 202 ignored; unknown event → ignored
if resp, raw := h.webhook(t, erp.WebhookEvent{Event: erp.EventPaymentEntrySubmit, Name: "PAY-9", Customer: "CUST-NOPE"}, "evt-8"); resp.StatusCode != 202 {
t.Fatalf("unknown customer: %d %s", resp.StatusCode, raw)
}
if _, raw := h.webhook(t, erp.WebhookEvent{Event: "bogus", Name: "X", TenantID: tn.ID}, "evt-9"); !bytes.Contains(raw, []byte("unknown_event")) {
t.Fatalf("unknown event: %s", raw)
}
_, raw = h.do("GET", "/v1/audit?tenant_id="+tn.ID+"&limit=100", nil)
for _, a := range []string{"erp.webhook", "entitlement.granted", "entitlement.revoked", "tenant.status_changed"} {
if !containsAction(raw, a) {
t.Fatalf("audit missing %s", a)
}
}
})
}
func TestErpWebhook_disabledWithoutSecret(t *testing.T) {
h := newMemoryHarness(t)
defer h.Close()
h.app.Cfg.ErpWebhookSecret = ""
if resp, _ := h.webhook(t, erp.WebhookEvent{Event: "x"}, ""); resp.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("got %d", resp.StatusCode)
}
}
func TestUsageEvents_idempotentAndQueued(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
tn := newTenant(t, h, "usage-co")
ev := map[string]any{"idempotency_key": "scan-1", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "scan.completed", "quantity": 1,
"occurred_at": time.Now().UTC().Format(time.RFC3339), "properties": map[string]any{"scan_type": "sbom"}}
resp, raw := h.do("POST", "/v1/usage/events", ev)
if resp.StatusCode != 202 || !bytes.Contains(raw, []byte(`"accepted":1`)) {
t.Fatalf("first: %d %s", resp.StatusCode, raw)
}
// batch with the duplicate + a new one + a rejected one
resp, raw = h.do("POST", "/v1/usage/events", map[string]any{"events": []map[string]any{
ev,
{"idempotency_key": "scan-2", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "scan.completed"},
{"idempotency_key": "bad", "tenant_id": tn.ID, "product": "nope", "metric": "x"},
}})
if resp.StatusCode != 202 || !bytes.Contains(raw, []byte(`"accepted":1`)) || !bytes.Contains(raw, []byte(`"duplicates":1`)) || !bytes.Contains(raw, []byte(`unknown_product`)) {
t.Fatalf("batch: %d %s", resp.StatusCode, raw)
}
// array form + bad timestamp
resp, raw = h.do("POST", "/v1/usage/events", []map[string]any{{"idempotency_key": "scan-3", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "target.added", "occurred_at": "yesterday"}})
if resp.StatusCode != 400 || !bytes.Contains(raw, []byte("RFC3339")) {
t.Fatalf("bad ts: %d %s", resp.StatusCode, raw)
}
resp, raw = h.do("GET", "/v1/usage/events?tenant_id="+tn.ID+"&product=pruefwerk&limit=10", nil)
items := decode[struct {
Items []store.UsageEvent `json:"items"`
}](t, raw).Items
if resp.StatusCode != 200 || len(items) != 2 {
t.Fatalf("list: %d %d", resp.StatusCode, len(items))
}
if _, raw := h.do("GET", "/v1/usage/events?tenant_id="+tn.ID+"&metric=scan.completed&since="+time.Now().Add(-time.Hour).UTC().Format(time.RFC3339), nil); !bytes.Contains(raw, []byte("scan-1")) {
t.Fatalf("filtered list: %s", raw)
}
for _, q := range []string{"", "?tenant_id=" + tn.ID + "&limit=0", "?tenant_id=" + tn.ID + "&since=bad"} {
if resp, _ := h.do("GET", "/v1/usage/events"+q, nil); resp.StatusCode != 400 {
t.Fatalf("list %q: %d", q, resp.StatusCode)
}
}
// outbox: customer upsert (from create) + 2 usage records pending
_, raw = h.do("GET", "/v1/internal/erp/status", nil)
if !bytes.Contains(raw, []byte(`"outbox_pending":3`)) {
t.Fatalf("status: %s", raw)
}
})
}
// TestOutbox_drainsIntoErpMock runs the worker against the ERP mock: customer
// upsert links erp_customer_id, usage records + leads land in the mock, the
// reconcile path mirrors mock subscriptions, and fired webhooks come back.
func TestOutbox_drainsIntoErpMock(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, "mock-co")
h.do("POST", "/v1/usage/events", map[string]any{"idempotency_key": "u-1", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "scan.completed"})
h.do("POST", "/v1/catalog/request", map[string]any{"tenant_id": tn.ID, "product": "werkpilot"})
// first drain: customer upsert succeeds, usage fails (no customer yet at claim time) → retried
if _, err := h.app.DrainOutbox(t.Context()); err != nil {
t.Fatal(err)
}
got := getTenant(t, h, tn.ID)
if got.ErpCustomerID == "" {
t.Fatalf("erp_customer_id not linked: %+v", got)
}
// force the retry due now and drain again
h.app.Now = func() time.Time { return time.Now().Add(3 * time.Hour) }
if _, err := h.app.DrainOutbox(t.Context()); err != nil {
t.Fatal(err)
}
h.app.Now = nil
_, raw := h.do("GET", "/v1/internal/erp/status", nil)
if !bytes.Contains(raw, []byte(`"outbox_pending":0`)) {
t.Fatalf("outbox not drained: %s", raw)
}
_, raw = h.do("GET", "/v1/usage/events?tenant_id="+tn.ID, nil)
if !bytes.Contains(raw, []byte("erp_synced_at")) {
t.Fatalf("usage not marked synced: %s", raw)
}
reqs := mockRequests(t, ms.URL)
if reqs["POST Usage Record"] != 1 || reqs["POST Lead"] != 1 || reqs["POST Customer"] != 1 {
t.Fatalf("mock requests: %v", reqs)
}
// fire a sales order from the mock → webhook → tenant active
fire := func(trigger string, body map[string]any) []byte {
buf, _ := json.Marshal(body)
resp, err := http.Post(ms.URL+"/_mock/fire/"+trigger, "application/json", bytes.NewReader(buf))
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
var out bytes.Buffer
_, _ = out.ReadFrom(resp.Body)
if resp.StatusCode != 200 {
t.Fatalf("fire %s: %d %s", trigger, resp.StatusCode, out.String())
}
return out.Bytes()
}
fire("sales-order-submit", map[string]any{"tenant_id": tn.ID, "items": []map[string]any{{"item_code": "DEV-WP-CLD-STD", "qty": 4}}})
if got = getTenant(t, h, tn.ID); got.Status != "active" || got.Plan != "standard" {
t.Fatalf("after fired SO: %+v", got)
}
fire("invoice-overdue", map[string]any{"tenant_id": tn.ID, "days_overdue": 2, "amount": 99})
if got = getTenant(t, h, tn.ID); got.Status != "warning" {
t.Fatalf("after fired overdue: %s", got.Status)
}
fire("payment-entry", map[string]any{"tenant_id": tn.ID, "amount": 99})
if got = getTenant(t, h, tn.ID); got.Status != "active" {
t.Fatalf("after fired payment: %s", got.Status)
}
// reconcile against the mock: cancel the subscription in ERP only, then reconcile → halted
fire("subscription-cancel", map[string]any{"tenant_id": tn.ID})
if got = getTenant(t, h, tn.ID); got.Status != "halted" {
t.Fatalf("after fired cancel: %s", got.Status)
}
// new order directly in the mock (no webhook) → reconcile picks it up
mock2 := erp.New(erp.Config{BaseURL: ms.URL, APIKey: "k", APISecret: "s"})
_ = mock2
buf, _ := json.Marshal(map[string]any{"party": got.ErpCustomerID, "status": "Active", "sales_order": "SAL-ORD-MANUAL", "plans": []map[string]any{{"plan": "DEV-FWK-CLD-ENT", "qty": 2}}})
req, _ := http.NewRequest("POST", ms.URL+"/api/resource/Subscription", bytes.NewReader(buf))
req.Header.Set("Authorization", "token k:s")
if resp, err := http.DefaultClient.Do(req); err != nil || resp.StatusCode != 200 {
t.Fatalf("mock subscription: %v %v", err, resp)
}
_, raw = h.do("POST", "/v1/internal/erp/reconcile", nil)
if !bytes.Contains(raw, []byte(`"changed":["mock-co"]`)) {
t.Fatalf("reconcile: %s", raw)
}
if got = getTenant(t, h, tn.ID); got.Status != "active" || got.Plan != "enterprise" {
t.Fatalf("after reconcile: %+v", got)
}
if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "firmwerk"}); !chk.Allowed || toF(chk.Limits["seats"]) != 2 {
t.Fatalf("firmwerk after reconcile: %+v", chk)
}
// second reconcile: nothing changes
if _, raw = h.do("POST", "/v1/internal/erp/reconcile", nil); !bytes.Contains(raw, []byte(`"changed":[]`)) {
t.Fatalf("idempotent reconcile: %s", raw)
}
})
}
func mockRequests(t *testing.T, base string) map[string]int {
t.Helper()
resp, err := http.Get(base + "/_mock/requests")
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
var out struct {
Requests []erpmock.Request `json:"requests"`
}
_ = json.NewDecoder(resp.Body).Decode(&out)
counts := map[string]int{}
for _, r := range out.Requests {
counts[r.Method+" "+r.Doctype]++
}
return counts
}
// A Starter bundle (PLT-BNDL-CLD-STD) carries its modules as their own lines
// at 0,00 €. A module line at rate 0 still grants the product, with its
// quantity as seats, on both paths: the sales-order webhook and the reconcile
// of ERP Subscriptions. Neither reads the rate.
func TestErp_zeroRateModuleLinesEntitle(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
// Webhook: the body as ERPNext might send it, with rates.
tn := newTenant(t, h, "bundle-so")
body := []byte(`{"event":"sales_order.submit","doctype":"Sales Order","name":"SAL-ORD-BNDL","tenant_id":"` + tn.ID + `","subscription":"SUB-BNDL",
"items":[{"item_code":"PLT-BNDL-CLD-STD","qty":1,"rate":990},{"item_code":"CRA-CSA-CLD-STD","qty":15,"rate":0},{"item_code":"DEV-FWK-CLD-STD","qty":15,"rate":0}]}`)
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/internal/erp/webhook", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set(erp.HeaderSignature, erp.Sign(testWebhookSecret, body))
req.Header.Set(erp.HeaderEventID, "evt-bndl")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("sales order: %d", resp.StatusCode)
}
if got := getTenant(t, h, tn.ID); got.Status != "active" || got.Plan != "standard" {
t.Fatalf("after bundle SO: status=%s plan=%s", got.Status, got.Plan)
}
for _, p := range []string{"pruefwerk", "firmwerk"} {
if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": p}); !chk.Allowed || toF(chk.Limits["seats"]) != 15 {
t.Fatalf("%s from a 0 € line: %+v", p, chk)
}
}
// Reconcile: an ERP Subscription with a 0 € module plan.
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"})
tr := newTenant(t, h, "bundle-sub")
if _, err := h.store.UpdateTenant(t.Context(), tr.ID, store.TenantUpdate{ErpCustomerID: ptr("CUST-BNDL")}); err != nil {
t.Fatal(err)
}
buf, _ := json.Marshal(map[string]any{"party": "CUST-BNDL", "status": "Active", "sales_order": "SAL-ORD-BNDL2", "plans": []map[string]any{
{"plan": "PLT-BNDL-CLD-STD", "qty": 1, "rate": 990}, {"plan": "CRA-CSA-CLD-STD", "qty": 15, "rate": 0},
}})
sreq, _ := http.NewRequest("POST", ms.URL+"/api/resource/Subscription", bytes.NewReader(buf))
sreq.Header.Set("Authorization", "token k:s")
sresp, err := http.DefaultClient.Do(sreq)
if err != nil {
t.Fatal(err)
}
_ = sresp.Body.Close()
if sresp.StatusCode != 200 {
t.Fatalf("mock subscription: %d", sresp.StatusCode)
}
if _, raw := h.do("POST", "/v1/internal/erp/reconcile", nil); !bytes.Contains(raw, []byte(`"bundle-sub"`)) {
t.Fatalf("reconcile: %s", raw)
}
if got := getTenant(t, h, tr.ID); got.Status != "active" {
t.Fatalf("after reconcile: %s", got.Status)
}
if chk := check(t, h, map[string]any{"tenant_id": tr.ID, "product": "pruefwerk"}); !chk.Allowed || toF(chk.Limits["seats"]) != 15 {
t.Fatalf("pruefwerk from a 0 € plan: %+v", chk)
}
_, raw := h.do("GET", "/v1/subscriptions?tenant_id="+tr.ID, nil)
subs := decode[struct {
Items []store.Subscription `json:"items"`
}](t, raw).Items
// The bundle fee unlocks nothing and is not mirrored.
if len(subs) != 1 || subs[0].SKU != "CRA-CSA-CLD-STD" || subs[0].Seats != 15 || subs[0].Status != store.SubscriptionActive {
t.Fatalf("subscriptions: %+v", subs)
}
})
}
func TestReconcile_ladderEscalation(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
warn := newTenant(t, h, "esc-warning")
h.do("POST", "/v1/tenants/"+warn.ID+"/status", map[string]any{"status": "warning"})
halted := newTenant(t, h, "esc-halted")
h.do("POST", "/v1/tenants/"+halted.ID+"/status", map[string]any{"status": "halted"})
trial := newTenant(t, h, "esc-trial") // trial_ends_at = +14d
// +1 day: nothing
h.app.Now = func() time.Time { return time.Now().Add(24 * time.Hour) }
_, raw := h.do("POST", "/v1/internal/erp/reconcile", nil)
if !bytes.Contains(raw, []byte(`"escalated":[]`)) {
t.Fatalf("day 1: %s", raw)
}
// +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 != "warning" || getTenant(t, h, trial.ID).Status != "restricted" {
t.Fatalf("day 15: %s", raw)
}
// 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 != "warning" {
t.Fatalf("day 31 warning: %s", raw)
}
// 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
})
}
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)
}
// 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 != "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})
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
})
}
// 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.
func TestOutbox_deadLettersAfterMaxAttempts(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, `{"exception":"down"}`, http.StatusInternalServerError)
}))
defer down.Close()
h.app.ERP = erp.New(erp.Config{BaseURL: down.URL, APIKey: "k", APISecret: "s"})
newTenant(t, h, "dead-co") // enqueues the customer upsert
start := time.Now()
defer func() { h.app.Now = nil }()
for i := 1; i <= server.MaxOutboxAttempts; i++ {
at := start.Add(time.Duration(i) * 2 * time.Hour) // always past the last backoff
h.app.Now = func() time.Time { return at }
if _, err := h.app.DrainOutbox(t.Context()); err != nil {
t.Fatal(err)
}
pending, err := h.app.Store.PendingOutbox(t.Context())
if err != nil {
t.Fatal(err)
}
if want := 1; i < server.MaxOutboxAttempts && pending != want {
t.Fatalf("attempt %d: pending %d, want %d", i, pending, want)
}
if i == server.MaxOutboxAttempts && pending != 0 {
t.Fatalf("not dead-lettered after %d attempts: pending %d", i, pending)
}
}
// a later drain claims nothing: the item is done, not retried
h.app.Now = func() time.Time { return start.Add(1000 * time.Hour) }
if n, err := h.app.DrainOutbox(t.Context()); err != nil || n != 0 {
t.Fatalf("drain after dead letter: n=%d err=%v", n, err)
}
})
}