Files
tenant-registry/internal/store/postgres_product_settings.go
T
sharangandSharang Parnerkar 32e10e0e13
ci / shared (push) Successful in 15s
ci / test (push) Successful in 26m37s
ci / image (push) Failing after 39s
feat(entitlements): Prüfwerk plan limits and Prüftag cap setting (t72) (#114)
Registry side of Prüfwerk metering (backlog t72). Stage first; nothing deployed.

## What changes

- **Entitlement check**: for `pruefwerk` the limits now always carry `included_targets`, `monthly_pruefungen` and `prueftag_cap`, with `null` meaning unlimited or no cap. The values come from one plan table in `internal/server/pruefwerk.go`:

  | Plan | SKU | included_targets | monthly_pruefungen | prueftag_cap |
  |---|---|---|---|---|
  | Standard | CRA-CSA-CLD-STD | 5 | 100 | the workspace's cap or null |
  | Business | CRA-CSA-CLD-BUS | 25 | 500 | the workspace's cap or null |
  | Enterprise | CRA-CSA-CLD-ENT | null | null | always null |

  The highest plan SKU in `config.skus` wins. A tenant with no plan SKU (trial, preview grant, SCAN-only order) gets Standard. The limits are built on a copy of `tenant_products.config`, so the existing keys stay and the stored config is not changed. Other products are unchanged.
- **Migration 0025** adds `tenant_product_settings(tenant_id, product, settings jsonb, updated_by, updated_at)`, PK `(tenant_id, product)`, with ON DELETE CASCADE. Both stores implement it (Postgres and Memory). `recomputeEntitlements` never touches this table, so the cap survives ERP recomputes.
- **`GET`/`PUT /v1/tenants/{id}/products/pruefwerk/settings`**: the body is `{"prueftag_cap": 0..10000 | null}`. Unknown keys, a missing key, non-integers and out-of-range values all return 400.
  - **User tokens** must be in their own tenant (404 otherwise) and have the IT_ADMIN, OWNER or FINANCE org role (403 `FORBIDDEN_ROLE` otherwise).
  - **Service clients** are gated by their route group, as for the company profile: GET needs `tenants.read`, PUT needs `tenants.write`. Staff come through the admin client with `X-Staff-*`.
  - **Audit**: a change is logged as `product_settings.changed` with `old`, `new`, `plan` and `applies`. A PUT that changes nothing writes nothing and logs nothing.
  - **Enterprise**: PUT still stores the cap and GET shows it with `cap_applies: false`, but the check sends `null`.
- **Usage metrics**: `prueftag.booked` and `target.extra` go through the existing `POST /v1/usage/events`. A test checks that both are stored once per idempotency key and that a repeat, even with a different quantity, counts as a duplicate. No update-in-place path, no invoicing, no ERP item or price changes.
- OpenAPI: the new path, a `PruefwerkSettings` schema, and the three keys described on `EntitlementCheck.limits`.

## Deploy note

Run **`migrate-up` (0025) before the new build takes traffic.** If reading the settings table fails, the Prüfwerk check returns 500 rather than silently sending `prueftag_cap: null`.

## Decisions not in the brief

1. OWNER is allowed alongside IT_ADMIN and FINANCE, because every other admin check in the registry treats OWNER like IT_ADMIN. Dropping it is a one-line change.
2. The registry enforces the org role only on user tokens. Service clients are trusted by route group (the portal checks roles for its users), which matches the company-profile route.
3. The plan table wins over same-named keys that a staff `activate` may have written into the config.
4. The settings response also carries `plan` and `cap_applies`. GET with nothing saved returns 200 with `prueftag_cap: null`.

## Tests

- `go build ./... && go vet ./...` pass.
- `go test -race ./...` passed with the Postgres harness, using rootless podman as the testcontainers backend.
- After two small edits I re-ran `-short` and the new and related tests against Postgres; all passed.
- New tests cover: plan resolution (STD, BUS, ENT, none, SCAN-only, mixed SKUs, JSONB `[]interface{}`); limits per plan, checking that null keys are present in the JSON rather than left out; settings validation; the role matrix with audit (user token, portal user, staff); a product client reading but not writing; the cap surviving an ERP recompute; the store contract on both stores; usage dedup for both metrics; and migration 0025 (table, one row per product, object check, cascade).

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

---------

Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #114
2026-11-06 14:29:49 +00:00

55 lines
1.7 KiB
Go

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
}