feat(pruefwerk): entry plan for one-off orders, granted by staff #150
No files matched your search
@@ -0,0 +1,152 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// Entry offers (see entryPlanSKU): staff grant the Prüfwerk entry plan to
|
||||
// the workspace of a one-off order.
|
||||
//
|
||||
// POST /v1/admin/tenants/{id}/entry-offer
|
||||
// {"included_targets": 1..10, "expires_at": RFC3339, "order_ref": "<invoice no.>"}
|
||||
//
|
||||
// The grant carries config source "entry", which recomputeEntitlements
|
||||
// leaves alone (it disables only "erp" grants) and which keeps an ERP event
|
||||
// from halting the workspace while the grant runs (hasEntryGrant). A trial
|
||||
// workspace becomes active, so the customer sees no trial banner. Sending
|
||||
// it again replaces targets, end and reference: staff set the end to 90
|
||||
// days after delivery once the result is delivered (LB Einstiegsangebote
|
||||
// § 7 Abs. 2). A Prüfwerk booking (subscription, ERP or activation grant)
|
||||
// supersedes the entry plan; the route refuses a workspace that has one. A
|
||||
// trial or preview grant of Prüfwerk is replaced.
|
||||
|
||||
type entryOfferReq struct {
|
||||
IncludedTargets int `json:"included_targets"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
OrderRef string `json:"order_ref"`
|
||||
}
|
||||
|
||||
// orderRefPattern is an invoice or order number, never a name or address.
|
||||
var orderRefPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/-]{0,63}$`)
|
||||
|
||||
// adminEntryOffer is POST /v1/admin/tenants/{id}/entry-offer.
|
||||
func (s *Server) adminEntryOffer(w http.ResponseWriter, r *http.Request) {
|
||||
if _, _, ok := s.staffActor(r); !ok {
|
||||
writeError(w, http.StatusForbidden, "staff_required", "entry offers are granted by a named staff member (X-Staff-Subject)")
|
||||
return
|
||||
}
|
||||
var in entryOfferReq
|
||||
if !decodeJSON(w, r, &in) {
|
||||
return
|
||||
}
|
||||
now := s.now()
|
||||
if in.IncludedTargets < 1 || in.IncludedTargets > entryTargetsMax {
|
||||
writeError(w, http.StatusBadRequest, "invalid_included_targets", "included_targets must be 1..10")
|
||||
return
|
||||
}
|
||||
if in.ExpiresAt.IsZero() || !in.ExpiresAt.After(now) || in.ExpiresAt.After(now.Add(entryMaxDuration)) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_expires_at", "expires_at must be in the future, at most 200 days ahead")
|
||||
return
|
||||
}
|
||||
if in.OrderRef != "" && !orderRefPattern.MatchString(in.OrderRef) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_order_ref", "order_ref is an invoice or order number: letters, digits, . _ / -, at most 64")
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
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 t.Status != store.StatusTrial && t.Status != store.StatusActive {
|
||||
writeError(w, http.StatusConflict, "invalid_status", "an entry offer is granted to a trial or active workspace, not a "+t.Status+" one")
|
||||
return
|
||||
}
|
||||
subs, err := s.Store.ListSubscriptions(ctx, t.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
for _, sub := range subs {
|
||||
if sub.Status == store.SubscriptionActive && sub.Product == pruefwerkProduct {
|
||||
writeError(w, http.StatusConflict, "already_booked", "the workspace has a Prüfwerk subscription; it supersedes the entry plan")
|
||||
return
|
||||
}
|
||||
}
|
||||
prod, err := s.Store.GetProduct(ctx, pruefwerkProduct)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", "prüfwerk is not in the catalogue: "+err.Error())
|
||||
return
|
||||
}
|
||||
meta := map[string]interface{}{
|
||||
"included_targets": in.IncludedTargets,
|
||||
"expires_at": in.ExpiresAt.UTC().Format(time.RFC3339),
|
||||
}
|
||||
tps, err := s.Store.ListTenantProducts(ctx, t.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
for _, old := range tps {
|
||||
if old.Product != pruefwerkProduct {
|
||||
continue
|
||||
}
|
||||
switch src := old.Config["source"]; {
|
||||
case src == entrySource:
|
||||
if old.ExpiresAt != nil {
|
||||
meta["previous_expires_at"] = old.ExpiresAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
case old.Enabled && !old.Preview && src != "trial":
|
||||
// A booking (ERP, activation): the entry plan would replace it.
|
||||
writeError(w, http.StatusConflict, "already_booked", "the workspace has booked Prüfwerk; it supersedes the entry plan")
|
||||
return
|
||||
}
|
||||
}
|
||||
cfg := map[string]interface{}{
|
||||
"source": entrySource,
|
||||
"skus": []string{entryPlanSKU},
|
||||
entryTargetsKey: in.IncludedTargets,
|
||||
}
|
||||
if in.OrderRef != "" {
|
||||
cfg[entryOrderRefKey] = in.OrderRef
|
||||
meta[entryOrderRefKey] = in.OrderRef
|
||||
}
|
||||
end := in.ExpiresAt.UTC()
|
||||
tp, err := s.Store.UpsertTenantProduct(ctx, store.TenantProduct{
|
||||
TenantID: t.ID, Product: pruefwerkProduct, Enabled: true, Config: cfg, ExpiresAt: &end,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
s.emitAudit(ctx, r, store.AuditEvent{
|
||||
TenantID: t.ID, Action: "entitlement.entry_granted", TargetID: pruefwerkProduct, TargetType: "product",
|
||||
TargetName: t.Slug, Product: pruefwerkProduct, Metadata: meta,
|
||||
})
|
||||
if t.Status == store.StatusTrial {
|
||||
if t, err = s.transition(ctx, r, t, store.StatusActive, "staff:entry_offer"); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
s.provisionProduct(ctx, r, t, prod, tp)
|
||||
writeJSON(w, http.StatusOK, tp)
|
||||
}
|
||||
|
||||
// hasEntryGrant reports whether one of the tenant's entitlements is a
|
||||
// running entry-offer grant.
|
||||
func hasEntryGrant(tps []store.TenantProduct, now time.Time) bool {
|
||||
for _, tp := range tps {
|
||||
if tp.Enabled && tp.Config["source"] == entrySource && (tp.ExpiresAt == nil || tp.ExpiresAt.After(now)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
func TestAdminEntryOffer(t *testing.T) {
|
||||
f := newTeamFixture(t, portal, "portal-svc:*")
|
||||
ctx := context.Background()
|
||||
staff := map[string]string{"X-Staff-Subject": "staff-1", "X-Staff-Email": "staff@breakpilot.test"}
|
||||
buyer, err := f.s.Store.CreateTenant(ctx, store.TenantCreate{Slug: "k-00099", Name: "K-00099"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := "/v1/admin/tenants/" + buyer.ID + "/entry-offer"
|
||||
at := func(d time.Duration) string { return time.Now().Add(d).UTC().Format(time.RFC3339) }
|
||||
month := at(30 * 24 * time.Hour)
|
||||
|
||||
if code, _, _ := f.call(t, "POST", path, `{"included_targets":1,"expires_at":"`+month+`"}`, nil); code != http.StatusForbidden {
|
||||
t.Fatalf("without a named staff member: %d", code)
|
||||
}
|
||||
for _, body := range []string{
|
||||
`{"expires_at":"` + month + `"}`,
|
||||
`{"included_targets":11,"expires_at":"` + month + `"}`,
|
||||
`{"included_targets":1}`,
|
||||
`{"included_targets":1,"expires_at":"` + at(-time.Hour) + `"}`,
|
||||
`{"included_targets":1,"expires_at":"` + at(201*24*time.Hour) + `"}`,
|
||||
`{"included_targets":1,"expires_at":"` + month + `","order_ref":"Max Mustermann"}`,
|
||||
} {
|
||||
if code, _, raw := f.call(t, "POST", path, body, staff); code != http.StatusBadRequest {
|
||||
t.Errorf("%s: %d %s", body, code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
// A trial workspace gets the plan and becomes active.
|
||||
code, _, raw := f.call(t, "POST", path, `{"included_targets":2,"expires_at":"`+month+`","order_ref":"RE-2026-0042"}`, staff)
|
||||
if code != http.StatusOK || !strings.Contains(raw, `"CRA-CSA-CLD-EIN"`) || !strings.Contains(raw, `"source":"entry"`) {
|
||||
t.Fatalf("grant: %d %s", code, raw)
|
||||
}
|
||||
if got, _ := f.s.Store.GetTenant(ctx, buyer.ID); got.Status != store.StatusActive {
|
||||
t.Fatalf("status after the grant: %s", got.Status)
|
||||
}
|
||||
plan, err := f.s.pruefwerkPlanOf(ctx, buyer.ID)
|
||||
if err != nil || plan.Name != "einstieg" || plan.IncludedTargets != 2 {
|
||||
t.Fatalf("plan: %+v %v", plan, err)
|
||||
}
|
||||
|
||||
// Sent again at delivery: the new end replaces the old one, audited with both.
|
||||
later := at(95 * 24 * time.Hour)
|
||||
if code, _, raw := f.call(t, "POST", path, `{"included_targets":2,"expires_at":"`+later+`","order_ref":"RE-2026-0042"}`, staff); code != http.StatusOK || !strings.Contains(raw, later[:10]) {
|
||||
t.Fatalf("reset end: %d %s", code, raw)
|
||||
}
|
||||
evs, _, _ := f.s.Store.ListAudit(ctx, store.AuditFilter{TenantID: buyer.ID, Action: "entitlement.entry_granted"})
|
||||
if len(evs) != 2 || evs[0].ActorType != "staff" || evs[0].ActorID != "staff-1" {
|
||||
t.Fatalf("audit: %+v", evs)
|
||||
}
|
||||
withPrevious := 0
|
||||
for _, e := range evs {
|
||||
if e.Metadata["order_ref"] != "RE-2026-0042" {
|
||||
t.Errorf("audit without the order reference: %+v", e.Metadata)
|
||||
}
|
||||
if e.Metadata["previous_expires_at"] != nil {
|
||||
withPrevious++
|
||||
}
|
||||
}
|
||||
if withPrevious != 1 {
|
||||
t.Errorf("previous end audited %d times, want once", withPrevious)
|
||||
}
|
||||
|
||||
// An ERP event without subscriptions does not halt it while the grant runs.
|
||||
cur, _ := f.s.Store.GetTenant(ctx, buyer.ID)
|
||||
if got, err := f.s.recomputeEntitlements(ctx, nil, cur, "test"); err != nil || got.Status != store.StatusActive {
|
||||
t.Fatalf("recompute with a running entry grant: %v %v", got, err)
|
||||
}
|
||||
// Once it has ended, the old rule applies.
|
||||
tps, _ := f.s.Store.ListTenantProducts(ctx, buyer.ID)
|
||||
for _, tp := range tps {
|
||||
if tp.Product == pruefwerkProduct {
|
||||
past := time.Now().Add(-time.Hour)
|
||||
tp.ExpiresAt = &past
|
||||
if _, err := f.s.Store.UpsertTenantProduct(ctx, tp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if got, err := f.s.recomputeEntitlements(ctx, nil, cur, "test"); err != nil || got.Status != store.StatusHalted {
|
||||
t.Fatalf("recompute after the entry grant ended: %v %v", got, err)
|
||||
}
|
||||
// Halted is neither trial nor active.
|
||||
if code, _, _ := f.call(t, "POST", path, `{"included_targets":1,"expires_at":"`+month+`"}`, staff); code != http.StatusConflict {
|
||||
t.Fatalf("grant to a halted workspace: %d", code)
|
||||
}
|
||||
|
||||
// acme has booked Prüfwerk: the booking supersedes the entry plan.
|
||||
acme := "/v1/admin/tenants/" + f.tenant.ID + "/entry-offer"
|
||||
if code, _, _ := f.call(t, "POST", acme, `{"included_targets":1,"expires_at":"`+month+`"}`, staff); code != http.StatusConflict {
|
||||
t.Fatalf("grant over a booked grant: %d", code)
|
||||
}
|
||||
// So does a subscription, with or without its grant.
|
||||
other, _ := f.s.Store.CreateTenant(ctx, store.TenantCreate{Slug: "k-00098", Name: "K-00098"})
|
||||
if _, err := f.s.Store.UpsertSubscription(ctx, store.Subscription{TenantID: other.ID, Product: pruefwerkProduct, SKU: "CRA-CSA-CLD-STD",
|
||||
Plan: "standard", Seats: 1, Status: store.SubscriptionActive, ErpSalesOrder: "SO-1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _, _ := f.call(t, "POST", "/v1/admin/tenants/"+other.ID+"/entry-offer", `{"included_targets":1,"expires_at":"`+month+`"}`, staff); code != http.StatusConflict {
|
||||
t.Fatalf("grant over a subscription: %d", code)
|
||||
}
|
||||
// A trial grant of Prüfwerk is replaced.
|
||||
trial, _ := f.s.Store.CreateTenant(ctx, store.TenantCreate{Slug: "k-00097", Name: "K-00097"})
|
||||
end := time.Now().Add(14 * 24 * time.Hour)
|
||||
if _, err := f.s.Store.UpsertTenantProduct(ctx, store.TenantProduct{TenantID: trial.ID, Product: pruefwerkProduct, Enabled: true,
|
||||
Config: map[string]interface{}{"source": "trial"}, ExpiresAt: &end}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _, raw := f.call(t, "POST", "/v1/admin/tenants/"+trial.ID+"/entry-offer", `{"included_targets":1,"expires_at":"`+month+`"}`, staff); code != http.StatusOK {
|
||||
t.Fatalf("grant over a trial grant: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
// An entry workspace keeps its trial end on record; once that passes it is
|
||||
// not restricted (only status trial expires), and a later subscription takes
|
||||
// Prüfwerk over: plan from the ERP, no end date.
|
||||
func TestEntryOfferLater(t *testing.T) {
|
||||
f := newTeamFixture(t, portal, "portal-svc:*")
|
||||
ctx := context.Background()
|
||||
staff := map[string]string{"X-Staff-Subject": "staff-1", "X-Staff-Email": "staff@breakpilot.test"}
|
||||
buyer, _ := f.s.Store.CreateTenant(ctx, store.TenantCreate{Slug: "k-00096", Name: "K-00096"})
|
||||
month := time.Now().Add(30 * 24 * time.Hour).UTC().Format(time.RFC3339)
|
||||
if code, _, raw := f.call(t, "POST", "/v1/admin/tenants/"+buyer.ID+"/entry-offer", `{"included_targets":1,"expires_at":"`+month+`"}`, staff); code != http.StatusOK {
|
||||
t.Fatalf("grant: %d %s", code, raw)
|
||||
}
|
||||
cur, _ := f.s.Store.GetTenant(ctx, buyer.ID)
|
||||
if cur.TrialEndsAt == nil {
|
||||
t.Fatal("expected the trial end to stay on record")
|
||||
}
|
||||
if next, why := f.s.escalation(cur, cur.TrialEndsAt.Add(24*time.Hour)); next != "" {
|
||||
t.Fatalf("an active entry workspace escalated after its trial end: %s (%s)", next, why)
|
||||
}
|
||||
|
||||
if _, err := f.s.Store.UpsertSubscription(ctx, store.Subscription{TenantID: buyer.ID, Product: pruefwerkProduct, SKU: "CRA-CSA-CLD-STD",
|
||||
Plan: "standard", Seats: 1, Status: store.SubscriptionActive, ErpSalesOrder: "SO-2"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.s.recomputeEntitlements(ctx, nil, cur, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tps, _ := f.s.Store.ListTenantProducts(ctx, buyer.ID)
|
||||
for _, tp := range tps {
|
||||
if tp.Product != pruefwerkProduct {
|
||||
continue
|
||||
}
|
||||
if tp.Config["source"] != "erp" || tp.ExpiresAt != nil || !tp.Enabled {
|
||||
t.Fatalf("subscription did not take over: %+v", tp)
|
||||
}
|
||||
if p := pruefwerkPlanOfConfig(tp.Config); p.Name != "standard" {
|
||||
t.Fatalf("plan after the subscription: %s", p.Name)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatal("no Prüfwerk entitlement after the subscription")
|
||||
}
|
||||
@@ -346,7 +346,10 @@ func (s *Server) recomputeEntitlements(ctx context.Context, r *http.Request, t *
|
||||
if t.Status != store.StatusActive && t.Status != store.StatusDemo {
|
||||
next = store.StatusActive
|
||||
}
|
||||
} else if t.Status == store.StatusActive || t.Status == store.StatusWarning || t.Status == store.StatusRestricted || t.Status == store.StatusFrozen {
|
||||
} else if (t.Status == store.StatusActive || t.Status == store.StatusWarning || t.Status == store.StatusRestricted || t.Status == store.StatusFrozen) &&
|
||||
!hasEntryGrant(existing, s.now()) {
|
||||
// A running entry-offer grant (admin_entry.go) is paid outside the
|
||||
// ERP; an ERP event without subscriptions does not stop it.
|
||||
next = store.StatusHalted
|
||||
}
|
||||
if next != t.Status {
|
||||
|
||||
@@ -46,15 +46,21 @@ const (
|
||||
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.
|
||||
// Unlimited: no target or Prüfung limit and no Prüftag cap. NoPrueftage:
|
||||
// the Prüftag cap is always 0, whatever the workspace saved.
|
||||
type pruefwerkPlan struct {
|
||||
Name string
|
||||
SKU string
|
||||
IncludedTargets int
|
||||
MonthlyPruefungen int
|
||||
Unlimited bool
|
||||
NoPrueftage bool
|
||||
}
|
||||
|
||||
// capApplies reports whether the workspace's saved Prüftag cap is the one
|
||||
// sent: not on Enterprise (no cap) and not on the entry plan (always 0).
|
||||
func (p pruefwerkPlan) capApplies() bool { return !p.Unlimited && !p.NoPrueftage }
|
||||
|
||||
// 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{
|
||||
@@ -63,9 +69,34 @@ var pruefwerkPlans = []pruefwerkPlan{
|
||||
{Name: "enterprise", SKU: "CRA-CSA-CLD-ENT", Unlimited: true},
|
||||
}
|
||||
|
||||
// Entry offers (CRA-Check, SBOM-Erstellung, CVE-Scan; LB Einstiegsangebote):
|
||||
// one-off orders paid by card or SEPA at booking, delivered by Breakpilot in
|
||||
// the customer's workspace, which stays open 90 days after delivery. Staff
|
||||
// grant the plan with POST /v1/admin/tenants/{id}/entry-offer; it is not a
|
||||
// subscription and never comes from the ERP.
|
||||
//
|
||||
// The plan has no monthly quota and no Prüftage, so nothing beyond the
|
||||
// order can be used or billed: the scans staff start for the delivery are
|
||||
// support scans, which never count; change-driven scans of the included
|
||||
// targets do not count either. The included targets are the order's
|
||||
// (entryTargetsMax at most), set per grant in config["included_targets"].
|
||||
const (
|
||||
entryPlanSKU = "CRA-CSA-CLD-EIN"
|
||||
entrySource = "entry"
|
||||
entryTargetsMax = 10
|
||||
entryTargetsKey = "included_targets"
|
||||
entryOrderRefKey = "order_ref"
|
||||
entryMaxDuration = 200 * 24 * time.Hour
|
||||
)
|
||||
|
||||
// pruefwerkEntryPlan is the entry plan with one included target; the grant's
|
||||
// config sets the order's number (pruefwerkPlanOfConfig).
|
||||
var pruefwerkEntryPlan = pruefwerkPlan{Name: "einstieg", SKU: entryPlanSKU, IncludedTargets: 1, MonthlyPruefungen: 0, NoPrueftage: true}
|
||||
|
||||
// pruefwerkPlanFor resolves the plan from tenant_products.config["skus"]:
|
||||
// []string as recomputeEntitlements writes it, []interface{} once it has
|
||||
// been through JSONB.
|
||||
// been through JSONB. Any subscription plan wins over the entry plan; no
|
||||
// plan SKU at all (trial, preview grant, SCAN-only order) is Standard.
|
||||
func pruefwerkPlanFor(skus interface{}) pruefwerkPlan {
|
||||
var list []string
|
||||
switch v := skus.(type) {
|
||||
@@ -78,15 +109,63 @@ func pruefwerkPlanFor(skus interface{}) pruefwerkPlan {
|
||||
}
|
||||
}
|
||||
}
|
||||
best := 0
|
||||
best, entry := -1, false
|
||||
for _, sku := range list {
|
||||
if sku == entryPlanSKU {
|
||||
entry = true
|
||||
}
|
||||
for i, p := range pruefwerkPlans {
|
||||
if p.SKU == sku && i > best {
|
||||
best = i
|
||||
}
|
||||
}
|
||||
}
|
||||
return pruefwerkPlans[best]
|
||||
switch {
|
||||
case best >= 0:
|
||||
return pruefwerkPlans[best]
|
||||
case entry:
|
||||
return pruefwerkEntryPlan
|
||||
}
|
||||
return pruefwerkStandard()
|
||||
}
|
||||
|
||||
// pruefwerkStandard is the plan without any plan SKU.
|
||||
func pruefwerkStandard() pruefwerkPlan { return pruefwerkPlans[0] }
|
||||
|
||||
// pruefwerkPlanOfConfig is the plan of a stored Prüfwerk entitlement: by
|
||||
// its SKUs, and on the entry plan with the order's included targets
|
||||
// (1..entryTargetsMax; anything else is 1).
|
||||
func pruefwerkPlanOfConfig(cfg map[string]interface{}) pruefwerkPlan {
|
||||
plan := pruefwerkPlanFor(cfg["skus"])
|
||||
if plan.Name == pruefwerkEntryPlan.Name {
|
||||
if n, ok := entryTargets(cfg[entryTargetsKey]); ok {
|
||||
plan.IncludedTargets = n
|
||||
}
|
||||
}
|
||||
return plan
|
||||
}
|
||||
|
||||
// entryTargets reads an included-targets value as Go or JSONB gives it.
|
||||
func entryTargets(v interface{}) (int, bool) {
|
||||
var n int
|
||||
switch x := v.(type) {
|
||||
case int:
|
||||
n = x
|
||||
case float64:
|
||||
if x != float64(int(x)) {
|
||||
return 0, false
|
||||
}
|
||||
n = int(x)
|
||||
case json.Number:
|
||||
i, err := x.Int64()
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
n = int(i)
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
return n, n >= 1 && n <= entryTargetsMax
|
||||
}
|
||||
|
||||
// pruefwerkLimits is the stored config plus the plan's limits and the
|
||||
@@ -96,14 +175,18 @@ func pruefwerkLimits(cfg map[string]interface{}, prueftagCap *int) map[string]in
|
||||
for k, v := range cfg {
|
||||
out[k] = v
|
||||
}
|
||||
plan := pruefwerkPlanFor(cfg["skus"])
|
||||
plan := pruefwerkPlanOfConfig(cfg)
|
||||
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)
|
||||
if plan.NoPrueftage {
|
||||
out[limitPrueftagCap] = 0
|
||||
} else {
|
||||
out[limitPrueftagCap] = capValue(prueftagCap)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -146,10 +229,10 @@ func (s *Server) pruefwerkPlanOf(ctx context.Context, tenantID string) (pruefwer
|
||||
}
|
||||
for _, tp := range tps {
|
||||
if tp.Product == pruefwerkProduct {
|
||||
return pruefwerkPlanFor(tp.Config["skus"]), nil
|
||||
return pruefwerkPlanOfConfig(tp.Config), nil
|
||||
}
|
||||
}
|
||||
return pruefwerkPlans[0], nil
|
||||
return pruefwerkStandard(), nil
|
||||
}
|
||||
|
||||
type pruefwerkSettingsResp struct {
|
||||
@@ -157,7 +240,8 @@ type pruefwerkSettingsResp struct {
|
||||
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.
|
||||
// on Enterprise and on the entry plan, where a saved cap is kept but not
|
||||
// applied (Enterprise sends none, the entry plan always 0).
|
||||
Plan string `json:"plan"`
|
||||
CapApplies bool `json:"cap_applies"`
|
||||
UpdatedBy string `json:"updated_by,omitempty"`
|
||||
@@ -167,7 +251,7 @@ type pruefwerkSettingsResp struct {
|
||||
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,
|
||||
Plan: plan.Name, CapApplies: plan.capApplies(),
|
||||
}
|
||||
if row != nil {
|
||||
at := row.UpdatedAt
|
||||
@@ -265,7 +349,7 @@ func (s *Server) putPruefwerkSettings(w http.ResponseWriter, r *http.Request) {
|
||||
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,
|
||||
"plan": plan.Name, "applies": plan.capApplies(),
|
||||
},
|
||||
})
|
||||
writeJSON(w, http.StatusOK, pruefwerkSettingsAnswer(t.ID, next, saved, plan))
|
||||
|
||||
@@ -32,6 +32,11 @@ func TestPruefwerkPlanFor(t *testing.T) {
|
||||
{"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"},
|
||||
{"entry", []string{"CRA-CSA-CLD-EIN"}, "einstieg"},
|
||||
{"entry from JSONB", []interface{}{"CRA-CSA-CLD-EIN"}, "einstieg"},
|
||||
{"entry with scan", []string{"CRA-CSA-CLD-SCAN", "CRA-CSA-CLD-EIN"}, "einstieg"},
|
||||
{"standard beats entry", []string{"CRA-CSA-CLD-EIN", "CRA-CSA-CLD-STD"}, "standard"},
|
||||
{"business beats entry", []string{"CRA-CSA-CLD-BUS", "CRA-CSA-CLD-EIN"}, "business"},
|
||||
} {
|
||||
if got := pruefwerkPlanFor(c.skus).Name; got != c.want {
|
||||
t.Errorf("%s: %s, want %s", c.name, got, c.want)
|
||||
@@ -216,3 +221,38 @@ func TestRouteGroup_pruefwerkSettings(t *testing.T) {
|
||||
t.Errorf("PUT group %q", g)
|
||||
}
|
||||
}
|
||||
|
||||
// The entry plan: the order's targets, no quota, and a Prüftag cap of 0
|
||||
// even when the workspace saved another (or none).
|
||||
func TestPruefwerkLimitsEntry(t *testing.T) {
|
||||
seven := 7
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
targets interface{}
|
||||
cap *int
|
||||
want int
|
||||
}{
|
||||
{"default one target", nil, nil, 1},
|
||||
{"three targets", 3, &seven, 3},
|
||||
{"from JSONB", float64(10), nil, 10},
|
||||
{"too many is one", 11, nil, 1},
|
||||
{"zero is one", 0, nil, 1},
|
||||
{"fraction is one", 2.5, nil, 1},
|
||||
{"string is one", "4", nil, 1},
|
||||
} {
|
||||
cfg := map[string]interface{}{"source": "entry", "skus": []interface{}{"CRA-CSA-CLD-EIN"}}
|
||||
if c.targets != nil {
|
||||
cfg["included_targets"] = c.targets
|
||||
}
|
||||
got := pruefwerkLimits(cfg, c.cap)
|
||||
if got[limitIncludedTargets] != c.want || got[limitMonthlyPruefungen] != 0 || got[limitPrueftagCap] != 0 {
|
||||
t.Errorf("%s: %v / %v / %v, want %d / 0 / 0", c.name, got[limitIncludedTargets], got[limitMonthlyPruefungen], got[limitPrueftagCap], c.want)
|
||||
}
|
||||
}
|
||||
if p := pruefwerkPlanOfConfig(map[string]interface{}{"skus": []string{"CRA-CSA-CLD-EIN"}}); p.capApplies() {
|
||||
t.Error("the saved cap applies on the entry plan")
|
||||
}
|
||||
if p := pruefwerkPlanOfConfig(map[string]interface{}{"skus": []string{"CRA-CSA-CLD-STD"}, "included_targets": 9}); p.IncludedTargets != 5 || !p.capApplies() {
|
||||
t.Errorf("standard took the entry targets or lost its cap: %+v", p)
|
||||
}
|
||||
}
|
||||
@@ -260,6 +260,8 @@ func NewRouter(s *Server) http.Handler {
|
||||
// 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)
|
||||
// Entry offers (one-off orders paid at booking; admin_entry.go).
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/entry-offer", s.cloudOnly(s.adminEntryOffer))
|
||||
mux.HandleFunc("GET /v1/admin/audit", s.listAudit)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/store/import", s.importStore)
|
||||
mux.HandleFunc("GET /v1/admin/tenants/{id}/company-profile", s.getCompanyProfile)
|
||||
|
||||
@@ -1829,6 +1829,44 @@ paths:
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { description: "The tenant has booked the product." }
|
||||
|
||||
/v1/admin/tenants/{id}/entry-offer:
|
||||
post:
|
||||
summary: Grant the Prüfwerk entry plan for a one-off order (staff only, audited, cloud only).
|
||||
description: |
|
||||
Entry offers (CRA-Check, SBOM-Erstellung, CVE-Scan) are paid at
|
||||
booking, outside the ERP. The grant is Prüfwerk with config
|
||||
source "entry", skus [CRA-CSA-CLD-EIN] and the order's included
|
||||
targets: no monthly quota and a Prüftag cap of 0, whatever the
|
||||
workspace saved, so nothing beyond the order is used or billed.
|
||||
A trial workspace becomes active. Sending it again replaces
|
||||
targets, end and reference (staff set the end to 90 days after
|
||||
delivery). While the grant runs, an ERP event without
|
||||
subscriptions does not halt the workspace. Refused (409) for a
|
||||
workspace with a Prüfwerk subscription, or one that is neither
|
||||
trial nor active. Needs a named staff member (X-Staff-Subject).
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [included_targets, expires_at]
|
||||
properties:
|
||||
included_targets: { type: integer, minimum: 1, maximum: 10 }
|
||||
expires_at: { type: string, format: date-time, description: "In the future, at most 200 days ahead." }
|
||||
order_ref: { type: string, maxLength: 64, pattern: "^[A-Za-z0-9][A-Za-z0-9._/-]{0,63}$", description: "Invoice or order number, never a name." }
|
||||
responses:
|
||||
"200":
|
||||
description: Granted (or updated).
|
||||
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: "Prüfwerk subscription, or a workspace neither trial nor active." }
|
||||
|
||||
/v1/admin/tenants/{id}/preview-grants/{product}:
|
||||
delete:
|
||||
summary: Revoke a preview grant (staff only, audited). A booking is never removed this way.
|
||||
|
||||
Reference in new issue
Block a user