AGB § 10 allows restricting access only "trotz Mahnung und angemessener Nachfrist". The ladder counted from the due date (restricted after 14, halted after 30 days overdue) and escalated any warning after 14 days. Now an overdue invoice alone means warning. The reconcile pass reads the customer's submitted, unresolved ERPNext Dunnings; the earliest one that names a still-open invoice sets the clock: restricted 14 days after its posting date, halted a further 14 days after the restriction. A Mahnung never halts directly, so a late-seen one errs in the customer's favour. A failed Dunning read keeps the tenant on warning and is reported. ERP_HALT_AFTER_DAYS defaults to 28 (was 30), so an expired trial is read-only for 14 days instead of 16 before it is halted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
768 lines
25 KiB
Go
768 lines
25 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"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 (read-only,
|
|
// RestrictAfterDays after a Mahnung) → halted (a further
|
|
// HaltAfterDays-RestrictAfterDays later, or cancelled) → archived (export window over). AGB § 10 allows
|
|
// restricting access only "trotz Mahnung und angemessener Nachfrist", so an
|
|
// overdue invoice alone never goes past warning.
|
|
|
|
// 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:
|
|
// days_overdue counts from the due date: warning only. Restriction
|
|
// needs a Mahnung, which the reconcile pass reads from ERPNext.
|
|
next, ok := s.overdueStep(t, false, 0)
|
|
if !ok {
|
|
if t.Status == store.StatusDemo || t.Status == store.StatusArchived || t.Status == store.StatusHalted {
|
|
return map[string]any{"status": "ignored", "tenant_status": t.Status}, nil
|
|
}
|
|
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
|
|
}
|
|
|
|
// overdueStep is the ladder rung for an overdue invoice. Without a Mahnung
|
|
// (dunned false) it is warning. With one, restricted from RestrictAfterDays
|
|
// after the Mahnung (sinceMahnung in calendar days). It never returns halted:
|
|
// a tenant is always read-only first, and escalation() halts it a further
|
|
// HaltAfterDays-RestrictAfterDays after the restriction, so a Mahnung seen
|
|
// late (back-dated, or ERPNext unreachable for a while) errs in the
|
|
// customer's favour. ok is false when the tenant is not billed (demo), already
|
|
// gone (halted, archived) or already on that rung or a higher one; the ladder
|
|
// never moves backwards on overdue.
|
|
func (s *Server) overdueStep(t *store.Tenant, dunned bool, sinceMahnung int) (string, bool) {
|
|
if t.Status == store.StatusDemo || t.Status == store.StatusArchived || t.Status == store.StatusHalted {
|
|
return "", false
|
|
}
|
|
next := store.StatusWarning
|
|
if dunned && sinceMahnung >= s.restrictAfterDays() {
|
|
next = store.StatusRestricted
|
|
}
|
|
if rank(next) <= rank(t.Status) && t.Status != store.StatusTrial && t.Status != store.StatusActive {
|
|
return "", false
|
|
}
|
|
return next, true
|
|
}
|
|
|
|
// applyOverdueInvoices is the reconcile half of the dunning ladder. Any open
|
|
// overdue invoice means warning; the earliest open Mahnung (Dunning) that
|
|
// names one of them decides restricted and halted. A Mahnung whose invoices
|
|
// are all paid does not count. When no invoice is left and the tenant was put
|
|
// on the ladder by an overdue invoice, it goes back to active (a payment
|
|
// matched by Zahlungsabgleich fires no event).
|
|
func (s *Server) applyOverdueInvoices(ctx context.Context, t *store.Tenant, invs []erp.Invoice, dunnings []erp.Dunning, now time.Time) (*store.Tenant, string, error) {
|
|
if len(invs) > 0 {
|
|
open := make(map[string]bool, len(invs))
|
|
oldest := invs[0]
|
|
for _, inv := range invs {
|
|
open[inv.Name] = true
|
|
if inv.DueDate < oldest.DueDate {
|
|
oldest = inv
|
|
}
|
|
}
|
|
var mahnung time.Time
|
|
mahnungName := ""
|
|
for _, d := range dunnings {
|
|
if !namesOpenInvoice(d, open) {
|
|
continue
|
|
}
|
|
at, err := time.ParseInLocation("2006-01-02", d.PostingDate, erpZone)
|
|
if err != nil {
|
|
return t, "", fmt.Errorf("dunning %s: posting date %q: %w", d.Name, d.PostingDate, err)
|
|
}
|
|
if mahnungName == "" || at.Before(mahnung) {
|
|
mahnung, mahnungName = at, d.Name
|
|
}
|
|
}
|
|
dunned := mahnungName != ""
|
|
days := 0
|
|
if dunned {
|
|
days = calendarDays(mahnung, berlinDate(now))
|
|
}
|
|
next, ok := s.overdueStep(t, dunned, days)
|
|
if !ok {
|
|
return t, "", nil
|
|
}
|
|
source := "reconcile:invoice_overdue:" + oldest.Name
|
|
if dunned && next != store.StatusWarning {
|
|
source += ":dunning:" + mahnungName
|
|
}
|
|
t2, err := s.transition(ctx, nil, t, next, source)
|
|
return t2, next, err
|
|
}
|
|
if t.Status != store.StatusWarning && t.Status != store.StatusRestricted && t.Status != store.StatusFrozen {
|
|
return t, "", nil
|
|
}
|
|
subs, err := s.Store.ListSubscriptions(ctx, t.ID)
|
|
if err != nil || !hasActive(subs) {
|
|
return t, "", err
|
|
}
|
|
if !s.onLadderForInvoices(ctx, t) {
|
|
return t, "", nil
|
|
}
|
|
t2, err := s.transition(ctx, nil, t, store.StatusActive, "reconcile:invoices_settled")
|
|
return t2, store.StatusActive, err
|
|
}
|
|
|
|
// namesOpenInvoice reports whether the Mahnung names an invoice that is still
|
|
// open and overdue.
|
|
func namesOpenInvoice(d erp.Dunning, open map[string]bool) bool {
|
|
for _, inv := range d.Invoices {
|
|
if open[inv] {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// calendarDays is the number of calendar days from one ERP-zone midnight to
|
|
// another (rounded, so a DST switch in between does not lose a day).
|
|
func calendarDays(from, to time.Time) int {
|
|
return int(math.Round(to.Sub(from).Hours() / 24))
|
|
}
|
|
|
|
// onLadderForInvoices reports whether the tenant's current status was set by
|
|
// the dunning ladder (not by staff or an expired trial), from the audit event
|
|
// that set it.
|
|
func (s *Server) onLadderForInvoices(ctx context.Context, t *store.Tenant) bool {
|
|
since := t.StatusChangedAt.Add(-time.Minute)
|
|
evs, _, err := s.Store.ListAudit(ctx, store.AuditFilter{TenantID: t.ID, Action: "tenant.status_changed", Since: &since, Limit: 50})
|
|
if err != nil || len(evs) == 0 {
|
|
return false
|
|
}
|
|
src, _ := evs[len(evs)-1].Metadata["source"].(string)
|
|
for _, p := range []string{"erp:invoice_overdue:", "reconcile:invoice_overdue:", "reconcile:grace_over"} {
|
|
if strings.HasPrefix(src, p) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// erpZone is the ERPNext company time zone; due dates are calendar days there.
|
|
var erpZone = func() *time.Location {
|
|
if l, err := time.LoadLocation("Europe/Berlin"); err == nil {
|
|
return l
|
|
}
|
|
return time.UTC
|
|
}()
|
|
|
|
// berlinDate is midnight of t's calendar day in the ERP time zone.
|
|
func berlinDate(t time.Time) time.Time {
|
|
y, m, d := t.In(erpZone).Date()
|
|
return time.Date(y, m, d, 0, 0, 0, 0, erpZone)
|
|
}
|
|
|
|
// 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 28
|
|
}
|
|
|
|
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 s.ERP.Enabled() && t.ErpCustomerID != "" {
|
|
invs, err := s.ERP.ListOverdueInvoices(ctx, t.ErpCustomerID, berlinDate(now).Format("2006-01-02"))
|
|
var dunnings []erp.Dunning
|
|
if err == nil && len(invs) > 0 {
|
|
// Without the Mahnungen the tenant can still get a warning,
|
|
// never more, so a failed read is reported and not fatal.
|
|
if dunnings, err = s.ERP.ListOpenDunnings(ctx, t.ErpCustomerID); err != nil {
|
|
rep.Errors = append(rep.Errors, t.Slug+": erp dunnings: "+err.Error())
|
|
dunnings, err = nil, nil
|
|
}
|
|
}
|
|
if err != nil {
|
|
rep.Errors = append(rep.Errors, t.Slug+": erp invoices: "+err.Error())
|
|
} else if t2, moved, err := s.applyOverdueInvoices(ctx, t, invs, dunnings, now); err != nil {
|
|
rep.Errors = append(rep.Errors, t.Slug+": invoices: "+err.Error())
|
|
} else {
|
|
if moved != "" {
|
|
rep.Escalated = append(rep.Escalated, t.Slug+"→"+moved)
|
|
}
|
|
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.StatusRestricted, store.StatusFrozen:
|
|
// non-payment and expired trials alike: read-only for
|
|
// HaltAfterDays-RestrictAfterDays (14 days by default), then halted
|
|
// (no access), then the export window. For non-payment that is
|
|
// HaltAfterDays after the Mahnung when it was seen on time. A warning
|
|
// never escalates by time alone: that needs a Mahnung (AGB § 10).
|
|
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,
|
|
"llm_keys_enabled": s.LLMKeys.Enabled(),
|
|
})
|
|
}
|
|
|
|
// 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})
|
|
}
|