/** * Billing bounded context (recurring billing engine) — Master Prompt * §6.10, docs/adr/0008-billing-finance-fiscal-separation.md. ADR-0008 is * explicit: Billing (this module) calculates *what is owed* and produces * an internal invoice; it is strictly separate from Finance/AR-AP * (collecting/paying — títulos, boletos, dunning, conciliação) and from * Fiscal (documento fiscal). Neither of those is built here. * * ADR-0008 lists nine Billing tables (billing_accounts, billing_cycles, * subscriptions/services, charge_components, usage_charges, invoices, * invoice_items, invoice_adjustments, billing_runs). This migration * builds the coherent MVP subset needed for a working, testable * subscription -> billing_run -> invoice flow: * * - billing_subscriptions (this migration) * - billing_runs (this migration) * - invoices (this migration) * - invoice_items (this migration) * * Explicitly DEFERRED, not forgotten: * - billing_accounts — this MVP hangs subscriptions/invoices directly * off `reseller_id`; a billing_account (grouping multiple subscriptions * under one consolidated bill) is deferred until there's a real need * to bill more than one subscription together. * - billing_cycles as its own table — this MVP derives the cycle from * the (billing_day, reference_year, reference_month) triple on the * run/subscription rather than a calendar table of cycle instances. * - charge_components / usage_charges — consumption/telephony billing; * needs the usage-rating module (out of scope), so every subscription * in this MVP bills a single flat `monthly_value` with no metered * component. * - invoice_adjustments / credit_debit_adjustments — the sanctioned way * to correct a *consolidated* invoice (never a silent edit); deferred, * so today a consolidated billing_run's invoices are simply immutable * from the application layer (see billing.ts's assertRunIsMutable). * - billing_run_logs — this MVP uses the shared `audit_log` * (auditRepo.appendAuditEvent) for every billing_run/invoice mutation * instead of a dedicated structured log table. * - proration — every subscription always bills the full monthly_value; * no day-proportional calculation for a subscription that started or * was cancelled mid-cycle. `invoice_items.item_type` already reserves * the 'proration' vocabulary value for when this lands, so it won't * need a migration of its own. * * Deferred cross-context foreign keys (no REFERENCES, plain UUID, same * pattern used by Quotes/Contracts/ClientRegistrations for tables owned by * a module built in a different worktree — see contracts' migration * header for precedent): * - billing_subscriptions.contract_id — `contracts` (Commercial/§6.6) is * not guaranteed to exist in every worktree this batch might land on. * - billing_subscriptions.reseller_id / invoices.reseller_id — * `resellers` is not present in THIS worktree's migration set either * (bootstrap-only checkout). Both FKs are integration work for * whoever merges this alongside the resellers/contracts migrations. */ exports.shorthands = undefined; exports.up = (pgm) => { pgm.sql(` -- ===================================================================== -- billing_subscriptions — a recurring billing subscription derived -- from an active contract -- ===================================================================== CREATE TABLE billing_subscriptions ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_by UUID REFERENCES users(id), updated_by UUID REFERENCES users(id), contract_id UUID NOT NULL, reseller_id UUID, monthly_value NUMERIC(14,2) NOT NULL CHECK (monthly_value >= 0), billing_day INTEGER NOT NULL CHECK (billing_day BETWEEN 1 AND 28), status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended', 'cancelled')), started_at TIMESTAMPTZ NOT NULL DEFAULT now(), cancelled_at TIMESTAMPTZ ); COMMENT ON TABLE billing_subscriptions IS 'Assinatura de cobrança recorrente derivada de um contrato ativo (Master Prompt §6.10). contract_id e reseller_id são UUID simples sem REFERENCES — mesmo padrão de FK cruzada adiada de Quotes/Contracts/ClientRegistrations: contracts/resellers não existem garantidamente neste worktree (checkout de bootstrap). A FK real é trabalho de integração central, não desta migration.'; COMMENT ON COLUMN billing_subscriptions.monthly_value IS 'Snapshot do valor mensal no momento da criação da subscription — NUNCA recalculado automaticamente se o contrato de origem mudar depois (isso seria uma reversão silenciosa de fatura, proibida pelo Master Prompt §24 invariante nº4). Uma mudança de valor exige cancelar e recriar a subscription (ou, quando existir, um endpoint explícito de reajuste) — nesta leva não há reajuste, só criação/cancelamento.'; COMMENT ON COLUMN billing_subscriptions.billing_day IS 'Dia do mês do ciclo de cobrança, limitado a 1-28 deliberadamente para nunca cair em um mês sem esse dia (evita a ambiguidade de dia 29-31 em fevereiro/meses de 30 dias) — não há regra de "último dia do mês" nesta leva.'; COMMENT ON COLUMN billing_subscriptions.cancelled_at IS 'Setado uma única vez, quando status transiciona para cancelled (camada de repositório) — nunca sobrescrito depois.'; CREATE INDEX idx_billing_subscriptions_reseller ON billing_subscriptions(reseller_id); CREATE INDEX idx_billing_subscriptions_status_day ON billing_subscriptions(status, billing_day); CREATE INDEX idx_billing_subscriptions_contract ON billing_subscriptions(contract_id); CREATE TRIGGER trg_billing_subscriptions_updated_at BEFORE UPDATE ON billing_subscriptions FOR EACH ROW EXECUTE FUNCTION set_updated_at(); -- ===================================================================== -- billing_runs — one billing-close execution for a -- (reference_year, reference_month, billing_day) period -- ===================================================================== CREATE TABLE billing_runs ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), reference_year INTEGER NOT NULL CHECK (reference_year BETWEEN 2000 AND 2100), reference_month INTEGER NOT NULL CHECK (reference_month BETWEEN 1 AND 12), billing_day INTEGER NOT NULL CHECK (billing_day BETWEEN 1 AND 28), status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'consolidated', 'failed')), consolidated_at TIMESTAMPTZ, triggered_by UUID REFERENCES users(id), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); COMMENT ON TABLE billing_runs IS 'Execução de fechamento de billing para um período + billing_day (Master Prompt §6.10). draft é reexecutável: rodar de novo com os mesmos (reference_year, reference_month, billing_day) sobre um run ainda draft SUBSTITUI (delete+reinsert, mesma transação) as invoices geradas em vez de duplicar — implementado em packages/database/src/repositories/billing.ts, generateOrRegenerateBillingRun(). consolidated é terminal e imutável pela aplicação (ver invoices.status e assertRunIsMutable). failed é reservado para quando esta leva ganhar um passo que possa falhar de forma parcial (ex. rating de consumo) — nada nesta leva efetivamente produz failed.'; COMMENT ON COLUMN billing_runs.triggered_by IS 'Ator (usuário) que disparou a criação/regeneração deste run — atualizado a cada regeneração em draft para refletir quem rodou por último.'; CREATE INDEX idx_billing_runs_period ON billing_runs(reference_year, reference_month, billing_day); -- Idempotência: no máximo um run 'draft' por (ano, mês, billing_day) — -- índice único parcial em vez de UNIQUE(reference_year, reference_month, -- billing_day, status) puro, porque este último permitiria dois runs -- 'consolidated' distintos para o mesmo período sem impedir a corrida -- de dois 'draft' concorrentes ao mesmo tempo (o problema real que essa -- invariante precisa resolver). A regra "não criar novo run para um -- período já consolidado" (refaturamento controlado é deferido) é -- reforçada na camada de aplicação, não aqui, porque múltiplos runs -- 'consolidated' históricos para o mesmo período não são logicamente -- impossíveis no schema (só indesejados pelo fluxo atual). CREATE UNIQUE INDEX uq_billing_runs_one_draft_per_period ON billing_runs(reference_year, reference_month, billing_day) WHERE status = 'draft'; -- ===================================================================== -- invoices — internal invoice generated by a billing_run for one -- billing_subscription -- ===================================================================== CREATE TABLE invoices ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), billing_run_id UUID NOT NULL REFERENCES billing_runs(id) ON DELETE CASCADE, billing_subscription_id UUID NOT NULL REFERENCES billing_subscriptions(id), reseller_id UUID, amount NUMERIC(14,2) NOT NULL CHECK (amount >= 0), reference_year INTEGER NOT NULL, reference_month INTEGER NOT NULL CHECK (reference_month BETWEEN 1 AND 12), status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'consolidated', 'cancelled')), due_date DATE, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), UNIQUE (billing_run_id, billing_subscription_id) ); COMMENT ON TABLE invoices IS 'Fatura interna (Billing) gerada por um billing_run — DISTINTA de um título de AR/AP (Finance) e de um documento fiscal (Fiscal), ADR-0008. status espelha o status do run no momento da geração (draft -> pode ser apagada/regerada enquanto o run ainda é draft; consolidated -> imutável pela aplicação, ver invariante em billing.ts). UNIQUE(billing_run_id, billing_subscription_id) é uma segunda barreira de idempotência a nível de banco: o mesmo run nunca pode gerar duas invoices para a mesma subscription.'; COMMENT ON COLUMN invoices.reseller_id IS 'Denormalizado a partir de billing_subscriptions.reseller_id no momento da geração — evita join obrigatório para filtrar por revenda em listagens/relatórios; nunca é a fonte da verdade (a subscription é). Sem REFERENCES pelo mesmo motivo de billing_subscriptions.reseller_id (ver cabeçalho da migration).'; COMMENT ON COLUMN invoices.due_date IS 'Nesta leva, due_date = dia billing_day do mês de referência (reference_year/reference_month) — regra de vencimento mais sofisticada (ex. carência após o fechamento) é responsabilidade do módulo Finance/AR-AP (ADR-0008), fora de escopo aqui.'; CREATE INDEX idx_invoices_run ON invoices(billing_run_id); CREATE INDEX idx_invoices_subscription ON invoices(billing_subscription_id); CREATE INDEX idx_invoices_reseller_status ON invoices(reseller_id, status); CREATE INDEX idx_invoices_period ON invoices(reference_year, reference_month); -- ===================================================================== -- invoice_items — invoice line items (generic vocabulary; this MVP -- only ever generates 'recurring' automatically) -- ===================================================================== CREATE TABLE invoice_items ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), invoice_id UUID NOT NULL REFERENCES invoices(id) ON DELETE CASCADE, description TEXT NOT NULL, amount NUMERIC(14,2) NOT NULL, item_type TEXT NOT NULL CHECK (item_type IN ('recurring', 'proration', 'implementation', 'adjustment')), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); COMMENT ON TABLE invoice_items IS 'Linhas da fatura, modeladas de forma genérica para não exigir migration nova quando proration/implementation/adjustment passarem a ser gerados automaticamente — nesta leva, a camada de aplicação só cria itens item_type=recurring (um por invoice, espelhando billing_subscriptions.monthly_value no momento da geração do run).'; CREATE INDEX idx_invoice_items_invoice ON invoice_items(invoice_id); `); }; exports.down = (pgm) => { pgm.sql(` DROP TABLE IF EXISTS invoice_items; DROP TABLE IF EXISTS invoices; DROP TABLE IF EXISTS billing_runs; DROP TABLE IF EXISTS billing_subscriptions; `); };