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/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 → restricted (read-only) 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 != "restricted" { t.Fatalf("after overdue 20d: %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) } // a later, shorter overdue never moves the tenant back up 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 } 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: warning → restricted, trial expired → restricted 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" { t.Fatalf("day 15: %s", raw) } // +31 days: halted → archived (export window); restricted (ex-warning) → halted 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) } // expired trial walks the same ladder: restricted → halted if getTenant(t, h, trial.ID).Status != "halted" { 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) } // 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 }) }