feat(entitlements): Staff preview grants for products not for sale yet
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Successful in 25m20s
ci / image (pull_request) Skipped

Lets BreakPilot staff open a product that is still disabled in the
catalogue (Werkmeister) for one tenant for a limited time, e.g. a seeded
staging tenant for portal#86, without a stage/prod divergence:

- Migration 0018: tenant_products.preview and preview_expires_at, kept
  apart from a booking's expires_at.
- Entitlement check: a disabled product is allowed only under an active
  preview (answer carries "preview": true); expiry is enforced at check
  time (reason preview_expired). A leftover plain row of a product off
  sale stays unknown_product.
- A real booking (ERP, trial, catalogue upsert) clears the preview and
  its expiry, so it never cuts off a paid entitlement; a preview over a
  booking is refused (409).
- Usage under a preview is accepted, tagged properties.preview=true and
  kept out of the ERP outbox; claims list a preview product only while
  it is active.
- Staff only, audited: POST /v1/admin/tenants/{id}/preview-grants
  {product, expires_at ≤ 180 d}, DELETE …/preview-grants/{product}; a
  named staff member (X-Staff-Subject) is required.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-10-14 01:25:04 +02:00
1 parent 5b4590d3bc
commit c99aa6908d
17 files changed
+507 -28

No files matched your search

