From 3f5319ea9b25f9e1bef6f680cf16a5e836dbb173 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:58:06 +0100 Subject: [PATCH] =?UTF-8?q?feat(entitlements):=20Pr=C3=BCfwerk=20plan=20li?= =?UTF-8?q?mits=20and=20Pr=C3=BCftag=20cap=20setting=20(t72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The entitlement check now always sends included_targets, monthly_pruefungen and prueftag_cap for Prüfwerk, from one plan table (Standard 5/100, Business 25/500, Enterprise null) resolved from the CRA-CSA-CLD-STD/-BUS/-ENT SKUs, highest wins; no plan SKU counts as Standard. The limits are a copy: the stored config is left as it is. The workspace's monthly Prüftag cap lives in the new tenant_product_settings table (0025), so recomputeEntitlements cannot reset it. GET/PUT /v1/tenants/{id}/products/pruefwerk/settings takes {"prueftag_cap": 0..10000 | null}; user tokens need IT_ADMIN, OWNER or FINANCE, service clients their route group. A change is audited (product_settings.changed, old/new). On Enterprise the cap is stored but the check sends null. prueftag.booked and target.extra go through POST /v1/usage/events as they are; a test pins the dedup by idempotency key. No invoicing yet. Co-Authored-By: Claude Opus 5.5 --- internal/server/entitlements.go | 9 + internal/server/openapi_test.go | 2 + internal/server/pruefwerk.go | 306 ++++++++++++++++++ internal/server/pruefwerk_internal_test.go | 216 +++++++++++++ internal/server/pruefwerk_test.go | 282 ++++++++++++++++ internal/server/server.go | 3 + internal/store/memory.go | 8 + internal/store/memory_product_settings.go | 36 +++ internal/store/postgres_product_settings.go | 54 ++++ internal/store/product_settings.go | 27 ++ internal/store/store.go | 8 + .../0025_tenant_product_settings.down.sql | 1 + .../0025_tenant_product_settings.up.sql | 14 + migrations/migrations_test.go | 24 +- openapi.yaml | 70 +++- 15 files changed, 1054 insertions(+), 6 deletions(-) create mode 100644 internal/server/pruefwerk.go create mode 100644 internal/server/pruefwerk_internal_test.go create mode 100644 internal/server/pruefwerk_test.go create mode 100644 internal/store/memory_product_settings.go create mode 100644 internal/store/postgres_product_settings.go create mode 100644 internal/store/product_settings.go create mode 100644 migrations/0025_tenant_product_settings.down.sql create mode 100644 migrations/0025_tenant_product_settings.up.sql diff --git a/internal/server/entitlements.go b/internal/server/entitlements.go index c57465e..b57e78d 100644 --- a/internal/server/entitlements.go +++ b/internal/server/entitlements.go @@ -133,6 +133,15 @@ func (s *Server) evaluateEntitlement(ctx context.Context, in entitlementCheckReq } out.Allowed = true out.Limits = tp.Config + if prod.Key == pruefwerkProduct { + // Plan limits and the workspace's Prüftag cap, always sent (null: + // unlimited / no cap), on a copy of the stored config. + set, _, err := s.loadPruefwerkSettings(ctx, t.ID) + if err != nil { + return EntitlementCheck{}, err + } + out.Limits = pruefwerkLimits(tp.Config, set.PrueftagCap) + } out.ExpiresAt = tp.ExpiresAt return out, nil } diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 7816840..66da889 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -53,6 +53,8 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset/revisions/2"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset/resolve?decision_type=r1.release_d01"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/pruefwerk/settings"}, + {"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/pruefwerk/settings"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/invites"}, {"PATCH", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1"}, {"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1"}, diff --git a/internal/server/pruefwerk.go b/internal/server/pruefwerk.go new file mode 100644 index 0000000..795ec47 --- /dev/null +++ b/internal/server/pruefwerk.go @@ -0,0 +1,306 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Prüfwerk metering (t72): the plan limits the Prüfwerk agent reads from +// the entitlement check, and the workspace's own monthly cap on Prüftage. +// +// GET /v1/tenants/{id}/products/pruefwerk/settings (tenants.read) +// PUT /v1/tenants/{id}/products/pruefwerk/settings (tenants.write) {"prueftag_cap": <0..10000> | null} +// +// Who may: a user token needs IT_ADMIN, OWNER or FINANCE in its own tenant +// (403 FORBIDDEN_ROLE otherwise). Service clients are gated by their route +// group; the portal calls as its service client for the users it allows +// (named in X-Portal-User-*), staff through the admin client (X-Staff-*), +// as for the company profile. +// +// The cap is kept in tenant_product_settings (0025), not in +// tenant_products.config, which recomputeEntitlements rebuilds from the +// ERP subscriptions. On Enterprise the cap is stored but not applied: the +// check sends prueftag_cap null whatever was saved, and keeps the saved +// value for a later change of plan. + +const pruefwerkProduct = "pruefwerk" + +// Limit keys of the entitlement check, always sent for Prüfwerk; null is +// unlimited (no cap set). +const ( + limitIncludedTargets = "included_targets" + limitMonthlyPruefungen = "monthly_pruefungen" + limitPrueftagCap = "prueftag_cap" +) + +// maxPrueftagCap bounds the cap a workspace can set. +const maxPrueftagCap = 10000 + +// pruefwerkPlan is one Prüfwerk plan, identified by its subscription SKU. +// Unlimited: no target or Prüfung limit and no Prüftag cap. +type pruefwerkPlan struct { + Name string + SKU string + IncludedTargets int + MonthlyPruefungen int + Unlimited bool +} + +// pruefwerkPlans, lowest first: a tenant holding several plan SKUs gets the +// highest, one without any (trial, preview grant, SCAN-only order) the first. +var pruefwerkPlans = []pruefwerkPlan{ + {Name: "standard", SKU: "CRA-CSA-CLD-STD", IncludedTargets: 5, MonthlyPruefungen: 100}, + {Name: "business", SKU: "CRA-CSA-CLD-BUS", IncludedTargets: 25, MonthlyPruefungen: 500}, + {Name: "enterprise", SKU: "CRA-CSA-CLD-ENT", Unlimited: true}, +} + +// pruefwerkPlanFor resolves the plan from tenant_products.config["skus"]: +// []string as recomputeEntitlements writes it, []interface{} once it has +// been through JSONB. +func pruefwerkPlanFor(skus interface{}) pruefwerkPlan { + var list []string + switch v := skus.(type) { + case []string: + list = v + case []interface{}: + for _, x := range v { + if s, ok := x.(string); ok { + list = append(list, s) + } + } + } + best := 0 + for _, sku := range list { + for i, p := range pruefwerkPlans { + if p.SKU == sku && i > best { + best = i + } + } + } + return pruefwerkPlans[best] +} + +// pruefwerkLimits is the stored config plus the plan's limits and the +// workspace's cap, as a new map: the stored config stays as it is. +func pruefwerkLimits(cfg map[string]interface{}, prueftagCap *int) map[string]interface{} { + out := make(map[string]interface{}, len(cfg)+3) + for k, v := range cfg { + out[k] = v + } + plan := pruefwerkPlanFor(cfg["skus"]) + if plan.Unlimited { + out[limitIncludedTargets], out[limitMonthlyPruefungen], out[limitPrueftagCap] = nil, nil, nil + return out + } + out[limitIncludedTargets] = plan.IncludedTargets + out[limitMonthlyPruefungen] = plan.MonthlyPruefungen + out[limitPrueftagCap] = capValue(prueftagCap) + return out +} + +// capValue is the cap as a JSON value: an untyped nil marshals as null. +func capValue(c *int) interface{} { + if c == nil { + return nil + } + return *c +} + +// pruefwerkSettings is the settings document of Prüfwerk. +type pruefwerkSettings struct { + PrueftagCap *int `json:"prueftag_cap"` +} + +// loadPruefwerkSettings returns the saved settings; none saved is the zero +// value and a nil row. +func (s *Server) loadPruefwerkSettings(ctx context.Context, tenantID string) (pruefwerkSettings, *store.TenantProductSettings, error) { + row, err := s.Store.GetTenantProductSettings(ctx, tenantID, pruefwerkProduct) + if errors.Is(err, store.ErrNotFound) { + return pruefwerkSettings{}, nil, nil + } + if err != nil { + return pruefwerkSettings{}, nil, err + } + var set pruefwerkSettings + if err := json.Unmarshal(row.Settings, &set); err != nil { + return pruefwerkSettings{}, nil, fmt.Errorf("stored pruefwerk settings of %s: %v", tenantID, err) + } + return set, row, nil +} + +// pruefwerkPlanOf is the tenant's current Prüfwerk plan (standard without a +// Prüfwerk entitlement). +func (s *Server) pruefwerkPlanOf(ctx context.Context, tenantID string) (pruefwerkPlan, error) { + tps, err := s.Store.ListTenantProducts(ctx, tenantID) + if err != nil { + return pruefwerkPlan{}, err + } + for _, tp := range tps { + if tp.Product == pruefwerkProduct { + return pruefwerkPlanFor(tp.Config["skus"]), nil + } + } + return pruefwerkPlans[0], nil +} + +var pruefwerkSettingsRole = map[string]bool{authn.RoleITAdmin: true, authn.RoleOwner: true, "FINANCE": true} + +type pruefwerkSettingsResp struct { + TenantID string `json:"tenant_id"` + Product string `json:"product"` + PrueftagCap *int `json:"prueftag_cap"` + // Plan is the Prüfwerk plan the limits come from; CapApplies is false + // on Enterprise, where a saved cap is kept but not applied. + Plan string `json:"plan"` + CapApplies bool `json:"cap_applies"` + UpdatedBy string `json:"updated_by,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +func pruefwerkSettingsAnswer(tenantID string, set pruefwerkSettings, row *store.TenantProductSettings, plan pruefwerkPlan) pruefwerkSettingsResp { + out := pruefwerkSettingsResp{ + TenantID: tenantID, Product: pruefwerkProduct, PrueftagCap: set.PrueftagCap, + Plan: plan.Name, CapApplies: !plan.Unlimited, + } + if row != nil { + at := row.UpdatedAt + out.UpdatedBy, out.UpdatedAt = row.UpdatedBy, &at + } + return out +} + +// pruefwerkSettingsRoleOK checks the org role of a user token; on false the +// response is written. +func pruefwerkSettingsRoleOK(w http.ResponseWriter, r *http.Request) bool { + if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !hasAnyRole(p.OrgRoles, pruefwerkSettingsRole) { + writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "Prüfwerk settings require the IT_ADMIN, OWNER or FINANCE org role") + return false + } + return true +} + +// getPruefwerkSettings is GET /v1/tenants/{id}/products/pruefwerk/settings. +// Nothing saved yet is prueftag_cap null. +func (s *Server) getPruefwerkSettings(w http.ResponseWriter, r *http.Request) { + if !pruefwerkSettingsRoleOK(w, r) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + set, row, err := s.loadPruefwerkSettings(ctx, t.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + plan, err := s.pruefwerkPlanOf(ctx, t.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, pruefwerkSettingsAnswer(t.ID, set, row, plan)) +} + +// putPruefwerkSettings is PUT /v1/tenants/{id}/products/pruefwerk/settings. +// A save that changes nothing writes nothing. +func (s *Server) putPruefwerkSettings(w http.ResponseWriter, r *http.Request) { + if !pruefwerkSettingsRoleOK(w, r) { + return + } + r.Body = http.MaxBytesReader(w, r.Body, 4096) + var in map[string]json.RawMessage + if !decodeJSON(w, r, &in) { + return + } + next, code, msg := parsePruefwerkSettings(in) + if code != "" { + writeError(w, http.StatusBadRequest, code, msg) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + cur, row, err := s.loadPruefwerkSettings(ctx, t.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + plan, err := s.pruefwerkPlanOf(ctx, t.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if sameCap(cur.PrueftagCap, next.PrueftagCap) { + writeJSON(w, http.StatusOK, pruefwerkSettingsAnswer(t.ID, cur, row, plan)) + return + } + doc, _ := json.Marshal(next) + actor := s.teamActor(r) + saved, err := s.Store.PutTenantProductSettings(ctx, store.TenantProductSettings{ + TenantID: t.ID, Product: pruefwerkProduct, Settings: doc, + UpdatedBy: firstNonEmpty(actor.Email, actor.ID), UpdatedAt: s.now(), + }) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "product_settings.changed", TargetID: pruefwerkProduct, TargetType: "product_settings", + TargetName: "Prüfwerk", ActorID: actor.ID, ActorName: actor.Email, ActorType: actor.Type, + Metadata: map[string]interface{}{ + "setting": limitPrueftagCap, "old": capValue(cur.PrueftagCap), "new": capValue(next.PrueftagCap), + "plan": plan.Name, "applies": !plan.Unlimited, + }, + }) + writeJSON(w, http.StatusOK, pruefwerkSettingsAnswer(t.ID, next, saved, plan)) +} + +// parsePruefwerkSettings checks a PUT body: exactly prueftag_cap, an integer +// 0..maxPrueftagCap or null. code is "" when the body is fine. +func parsePruefwerkSettings(in map[string]json.RawMessage) (set pruefwerkSettings, code, msg string) { + if in == nil { + return set, "invalid_body", "request body must be a JSON object" + } + for k := range in { + if k != limitPrueftagCap { + return set, "unknown_setting", fmt.Sprintf("unknown setting %q", k) + } + } + raw, ok := in[limitPrueftagCap] + if !ok { + return set, "prueftag_cap_required", "prueftag_cap is required (null for no cap)" + } + if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + return set, "", "" + } + var n int + if err := json.Unmarshal(raw, &n); err != nil || n < 0 || n > maxPrueftagCap { + return set, "invalid_prueftag_cap", fmt.Sprintf("prueftag_cap must be an integer 0..%d or null", maxPrueftagCap) + } + set.PrueftagCap = &n + return set, "", "" +} + +func sameCap(a, b *int) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + return *a == *b +} diff --git a/internal/server/pruefwerk_internal_test.go b/internal/server/pruefwerk_internal_test.go new file mode 100644 index 0000000..d4a1d9b --- /dev/null +++ b/internal/server/pruefwerk_internal_test.go @@ -0,0 +1,216 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +func TestPruefwerkPlanFor(t *testing.T) { + for _, c := range []struct { + name string + skus interface{} + want string + }{ + {"none", nil, "standard"}, + {"empty", []string{}, "standard"}, + {"scan only", []string{"CRA-CSA-CLD-SCAN"}, "standard"}, + {"werkbank add-on only", []string{"CRA-WBK-CLD-ENT"}, "standard"}, + {"standard", []string{"CRA-CSA-CLD-STD"}, "standard"}, + {"business", []string{"CRA-CSA-CLD-BUS"}, "business"}, + {"enterprise", []string{"CRA-CSA-CLD-ENT"}, "enterprise"}, + {"business with add-on and scan", []string{"CRA-CSA-CLD-SCAN", "CRA-WBK-CLD-ENT", "CRA-CSA-CLD-BUS"}, "business"}, + {"all three", []string{"CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-STD"}, "enterprise"}, + {"standard and business", []string{"CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS"}, "business"}, + {"from JSONB", []interface{}{"CRA-CSA-CLD-STD", "CRA-CSA-CLD-ENT"}, "enterprise"}, + {"JSONB with junk", []interface{}{42, "CRA-CSA-CLD-BUS", nil}, "business"}, + {"not a list", "CRA-CSA-CLD-ENT", "standard"}, + {"other product's SKU", []string{"DEV-FWK-CLD-ENT"}, "standard"}, + } { + if got := pruefwerkPlanFor(c.skus).Name; got != c.want { + t.Errorf("%s: %s, want %s", c.name, got, c.want) + } + } +} + +func TestPruefwerkLimits(t *testing.T) { + seven := 7 + for _, c := range []struct { + skus []string + cap *int + targets, pruefungen, cap2 interface{} + }{ + {nil, nil, 5, 100, nil}, + {[]string{"CRA-CSA-CLD-STD"}, &seven, 5, 100, 7}, + {[]string{"CRA-CSA-CLD-BUS"}, &seven, 25, 500, 7}, + {[]string{"CRA-CSA-CLD-BUS"}, nil, 25, 500, nil}, + {[]string{"CRA-CSA-CLD-ENT"}, &seven, nil, nil, nil}, + } { + cfg := map[string]interface{}{"source": "erp", "runners": 2} + if c.skus != nil { + cfg["skus"] = c.skus + } + got := pruefwerkLimits(cfg, c.cap) + if len(cfg) != 2+boolInt(c.skus != nil) { + t.Fatalf("%v: stored config changed: %+v", c.skus, cfg) + } + if got["source"] != "erp" || got["runners"] != 2 { + t.Errorf("%v: config keys lost: %+v", c.skus, got) + } + raw, _ := json.Marshal(got) + for key, want := range map[string]interface{}{limitIncludedTargets: c.targets, limitMonthlyPruefungen: c.pruefungen, limitPrueftagCap: c.cap2} { + v, ok := got[key] + if !ok || v != want { + t.Errorf("%v %s = %v (present %v), want %v", c.skus, key, v, ok, want) + } + if want == nil && !strings.Contains(string(raw), `"`+key+`":null`) { + t.Errorf("%v %s not null in JSON: %s", c.skus, key, raw) + } + } + } +} + +func boolInt(b bool) int { + if b { + return 1 + } + return 0 +} + +func TestPruefwerkSettings_roles(t *testing.T) { + tenantID := "00000000-0000-0000-0000-000000000001" + path := "/v1/tenants/" + tenantID + "/products/pruefwerk/settings" + for _, c := range []struct { + name string + roles []string + want int + }{ + {"it admin", []string{"IT_ADMIN"}, http.StatusOK}, + {"owner", []string{"OWNER"}, http.StatusOK}, + {"finance", []string{"USER", "FINANCE"}, http.StatusOK}, + {"finance lower case", []string{"finance"}, http.StatusOK}, + {"cxo", []string{"CXO"}, http.StatusForbidden}, + {"legal", []string{"LEGAL"}, http.StatusForbidden}, + {"plain user", []string{"USER"}, http.StatusForbidden}, + {"no roles", nil, http.StatusForbidden}, + } { + t.Run(c.name, func(t *testing.T) { + p := &authn.Principal{Subject: "u-1", ClientID: "portal", TenantID: tenantID, Email: "u1@acme.test", OrgRoles: c.roles} + s, h, tenant := scopedServer(t, p) + for _, req := range []*http.Request{ + httptest.NewRequest(http.MethodGet, path, nil), + httptest.NewRequest(http.MethodPut, path, strings.NewReader(`{"prueftag_cap":20}`)), + } { + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + if rr.Code != c.want { + t.Fatalf("%s: %d, want %d: %s", req.Method, rr.Code, c.want, rr.Body.String()) + } + if c.want == http.StatusForbidden && !strings.Contains(rr.Body.String(), "FORBIDDEN_ROLE") { + t.Fatalf("%s error code: %s", req.Method, rr.Body.String()) + } + } + evs, _, _ := s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: tenant.ID, Action: "product_settings.changed"}) + if c.want == http.StatusForbidden { + if len(evs) != 0 { + t.Fatalf("refused change audited: %+v", evs) + } + if _, err := s.Store.GetTenantProductSettings(context.Background(), tenant.ID, pruefwerkProduct); err == nil { + t.Fatal("refused change stored") + } + return + } + if len(evs) != 1 { + t.Fatalf("audit: %+v", evs) + } + ev := evs[0] + if ev.ActorID != "u-1" || ev.ActorName != "u1@acme.test" || ev.ActorType != "user" || ev.TargetID != pruefwerkProduct || + ev.Metadata["old"] != nil || toFloat(ev.Metadata["new"]) != 20 || ev.Metadata["setting"] != limitPrueftagCap { + t.Fatalf("audit event: %+v", ev) + } + }) + } + + // Another tenant's IT_ADMIN: 404, never a hint it exists. + other := &authn.Principal{Subject: "u-x", ClientID: "portal", TenantID: "11111111-1111-1111-1111-111111111111", OrgRoles: []string{"IT_ADMIN"}} + _, h, _ := scopedServer(t, other) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodPut, path, strings.NewReader(`{"prueftag_cap":1}`))) + if rr.Code != http.StatusNotFound { + t.Fatalf("cross-tenant: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestPruefwerkSettings_clients(t *testing.T) { + const rules = "portal-svc:tenants,users,users.act,admin;pruefwerk-svc:entitlements,tenants.read" + tenantID := "00000000-0000-0000-0000-000000000001" + path := "/v1/tenants/" + tenantID + "/products/pruefwerk/settings" + + // A product client reads (tenants.read) but may not write. + pw := &authn.Principal{Subject: "svc-pw", ClientID: "pruefwerk-svc"} + _, h, _ := scopedServer(t, pw, rules) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, path, nil)) + if rr.Code != http.StatusOK { + t.Fatalf("product client read: %d %s", rr.Code, rr.Body.String()) + } + rr = httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodPut, path, strings.NewReader(`{"prueftag_cap":1}`))) + if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "FORBIDDEN_CLIENT") { + t.Fatalf("product client write: %d %s", rr.Code, rr.Body.String()) + } + + // Staff through the portal's admin client: audited as the staff member; + // the portal for a workspace user: audited as that user. + portal := &authn.Principal{Subject: "svc-portal", ClientID: "portal-svc"} + s, h, tenant := scopedServer(t, portal, rules) + send := func(body string, hdr ...string) { + t.Helper() + req := httptest.NewRequest(http.MethodPut, path, strings.NewReader(body)) + for i := 0; i+1 < len(hdr); i += 2 { + req.Header.Set(hdr[i], hdr[i+1]) + } + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("portal put: %d %s", rr.Code, rr.Body.String()) + } + } + send(`{"prueftag_cap":3}`, "X-Staff-Subject", "staff-1", "X-Staff-Email", "ops@breakpilot.com") + send(`{"prueftag_cap":4}`, "X-Portal-User-Subject", "u-fin", "X-Portal-User-Email", "fin@acme.test") + send(`{"prueftag_cap":4}`, "X-Portal-User-Subject", "u-fin", "X-Portal-User-Email", "fin@acme.test") // unchanged: no event + evs, _, _ := s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: tenant.ID, Action: "product_settings.changed"}) + if len(evs) != 2 { + t.Fatalf("audit events: %+v", evs) + } + byActor := map[string]store.AuditEvent{} + for _, ev := range evs { + byActor[ev.ActorType] = ev + } + if st := byActor["staff"]; st.ActorID != "staff-1" || st.ActorName != "ops@breakpilot.com" || st.Metadata["old"] != nil || toFloat(st.Metadata["new"]) != 3 { + t.Fatalf("staff event: %+v", st) + } + if u := byActor["user"]; u.ActorID != "u-fin" || u.ActorName != "fin@acme.test" || toFloat(u.Metadata["old"]) != 3 || toFloat(u.Metadata["new"]) != 4 { + t.Fatalf("portal user event: %+v", u) + } + row, err := s.Store.GetTenantProductSettings(context.Background(), tenant.ID, pruefwerkProduct) + if err != nil || row.UpdatedBy != "fin@acme.test" { + t.Fatalf("stored: %+v %v", row, err) + } +} + +func TestRouteGroup_pruefwerkSettings(t *testing.T) { + path := "/v1/tenants/x/products/pruefwerk/settings" + if g := routeGroup(http.MethodGet, path); g != "tenants.read" { + t.Errorf("GET group %q", g) + } + if g := routeGroup(http.MethodPut, path); g != "tenants.write" { + t.Errorf("PUT group %q", g) + } +} diff --git a/internal/server/pruefwerk_test.go b/internal/server/pruefwerk_test.go new file mode 100644 index 0000000..91fb1ee --- /dev/null +++ b/internal/server/pruefwerk_test.go @@ -0,0 +1,282 @@ +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) + } + } + }) +} diff --git a/internal/server/server.go b/internal/server/server.go index 00d5132..3389cf2 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -155,6 +155,9 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("PUT /v1/tenants/{id}/role-dataset", s.saveRoleDataset) mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/revisions/{rev}", s.getRoleDatasetRevision) mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/resolve", s.resolveRoleDataset) + // Prüfwerk settings (0025, t72): the workspace's Prüftag cap. + mux.HandleFunc("GET /v1/tenants/{id}/products/pruefwerk/settings", s.getPruefwerkSettings) + mux.HandleFunc("PUT /v1/tenants/{id}/products/pruefwerk/settings", s.putPruefwerkSettings) // entitlements mux.HandleFunc("GET /v1/entitlements", s.listTenantProducts) diff --git a/internal/store/memory.go b/internal/store/memory.go index 532112c..ae8962a 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -45,6 +45,8 @@ type Memory struct { roleSets map[string][]RoleDataset // tenant_id → every revision, oldest first (0024) mail []*MailItem mailID int64 + + prodSets map[string]*TenantProductSettings // tenant_id + "/" + product (0025) } type apiKeyWithHash struct { @@ -75,6 +77,7 @@ func NewMemory() *Memory { roleSets: make(map[string][]RoleDataset), documents: make(map[string]*Document), + prodSets: make(map[string]*TenantProductSettings), } now := time.Now().UTC() seed := &Tenant{ @@ -589,6 +592,11 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error { delete(m.tenants, id) delete(m.bySlug, t.Slug) delete(m.products, id) + for k, ps := range m.prodSets { + if ps.TenantID == id { + delete(m.prodSets, k) + } + } for kid, k := range m.apiKeys { if k.TenantID == id { delete(m.apiKeys, kid) diff --git a/internal/store/memory_product_settings.go b/internal/store/memory_product_settings.go new file mode 100644 index 0000000..e0f08d4 --- /dev/null +++ b/internal/store/memory_product_settings.go @@ -0,0 +1,36 @@ +package store + +import ( + "context" + "encoding/json" +) + +func (m *Memory) GetTenantProductSettings(_ context.Context, tenantID, product string) (*TenantProductSettings, error) { + m.mu.RLock() + defer m.mu.RUnlock() + ps, ok := m.prodSets[tenantID+"/"+product] + if !ok { + return nil, ErrNotFound + } + cp := *ps + cp.Settings = append(json.RawMessage(nil), ps.Settings...) + return &cp, nil +} + +func (m *Memory) PutTenantProductSettings(_ context.Context, ps TenantProductSettings) (*TenantProductSettings, error) { + if !validProductSettings(ps) { + return nil, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.tenants[ps.TenantID]; !ok { + return nil, ErrNotFound + } + row := ps + row.Settings = append(json.RawMessage(nil), ps.Settings...) + row.UpdatedAt = ps.UpdatedAt.UTC() + m.prodSets[ps.TenantID+"/"+ps.Product] = &row + cp := row + cp.Settings = append(json.RawMessage(nil), row.Settings...) + return &cp, nil +} diff --git a/internal/store/postgres_product_settings.go b/internal/store/postgres_product_settings.go new file mode 100644 index 0000000..9d238c3 --- /dev/null +++ b/internal/store/postgres_product_settings.go @@ -0,0 +1,54 @@ +package store + +import ( + "context" + "encoding/json" + "errors" + + "github.com/jackc/pgx/v5" +) + +func scanProductSettings(row pgx.Row) (*TenantProductSettings, error) { + var ps TenantProductSettings + var data []byte + if err := row.Scan(&ps.TenantID, &ps.Product, &data, &ps.UpdatedBy, &ps.UpdatedAt); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + ps.Settings = json.RawMessage(data) + return &ps, nil +} + +func (p *Postgres) GetTenantProductSettings(ctx context.Context, tenantID, product string) (*TenantProductSettings, error) { + ps, err := scanProductSettings(p.pool.QueryRow(ctx, ` + SELECT tenant_id::text, product, settings, updated_by, updated_at + FROM tenant_product_settings WHERE tenant_id = $1::uuid AND product = $2`, tenantID, product)) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + return ps, err +} + +func (p *Postgres) PutTenantProductSettings(ctx context.Context, ps TenantProductSettings) (*TenantProductSettings, error) { + if !validProductSettings(ps) { + return nil, ErrInvalidInput + } + saved, err := scanProductSettings(p.pool.QueryRow(ctx, ` + INSERT INTO tenant_product_settings (tenant_id, product, settings, updated_by, updated_at) + VALUES ($1::uuid, $2, $3::jsonb, $4, $5) + ON CONFLICT (tenant_id, product) DO UPDATE + SET settings = EXCLUDED.settings, updated_by = EXCLUDED.updated_by, updated_at = EXCLUDED.updated_at + RETURNING tenant_id::text, product, settings, updated_by, updated_at`, + ps.TenantID, ps.Product, string(ps.Settings), ps.UpdatedBy, ps.UpdatedAt.UTC())) + switch { + case err == nil: + return saved, nil + case isFKViolation(err), isInvalidUUID(err): + return nil, ErrNotFound + case isCheckViolation(err): + return nil, ErrInvalidInput + } + return nil, err +} diff --git a/internal/store/product_settings.go b/internal/store/product_settings.go new file mode 100644 index 0000000..0a15812 --- /dev/null +++ b/internal/store/product_settings.go @@ -0,0 +1,27 @@ +package store + +import ( + "encoding/json" + "time" +) + +// TenantProductSettings is what a workspace chose for one booked product +// (0025, t72), kept apart from tenant_products.config, which the ERP +// recompute rebuilds. Settings is a JSON object; the server checks its keys +// per product before it reaches the store. +type TenantProductSettings struct { + TenantID string `json:"tenant_id"` + Product string `json:"product"` + Settings json.RawMessage `json:"settings"` + UpdatedBy string `json:"updated_by"` + UpdatedAt time.Time `json:"updated_at"` +} + +// validProductSettings checks the write before either store takes it. +func validProductSettings(ps TenantProductSettings) bool { + if n := len(ps.Product); n < 1 || n > 40 { + return false + } + var obj map[string]json.RawMessage + return json.Unmarshal(ps.Settings, &obj) == nil && obj != nil +} diff --git a/internal/store/store.go b/internal/store/store.go index 998f06b..54e428b 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -249,6 +249,14 @@ type Store interface { SaveRoleDataset(ctx context.Context, w RoleDatasetWrite) (dataset *RoleDataset, changed bool, err error) GetRoleDatasetRevision(ctx context.Context, tenantID string, revision int) (*RoleDataset, error) + // Product settings (0025): the workspace's own choices per product, + // untouched by the ERP recompute. GetTenantProductSettings is + // ErrNotFound when none were saved; PutTenantProductSettings replaces + // the document (ErrNotFound for an unknown tenant, ErrInvalidInput when + // settings is not a JSON object). + GetTenantProductSettings(ctx context.Context, tenantID, product string) (*TenantProductSettings, error) + PutTenantProductSettings(ctx context.Context, ps TenantProductSettings) (*TenantProductSettings, error) + // Managed services (0012, portal#77), listed by created_at. One row per // (tenant, kind, url): ErrConflict otherwise. ListManagedServices(ctx context.Context, tenantID string) ([]ManagedService, error) diff --git a/migrations/0025_tenant_product_settings.down.sql b/migrations/0025_tenant_product_settings.down.sql new file mode 100644 index 0000000..ebfe31c --- /dev/null +++ b/migrations/0025_tenant_product_settings.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS tenant_product_settings; diff --git a/migrations/0025_tenant_product_settings.up.sql b/migrations/0025_tenant_product_settings.up.sql new file mode 100644 index 0000000..c83c886 --- /dev/null +++ b/migrations/0025_tenant_product_settings.up.sql @@ -0,0 +1,14 @@ +-- Customer settings per booked product (t72): what the workspace itself +-- chooses, as opposed to what it bought. tenant_products.config is rebuilt +-- from the ERP subscriptions on every recompute, so a customer's choice +-- cannot live there. First user: Prüfwerk's monthly cap on Prüftage +-- ({"prueftag_cap": | null}); the registry checks the keys per +-- product, the table only keeps the document. +CREATE TABLE tenant_product_settings ( + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + product TEXT NOT NULL CHECK (char_length(product) BETWEEN 1 AND 40), + settings JSONB NOT NULL CHECK (jsonb_typeof(settings) = 'object'), + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id, product) +); diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index 624bd91..c15b196 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -103,6 +103,7 @@ func TestMigrate_upDownRoundTrip(t *testing.T) { "managed_services", "role_datasets", "role_dataset_revisions", + "tenant_product_settings", } for _, table := range wantTables { var exists bool @@ -118,8 +119,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) { } } - // Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets). - for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}} { + // Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings). + for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}} { var exists bool err := db.QueryRow( "SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)", @@ -299,14 +300,27 @@ func TestSeed_canInsertAndQuery(t *testing.T) { } } + // 0025: one settings object per (tenant, product). + insSet := `INSERT INTO tenant_product_settings (tenant_id, product, settings) VALUES ($1, 'pruefwerk', $2::jsonb)` + if _, err := db.ExecContext(ctx, insSet, tid, `{"prueftag_cap":null}`); err != nil { + t.Fatalf("insert product settings: %v", err) + } + if _, err := db.ExecContext(ctx, insSet, tid, `{"prueftag_cap":5}`); err == nil { + t.Error("second settings row for the same product was stored") + } + if _, err := db.ExecContext(ctx, `INSERT INTO tenant_product_settings (tenant_id, product, settings) VALUES ($1, 'firmwerk', '[1]'::jsonb)`, tid); err == nil { + t.Error("settings that are not an object were stored") + } + // FK cascade — delete tenant, projects/products/keys/audit_log handling. if _, err := db.ExecContext(ctx, `DELETE FROM tenants WHERE id = $1`, tid); err != nil { t.Fatalf("delete tenant: %v", err) } - var nServices int + var nServices, nSettings int _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM managed_services WHERE tenant_id = $1`, tid).Scan(&nServices) - if nServices != 0 { - t.Errorf("FK cascade incomplete: managed_services=%d", nServices) + _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_product_settings WHERE tenant_id = $1`, tid).Scan(&nSettings) + if nServices != 0 || nSettings != 0 { + t.Errorf("FK cascade incomplete: managed_services=%d tenant_product_settings=%d", nServices, nSettings) } var nProjects, nProducts, nKeys int _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_projects WHERE tenant_id = $1`, tid).Scan(&nProjects) diff --git a/openapi.yaml b/openapi.yaml index 2173b60..cfd907b 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -574,6 +574,54 @@ paths: "400": { description: "unknown_decision_type or scope_required." } "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/products/pruefwerk/settings: + get: + summary: The workspace's Prüfwerk settings (the monthly Prüftag cap). + description: | + User tokens reach their own tenant only and need the org role + IT_ADMIN, OWNER or FINANCE (else 403 FORBIDDEN_ROLE); service + clients read with tenants.read. Nothing saved yet is + `prueftag_cap: null`. Kept apart from the ERP-derived entitlement + config, so a recompute never resets it. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The settings. + content: + application/json: { schema: { $ref: "#/components/schemas/PruefwerkSettings" } } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + put: + summary: Set or clear the monthly Prüftag cap. + description: | + Same roles as the GET; service clients write with tenants.write (the + portal for the users it allows, staff through the admin client). + A change is audited as `product_settings.changed` with the old and + new value; a save that changes nothing writes nothing. On the + Enterprise plan the cap is stored but not applied: the entitlement + check sends `prueftag_cap: null` (`cap_applies: false`). + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [prueftag_cap] + additionalProperties: false + properties: + prueftag_cap: { type: integer, minimum: 0, maximum: 10000, nullable: true, description: "null: no cap" } + responses: + "200": + description: Saved (or unchanged). + content: + application/json: { schema: { $ref: "#/components/schemas/PruefwerkSettings" } } + "400": { description: "invalid_body, unknown_setting, prueftag_cap_required or invalid_prueftag_cap." } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/managed-services: get: summary: A tenant's managed services (Verwaltete Infrastruktur), oldest first. @@ -2079,7 +2127,16 @@ components: allowed: { type: boolean } read_only: { type: boolean } status: { $ref: "#/components/schemas/TenantStatus" } - limits: { type: object, additionalProperties: true, description: "tenant_products.config — purchased limits" } + limits: + type: object + additionalProperties: true + description: | + tenant_products.config — purchased limits. For pruefwerk always + also `included_targets`, `monthly_pruefungen` (Standard 5/100, + Business 25/500, Enterprise null; no plan SKU counts as Standard) + and `prueftag_cap` (the workspace's monthly cap on Prüftage, + null when none is set and always null on Enterprise). null means + unlimited. expires_at: { type: string, format: date-time, nullable: true } reason: { type: string, enum: [unknown_product, unknown_addon, tenant_not_found, tenant_archived, tenant_halted, entitlement_disabled, entitlement_expired, preview_expired, addon_not_purchased, not_entitled, member_blocked, user_unknown] } preview: { type: boolean, description: "allowed through a staff preview grant; usage under it is not invoiced" } @@ -2223,6 +2280,17 @@ components: state: { type: string, enum: [wirksam, hinterlegt] } reasons: { type: array, items: { type: string, enum: [basis_missing, not_yet_valid, expired, authorization_missing] } } catalogue: { type: object, description: "Functions (key, label, sources, per, multiple, external, d02_row), decision types (key, label, default) and document keys." } + PruefwerkSettings: + type: object + required: [tenant_id, product, prueftag_cap, plan, cap_applies] + properties: + tenant_id: { type: string, format: uuid } + product: { type: string, enum: [pruefwerk] } + prueftag_cap: { type: integer, minimum: 0, maximum: 10000, nullable: true } + plan: { type: string, enum: [standard, business, enterprise], description: "the Prüfwerk plan the limits come from" } + cap_applies: { type: boolean, description: "false on Enterprise: the cap is kept but not applied" } + updated_by: { type: string } + updated_at: { type: string, format: date-time } RoleDatasetRevision: type: object properties: -- 2.54.1