railyard/apps/rago/crates/rago-db/migrations/0003_payments_webhooks.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

46 lines
1.6 KiB
SQL

-- Payments + outbound webhook delivery records.
-- Organizations gain an HMAC key used to sign webhooks (Lago `hmac_key`).
ALTER TABLE organizations ADD COLUMN IF NOT EXISTS hmac_key varchar;
UPDATE organizations SET hmac_key = gen_random_uuid()::text WHERE hmac_key IS NULL;
CREATE TABLE IF NOT EXISTS payments (
id uuid DEFAULT gen_random_uuid() NOT NULL PRIMARY KEY,
organization_id uuid NOT NULL,
invoice_id uuid NOT NULL,
provider varchar NOT NULL,
provider_payment_id varchar,
provider_status varchar,
status varchar NOT NULL,
amount_cents bigint NOT NULL,
amount_currency varchar NOT NULL,
created_at timestamp(6) NOT NULL,
updated_at timestamp(6) NOT NULL
);
CREATE TABLE IF NOT EXISTS webhooks (
id uuid DEFAULT gen_random_uuid() NOT NULL PRIMARY KEY,
organization_id uuid NOT NULL,
webhook_type varchar NOT NULL,
object_type varchar NOT NULL,
endpoint varchar NOT NULL,
payload jsonb DEFAULT '{}' NOT NULL,
status varchar DEFAULT 'pending' NOT NULL,
http_status integer,
response text,
retries integer DEFAULT 0 NOT NULL,
last_retried_at timestamp(6),
created_at timestamp(6) NOT NULL,
updated_at timestamp(6) NOT NULL
);
CREATE INDEX IF NOT EXISTS index_webhooks_on_status ON webhooks (status);
CREATE TABLE IF NOT EXISTS webhook_endpoints (
id uuid DEFAULT gen_random_uuid() NOT NULL PRIMARY KEY,
organization_id uuid NOT NULL,
webhook_url varchar NOT NULL,
signature_algo varchar DEFAULT 'hmac' NOT NULL,
created_at timestamp(6) NOT NULL,
updated_at timestamp(6) NOT NULL
);