M-MIG-7 (ERP/02, decisions 3, 12, 13, 18):
- migration 0004: subscriptions, usage_events, erp_outbox,
erp_webhook_receipts, licences; tenants.status_changed_at (trigger)
- internal/erp: Frappe REST client (Customer upsert by tenant_id,
Subscription list, Usage Record, Lead) + webhook signing/verification
- internal/erpmock + cmd/erpmock: ERPNext stand-in for staging —
/api/resource/{doctype} with token auth, request log, /_mock/fire/*
triggers that mutate docs and deliver signed webhooks
- POST /v1/internal/erp/webhook (HMAC, idempotent by event id):
sales_order.submit → subscriptions + entitlements (SKU → product/plan,
add-on SKUs → limits) + active; sales_invoice.overdue → warning /
restricted / halted by days overdue; payment_entry.submit → active;
subscription.cancel → halted
- outbox worker (customer.upsert on tenant create, usage.record,
lead.create on catalog request) with backoff; reconcile job mirrors
ERP subscriptions and applies the time-based ladder (trial expiry,
warning→restricted 14 d, restricted→halted 30 d, halted→archived 30 d)
- POST/GET /v1/usage/events (idempotency_key, batch), GET
/v1/subscriptions, GET /v1/internal/erp/status, POST
/v1/internal/erp/reconcile
- CLI licences: Ed25519 signer (LICENCE_SIGNING_KEY), POST /v1/licences
(entitlement-gated, expiry capped by the entitlement), GET
/.well-known/licence-keys.json, POST /v1/licences/heartbeat (grace
ladder, renewal past half-life, revoked), revoke/list
- authn Principal carries tenant-context claims (user tokens scope usage
and licence calls to their own tenant); authz groups usage(.read)
- tests for every path (both stores), erpmock, erp client, licence pkg;
openapi.yaml + README updated; Dockerfile ships /erpmock
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
167 lines
5.2 KiB
Go
167 lines
5.2 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// The catalog lives in the products table (migration 0003) since M-MIG-5.
|
|
// Launch URLs are resolved for this registry's environment (APP_ENV) so the
|
|
// portal can link straight to the product host.
|
|
|
|
func (s *Server) getCatalog(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
defer cancel()
|
|
products, err := s.Store.ListProducts(ctx, false)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
items := make([]store.CatalogEntry, 0, len(products))
|
|
for _, p := range products {
|
|
items = append(items, p.Catalog(s.env()))
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
|
}
|
|
|
|
// env is the environment key used for per-env product URLs. "dev" reads the
|
|
// stage URLs so a laptop portal links somewhere real.
|
|
func (s *Server) env() string {
|
|
if s.Cfg == nil || s.Cfg.Env == "" || s.Cfg.Env == "dev" {
|
|
return "stage"
|
|
}
|
|
return s.Cfg.Env
|
|
}
|
|
|
|
// product returns an enabled catalog product or ErrNotFound.
|
|
func (s *Server) product(ctx context.Context, key string) (*store.Product, error) {
|
|
p, err := s.Store.GetProduct(ctx, key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !p.Enabled {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
func (s *Server) knownProduct(ctx context.Context, key string) bool {
|
|
_, err := s.product(ctx, key)
|
|
return err == nil
|
|
}
|
|
|
|
type catalogRequestReq struct {
|
|
TenantID string `json:"tenant_id"`
|
|
Product string `json:"product"`
|
|
}
|
|
|
|
// catalogRequest — customer requests a non-subscribed product. Emits an
|
|
// audit event; the ERP outbox (M-MIG-7) turns it into a CRM Lead.
|
|
func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
|
|
var in catalogRequestReq
|
|
if !decodeJSON(w, r, &in) {
|
|
return
|
|
}
|
|
if in.TenantID == "" || in.Product == "" {
|
|
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id and product are required")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
defer cancel()
|
|
if !s.knownProduct(ctx, in.Product) {
|
|
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
|
|
return
|
|
}
|
|
t, err := s.Store.GetTenant(ctx, in.TenantID)
|
|
if err != nil {
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
s.emitAudit(ctx, r, store.AuditEvent{
|
|
TenantID: in.TenantID, Action: "catalog.requested",
|
|
TargetID: in.Product, TargetType: "product",
|
|
Metadata: map[string]interface{}{"product": in.Product},
|
|
})
|
|
// CRM lead through the ERP outbox (M-MIG-7).
|
|
email := ""
|
|
if p, _ := authn.PrincipalFrom(r.Context()); p != nil {
|
|
email = p.Email
|
|
}
|
|
if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{Kind: store.OutboxLeadCreate, TenantID: in.TenantID,
|
|
Payload: map[string]interface{}{"lead_name": t.Name, "company_name": t.Name, "email": email, "product": in.Product,
|
|
"notes": "Requested " + in.Product + " from the platform catalog"}}); err != nil {
|
|
s.Log.Error("enqueue lead failed", "tenant_id", in.TenantID, "err", err)
|
|
}
|
|
writeJSON(w, http.StatusAccepted, map[string]string{
|
|
"status": "accepted",
|
|
"message": "request recorded; sales will be in touch",
|
|
})
|
|
}
|
|
|
|
// catalogTrialRequest — self-serve trial of a product that supports it.
|
|
// Provisions the entitlement immediately (trial_days from the catalog).
|
|
func (s *Server) catalogTrialRequest(w http.ResponseWriter, r *http.Request) {
|
|
var in catalogRequestReq
|
|
if !decodeJSON(w, r, &in) {
|
|
return
|
|
}
|
|
if in.TenantID == "" || in.Product == "" {
|
|
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id and product are required")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
defer cancel()
|
|
entry, err := s.product(ctx, in.Product)
|
|
if err != nil {
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
if !entry.SupportsTrial {
|
|
writeError(w, http.StatusBadRequest, "trial_unavailable", "product does not support self-serve trial")
|
|
return
|
|
}
|
|
t, err := s.Store.GetTenant(ctx, in.TenantID)
|
|
if err != nil {
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
days := entry.TrialDays
|
|
if days <= 0 {
|
|
days = 14
|
|
}
|
|
expiresAt := time.Now().UTC().Add(time.Duration(days) * 24 * time.Hour)
|
|
tp, err := s.Store.UpsertTenantProduct(ctx, store.TenantProduct{
|
|
TenantID: in.TenantID, Product: in.Product, Enabled: true,
|
|
Config: map[string]interface{}{"source": "trial"}, ExpiresAt: &expiresAt,
|
|
})
|
|
if err != nil {
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
s.emitAudit(ctx, r, store.AuditEvent{
|
|
TenantID: in.TenantID, Action: "catalog.trial_started",
|
|
TargetID: in.Product, TargetType: "product",
|
|
Metadata: map[string]interface{}{"product": in.Product, "expires_at": expiresAt.Format(time.RFC3339)},
|
|
})
|
|
s.provisionProduct(ctx, r, t, entry, tp)
|
|
writeJSON(w, http.StatusCreated, tp)
|
|
}
|