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
104 lines
4.3 KiB
PL/PgSQL
104 lines
4.3 KiB
PL/PgSQL
-- M-MIG-7 — the always-on customer ⇄ CRM ⇄ ERP link (ERP/02, decision 3):
|
|
-- subscriptions mirrored from ERPNext Sales Orders, continuous usage events,
|
|
-- an outbox for ERP writes with retry, webhook idempotency, and CLI licences
|
|
-- issued by the registry (decision 13).
|
|
|
|
-- Ladder timing: when the current status was entered (grace escalation and
|
|
-- the halted → archived export window key off this).
|
|
ALTER TABLE tenants ADD COLUMN status_changed_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
|
|
|
|
CREATE OR REPLACE FUNCTION touch_status_changed_at() RETURNS trigger AS $$
|
|
BEGIN
|
|
IF NEW.status IS DISTINCT FROM OLD.status THEN
|
|
NEW.status_changed_at = NOW();
|
|
END IF;
|
|
RETURN NEW;
|
|
END;
|
|
$$ LANGUAGE plpgsql;
|
|
|
|
CREATE TRIGGER tenants_touch_status_changed_at
|
|
BEFORE UPDATE ON tenants
|
|
FOR EACH ROW EXECUTE FUNCTION touch_status_changed_at();
|
|
|
|
-- subscriptions — one row per (tenant, SKU, ERP Sales Order). The registry
|
|
-- derives entitlements (tenant_products) from active rows.
|
|
CREATE TABLE subscriptions (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
|
product TEXT NOT NULL,
|
|
sku TEXT NOT NULL,
|
|
plan TEXT NOT NULL DEFAULT '',
|
|
seats INT NOT NULL DEFAULT 1 CHECK (seats >= 0),
|
|
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'cancelled')),
|
|
erp_sales_order TEXT NOT NULL DEFAULT '',
|
|
erp_subscription TEXT NOT NULL DEFAULT '',
|
|
period_start DATE,
|
|
period_end DATE,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
UNIQUE (tenant_id, sku, erp_sales_order)
|
|
);
|
|
|
|
CREATE INDEX subscriptions_tenant_idx ON subscriptions (tenant_id) WHERE status = 'active';
|
|
|
|
CREATE TRIGGER subscriptions_touch_updated_at
|
|
BEFORE UPDATE ON subscriptions
|
|
FOR EACH ROW EXECUTE FUNCTION touch_updated_at();
|
|
|
|
-- usage_events — pushed by products (PRODUCT_INTEGRATION_SPEC 2.0 §9.2).
|
|
-- idempotency_key makes retries safe; erp_synced_at is set by the outbox.
|
|
CREATE TABLE usage_events (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
idempotency_key TEXT NOT NULL UNIQUE,
|
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
|
product TEXT NOT NULL,
|
|
metric TEXT NOT NULL,
|
|
quantity DOUBLE PRECISION NOT NULL DEFAULT 1,
|
|
occurred_at TIMESTAMPTZ NOT NULL,
|
|
properties JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
erp_synced_at TIMESTAMPTZ
|
|
);
|
|
|
|
CREATE INDEX usage_events_tenant_idx ON usage_events (tenant_id, occurred_at DESC);
|
|
|
|
-- erp_outbox — every ERP write goes through here (customer upsert, usage
|
|
-- record, CRM lead). The worker claims due rows, retries with backoff and
|
|
-- marks them done; nothing is lost when ERPNext is unreachable.
|
|
CREATE TABLE erp_outbox (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
kind TEXT NOT NULL,
|
|
tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
|
|
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
attempts INT NOT NULL DEFAULT 0,
|
|
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
last_error TEXT NOT NULL DEFAULT '',
|
|
done_at TIMESTAMPTZ,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX erp_outbox_pending_idx ON erp_outbox (next_attempt_at) WHERE done_at IS NULL;
|
|
|
|
-- erp_webhook_receipts — inbound ERPNext webhooks are idempotent by event id.
|
|
CREATE TABLE erp_webhook_receipts (
|
|
event_id TEXT PRIMARY KEY,
|
|
received_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
|
|
-- licences — CLI licences (Werkpilot, Firmwerk) issued as Ed25519 JWTs; the
|
|
-- row is the revocation + heartbeat record, the JWT itself is not stored.
|
|
CREATE TABLE licences (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
kid TEXT NOT NULL,
|
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
|
product TEXT NOT NULL,
|
|
subject TEXT NOT NULL,
|
|
device TEXT NOT NULL DEFAULT '',
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
revoked_at TIMESTAMPTZ,
|
|
last_seen_at TIMESTAMPTZ,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX licences_tenant_idx ON licences (tenant_id, product) WHERE revoked_at IS NULL;
|