package server_test import ( "bytes" "context" "encoding/json" "errors" "net/http" "testing" "time" "git.breakpilot.com/platform/tenant-registry/internal/erp" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // pruefwerkCheck posts the entitlement check and returns the raw body too, // so a test can tell a null limit from a missing one. func pruefwerkCheck(t *testing.T, h *testHarness, tenantID string) (map[string]any, []byte) { t.Helper() resp, raw := h.do("POST", "/v1/internal/entitlements/check", map[string]any{"tenant_id": tenantID, "product": "pruefwerk"}) if resp.StatusCode != http.StatusOK { t.Fatalf("check: %d %s", resp.StatusCode, raw) } var out struct { Allowed bool `json:"allowed"` Limits map[string]any `json:"limits"` } if err := json.Unmarshal(raw, &out); err != nil || !out.Allowed { t.Fatalf("check: %v %s", err, raw) } return out.Limits, raw } // bookSKUs submits a sales order for the tenant with the given items. func bookSKUs(t *testing.T, h *testHarness, tenantID, order string, skus ...string) { t.Helper() items := make([]erp.WebhookItem, len(skus)) for i, sku := range skus { items[i] = erp.WebhookItem{ItemCode: sku, Qty: 1} } ev := erp.WebhookEvent{Event: erp.EventSalesOrderSubmit, Doctype: "Sales Order", Name: order, TenantID: tenantID, Subscription: "SUB-" + order, Items: items} if resp, raw := h.webhook(t, ev, "evt-"+order); resp.StatusCode != http.StatusOK { t.Fatalf("sales order %s: %d %s", order, resp.StatusCode, raw) } } func putCap(t *testing.T, h *testHarness, tenantID, body string) (*http.Response, []byte) { t.Helper() return h.doRaw("PUT", "/v1/tenants/"+tenantID+"/products/pruefwerk/settings", body) } // The three Prüfwerk keys per plan, always present; null where unlimited. func TestEntitlementCheck_pruefwerkPlanLimits(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { cases := []struct { slug string skus []string // nil: a trial, no plan SKU targets any pruefung any plan string }{ {"pw-trial", nil, 5.0, 100.0, "standard"}, {"pw-scan", []string{"CRA-CSA-CLD-SCAN"}, 5.0, 100.0, "standard"}, {"pw-std", []string{"CRA-CSA-CLD-STD"}, 5.0, 100.0, "standard"}, {"pw-bus", []string{"CRA-CSA-CLD-BUS", "CRA-WBK-CLD-ENT"}, 25.0, 500.0, "business"}, {"pw-mixed", []string{"CRA-CSA-CLD-STD", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-BUS"}, nil, nil, "enterprise"}, {"pw-ent", []string{"CRA-CSA-CLD-ENT"}, nil, nil, "enterprise"}, } for i, c := range cases { tn := newTenant(t, h, c.slug) if c.skus == nil { if resp, raw := h.do("POST", "/v1/catalog/trial-request", map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); resp.StatusCode != http.StatusCreated { t.Fatalf("%s trial: %d %s", c.slug, resp.StatusCode, raw) } } else { bookSKUs(t, h, tn.ID, "SO-PW-"+string(rune('A'+i)), c.skus...) } // A cap the workspace set: passed on below Enterprise only. if resp, raw := putCap(t, h, tn.ID, `{"prueftag_cap":12}`); resp.StatusCode != http.StatusOK { t.Fatalf("%s put: %d %s", c.slug, resp.StatusCode, raw) } limits, raw := pruefwerkCheck(t, h, tn.ID) wantCap := any(12.0) if c.plan == "enterprise" { wantCap = nil } for key, want := range map[string]any{"included_targets": c.targets, "monthly_pruefungen": c.pruefung, "prueftag_cap": wantCap} { got, ok := limits[key] if !ok || got != want { t.Errorf("%s %s = %v (present %v), want %v; %s", c.slug, key, got, ok, want, raw) } if want == nil && !bytes.Contains(raw, []byte(`"`+key+`":null`)) { t.Errorf("%s %s not sent as null: %s", c.slug, key, raw) } } if c.skus != nil && limits["skus"] == nil { t.Errorf("%s: stored config keys dropped: %s", c.slug, raw) } _, raw = h.do("GET", "/v1/tenants/"+tn.ID+"/products/pruefwerk/settings", nil) got := decode[map[string]any](t, raw) if got["plan"] != c.plan || got["cap_applies"] != (c.plan != "enterprise") || got["prueftag_cap"] != 12.0 { t.Errorf("%s settings: %s", c.slug, raw) } } // The limits are a copy: the stored config gains none of the keys. tn := newTenant(t, h, "pw-copy") bookSKUs(t, h, tn.ID, "SO-PW-COPY", "CRA-CSA-CLD-BUS") pruefwerkCheck(t, h, tn.ID) tps, err := h.store.ListTenantProducts(context.Background(), tn.ID) if err != nil { t.Fatal(err) } for _, tp := range tps { if _, ok := tp.Config["included_targets"]; ok { t.Fatalf("stored config mutated: %+v", tp.Config) } } // Other products are unchanged. bookSKUs(t, h, tn.ID, "SO-PW-FWK", "DEV-FWK-CLD-STD") resp, raw := h.do("POST", "/v1/internal/entitlements/check", map[string]any{"tenant_id": tn.ID, "product": "firmwerk"}) if resp.StatusCode != http.StatusOK || bytes.Contains(raw, []byte("included_targets")) || bytes.Contains(raw, []byte("prueftag_cap")) { t.Fatalf("firmwerk check: %d %s", resp.StatusCode, raw) } }) } // recomputeEntitlements rebuilds tenant_products.config; the cap lives // elsewhere and stays. func TestPruefwerkSettings_surviveRecompute(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { tn := newTenant(t, h, "pw-recompute") bookSKUs(t, h, tn.ID, "SO-RC-1", "CRA-CSA-CLD-STD") if resp, raw := putCap(t, h, tn.ID, `{"prueftag_cap":7}`); resp.StatusCode != http.StatusOK { t.Fatalf("put: %d %s", resp.StatusCode, raw) } // Upgrade: a new order recomputes the entitlement from scratch. bookSKUs(t, h, tn.ID, "SO-RC-2", "CRA-CSA-CLD-BUS") limits, raw := pruefwerkCheck(t, h, tn.ID) if limits["prueftag_cap"] != 7.0 || limits["included_targets"] != 25.0 { t.Fatalf("after recompute: %s", raw) } tps, err := h.store.ListTenantProducts(context.Background(), tn.ID) if err != nil { t.Fatal(err) } for _, tp := range tps { if _, ok := tp.Config["prueftag_cap"]; ok { t.Fatalf("cap leaked into the ERP-derived config: %+v", tp.Config) } } }) } func TestPruefwerkSettings_putValidation(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { id := h.tenant.ID _, raw := h.do("GET", "/v1/tenants/"+id+"/products/pruefwerk/settings", nil) if got := decode[map[string]any](t, raw); got["prueftag_cap"] != nil || !bytes.Contains(raw, []byte(`"prueftag_cap":null`)) { t.Fatalf("nothing saved: %s", raw) } for _, c := range []struct { body string code int want string }{ {`{"prueftag_cap":0}`, 200, `"prueftag_cap":0`}, {`{"prueftag_cap":10000}`, 200, `"prueftag_cap":10000`}, {`{"prueftag_cap":null}`, 200, `"prueftag_cap":null`}, {`{"prueftag_cap":-1}`, 400, "invalid_prueftag_cap"}, {`{"prueftag_cap":10001}`, 400, "invalid_prueftag_cap"}, {`{"prueftag_cap":2.5}`, 400, "invalid_prueftag_cap"}, {`{"prueftag_cap":"5"}`, 400, "invalid_prueftag_cap"}, {`{"prueftag_cap":true}`, 400, "invalid_prueftag_cap"}, {`{"prueftag_cap":5,"monthly_pruefungen":900}`, 400, "unknown_setting"}, {`{}`, 400, "prueftag_cap_required"}, {`null`, 400, "invalid_body"}, {`[5]`, 400, "invalid_body"}, } { resp, raw := putCap(t, h, id, c.body) if resp.StatusCode != c.code || !bytes.Contains(raw, []byte(c.want)) { t.Errorf("PUT %s: %d %s", c.body, resp.StatusCode, raw) } } _, raw = h.do("GET", "/v1/tenants/"+id+"/products/pruefwerk/settings", nil) if !bytes.Contains(raw, []byte(`"prueftag_cap":null`)) { t.Fatalf("after clearing: %s", raw) } // 0 → 10000 → null: three changes, each audited with old and new. _, raw = h.do("GET", "/v1/audit?tenant_id="+id+"&action=product_settings.changed&limit=10", nil) evs := decode[struct { Items []store.AuditEvent `json:"items"` }](t, raw).Items if len(evs) != 3 { t.Fatalf("audit events: %s", raw) } if resp, _ := putCap(t, h, "00000000-0000-0000-0000-00000000beef", `{"prueftag_cap":1}`); resp.StatusCode != http.StatusNotFound { t.Fatalf("unknown tenant: %d", resp.StatusCode) } }) } // Both stores: replace, read back, unknown tenant, bad id, not an object. func TestProductSettingsStore(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { ctx := context.Background() put := func(tenantID, doc string) (*store.TenantProductSettings, error) { return h.store.PutTenantProductSettings(ctx, store.TenantProductSettings{ TenantID: tenantID, Product: "pruefwerk", Settings: json.RawMessage(doc), UpdatedBy: "u-1", UpdatedAt: time.Now(), }) } if _, err := h.store.GetTenantProductSettings(ctx, h.tenant.ID, "pruefwerk"); !errors.Is(err, store.ErrNotFound) { t.Fatalf("none yet: %v", err) } if _, err := put(h.tenant.ID, `{"prueftag_cap":3}`); err != nil { t.Fatal(err) } got, err := put(h.tenant.ID, `{"prueftag_cap":null}`) if err != nil || got.UpdatedBy != "u-1" || mustCanon(t, got.Settings) != `{"prueftag_cap":null}` { t.Fatalf("replace: %+v %v", got, err) } got, err = h.store.GetTenantProductSettings(ctx, h.tenant.ID, "pruefwerk") if err != nil || mustCanon(t, got.Settings) != `{"prueftag_cap":null}` || got.Product != "pruefwerk" { t.Fatalf("read back: %+v %v", got, err) } if _, err := h.store.GetTenantProductSettings(ctx, h.tenant.ID, "firmwerk"); !errors.Is(err, store.ErrNotFound) { t.Fatalf("other product: %v", err) } if _, err := put("00000000-0000-0000-0000-00000000beef", `{}`); !errors.Is(err, store.ErrNotFound) { t.Fatalf("unknown tenant: %v", err) } if _, err := h.store.GetTenantProductSettings(ctx, "not-a-uuid", "pruefwerk"); !errors.Is(err, store.ErrNotFound) { t.Fatalf("bad id: %v", err) } if _, err := put(h.tenant.ID, `[1]`); !errors.Is(err, store.ErrInvalidInput) { t.Fatalf("not an object: %v", err) } }) } // The two Prüfwerk metering metrics go through the generic usage path: // stored once per idempotency key, a repeat is a duplicate (no update in // place, so a later, higher target.extra peak comes with its own key). func TestUsageEvents_pruefwerkMeteringMetrics(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { tn := newTenant(t, h, "pw-usage") events := []map[string]any{ {"idempotency_key": "prueftag:" + tn.ID + ":tgt-1:2026-11-05", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "prueftag.booked", "quantity": 1, "occurred_at": "2026-11-05T09:00:00Z"}, {"idempotency_key": "target-extra:" + tn.ID + ":2026-11:3", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "target.extra", "quantity": 3, "occurred_at": "2026-11-05T09:00:00Z"}, } resp, raw := h.do("POST", "/v1/usage/events", map[string]any{"events": events}) if resp.StatusCode != http.StatusAccepted || !bytes.Contains(raw, []byte(`"accepted":2`)) { t.Fatalf("first: %d %s", resp.StatusCode, raw) } resp, raw = h.do("POST", "/v1/usage/events", map[string]any{"events": events}) if resp.StatusCode != http.StatusAccepted || !bytes.Contains(raw, []byte(`"accepted":0`)) || !bytes.Contains(raw, []byte(`"duplicates":2`)) { t.Fatalf("repeat: %d %s", resp.StatusCode, raw) } // Same Prüftag key with another quantity: still the first event. again := map[string]any{} for k, v := range events[0] { again[k] = v } again["quantity"] = 5 if _, raw := h.do("POST", "/v1/usage/events", again); !bytes.Contains(raw, []byte(`"duplicates":1`)) { t.Fatalf("changed repeat: %s", raw) } for metric, qty := range map[string]float64{"prueftag.booked": 1, "target.extra": 3} { _, raw := h.do("GET", "/v1/usage/events?tenant_id="+tn.ID+"&metric="+metric, nil) items := decode[struct { Items []store.UsageEvent `json:"items"` }](t, raw).Items if len(items) != 1 || items[0].Quantity != qty || items[0].Product != "pruefwerk" { t.Fatalf("%s: %s", metric, raw) } } }) }