Files
tenant-registry/internal/server/erp_test.go
T
sharangandSharang Parnerkar 1332ad7bc5
ci / shared (push) Successful in 15s
ci / test (push) Successful in 26m35s
ci / image (push) Successful in 53s
feat(erpsetup): catalogue for Leistungsbeschreibung 1.0.0, opt-in -sync-catalog (#115)
Brings the ERPNext sales catalogue in line with the frozen Leistungsbeschreibungen 1.0.0. This PR changes code and tests only. No ERP was called; the live run is yours, using the erpsetup CLI.

## Dry run first (with the flag; only this path prints `field old → new`)

```sh
ERP_BASE_URL=https://erp.breakpilot.com ERP_API_KEY=… ERP_API_SECRET=… ERP_WEBHOOK_SECRET=… \
  go run ./cmd/erpsetup -webhook-url https://registry.breakpilot.com/v1/internal/erp/webhook -sync-catalog -dry-run
```

(`ERP_LEAD_DOCTYPE` is optional, as before.) Leave out `-dry-run` for the real run.

## What a run does with and without `-sync-catalog`

| | without the flag (as today) | with `-sync-catalog` |
|---|---|---|
| New items, unit "Prüftag", their list prices | created | created |
| Item **description** | **updated (this already happens on every run today)** | updated |
| Item `item_name`, `disabled` | untouched | updated when they differ |
| Standard Selling `price_list_rate` (rows without a customer) | set once, never changed | updated when it differs |
| Customer-specific Item Prices | untouched | untouched |
| Quote print format (Mehrverbrauch row) | updated | updated |

**A plain run is not inert.** It creates the 5 new items, the new unit and 5 new prices, rewrites every changed description, and updates the quote template. Only names, the disabled flags and price changes wait for the flag. Nothing is ever deleted. Only the doctypes Item, Item Price and UOM are touched beyond what erpsetup already manages.

## Catalogue changes

| Code | Status | Price old → new (EUR) |
|---|---|---|
| PLT-CORE-CLD-STD/BUS/ENT | keep (name "Breakpilot …", new text) | 290 / 790 / 1990 (unchanged) |
| PLT-BNDL-CLD-STD | **new** Starter-Modulpaket | 990 |
| PLT-BNDL-CLD-ADD | **new** Weiteres Modul | 499 |
| CRA-CSA-CLD-STD | keep | **1490 → 490** |
| CRA-CSA-CLD-BUS | keep | **3990 → 1290** |
| CRA-CSA-CLD-ENT | keep | **9900 → 0** (Preis nach Vereinbarung: a quote shows 0,00 € unless the rate is entered by hand) |
| CRA-CSA-CLD-TGT | **new** extra Prüfobjekt / Monat | 5.99 |
| CRA-CSA-CLD-DAY | **new** Prüftag (unit Prüftag) | 9.99 |
| CRA-CSA-CLD-SCAN | **disable** | 12 (unchanged) |
| CRA-WBK-CLD-STD/BUS/ENT | **disable** | unchanged |
| DEV-WP-CLD-STD | keep ("Werkpilot Cloud") | 59 |
| DEV-WP-CLD-BUS/ENT | **disable** | unchanged |
| DEV-WP-OPR-*, DEV-FWK-OPR-*, INF-GIT-OPR-*, INF-CI-OPR-* | keep, new texts | unchanged |
| DEV-FWK-CLD-STD | keep ("Firmwerk Cloud") | 89 |
| DEV-FWK-CLD-BUS/ENT | **disable** | unchanged |
| INF-GIT-CLD-STD/BUS/ENT | keep, new texts | 190 / 390 / 790 |
| INF-GIT-CLD-USR | **new** extra user | 19 |
| INF-CI-CLD-STD/BUS/ENT | keep, new texts | 149 / 290 / 590 |

The item group stays "BreakPilot Abonnements".

Correction to the spec, applied here: PLT-CORE-CLD-STD no longer mentions "Rechnungen", because LB Plattform §2(3) says the portal provides no invoices. The text is now "Arbeitsbereich mit Anmeldung und Team für bis 25 Nutzer, Standard-Support. Module werden einzeln gebucht." No other item text mentions invoices, and a test now checks that none does.

## Other changes

- `sku.Disabled` is sent to ERPNext as the Item field `disabled: 1`. Disabled items stay in ERPNext so old documents keep working. Since the disabled items already exist on prod, their flag only changes with `-sync-catalog`.
- **Quote, Mehrverbrauch row:** "Zusätzliche Prüfobjekte werden mit {TGT} netto je Monat berechnet, Prüftage nach verbrauchtem Monatskontingent mit {DAY} netto (Leistungsbeschreibung Prüfwerk, Abschnitt 7)." If a rate is missing, the text says "gemäß der jeweils gültigen Preisliste" instead, per rate. If both are missing, one combined sentence is printed. Quotes with INF-GIT-CLD-STD/BUS/ENT or PLT-BNDL-* add the sentence on extra users (Leistungsbeschreibung Breakpilot Plattform, Abschnitt 4). The Jinja was parsed and rendered locally with jinja2 against mocks for eight item mixes.
- **Migration 0026** adds CRA-CSA-CLD-TGT and -DAY to the `pruefwerk` product. SCAN stays so old orders still map. The up is guarded so it can run twice; the down removes the two SKUs. `DefaultProducts` and the ERP mock's SKU list follow. **Run `migrate-up` with the deploy.** Without it, TGT/DAY lines on an order log "sales order item without catalog product".
- **0 € module lines:** nothing needed fixing. Neither the webhook path nor reconcile reads the rate: the webhook template sends only `item_code` and `qty`, and `SubscriptionPlan` has no rate. A new test covers both paths: a bundle order with modules at rate 0 and qty 15 gives an active tenant, plan standard, and seats 15 per module.

## Decisions the spec did not cover

1. **No Prüfwerk Mehrverbrauch sentence on Enterprise quotes.** CRA-CSA-CLD-ENT is "ohne Begrenzung". Edge case: a quote with both -STD and -ENT also prints no Prüfwerk sentence. The extra-users sentence is not affected.
2. The run without the flag still writes descriptions, as `Run` has done until now (see the table).
3. `-sync-catalog` only changes Item Price rows without a `customer`. If there are several such rows for an item, the run reports "not synced". If there are none, it creates the list price.
4. The quote template's Item Price lookup still has no customer filter (unchanged from before).
5. INF-GIT-OPR texts: STD uses the spec text exactly, so "kein Quellcode verlässt das Haus" is gone. BUS keeps "für mittelgroße Teams" and loses "schnellerer Patch-Rhythmus", like CI. ENT says "für große Entwicklungsorganisationen".
6. INF-CI-OPR texts differ only by size ("mindestens 2 vCPU / 4 GB" etc.); "für größere/umfangreiche Builds" was dropped.
7. DEV-WP-OPR and DEV-FWK-OPR texts: the tier phrase sits after "im eigenen Netz", e.g. "Werkpilot im eigenen Netz für mittlere Teams, mit einem vom Kunden betriebenen KI-Modell; …".
8. TGT/DAY quantities on an order or subscription count toward Prüfwerk `seats`, exactly as SCAN already does. Not changed here.
9. Bundle revenue goes to cost center Plattform (PLT-*). Module lines at 0 € book nothing on Prüfwerk, Firmwerk or Werkpilot. Whether to allocate it is an accounting decision for you.
10. The dry run prints texts in full (no truncation), so the wording can be read before it goes live.
11. `TestEverySKUHasAListPrice` now allows exactly one item at 0: CRA-CSA-CLD-ENT.
12. The ERP mock's `DefaultSKUs` now also lists PLT-BNDL-* and CRA-CSA-CLD-TGT/DAY.

## Tests

`go build ./... && go vet ./... && go test ./...` all pass. The Postgres testcontainers suites ran (podman socket) with no skips: server 463 s, migrations 32 s. New tests:

- catalogue consistency: unique codes, units, disabled set, prices including 5.99/9.99, brand spelling
- `TestSyncCatalog`: the dry run writes nothing and names every change; the run updates name, description, disabled and price and keeps the customer price; a second run makes no updates; without the flag only the description changes
- quote template phrases
- `TestMigrate_productsSeedMatchesDefaults`: seed equals `DefaultProducts`, 0026 applied twice, down
- `TestErp_zeroRateModuleLinesEntitle`: webhook and reconcile, memory and Postgres

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #115
2026-11-06 16:20:22 +00:00

561 lines
25 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 → 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
}
// 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: 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
})
}
// 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)
}
})
}