+94
View File
@@ -0,0 +1,94 @@
package server
import (
"context"
"errors"
"net/http"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// Preview grants (migration 0018): BreakPilot staff let a tenant use a product
// that is not for sale yet — e.g. Werkmeister on a staging tenant — for a
// limited time. No catalogue or trial visibility, no subscription, no ERP;
// usage under a preview is tagged preview=true and never invoiced. A real
// booking replaces the grant.
// maxPreview bounds a preview grant, so none stays forever by accident.
const maxPreview = 180 * 24 * time.Hour
type previewGrantReq struct {
Product string `json:"product"`
ExpiresAt time.Time `json:"expires_at"`
}
// adminGrantPreview — POST /v1/admin/tenants/{id}/preview-grants.
func (s *Server) adminGrantPreview(w http.ResponseWriter, r *http.Request) {
if _, _, ok := s.staffActor(r); !ok {
writeError(w, http.StatusForbidden, "staff_required", "preview grants are made by a named staff member (X-Staff-Subject)")
return
}
var in previewGrantReq
if !decodeJSON(w, r, &in) {
return
}
now := s.now()
if in.Product == "" || in.ExpiresAt.IsZero() || !in.ExpiresAt.After(now) || in.ExpiresAt.After(now.Add(maxPreview)) {
writeError(w, http.StatusBadRequest, "invalid_input", "product and expires_at (in the future, at most 180 days ahead) are required")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
t, err := s.Store.GetTenant(ctx, r.PathValue("id"))
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if _, err := s.Store.GetProduct(ctx, in.Product); err != nil {
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalogue")
return
}
tp, err := s.Store.SetPreviewGrant(ctx, t.ID, in.Product, in.ExpiresAt.UTC())
if errors.Is(err, store.ErrConflict) {
writeError(w, http.StatusConflict, "already_booked", "the tenant has booked this product; a preview grant would not change anything")
return
}
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: "entitlement.preview_granted", TargetID: in.Product, TargetType: "product", TargetName: t.Slug,
Product: in.Product, Metadata: map[string]interface{}{"preview_expires_at": in.ExpiresAt.UTC().Format(time.RFC3339)},
})
writeJSON(w, http.StatusCreated, tp)
}
// adminRevokePreview — DELETE /v1/admin/tenants/{id}/preview-grants/{product}.
func (s *Server) adminRevokePreview(w http.ResponseWriter, r *http.Request) {
if _, _, ok := s.staffActor(r); !ok {
writeError(w, http.StatusForbidden, "staff_required", "preview grants are revoked by a named staff member (X-Staff-Subject)")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
tenantID, product := r.PathValue("id"), r.PathValue("product")
if err := s.Store.RevokePreviewGrant(ctx, tenantID, product); err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: tenantID, Action: "entitlement.preview_revoked", TargetID: product, TargetType: "product", Product: product,
})
w.WriteHeader(http.StatusNoContent)
}
+55
View File
@@ -0,0 +1,55 @@
package server
import (
"context"
"net/http"
"strings"
"testing"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
func TestAdminPreviewGrantRoutes(t *testing.T) {
f := newTeamFixture(t, portal, "portal-svc:*")
staff := map[string]string{"X-Staff-Subject": "staff-1", "X-Staff-Email": "staff@breakpilot.test"}
path := "/v1/admin/tenants/" + f.tenant.ID + "/preview-grants"
soon := time.Now().Add(30 * 24 * time.Hour).UTC().Format(time.RFC3339)
if code, _, _ := f.call(t, "POST", path, `{"product":"werkmeister","expires_at":"`+soon+`"}`, nil); code != http.StatusForbidden {
t.Fatalf("without a named staff member: %d", code)
}
for _, body := range []string{
`{"product":"werkmeister"}`,
`{"product":"werkmeister","expires_at":"` + time.Now().Add(-time.Hour).UTC().Format(time.RFC3339) + `"}`,
`{"product":"werkmeister","expires_at":"` + time.Now().Add(200*24*time.Hour).UTC().Format(time.RFC3339) + `"}`,
`{"product":"nope","expires_at":"` + soon + `"}`,
} {
if code, _, raw := f.call(t, "POST", path, body, staff); code != http.StatusBadRequest {
t.Errorf("%s: %d %s", body, code, raw)
}
}
if code, _, raw := f.call(t, "POST", path, `{"product":"werkmeister","expires_at":"`+soon+`"}`, staff); code != http.StatusCreated || !strings.Contains(raw, `"preview":true`) {
t.Fatalf("grant: %d %s", code, raw)
}
// acme has really booked Prüfwerk: a preview would change nothing.
if code, _, _ := f.call(t, "POST", path, `{"product":"pruefwerk","expires_at":"`+soon+`"}`, staff); code != http.StatusConflict {
t.Fatalf("preview over a booking: %d", code)
}
if code, _, _ := f.call(t, "DELETE", path+"/werkmeister", "", staff); code != http.StatusNoContent {
t.Fatalf("revoke: %d", code)
}
if code, _, _ := f.call(t, "DELETE", path+"/werkmeister", "", staff); code != http.StatusNotFound {
t.Fatalf("revoke again: %d", code)
}
evs, _, _ := f.s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: f.tenant.ID})
granted := false
for _, e := range evs {
if e.Action == "entitlement.preview_granted" && e.ActorType == "staff" && e.ActorID == "staff-1" {
granted = true
}
}
if !granted {
t.Fatal("grant not audited under the staff member")
}
}
+1 -1
View File
@@ -350,7 +350,7 @@ func (s *Server) entitledProducts(ctx context.Context, tenantID string) (map[str
}
now := time.Now()
for _, tp := range tps {
if tp.Enabled && (tp.ExpiresAt == nil || tp.ExpiresAt.After(now)) {
if tp.Enabled && (tp.ExpiresAt == nil || tp.ExpiresAt.After(now)) && (!tp.Preview || tp.PreviewActive(now)) {
out[tp.Product] = true
}
}
+20 -1
View File
@@ -29,6 +29,9 @@ type EntitlementCheck struct {
Limits map[string]interface{} `json:"limits,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Reason string `json:"reason,omitempty"`
// Preview: allowed through a staff preview grant (product not for sale
// yet). Products may show it; usage under it is not invoiced.
Preview bool `json:"preview,omitempty"`
}
// checkEntitlement is POST /v1/internal/entitlements/check.
@@ -63,7 +66,9 @@ func (s *Server) checkEntitlement(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) evaluateEntitlement(ctx context.Context, in entitlementCheckReq) (EntitlementCheck, error) {
prod, err := s.product(ctx, in.Product)
// Disabled products (not for sale yet) are reachable only through a
// staff preview grant, checked below.
prod, err := s.Store.GetProduct(ctx, in.Product)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return EntitlementCheck{Allowed: false, Reason: "unknown_product"}, nil
@@ -100,6 +105,16 @@ func (s *Server) evaluateEntitlement(ctx context.Context, in entitlementCheckReq
if tp.Product != prod.Key {
continue
}
if tp.Preview {
if !tp.PreviewActive(now) {
out.Reason = "preview_expired"
out.ExpiresAt = tp.PreviewExpiresAt
return out, nil
}
out.Preview = true
} else if !prod.Enabled {
break // a leftover row of a product not for sale: unknown_product
}
if !tp.Enabled {
out.Reason = "entitlement_disabled"
return out, nil
@@ -121,6 +136,10 @@ func (s *Server) evaluateEntitlement(ctx context.Context, in entitlementCheckReq
out.ExpiresAt = tp.ExpiresAt
return out, nil
}
if !prod.Enabled {
out.Reason = "unknown_product"
return out, nil
}
out.Reason = "not_entitled"
return out, nil
}
+1 -1
View File
@@ -106,7 +106,7 @@ func (s *Server) kcClaims(w http.ResponseWriter, r *http.Request) {
}
productKeys := make([]string, 0, len(products))
for _, p := range products {
if p.Enabled {
if p.Enabled && (!p.Preview || p.PreviewActive(time.Now())) {
productKeys = append(productKeys, p.Product)
}
}
+2
View File
@@ -54,6 +54,8 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
{"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1"},
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/resend"},
{"PATCH", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/members/u-1"},
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/preview-grants"},
{"DELETE", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/preview-grants/werkmeister"},
{"DELETE", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/members/u-1"},
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/members/u-1/resend"},
{"GET", "/v1/admin/tenants?q=acme"},
+127
View File
@@ -0,0 +1,127 @@
package server_test
import (
"context"
"errors"
"net/http"
"testing"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
type checkResult struct {
Allowed bool `json:"allowed"`
Reason string `json:"reason"`
Preview bool `json:"preview"`
}
func entCheck(t *testing.T, h *testHarness, tenantID, product string) checkResult {
t.Helper()
resp, body := h.do("POST", "/v1/internal/entitlements/check", map[string]any{"tenant_id": tenantID, "product": product})
if resp.StatusCode != http.StatusOK {
t.Fatalf("check: %d %s", resp.StatusCode, body)
}
return decode[checkResult](t, body)
}
// Werkmeister is in the catalogue but not for sale (enabled = false).
func TestPreviewGrant_opensADisabledProductUntilItExpires(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
ctx := context.Background()
tn := newTenant(t, h, "preview-co")
if r := entCheck(t, h, tn.ID, "werkmeister"); r.Allowed || r.Reason != "unknown_product" {
t.Fatalf("before the grant: %+v", r)
}
if _, err := h.store.SetPreviewGrant(ctx, tn.ID, "werkmeister", time.Now().Add(24*time.Hour)); err != nil {
t.Fatal(err)
}
if r := entCheck(t, h, tn.ID, "werkmeister"); !r.Allowed || !r.Preview {
t.Fatalf("with the grant: %+v", r)
}
// The expiry is enforced when checking, not only when granting.
if _, err := h.store.SetPreviewGrant(ctx, tn.ID, "werkmeister", time.Now().Add(-time.Minute)); err != nil {
t.Fatal(err)
}
if r := entCheck(t, h, tn.ID, "werkmeister"); r.Allowed || r.Reason != "preview_expired" {
t.Fatalf("expired grant: %+v", r)
}
if err := h.store.RevokePreviewGrant(ctx, tn.ID, "werkmeister"); err != nil {
t.Fatal(err)
}
if err := h.store.RevokePreviewGrant(ctx, tn.ID, "werkmeister"); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("second revoke: %v", err)
}
if r := entCheck(t, h, tn.ID, "werkmeister"); r.Allowed || r.Reason != "unknown_product" {
t.Fatalf("after revoke: %+v", r)
}
})
}
func TestPreviewGrant_realBookingWins(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
ctx := context.Background()
tn := newTenant(t, h, "booking-co")
if _, err := h.store.SetPreviewGrant(ctx, tn.ID, "firmwerk", time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
// A real booking (ERP, trial, catalogue) clears the preview and its
// expiry, so the preview can never cut off a paid entitlement.
if _, err := h.store.UpsertTenantProduct(ctx, store.TenantProduct{TenantID: tn.ID, Product: "firmwerk", Enabled: true, Config: map[string]interface{}{"source": "erp"}}); err != nil {
t.Fatal(err)
}
tps, _ := h.store.ListTenantProducts(ctx, tn.ID)
for _, tp := range tps {
if tp.Product == "firmwerk" && (tp.Preview || tp.PreviewExpiresAt != nil) {
t.Fatalf("booking kept the preview: %+v", tp)
}
}
if r := entCheck(t, h, tn.ID, "firmwerk"); !r.Allowed || r.Preview {
t.Fatalf("booked: %+v", r)
}
if _, err := h.store.SetPreviewGrant(ctx, tn.ID, "firmwerk", time.Now().Add(time.Hour)); !errors.Is(err, store.ErrConflict) {
t.Fatalf("preview over a booking: %v", err)
}
if err := h.store.RevokePreviewGrant(ctx, tn.ID, "firmwerk"); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("revoking a booking through preview: %v", err)
}
})
}
// A plain leftover row of a product taken off sale does not open it.
func TestDisabledProductWithoutPreviewStaysClosed(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
tn := newTenant(t, h, "leftover-co")
if _, err := h.store.UpsertTenantProduct(context.Background(), store.TenantProduct{TenantID: tn.ID, Product: "compliance", Enabled: true, Config: map[string]interface{}{}}); err != nil {
t.Fatal(err)
}
if r := entCheck(t, h, tn.ID, "compliance"); r.Allowed || r.Reason != "unknown_product" {
t.Fatalf("leftover row: %+v", r)
}
})
}
func TestPreviewUsageIsTaggedAndNotInvoiced(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
ctx := context.Background()
tn := newTenant(t, h, "usage-preview-co")
pendingBefore, _ := h.store.PendingOutbox(ctx)
ev := map[string]any{"idempotency_key": "wm-1", "tenant_id": tn.ID, "product": "werkmeister", "metric": "run.completed"}
if resp, body := h.do("POST", "/v1/usage/events", ev); resp.StatusCode != http.StatusBadRequest {
t.Fatalf("usage for a product not for sale without a grant: %d %s", resp.StatusCode, body)
}
if _, err := h.store.SetPreviewGrant(ctx, tn.ID, "werkmeister", time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
if resp, body := h.do("POST", "/v1/usage/events", ev); resp.StatusCode != http.StatusAccepted {
t.Fatalf("usage under preview: %d %s", resp.StatusCode, body)
}
evs, _ := h.store.ListUsageEvents(ctx, store.UsageFilter{TenantID: tn.ID})
if len(evs) != 1 || evs[0].Properties["preview"] != true {
t.Fatalf("usage not tagged: %+v", evs)
}
if pending, _ := h.store.PendingOutbox(ctx); pending != pendingBefore {
t.Fatalf("preview usage reached the ERP outbox: %d → %d", pendingBefore, pending)
}
})
}
+3
View File
@@ -190,6 +190,9 @@ func NewRouter(s *Server) http.Handler {
mux.HandleFunc("POST /v1/admin/tenants/{id}/members/{uid}/resend", s.adminResendMember)
mux.HandleFunc("POST /v1/admin/tenants/{id}/reprovision", s.adminReprovision)
mux.HandleFunc("DELETE /v1/admin/tenants/{id}", s.adminPurgeTenant)
// Preview grants of products not for sale yet (staff only, audited).
mux.HandleFunc("POST /v1/admin/tenants/{id}/preview-grants", s.adminGrantPreview)
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/preview-grants/{product}", s.adminRevokePreview)
mux.HandleFunc("GET /v1/admin/audit", s.listAudit)
mux.HandleFunc("GET /v1/admin/tenants/{id}/documents", s.adminListDocuments)
mux.HandleFunc("POST /v1/admin/tenants/{id}/documents", s.adminUploadDocument)
+33 -1
View File
@@ -81,10 +81,22 @@ func (s *Server) postUsageEvents(w http.ResponseWriter, r *http.Request) {
rejected = append(rejected, map[string]any{"index": i, "reason": "idempotency_key, tenant_id, product and metric are required"})
continue
}
if !s.knownProduct(ctx, in.Product) {
// Usage under a staff preview grant is metered but never invoiced:
// tagged preview=true and kept out of the ERP outbox. A product not
// for sale yet is accepted only under such a grant.
preview := s.previewActive(ctx, in.TenantID, in.Product)
if !preview && !s.knownProduct(ctx, in.Product) {
rejected = append(rejected, map[string]any{"index": i, "reason": "unknown_product"})
continue
}
if preview {
props := map[string]interface{}{}
for k, v := range in.Properties {
props[k] = v
}
props["preview"] = true
in.Properties = props
}
qty := 1.0
if in.Quantity != nil {
qty = *in.Quantity
@@ -119,6 +131,9 @@ func (s *Server) postUsageEvents(w http.ResponseWriter, r *http.Request) {
continue
}
accepted++
if preview {
continue
}
if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{
Kind: store.OutboxUsageRecord, TenantID: ev.TenantID,
Payload: map[string]interface{}{"usage_event_id": ev.ID, "idempotency_key": ev.IdempotencyKey, "product": ev.Product,
@@ -172,3 +187,20 @@ func (s *Server) listUsageEvents(w http.ResponseWriter, r *http.Request) {
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// previewActive reports whether the tenant uses product under an unexpired
// staff preview grant. Lookup errors count as no: the event is then treated
// like any other and refused for a product not for sale.
func (s *Server) previewActive(ctx context.Context, tenantID, product string) bool {
tps, err := s.Store.ListTenantProducts(ctx, tenantID)
if err != nil {
return false
}
now := s.now()
for _, tp := range tps {
if tp.Product == product && tp.PreviewActive(now) {
return true
}
}
return false
}
+1 -1
View File
@@ -85,7 +85,7 @@ func (s *Server) enrichMembership(ctx context.Context, c keycloak.Claims) member
products := []string{}
if tps, perr := s.Store.ListTenantProducts(ctx, t.ID); perr == nil {
for _, p := range tps {
if p.Enabled {
if p.Enabled && (!p.Preview || p.PreviewActive(time.Now())) {
products = append(products, p.Product)
}
}
+36
View File
@@ -341,11 +341,47 @@ func (m *Memory) UpsertTenantProduct(_ context.Context, tp TenantProduct) (*Tena
stored.Enabled = tp.Enabled
stored.Config = tp.Config
stored.ExpiresAt = tp.ExpiresAt
stored.Preview, stored.PreviewExpiresAt = false, nil // a real booking ends a preview
stored.UpdatedAt = now
cp := *stored
return &cp, nil
}
func (m *Memory) SetPreviewGrant(_ context.Context, tenantID, product string, expiresAt time.Time) (*TenantProduct, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[tenantID]; !ok {
return nil, ErrNotFound
}
if _, ok := m.products[tenantID]; !ok {
m.products[tenantID] = map[string]*TenantProduct{}
}
now := time.Now().UTC()
stored, exists := m.products[tenantID][product]
if exists && stored.Enabled && !stored.Preview {
return nil, ErrConflict
}
if !exists {
stored = &TenantProduct{TenantID: tenantID, Product: product, Config: map[string]interface{}{}, CreatedAt: now}
m.products[tenantID][product] = stored
}
exp := expiresAt
stored.Enabled, stored.Preview, stored.PreviewExpiresAt, stored.UpdatedAt = true, true, &exp, now
cp := *stored
return &cp, nil
}
func (m *Memory) RevokePreviewGrant(_ context.Context, tenantID, product string) error {
m.mu.Lock()
defer m.mu.Unlock()
stored, ok := m.products[tenantID][product]
if !ok || !stored.Preview {
return ErrNotFound
}
delete(m.products[tenantID], product)
return nil
}
func (m *Memory) ListTenantProducts(_ context.Context, tenantID string) ([]TenantProduct, error) {
m.mu.RLock()
defer m.mu.RUnlock()
+58 -20
View File
@@ -190,14 +190,15 @@ func (p *Postgres) UpsertTenantProduct(ctx context.Context, tp TenantProduct) (*
ON CONFLICT (tenant_id, product) DO UPDATE SET
enabled = EXCLUDED.enabled,
config = EXCLUDED.config,
expires_at = EXCLUDED.expires_at
RETURNING tenant_id::text, product, enabled, config, expires_at, created_at, updated_at`,
expires_at = EXCLUDED.expires_at,
-- a real booking ends a preview grant (its expiry must never cut
-- off a paid entitlement)
preview = FALSE,
preview_expires_at = NULL
RETURNING `+tenantProductCols,
tp.TenantID, tp.Product, tp.Enabled, cfg, tp.ExpiresAt,
)
var out TenantProduct
var rawCfg []byte
var expires *time.Time
err = row.Scan(&out.TenantID, &out.Product, &out.Enabled, &rawCfg, &expires, &out.CreatedAt, &out.UpdatedAt)
out, err := scanTenantProduct(row)
if err != nil {
// FK violation on tenant_id → not found
var pgErr *pgconn.PgError
@@ -206,11 +207,54 @@ func (p *Postgres) UpsertTenantProduct(ctx context.Context, tp TenantProduct) (*
}
return nil, err
}
out.ExpiresAt = expires
if err := json.Unmarshal(rawCfg, &out.Config); err != nil {
out.Config = map[string]interface{}{}
return out, nil
}
const tenantProductCols = `tenant_id::text, product, enabled, config, expires_at, preview, preview_expires_at, created_at, updated_at`
func scanTenantProduct(row pgx.Row) (*TenantProduct, error) {
var tp TenantProduct
var rawCfg []byte
if err := row.Scan(&tp.TenantID, &tp.Product, &tp.Enabled, &rawCfg, &tp.ExpiresAt, &tp.Preview, &tp.PreviewExpiresAt, &tp.CreatedAt, &tp.UpdatedAt); err != nil {
return nil, err
}
return &out, nil
if err := json.Unmarshal(rawCfg, &tp.Config); err != nil || tp.Config == nil {
tp.Config = map[string]interface{}{}
}
return &tp, nil
}
func (p *Postgres) SetPreviewGrant(ctx context.Context, tenantID, product string, expiresAt time.Time) (*TenantProduct, error) {
tp, err := scanTenantProduct(p.pool.QueryRow(ctx, `
INSERT INTO tenant_products (tenant_id, product, enabled, config, preview, preview_expires_at)
VALUES ($1::uuid, $2, TRUE, '{}'::jsonb, TRUE, $3)
ON CONFLICT (tenant_id, product) DO UPDATE SET
enabled = TRUE, preview = TRUE, preview_expires_at = EXCLUDED.preview_expires_at
WHERE tenant_products.preview OR NOT tenant_products.enabled
RETURNING `+tenantProductCols, tenantID, product, expiresAt))
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrConflict // really booked: the WHERE refused the update
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && (pgErr.Code == pgerrcode.ForeignKeyViolation || pgErr.Code == pgerrcode.InvalidTextRepresentation) {
return nil, ErrNotFound
}
return tp, err
}
func (p *Postgres) RevokePreviewGrant(ctx context.Context, tenantID, product string) error {
tag, err := p.pool.Exec(ctx, `DELETE FROM tenant_products WHERE tenant_id = $1::uuid AND product = $2 AND preview`, tenantID, product)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.InvalidTextRepresentation {
return ErrNotFound
}
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (p *Postgres) ListTenantProducts(ctx context.Context, tenantID string) ([]TenantProduct, error) {
@@ -219,7 +263,7 @@ func (p *Postgres) ListTenantProducts(ctx context.Context, tenantID string) ([]T
return nil, err
}
rows, err := p.pool.Query(ctx, `
SELECT tenant_id::text, product, enabled, config, expires_at, created_at, updated_at
SELECT `+tenantProductCols+`
FROM tenant_products WHERE tenant_id = $1::uuid ORDER BY product`, tenantID)
if err != nil {
return nil, err
@@ -227,17 +271,11 @@ func (p *Postgres) ListTenantProducts(ctx context.Context, tenantID string) ([]T
defer rows.Close()
out := []TenantProduct{}
for rows.Next() {
var tp TenantProduct
var rawCfg []byte
var expires *time.Time
if err := rows.Scan(&tp.TenantID, &tp.Product, &tp.Enabled, &rawCfg, &expires, &tp.CreatedAt, &tp.UpdatedAt); err != nil {
tp, err := scanTenantProduct(rows)
if err != nil {
return nil, err
}
tp.ExpiresAt = expires
if err := json.Unmarshal(rawCfg, &tp.Config); err != nil {
tp.Config = map[string]interface{}{}
}
out = append(out, tp)
out = append(out, *tp)
}
return out, rows.Err()
}
+6
View File
@@ -96,6 +96,12 @@ type Store interface {
// Entitlements
UpsertTenantProduct(ctx context.Context, tp TenantProduct) (*TenantProduct, error)
ListTenantProducts(ctx context.Context, tenantID string) ([]TenantProduct, error)
// SetPreviewGrant grants (or extends) a preview of product until
// expiresAt; ErrConflict when the tenant has really booked it.
SetPreviewGrant(ctx context.Context, tenantID, product string, expiresAt time.Time) (*TenantProduct, error)
// RevokePreviewGrant removes a preview grant; ErrNotFound when there is
// none (a real booking is never removed this way).
RevokePreviewGrant(ctx context.Context, tenantID, product string) error
// API keys
CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, error)
+11 -2
View File
@@ -39,8 +39,17 @@ type TenantProduct struct {
Enabled bool `json:"enabled"`
Config map[string]interface{} `json:"config"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Preview: a staff grant of a product not yet for sale, valid until
// PreviewExpiresAt (migration 0018). A real booking clears both.
Preview bool `json:"preview,omitempty"`
PreviewExpiresAt *time.Time `json:"preview_expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// PreviewActive reports whether tp is a preview grant that has not expired.
func (tp TenantProduct) PreviewActive(now time.Time) bool {
return tp.Preview && tp.PreviewExpiresAt != nil && tp.PreviewExpiresAt.After(now)
}
// API key kinds (migration 0015).
+5
View File
@@ -0,0 +1,5 @@
-- Preview grants become plain rows of a disabled product (still refused).
ALTER TABLE tenant_products
DROP CONSTRAINT IF EXISTS tenant_products_preview_expiry,
DROP COLUMN preview_expires_at,
DROP COLUMN preview;
+8
View File
@@ -0,0 +1,8 @@
-- Staff preview grants (tenant-registry ADR 0001 follow-up, Werkmeister W1):
-- a tenant may use a product that is not for sale yet (catalogue enabled =
-- false) while preview is true and preview_expires_at lies ahead. A real
-- booking clears both. Kept apart from expires_at, the booking's period end.
ALTER TABLE tenant_products
ADD COLUMN preview BOOLEAN NOT NULL DEFAULT FALSE,
ADD COLUMN preview_expires_at TIMESTAMPTZ,
ADD CONSTRAINT tenant_products_preview_expiry CHECK (preview = (preview_expires_at IS NOT NULL));
+46 -1
View File
@@ -830,6 +830,48 @@ paths:
"204": { description: Deleted. }
"404": { $ref: "#/components/responses/NotFound" }
/v1/admin/tenants/{id}/preview-grants:
post:
summary: Grant a preview of a product not for sale yet (staff only, audited).
description: |
Lets the tenant use the product (catalogue enabled=false allowed) until
expires_at, at most 180 days ahead. No catalogue or trial visibility,
no subscription, no ERP; usage under a preview is tagged preview=true
and never invoiced. A real booking replaces the grant. Needs a named
staff member (X-Staff-Subject) from a client with the admin group.
parameters:
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [product, expires_at]
properties:
product: { type: string }
expires_at: { type: string, format: date-time }
responses:
"201":
description: Granted (or extended).
content:
application/json: { schema: { $ref: "#/components/schemas/TenantProduct" } }
"400": { $ref: "#/components/responses/BadRequest" }
"403": { description: "No named staff member." }
"404": { $ref: "#/components/responses/NotFound" }
"409": { description: "The tenant has booked the product." }
/v1/admin/tenants/{id}/preview-grants/{product}:
delete:
summary: Revoke a preview grant (staff only, audited). A booking is never removed this way.
parameters:
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
- { in: path, name: product, required: true, schema: { type: string } }
responses:
"204": { description: Revoked. }
"403": { description: "No named staff member." }
"404": { $ref: "#/components/responses/NotFound" }
/v1/admin/tenants/{id}/managed-services:
get:
summary: A tenant's managed services with instance id and notes (staff).
@@ -1703,7 +1745,8 @@ components:
status: { $ref: "#/components/schemas/TenantStatus" }
limits: { type: object, additionalProperties: true, description: "tenant_products.config — purchased limits" }
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, addon_not_purchased, not_entitled, member_blocked, user_unknown] }
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" }
ProductAddon:
type: object
@@ -1928,6 +1971,8 @@ components:
enabled: { type: boolean }
config: { type: object, additionalProperties: true }
expires_at: { type: string, format: date-time, nullable: true }
preview: { type: boolean, description: "staff preview grant of a product not for sale yet" }
preview_expires_at: { type: string, format: date-time, nullable: true }
created_at: { type: string, format: date-time }
updated_at: { type: string, format: date-time }