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": ""} // // 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 }