-- 006_relay_integration.sql -- Relay Financial integration — filing payment tracking and commission payouts. BEGIN; -- Track every payment made via the Relay card to state portals CREATE TABLE IF NOT EXISTS filing_payments ( id SERIAL PRIMARY KEY, formation_order_id INTEGER REFERENCES formation_orders(id), state_code CHAR(2) NOT NULL, amount_cents INTEGER NOT NULL, card_last4 TEXT NOT NULL, -- last 4 digits for reconciliation portal_confirmation TEXT, -- confirmation number from state portal relay_transaction_id TEXT, -- matched Relay/bank transaction (after reconciliation) reconciled BOOLEAN DEFAULT FALSE, reconciled_at TIMESTAMPTZ, notes TEXT, created_at TIMESTAMPTZ DEFAULT now() ); CREATE INDEX IF NOT EXISTS idx_filing_payments_order ON filing_payments(formation_order_id); CREATE INDEX IF NOT EXISTS idx_filing_payments_reconciled ON filing_payments(reconciled); -- Commission payouts to referral partners CREATE TABLE IF NOT EXISTS commission_payouts ( id SERIAL PRIMARY KEY, referral_partner TEXT NOT NULL, partner_email TEXT NOT NULL, amount_cents INTEGER NOT NULL, period_start DATE, -- payout period period_end DATE, order_count INTEGER DEFAULT 0, order_numbers TEXT[], -- array of order numbers included status TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'sent', 'confirmed')), sent_via TEXT DEFAULT 'relay_ach', -- 'relay_ach', 'check', 'wire' relay_transaction_id TEXT, approved_by TEXT, approved_at TIMESTAMPTZ, sent_at TIMESTAMPTZ, notes TEXT, created_at TIMESTAMPTZ DEFAULT now() ); CREATE INDEX IF NOT EXISTS idx_commission_payouts_partner ON commission_payouts(referral_partner); CREATE INDEX IF NOT EXISTS idx_commission_payouts_status ON commission_payouts(status); COMMIT;