railyard/apps/rago/crates/rago-db/migrations/0011_dunning_lifetime.sql
caelum0x 03a3fe911d feat(rago): Lago-port billing service with idempotent payment/invoice guards
Lands the previously-untracked rago app: a Rust port of Lago billing with
the three audit fixes from the 2026-09-03 railyard audit baked in:

- CRITICAL: deterministic Stripe idempotency key (UUIDv5 of invoice id,
  sent as 'Idempotency-Key: payment-<id>') replacing the random-UUID-per-
  attempt pattern that allowed retry double-charges
- HIGH: unique index on events(organization_id, external_subscription_id,
  transaction_id) with idempotent ON CONFLICT DO NOTHING insert; duplicate
  transaction_id surfaces as an API validation error, not a 500
- HIGH: partial unique index on invoice_subscriptions(subscription_id,
  charges_from_datetime, charges_to_datetime) WHERE recurring, with
  insert_subscription_invoice_guarded returning Created|AlreadyBilled,
  wired into bill_subscription and the scheduler

Includes real-Postgres #[sqlx::test] suites (rago-db idempotency/parity,
rago-jobs rebill/clock, rago-graphql admin1-5, rago-api rest_crud).
2026-09-05 16:35:33 +03:00

30 lines
1.2 KiB
SQL

-- Phase 15: dunning-campaign configuration + lifetime-usage accumulation.
CREATE TABLE IF NOT EXISTS dunning_campaigns (
id uuid DEFAULT gen_random_uuid() NOT NULL PRIMARY KEY,
organization_id uuid NOT NULL,
name varchar NOT NULL,
code varchar NOT NULL,
description varchar,
max_attempts integer DEFAULT 3 NOT NULL,
days_between_attempts integer DEFAULT 7 NOT NULL,
bcc_emails jsonb DEFAULT '[]' NOT NULL,
applied_to_organization boolean DEFAULT false NOT NULL,
created_at timestamp(6) NOT NULL,
updated_at timestamp(6) NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_dunning_campaigns_org ON dunning_campaigns (organization_id);
-- Cumulative (lifetime) usage per subscription — the invoiced total plus the
-- live current-period usage, used for lifetime-usage threshold alerts and
-- progressive-billing true-ups.
CREATE TABLE IF NOT EXISTS lifetime_usages (
id uuid DEFAULT gen_random_uuid() NOT NULL PRIMARY KEY,
organization_id uuid NOT NULL,
subscription_external_id varchar NOT NULL,
invoiced_usage_amount_cents bigint DEFAULT 0 NOT NULL,
current_usage_amount_cents bigint DEFAULT 0 NOT NULL,
updated_at timestamp(6) NOT NULL,
UNIQUE (organization_id, subscription_external_id)
);