Files
tenant-registry/internal/erpmock/server_test.go
T
Sharang ParnerkarandClaude Fable 5.1 7b02cd1c21
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Failing after 14m32s
ci / image (pull_request) Skipped
feat(erp): always-on ERP link, usage events, outbox, CLI licences
M-MIG-7 (ERP/02, decisions 3, 12, 13, 18):

- migration 0004: subscriptions, usage_events, erp_outbox,
  erp_webhook_receipts, licences; tenants.status_changed_at (trigger)
- internal/erp: Frappe REST client (Customer upsert by tenant_id,
  Subscription list, Usage Record, Lead) + webhook signing/verification
- internal/erpmock + cmd/erpmock: ERPNext stand-in for staging —
  /api/resource/{doctype} with token auth, request log, /_mock/fire/*
  triggers that mutate docs and deliver signed webhooks
- POST /v1/internal/erp/webhook (HMAC, idempotent by event id):
  sales_order.submit → subscriptions + entitlements (SKU → product/plan,
  add-on SKUs → limits) + active; sales_invoice.overdue → warning /
  restricted / halted by days overdue; payment_entry.submit → active;
  subscription.cancel → halted
- outbox worker (customer.upsert on tenant create, usage.record,
  lead.create on catalog request) with backoff; reconcile job mirrors
  ERP subscriptions and applies the time-based ladder (trial expiry,
  warning→restricted 14 d, restricted→halted 30 d, halted→archived 30 d)
- POST/GET /v1/usage/events (idempotency_key, batch), GET
  /v1/subscriptions, GET /v1/internal/erp/status, POST
  /v1/internal/erp/reconcile
- CLI licences: Ed25519 signer (LICENCE_SIGNING_KEY), POST /v1/licences
  (entitlement-gated, expiry capped by the entitlement), GET
  /.well-known/licence-keys.json, POST /v1/licences/heartbeat (grace
  ladder, renewal past half-life, revoked), revoke/list
- authn Principal carries tenant-context claims (user tokens scope usage
  and licence calls to their own tenant); authz groups usage(.read)
- tests for every path (both stores), erpmock, erp client, licence pkg;
  openapi.yaml + README updated; Dockerfile ships /erpmock

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-12 09:45:05 +02:00

158 lines
6.6 KiB
Go

package erpmock
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/erp"
)
func call(t *testing.T, base, method, path string, body any, auth bool) (int, []byte) {
t.Helper()
var reader io.Reader
if body != nil {
buf, _ := json.Marshal(body)
reader = bytes.NewReader(buf)
}
req, _ := http.NewRequest(method, base+path, reader)
if auth {
req.Header.Set("Authorization", "token k:s")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(resp.Body)
return resp.StatusCode, raw
}
func TestMock_resourceAPI(t *testing.T) {
// receiver that records the webhook
var got erp.WebhookEvent
var sig, eventID string
recv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
sig = r.Header.Get(erp.HeaderSignature)
eventID = r.Header.Get(erp.HeaderEventID)
if !erp.VerifySignature("sec", body, sig) {
w.WriteHeader(401)
return
}
_ = json.Unmarshal(body, &got)
w.WriteHeader(200)
}))
defer recv.Close()
srv := httptest.NewServer(New(Config{APIKey: "k", APISecret: "s", WebhookURL: recv.URL, WebhookSecret: "sec"}))
defer srv.Close()
if code, _ := call(t, srv.URL, "GET", "/api/resource/Item", nil, false); code != 401 {
t.Fatalf("no auth: %d", code)
}
code, raw := call(t, srv.URL, "GET", `/api/resource/Item?fields=["name"]`, nil, true)
if code != 200 || !bytes.Contains(raw, []byte("CRA-CSA-CLD-STD")) {
t.Fatalf("items: %d %s", code, raw)
}
code, raw = call(t, srv.URL, "POST", "/api/resource/Customer", map[string]any{"customer_name": "Acme", "tenant_id": "t-1"}, true)
if code != 200 || !bytes.Contains(raw, []byte(`"name":"CUST-00001"`)) {
t.Fatalf("create: %d %s", code, raw)
}
code, raw = call(t, srv.URL, "GET", `/api/resource/Customer?filters=[["tenant_id","=","t-1"]]&fields=["name","tenant_id"]`, nil, true)
if code != 200 || !bytes.Contains(raw, []byte(`CUST-00001`)) {
t.Fatalf("filter: %d %s", code, raw)
}
if _, raw = call(t, srv.URL, "GET", `/api/resource/Customer?filters=[["tenant_id","=","t-2"]]`, nil, true); !bytes.Contains(raw, []byte(`"data":[]`)) {
t.Fatalf("filter miss: %s", raw)
}
if code, _ = call(t, srv.URL, "GET", `/api/resource/Customer?filters=nope`, nil, true); code != 400 {
t.Fatalf("bad filter: %d", code)
}
if code, raw = call(t, srv.URL, "PUT", "/api/resource/Customer/CUST-00001", map[string]any{"territory": "Germany"}, true); code != 200 || !bytes.Contains(raw, []byte("Germany")) {
t.Fatalf("update: %d %s", code, raw)
}
if code, _ = call(t, srv.URL, "GET", "/api/resource/Customer/CUST-00009", nil, true); code != 404 {
t.Fatalf("get missing: %d", code)
}
if code, _ = call(t, srv.URL, "PUT", "/api/resource/Customer/CUST-00009", map[string]any{}, true); code != 404 {
t.Fatalf("update missing: %d", code)
}
// fire: unknown customer, missing items, then a real order
if code, _ = call(t, srv.URL, "POST", "/_mock/fire/sales-order-submit", map[string]any{"tenant_id": "nope"}, false); code != 404 {
t.Fatalf("fire unknown: %d", code)
}
if code, _ = call(t, srv.URL, "POST", "/_mock/fire/sales-order-submit", map[string]any{"tenant_id": "t-1"}, false); code != 400 {
t.Fatalf("fire no items: %d", code)
}
if code, _ = call(t, srv.URL, "POST", "/_mock/fire/bogus", map[string]any{"tenant_id": "t-1"}, false); code != 404 {
t.Fatalf("fire bogus: %d", code)
}
code, raw = call(t, srv.URL, "POST", "/_mock/fire/sales-order-submit", map[string]any{"customer": "CUST-00001", "items": []map[string]any{{"item_code": "CRA-CSA-CLD-STD", "qty": 2}}}, false)
if code != 200 {
t.Fatalf("fire: %d %s", code, raw)
}
if got.Event != erp.EventSalesOrderSubmit || got.Customer != "CUST-00001" || got.TenantID != "t-1" || len(got.Items) != 1 || got.Subscription == "" || sig == "" || eventID == "" {
t.Fatalf("delivered event: %+v sig=%q id=%q", got, sig, eventID)
}
// the Subscription doc exists and lists the plan
_, raw = call(t, srv.URL, "GET", `/api/resource/Subscription?filters=[["party","=","CUST-00001"]]&fields=["*"]`, nil, true)
if !bytes.Contains(raw, []byte(`"plan":"CRA-CSA-CLD-STD"`)) || !bytes.Contains(raw, []byte(`"status":"Active"`)) {
t.Fatalf("subscription doc: %s", raw)
}
call(t, srv.URL, "POST", "/_mock/fire/invoice-overdue", map[string]any{"customer": "CUST-00001", "days_overdue": 5, "amount": 10}, false)
if got.Event != erp.EventInvoiceOverdue || got.DaysOverdue != 5 {
t.Fatalf("overdue: %+v", got)
}
call(t, srv.URL, "POST", "/_mock/fire/payment-entry", map[string]any{"customer": "CUST-00001", "amount": 10}, false)
if got.Event != erp.EventPaymentEntrySubmit {
t.Fatalf("payment: %+v", got)
}
_, raw = call(t, srv.URL, "GET", "/_mock/docs/Sales Invoice", nil, false)
if !bytes.Contains(raw, []byte(`"status":"Paid"`)) {
t.Fatalf("invoice not paid: %s", raw)
}
call(t, srv.URL, "POST", "/_mock/fire/subscription-cancel", map[string]any{"customer": "CUST-00001"}, false)
if got.Event != erp.EventSubscriptionCancel || got.Subscription == "" {
t.Fatalf("cancel: %+v", got)
}
if code, _ = call(t, srv.URL, "POST", "/_mock/fire/subscription-cancel", map[string]any{"customer": "CUST-00001"}, false); code != 404 {
t.Fatalf("second cancel: %d", code)
}
// logs
_, raw = call(t, srv.URL, "GET", "/_mock/requests?doctype=Customer&method=POST", nil, false)
if strings.Count(string(raw), `"method":"POST"`) != 1 {
t.Fatalf("request log: %s", raw)
}
_, raw = call(t, srv.URL, "GET", "/_mock/deliveries", nil, false)
if strings.Count(string(raw), `"status":200`) != 4 {
t.Fatalf("deliveries: %s", raw)
}
if code, _ = call(t, srv.URL, "DELETE", "/_mock/requests", nil, false); code != 200 {
t.Fatalf("clear: %d", code)
}
if code, _ = call(t, srv.URL, "DELETE", "/api/resource/Customer/CUST-00001", nil, true); code != 202 {
t.Fatalf("delete: %d", code)
}
if code, _ = call(t, srv.URL, "POST", "/_mock/reset", nil, false); code != 200 {
t.Fatalf("reset: %d", code)
}
if _, raw = call(t, srv.URL, "GET", `/api/resource/Customer?fields=["*"]`, nil, true); !bytes.Contains(raw, []byte(`"data":[]`)) {
t.Fatalf("after reset: %s", raw)
}
}
func TestMock_noWebhookURL(t *testing.T) {
srv := httptest.NewServer(New(Config{APIKey: "k", APISecret: "s"}))
defer srv.Close()
call(t, srv.URL, "POST", "/api/resource/Customer", map[string]any{"customer_name": "A", "tenant_id": "t"}, true)
code, raw := call(t, srv.URL, "POST", "/_mock/fire/invoice-overdue", map[string]any{"tenant_id": "t"}, false)
if code != 502 || !bytes.Contains(raw, []byte("not configured")) {
t.Fatalf("got %d %s", code, raw)
}
}