package server import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "io" "net/http" "sort" "strings" "time" "git.breakpilot.com/platform/tenant-registry/internal/erp" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // ─── ERP link (M-MIG-7): webhook receiver, subscription → entitlement // mapping, ladder transitions, reconcile ────────────────────────────────── // // ERPNext is the commercial authority (Sales Orders / Subscriptions / // Invoices / Payments); the registry mirrors what it hears into // subscriptions + tenant_products and moves the tenant on the ladder // (ERP/02): active → warning (invoice overdue) → restricted (grace over, // read-only) → halted (cancelled / hard stop) → archived (export window over). // erpWebhook is POST /v1/internal/erp/webhook (PUBLIC_EXPLICIT, HMAC). func (s *Server) erpWebhook(w http.ResponseWriter, r *http.Request) { secret := s.cfg().ErpWebhookSecret if secret == "" { writeError(w, http.StatusServiceUnavailable, "webhook_disabled", "ERP_WEBHOOK_SECRET is not configured") return } body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil { writeError(w, http.StatusBadRequest, "invalid_body", err.Error()) return } sig := r.Header.Get(erp.HeaderSignature) if sig == "" { sig = r.Header.Get("X-Hub-Signature-256") } if !erp.VerifySignature(secret, body, sig) { s.Log.Warn("erp webhook signature rejected", "ip", clientIP(r)) writeError(w, http.StatusUnauthorized, "bad_signature", "webhook signature invalid") return } var ev erp.WebhookEvent if err := json.Unmarshal(body, &ev); err != nil { writeError(w, http.StatusBadRequest, "invalid_json", err.Error()) return } if ev.Event == "" { ev.Event = r.Header.Get(erp.HeaderEvent) } eventID := r.Header.Get(erp.HeaderEventID) if eventID == "" { sum := sha256.Sum256(body) eventID = ev.Event + ":" + ev.Name + ":" + ev.Modified + ":" + hex.EncodeToString(sum[:8]) } ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) defer cancel() fresh, err := s.Store.RecordWebhookReceipt(ctx, eventID) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } if !fresh { writeJSON(w, http.StatusOK, map[string]any{"status": "duplicate", "event_id": eventID}) return } t, err := s.resolveWebhookTenant(ctx, ev) if err != nil { if errors.Is(err, store.ErrNotFound) { // Not ours (e.g. a customer without tenant_id). Acknowledge so // ERPNext does not retry forever; the receipt keeps it idempotent. s.Log.Warn("erp webhook for unknown tenant", "event", ev.Event, "customer", ev.Customer, "tenant_id", ev.TenantID) writeJSON(w, http.StatusAccepted, map[string]any{"status": "ignored", "reason": "tenant_not_found", "event_id": eventID}) return } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } res, err := s.applyErpEvent(ctx, r, t, ev) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } res["event_id"] = eventID writeJSON(w, http.StatusOK, res) } func (s *Server) resolveWebhookTenant(ctx context.Context, ev erp.WebhookEvent) (*store.Tenant, error) { if ev.TenantID != "" { if t, err := s.Store.GetTenant(ctx, ev.TenantID); err == nil { return t, nil } else if !errors.Is(err, store.ErrNotFound) { return nil, err } } return s.Store.GetTenantByErpCustomerID(ctx, ev.Customer) } // applyErpEvent maps one webhook onto the ladder. Returns a small result map. func (s *Server) applyErpEvent(ctx context.Context, r *http.Request, t *store.Tenant, ev erp.WebhookEvent) (map[string]any, error) { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "erp.webhook", TargetID: ev.Name, TargetType: ev.Doctype, ActorType: "service", Metadata: map[string]interface{}{"event": ev.Event, "customer": ev.Customer}, }) switch ev.Event { case erp.EventSalesOrderSubmit: for _, it := range ev.Items { prod := s.productForSKU(ctx, it.ItemCode) if prod == nil { s.Log.Warn("sales order item without catalog product", "sku", it.ItemCode, "tenant_id", t.ID) continue } qty := it.Qty if qty <= 0 { qty = 1 } if _, err := s.Store.UpsertSubscription(ctx, store.Subscription{ TenantID: t.ID, Product: prod.Key, SKU: it.ItemCode, Plan: planForSKU(it.ItemCode), Seats: int(qty), Status: store.SubscriptionActive, ErpSalesOrder: ev.Name, ErpSubscription: ev.Subscription, }); err != nil { return nil, err } } t2, err := s.recomputeEntitlements(ctx, r, t, "erp:"+ev.Name) if err != nil { return nil, err } return map[string]any{"status": "applied", "tenant_status": t2.Status}, nil case erp.EventInvoiceOverdue: if t.Status == store.StatusDemo || t.Status == store.StatusArchived || t.Status == store.StatusHalted { return map[string]any{"status": "ignored", "tenant_status": t.Status}, nil } next := store.StatusWarning if ev.DaysOverdue >= s.restrictAfterDays() { next = store.StatusRestricted } if ev.DaysOverdue >= s.haltAfterDays() { next = store.StatusHalted } if rank(next) <= rank(t.Status) && t.Status != store.StatusTrial && t.Status != store.StatusActive { return map[string]any{"status": "unchanged", "tenant_status": t.Status}, nil } t2, err := s.transition(ctx, r, t, next, "erp:invoice_overdue:"+ev.Name) if err != nil { return nil, err } return map[string]any{"status": "applied", "tenant_status": t2.Status}, nil case erp.EventPaymentEntrySubmit: if t.Status != store.StatusWarning && t.Status != store.StatusRestricted && t.Status != store.StatusFrozen && t.Status != store.StatusHalted { return map[string]any{"status": "unchanged", "tenant_status": t.Status}, nil } subs, err := s.Store.ListSubscriptions(ctx, t.ID) if err != nil { return nil, err } if !hasActive(subs) { return map[string]any{"status": "unchanged", "tenant_status": t.Status, "reason": "no_active_subscription"}, nil } t2, err := s.transition(ctx, r, t, store.StatusActive, "erp:payment:"+ev.Name) if err != nil { return nil, err } return map[string]any{"status": "applied", "tenant_status": t2.Status}, nil case erp.EventSubscriptionCancel: subs, err := s.Store.ListSubscriptions(ctx, t.ID) if err != nil { return nil, err } for _, sub := range subs { if sub.Status != store.SubscriptionActive { continue } if ev.Subscription != "" && sub.ErpSubscription != ev.Subscription && sub.ErpSalesOrder != ev.Name { continue } sub.Status = store.SubscriptionCancelled if _, err := s.Store.UpsertSubscription(ctx, sub); err != nil { return nil, err } } t2, err := s.recomputeEntitlements(ctx, r, t, "erp:cancel:"+ev.Name) if err != nil { return nil, err } return map[string]any{"status": "applied", "tenant_status": t2.Status}, nil } return map[string]any{"status": "ignored", "reason": "unknown_event"}, nil } // applySubscriptions mirrors the ERP Subscription list (reconcile path). func (s *Server) applySubscriptions(ctx context.Context, t *store.Tenant, subs []erp.Subscription) (*store.Tenant, bool, error) { changed := false local, err := s.Store.ListSubscriptions(ctx, t.ID) if err != nil { return nil, false, err } seen := map[string]bool{} for _, es := range subs { status := store.SubscriptionActive switch strings.ToLower(es.Status) { case "cancelled", "canceled", "completed": status = store.SubscriptionCancelled } for _, pl := range es.Plans { prod := s.productForSKU(ctx, pl.Plan) if prod == nil { continue } key := pl.Plan + "|" + es.SalesOrder seen[key] = true qty := int(pl.Qty) if qty <= 0 { qty = 1 } cur := findSub(local, pl.Plan, es.SalesOrder) if cur != nil && cur.Status == status && cur.Seats == qty && cur.ErpSubscription == es.Name { continue } if _, err := s.Store.UpsertSubscription(ctx, store.Subscription{ TenantID: t.ID, Product: prod.Key, SKU: pl.Plan, Plan: planForSKU(pl.Plan), Seats: qty, Status: status, ErpSalesOrder: es.SalesOrder, ErpSubscription: es.Name, }); err != nil { return nil, false, err } changed = true } } // Local active rows the ERP no longer lists → cancelled. for _, l := range local { if l.Status == store.SubscriptionActive && l.ErpSubscription != "" && !seen[l.SKU+"|"+l.ErpSalesOrder] { l.Status = store.SubscriptionCancelled if _, err := s.Store.UpsertSubscription(ctx, l); err != nil { return nil, false, err } changed = true } } if !changed { return t, false, nil } t2, err := s.recomputeEntitlements(ctx, nil, t, "erp:reconcile") return t2, true, err } func findSub(list []store.Subscription, sku, so string) *store.Subscription { for i := range list { if list[i].SKU == sku && list[i].ErpSalesOrder == so { return &list[i] } } return nil } func hasActive(subs []store.Subscription) bool { for _, sub := range subs { if sub.Status == store.SubscriptionActive { return true } } return false } // recomputeEntitlements derives tenant_products from active subscriptions // and moves the tenant to active (has subscriptions) or halted (none). func (s *Server) recomputeEntitlements(ctx context.Context, r *http.Request, t *store.Tenant, source string) (*store.Tenant, error) { subs, err := s.Store.ListSubscriptions(ctx, t.ID) if err != nil { return nil, err } products, err := s.Store.ListProducts(ctx, true) if err != nil { return nil, err } existing, err := s.Store.ListTenantProducts(ctx, t.ID) if err != nil { return nil, err } best := "" for _, p := range products { cfg := map[string]interface{}{"source": "erp"} seats := 0 skus := []string{} active := false addons := map[string]int{} for _, sub := range subs { if sub.Status != store.SubscriptionActive || sub.Product != p.Key { continue } active = true skus = append(skus, sub.SKU) if addon := addonForSKU(&p, sub.SKU); addon != nil { addons[addon.LimitKey] += sub.Seats } else { seats += sub.Seats } if rankPlan(sub.Plan) > rankPlan(best) { best = sub.Plan } } if active { sort.Strings(skus) cfg["skus"] = skus if seats > 0 { cfg["seats"] = seats } for k, v := range addons { cfg[k] = v } tp, err := s.Store.UpsertTenantProduct(ctx, store.TenantProduct{TenantID: t.ID, Product: p.Key, Enabled: true, Config: cfg}) if err != nil { return nil, err } s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "entitlement.granted", TargetID: p.Key, TargetType: "product", ActorType: "service", Metadata: map[string]interface{}{"config": cfg, "source": source}}) s.provisionProduct(ctx, r, t, &p, tp) continue } // no active subscription: disable only ERP-sourced grants (trials stay) for _, e := range existing { if e.Product == p.Key && e.Enabled && e.Config["source"] == "erp" { e.Enabled = false if _, err := s.Store.UpsertTenantProduct(ctx, e); err != nil { return nil, err } s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "entitlement.revoked", TargetID: p.Key, TargetType: "product", ActorType: "service", Metadata: map[string]interface{}{"source": source}}) } } } upd := store.TenantUpdate{} next := t.Status if hasActive(subs) { if best != "" && best != t.Plan { upd.Plan = &best } 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 { next = store.StatusHalted } if next != t.Status { upd.Status = &next } if upd.Status == nil && upd.Plan == nil { return t, nil } t2, err := s.Store.UpdateTenant(ctx, t.ID, upd) if err != nil { return nil, err } if upd.Status != nil { s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "tenant.status_changed", TargetID: t.ID, TargetType: "tenant", ActorType: "service", Metadata: map[string]interface{}{"from": t.Status, "to": t2.Status, "source": source}}) s.syncTenantStatus(ctx, r, t2) } return t2, nil } // transition moves a tenant to `next` with audit + Keycloak sync. func (s *Server) transition(ctx context.Context, r *http.Request, t *store.Tenant, next, source string) (*store.Tenant, error) { if t.Status == next { return t, nil } t2, err := s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{Status: ptrStr(next)}) if err != nil { return nil, err } s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "tenant.status_changed", TargetID: t.ID, TargetType: "tenant", ActorType: "service", Metadata: map[string]interface{}{"from": t.Status, "to": next, "source": source}}) s.syncTenantStatus(ctx, r, t2) return t2, nil } // productForSKU finds the product selling sku (as base SKU or add-on SKU). func (s *Server) productForSKU(ctx context.Context, sku string) *store.Product { products, err := s.Store.ListProducts(ctx, true) if err != nil { return nil } for i := range products { p := products[i] for _, x := range p.SKUs { if x == sku { return &p } } if addonForSKU(&p, sku) != nil { return &p } } return nil } func addonForSKU(p *store.Product, sku string) *store.ProductAddon { for i := range p.Addons { for _, x := range p.Addons[i].SKUs { if x == sku { a := p.Addons[i] if a.LimitKey == "" { a.LimitKey = a.ID } return &a } } } return nil } // planForSKU maps the SKU tier suffix onto the plan names of the catalog. func planForSKU(sku string) string { switch { case strings.HasSuffix(sku, "-ENT"): return "enterprise" case strings.HasSuffix(sku, "-BUS"): return "business" case strings.HasSuffix(sku, "-STD"): return "standard" } return "" } func rankPlan(p string) int { switch p { case "enterprise": return 3 case "business": return 2 case "standard": return 1 } return 0 } // rank orders the ladder for "never move backwards on overdue" checks. func rank(status string) int { switch status { case store.StatusActive, store.StatusTrial, store.StatusDemo: return 0 case store.StatusWarning: return 1 case store.StatusRestricted, store.StatusFrozen: return 2 case store.StatusHalted: return 3 case store.StatusArchived: return 4 } return 0 } func (s *Server) restrictAfterDays() int { if d := s.cfg().RestrictAfterDays; d > 0 { return d } return 14 } func (s *Server) haltAfterDays() int { if d := s.cfg().HaltAfterDays; d > 0 { return d } return 30 } func (s *Server) exportWindowDays() int { if d := s.cfg().ExportWindowDays; d > 0 { return d } return 30 } // ─── reconcile ──────────────────────────────────────────────────────────── // ReconcileReport summarises one reconcile pass. type ReconcileReport struct { Tenants int `json:"tenants"` ErpChecked int `json:"erp_checked"` Changed []string `json:"changed"` Escalated []string `json:"escalated"` Errors []string `json:"errors,omitempty"` ErpAvailable bool `json:"erp_available"` } // Reconcile walks every tenant: mirrors ERP subscriptions (when the ERP // client is configured) and applies time-based ladder steps — trial expiry, // warning → restricted, restricted → halted, halted → archived. func (s *Server) Reconcile(ctx context.Context) ReconcileReport { rep := ReconcileReport{Changed: []string{}, Escalated: []string{}, ErpAvailable: s.ERP.Enabled()} now := s.now() cursor := "" for { page, next, err := s.Store.ListTenants(ctx, store.TenantFilter{Limit: 200, Cursor: cursor}) if err != nil { rep.Errors = append(rep.Errors, "list tenants: "+err.Error()) return rep } for i := range page { t := &page[i] rep.Tenants++ if s.ERP.Enabled() && t.ErpCustomerID != "" { subs, err := s.ERP.ListSubscriptions(ctx, t.ErpCustomerID) if err != nil { rep.Errors = append(rep.Errors, t.Slug+": erp: "+err.Error()) } else { rep.ErpChecked++ t2, changed, err := s.applySubscriptions(ctx, t, subs) if err != nil { rep.Errors = append(rep.Errors, t.Slug+": apply: "+err.Error()) } else { if changed { rep.Changed = append(rep.Changed, t.Slug) } t = t2 } } } if next, why := s.escalation(t, now); next != "" { if _, err := s.transition(ctx, nil, t, next, "reconcile:"+why); err != nil { rep.Errors = append(rep.Errors, t.Slug+": escalate: "+err.Error()) } else { rep.Escalated = append(rep.Escalated, t.Slug+"→"+next) } } } if next == "" { break } cursor = next } return rep } // escalation returns the time-based next rung for t at `now` ("" = none). func (s *Server) escalation(t *store.Tenant, now time.Time) (string, string) { day := 24 * time.Hour age := now.Sub(t.StatusChangedAt) switch t.Status { case store.StatusTrial: if t.TrialEndsAt != nil && now.After(*t.TrialEndsAt) { return store.StatusRestricted, "trial_expired" } case store.StatusWarning: if age >= time.Duration(s.restrictAfterDays())*day { return store.StatusRestricted, "grace_over" } case store.StatusRestricted, store.StatusFrozen: // non-payment and expired trials alike: read-only for the rest of the // grace window, then halted (no access), then the export window. if age >= time.Duration(s.haltAfterDays()-s.restrictAfterDays())*day { return store.StatusHalted, "hard_stop" } case store.StatusHalted: if age >= time.Duration(s.exportWindowDays())*day { return store.StatusArchived, "export_window_over" } } return "", "" } // erpReconcileNow — POST /v1/internal/erp/reconcile (ops / tests). func (s *Server) erpReconcileNow(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second) defer cancel() writeJSON(w, http.StatusOK, s.Reconcile(ctx)) } // erpStatus — GET /v1/internal/erp/status. func (s *Server) erpStatus(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() pending, err := s.Store.PendingOutbox(ctx) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{ "erp_configured": s.ERP.Enabled(), "webhook_enabled": s.cfg().ErpWebhookSecret != "", "outbox_pending": pending, "licences_enabled": s.Licences != nil, }) } // listSubscriptions — GET /v1/subscriptions?tenant_id= func (s *Server) listSubscriptions(w http.ResponseWriter, r *http.Request) { tenantID := r.URL.Query().Get("tenant_id") if tenantID == "" { writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required") return } ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() list, err := s.Store.ListSubscriptions(ctx, tenantID) if err != nil { if mapStoreError(w, err) { return } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{"items": list}) }