Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(accounting): period closing, budgeting, bank reconciliation (#1013)

Brad Barbin750ef6069f8d
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 95f87f107f..e4a62e01b4 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -46,6 +46,16 @@ Format: `Context → Problem → Rule → Applies to`
**Applies to:** All forms in `apps/erp/app/routes/`, `packages/form/`.
+## Posting-group-style matrices are a rejected pattern
+
+**Context:** Designing multi-jurisdiction tax determination; the spec anchored on the customerType × itemPostingGroup posting-group matrix as "Carbon precedent."
+
+**Problem:** The posting-group matrix was deliberately REMOVED (`20260229000000_drop-posting-groups.sql`) because the indirection was confusing — but the 2023 creation migration still exists, so searches find it first and it masquerades as live precedent. Anchoring a new design on it resurrects a pattern the project already rejected.
+
+**Rule:** Do not design N×M classification-matrix configuration (party-group × item-group → outcome). Prefer flat company defaults (`accountDefault`) plus direct per-entity assignment with per-child override (the Xero model). Before citing any schema "precedent," grep for a later `DROP`/rename migration.
+
+**Applies to:** New config/settings design anywhere; accounting/tax/posting; `.ai/specs/`, `packages/database/supabase/migrations/`.
+
## Backdated migration timestamps break remote deploys
**Context:** CI `supabase db push --include-all` failed on all remotes with `column pi.balance does not exist` while applying `20260616061244`, which recreated the `purchaseInvoices` view.
diff --git a/.ai/plans/2026-07-02-bank-reconciliation-phase-1.md b/.ai/plans/2026-07-02-bank-reconciliation-phase-1.md
new file mode 100644
index 0000000000..0fb4761098
--- /dev/null
+++ b/.ai/plans/2026-07-02-bank-reconciliation-phase-1.md
@@ -0,0 +1,2178 @@
+# Bank Reconciliation — Phase 1 (Foundations) Implementation Plan
+
+> ⚠️ **2026-07-03 delta (readiness roadmap):** `journalLine.sourceAmount`/`sourceCurrencyCode` population is now **mandatory on every posting path** (base-currency documents write base amount + base code), not best-effort — see the spec's FX section and `.ai/plans/2026-07-03-public-company-readiness-roadmap.md`. The posting-path tasks in this plan must cover all `post-*` edge functions and app-side posters.
+
+## Overview
+
+- **Design Spec:** `.ai/specs/2026-07-02-bank-reconciliation.md` (status: in-progress; all open questions resolved)
+- **Research:** `.ai/research/bank-reconciliation.md`
+- **Scope:** Phase 1 only — schema (incl. `journalLine` FX columns), bank accounts, CSV + OFX statement import, deterministic matching + N:M match groups, reconcile workspace, close-out with optional approval workflow, on-demand PDF report. Plaid (Phase 2), BAI2/MT940/CAMT.053 + rules engine + auto-match tolerance (Phase 3), intelligence (Phase 4) are out.
+- **Tasks:** 24 tasks ≈ 2 hours of focused execution
+- **Branch:** `period-closing-spec` (shared with the period-close work per Brad's call, 2026-07-02 — coordinate edits to `accounting.service.ts` / `types.ts` / `path.ts` with that workstream)
+
+### Execution notes (read before Task 1)
+
+1. **Generated DB types**: `pnpm db:migrate` regenerates types locally — fine for local typechecking, but **do not commit the regenerated types file** (committed types come from the cloud DB; a local regen produces a huge divergent per-company diff — see project memory). Before the PR merges, Brad applies the migration to the cloud dev DB and regenerates the committed types. All service code below assumes typed tables exist locally.
+2. **Plan deviations from the spec** (confirm at approval; Task 24 syncs the spec):
+ - **PDF is rendered on-demand** via a `file+` route (`renderToStream`, the `sales-invoice` precedent) instead of generated-and-stored at completion. Completed reconciliations are immutable, so on-demand output is identical with far less machinery. The `reportDocumentPath` column is dropped.
+ - **Tolerance** ships in Phase 1 for **manual** match groups only (per Phase 1 acceptance criteria); the auto-match tolerance layer stays in Phase 3 (per the phasing table — the spec is internally ambiguous here).
+ - **Reference agreement in auto-match is dropped from the RPC**: `journalLine` has no structured reference column, so reference matching would be description-fuzzing. Auto-match = exact amount + ±7d + unique candidate. Reference/description similarity returns as a *suggestion* ranker in Phase 4.
+3. **PK style**: single-column PKs + `companyId` FK + RLS, matching `payment`/`memo`/`invoiceSettlement` (2026-06-30) — the spec's accepted design decision. This intentionally deviates from the composite-PK line in `workflow-database-migration.md` per its own "newest migration wins" rule.
+4. **Audit**: event-system driven in Carbon (no imperative audit inserts). Who/when columns (`createdBy`, `completedBy`, `submittedBy`, `voidedBy`, `matchType`) capture the trail in v1.
+5. **Never** run whole-project `tsc --noEmit` (OOM). Use `pnpm run typecheck` (turbo, per-package).
+
+### Dependencies
+
+```
+T1 (migration) ─▶ T2 (apply) ─▶ T3 (models) ─▶ T4 (types) ─▶ T5..T10 (services, parallelizable)
+T2 ─▶ T11 (sourceAmount in post-payment) T2 ─▶ T12..T14 (edge function)
+T3 ─▶ T15 (paths/sidebar) ─▶ T16..T22 (routes/UI; 16-18 ∥ 19-21 ∥ 22)
+T5..T14 ─▶ T19..T22 T23 (settings UI) after T3 T24 (verify + sync) last
+```
+
+---
+
+## Task 1: Branch + migration
+
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_bank-reconciliation.sql`
+
+**Steps:**
+
+1. Create the migration file on the current `period-closing-spec` branch (HHMMSS must not be `000000` — the CLI stamps the real time):
+ ```bash
+ pnpm db:migrate:new bank-reconciliation
+ # Expected: Created new migration at supabase/migrations/<ts>_bank-reconciliation.sql
+ ```
+
+2. Write the migration (full contents):
+
+ ```sql
+ -- Bank Reconciliation Phase 1
+ -- Spec: .ai/specs/2026-07-02-bank-reconciliation.md
+
+ DO $$ BEGIN
+ CREATE TYPE "bankAccountType" AS ENUM ('Checking', 'Savings', 'Credit Card', 'Other');
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+ DO $$ BEGIN
+ CREATE TYPE "bankAccountSource" AS ENUM ('Manual', 'Plaid');
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+ DO $$ BEGIN
+ CREATE TYPE "bankConnectionStatus" AS ENUM ('Connected', 'Requires Reauth', 'Error');
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+ DO $$ BEGIN
+ CREATE TYPE "bankTransactionSource" AS ENUM ('Plaid', 'Import');
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+ DO $$ BEGIN
+ CREATE TYPE "bankTransactionStatus" AS ENUM ('Pending', 'Unmatched', 'Matched', 'Excluded', 'Reconciled');
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+ DO $$ BEGIN
+ CREATE TYPE "bankMatchType" AS ENUM ('Auto', 'Rule', 'Manual');
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+ DO $$ BEGIN
+ CREATE TYPE "bankStatementFormat" AS ENUM ('CSV', 'OFX', 'BAI2', 'MT940', 'CAMT053');
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+ DO $$ BEGIN
+ CREATE TYPE "bankReconciliationStatus" AS ENUM ('Draft', 'In Review', 'Completed', 'Voided');
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+ -- FX groundwork: source-currency amounts on journal lines (additive, nullable)
+ ALTER TABLE "journalLine"
+ ADD COLUMN IF NOT EXISTS "sourceAmount" NUMERIC,
+ ADD COLUMN IF NOT EXISTS "sourceCurrencyCode" TEXT REFERENCES "currencyCode"("code");
+
+ CREATE TABLE IF NOT EXISTS "bankAccount" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('bka'),
+ "name" TEXT NOT NULL,
+ "bankName" TEXT,
+ "accountNumberLastFour" TEXT,
+ "type" "bankAccountType" NOT NULL DEFAULT 'Checking',
+ "currencyCode" TEXT NOT NULL REFERENCES "currencyCode"("code"),
+ "glAccountId" TEXT NOT NULL REFERENCES "account"("id") ON DELETE RESTRICT,
+ "openingBalance" NUMERIC NOT NULL DEFAULT 0,
+ "openingDate" DATE,
+ "source" "bankAccountSource" NOT NULL DEFAULT 'Manual',
+ "plaidItemId" TEXT,
+ "plaidAccountId" TEXT,
+ "connectionStatus" "bankConnectionStatus",
+ "lastSyncedAt" TIMESTAMP WITH TIME ZONE,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB
+ );
+ CREATE UNIQUE INDEX IF NOT EXISTS "bankAccount_glAccount_idx" ON "bankAccount" ("glAccountId", "companyId");
+ CREATE UNIQUE INDEX IF NOT EXISTS "bankAccount_plaid_idx" ON "bankAccount" ("plaidAccountId", "companyId") WHERE "plaidAccountId" IS NOT NULL;
+ CREATE INDEX IF NOT EXISTS "bankAccount_companyId_idx" ON "bankAccount" ("companyId");
+ CREATE INDEX IF NOT EXISTS "bankAccount_createdBy_idx" ON "bankAccount" ("createdBy");
+
+ CREATE TABLE IF NOT EXISTS "bankStatementImport" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('bsi'),
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "fileName" TEXT NOT NULL,
+ "filePath" TEXT NOT NULL,
+ "format" "bankStatementFormat" NOT NULL,
+ "status" TEXT NOT NULL DEFAULT 'Pending',
+ "error" TEXT,
+ "importedCount" INTEGER,
+ "duplicateCount" INTEGER,
+ "statementOpeningBalance" NUMERIC,
+ "statementEndingBalance" NUMERIC,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+ );
+ CREATE INDEX IF NOT EXISTS "bankStatementImport_bankAccountId_idx" ON "bankStatementImport" ("bankAccountId");
+ CREATE INDEX IF NOT EXISTS "bankStatementImport_companyId_idx" ON "bankStatementImport" ("companyId");
+ CREATE INDEX IF NOT EXISTS "bankStatementImport_createdBy_idx" ON "bankStatementImport" ("createdBy");
+
+ CREATE TABLE IF NOT EXISTS "bankReconciliation" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('brc'),
+ "reconciliationId" TEXT NOT NULL,
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "statementDate" DATE NOT NULL,
+ "startingBalance" NUMERIC NOT NULL,
+ "statementEndingBalance" NUMERIC NOT NULL,
+ "status" "bankReconciliationStatus" NOT NULL DEFAULT 'Draft',
+ "notes" TEXT,
+ "submittedAt" TIMESTAMP WITH TIME ZONE,
+ "submittedBy" TEXT REFERENCES "user"("id"),
+ "completedAt" TIMESTAMP WITH TIME ZONE,
+ "completedBy" TEXT REFERENCES "user"("id"),
+ "voidedAt" TIMESTAMP WITH TIME ZONE,
+ "voidedBy" TEXT REFERENCES "user"("id"),
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE
+ );
+ CREATE UNIQUE INDEX IF NOT EXISTS "bankReconciliation_statement_idx"
+ ON "bankReconciliation" ("bankAccountId", "statementDate") WHERE "status" <> 'Voided';
+ CREATE UNIQUE INDEX IF NOT EXISTS "bankReconciliation_readable_idx"
+ ON "bankReconciliation" ("reconciliationId", "companyId");
+ CREATE INDEX IF NOT EXISTS "bankReconciliation_companyId_idx" ON "bankReconciliation" ("companyId");
+ CREATE INDEX IF NOT EXISTS "bankReconciliation_bankAccountId_idx" ON "bankReconciliation" ("bankAccountId");
+
+ CREATE TABLE IF NOT EXISTS "bankTransaction" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('btx'),
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "transactionDate" DATE NOT NULL,
+ "amount" NUMERIC NOT NULL,
+ "description" TEXT NOT NULL,
+ "counterparty" TEXT,
+ "reference" TEXT,
+ "externalId" TEXT NOT NULL,
+ "pendingExternalId" TEXT,
+ "source" "bankTransactionSource" NOT NULL,
+ "importId" TEXT REFERENCES "bankStatementImport"("id") ON DELETE SET NULL,
+ "status" "bankTransactionStatus" NOT NULL DEFAULT 'Unmatched',
+ "reconciliationId" TEXT REFERENCES "bankReconciliation"("id") ON DELETE SET NULL,
+ "needsReview" BOOLEAN NOT NULL DEFAULT FALSE,
+ "suggestion" JSONB,
+ "raw" JSONB,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE
+ );
+ CREATE UNIQUE INDEX IF NOT EXISTS "bankTransaction_external_idx" ON "bankTransaction" ("bankAccountId", "externalId");
+ CREATE INDEX IF NOT EXISTS "bankTransaction_account_status_idx" ON "bankTransaction" ("bankAccountId", "status", "transactionDate");
+ CREATE INDEX IF NOT EXISTS "bankTransaction_companyId_idx" ON "bankTransaction" ("companyId");
+ CREATE INDEX IF NOT EXISTS "bankTransaction_reconciliationId_idx" ON "bankTransaction" ("reconciliationId");
+ CREATE INDEX IF NOT EXISTS "bankTransaction_importId_idx" ON "bankTransaction" ("importId");
+
+ CREATE TABLE IF NOT EXISTS "bankMatchGroup" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('bmg'),
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "matchType" "bankMatchType" NOT NULL DEFAULT 'Manual',
+ "toleranceJournalId" TEXT REFERENCES "journal"("id"),
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+ );
+ CREATE INDEX IF NOT EXISTS "bankMatchGroup_bankAccountId_idx" ON "bankMatchGroup" ("bankAccountId");
+ CREATE INDEX IF NOT EXISTS "bankMatchGroup_companyId_idx" ON "bankMatchGroup" ("companyId");
+ CREATE INDEX IF NOT EXISTS "bankMatchGroup_createdBy_idx" ON "bankMatchGroup" ("createdBy");
+
+ CREATE TABLE IF NOT EXISTS "bankMatchGroupTransaction" (
+ "groupId" TEXT NOT NULL REFERENCES "bankMatchGroup"("id") ON DELETE CASCADE,
+ "bankTransactionId" TEXT NOT NULL UNIQUE REFERENCES "bankTransaction"("id") ON DELETE CASCADE,
+ PRIMARY KEY ("groupId", "bankTransactionId")
+ );
+ CREATE TABLE IF NOT EXISTS "bankMatchGroupJournalLine" (
+ "groupId" TEXT NOT NULL REFERENCES "bankMatchGroup"("id") ON DELETE CASCADE,
+ "journalLineId" TEXT NOT NULL UNIQUE REFERENCES "journalLine"("id") ON DELETE RESTRICT,
+ PRIMARY KEY ("groupId", "journalLineId")
+ );
+
+ CREATE TABLE IF NOT EXISTS "bankAccountBalance" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT xid(),
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "date" DATE NOT NULL,
+ "balance" NUMERIC NOT NULL,
+ "source" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+ );
+ CREATE UNIQUE INDEX IF NOT EXISTS "bankAccountBalance_day_idx" ON "bankAccountBalance" ("bankAccountId", "date");
+ CREATE INDEX IF NOT EXISTS "bankAccountBalance_companyId_idx" ON "bankAccountBalance" ("companyId");
+
+ -- Settings + defaults
+ ALTER TABLE "companySettings"
+ ADD COLUMN IF NOT EXISTS "bankMatchToleranceAmount" NUMERIC NOT NULL DEFAULT 0,
+ ADD COLUMN IF NOT EXISTS "bankRecRequireApproval" BOOLEAN NOT NULL DEFAULT FALSE;
+ ALTER TABLE "accountDefault"
+ ADD COLUMN IF NOT EXISTS "bankFeesAccount" TEXT REFERENCES "account"("id");
+ -- Idempotent backfill so bankFeesAccount is never NULL (interestAccount is NOT NULL on accountDefault)
+ UPDATE "accountDefault" SET "bankFeesAccount" = "interestAccount" WHERE "bankFeesAccount" IS NULL;
+
+ -- Readable reconciliation ids
+ INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")
+ SELECT 'bankReconciliation', 'Bank Reconciliation', 'REC-%{yyyy}-%{mm}-', NULL, 0, 6, 1, c.id
+ FROM "company" c
+ ON CONFLICT DO NOTHING;
+
+ -- Matchable GL lines (posted lines on any account + their match state)
+ DROP VIEW IF EXISTS "bankMatchableJournalLine";
+ CREATE VIEW "bankMatchableJournalLine" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ jl."id",
+ jl."accountId",
+ jl."amount",
+ jl."sourceAmount",
+ jl."sourceCurrencyCode",
+ jl."description",
+ jl."companyId",
+ j."id" AS "journalId",
+ j."journalEntryId",
+ j."postingDate",
+ j."sourceType",
+ m."groupId"
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id" = jl."journalId"
+ LEFT JOIN "bankMatchGroupJournalLine" m ON m."journalLineId" = jl."id"
+ WHERE j."status" = 'Posted';
+
+ -- Bank accounts list view (GL account info + unmatched count)
+ DROP VIEW IF EXISTS "bankAccounts";
+ CREATE VIEW "bankAccounts" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ ba.*,
+ a."number" AS "glAccountNumber",
+ a."name" AS "glAccountName",
+ a."class" AS "glAccountClass",
+ (SELECT COUNT(*) FROM "bankTransaction" bt
+ WHERE bt."bankAccountId" = ba."id" AND bt."status" = 'Unmatched') AS "unmatchedCount",
+ (SELECT MAX(br."statementDate") FROM "bankReconciliation" br
+ WHERE br."bankAccountId" = ba."id" AND br."status" = 'Completed') AS "lastReconciledDate"
+ FROM "bankAccount" ba
+ JOIN "account" a ON a."id" = ba."glAccountId";
+
+ -- RLS
+ ALTER TABLE "bankAccount" ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE "bankStatementImport" ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE "bankReconciliation" ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE "bankTransaction" ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE "bankMatchGroup" ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE "bankMatchGroupTransaction" ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE "bankMatchGroupJournalLine" ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE "bankAccountBalance" ENABLE ROW LEVEL SECURITY;
+
+ DO $$
+ DECLARE t TEXT;
+ BEGIN
+ FOREACH t IN ARRAY ARRAY['bankAccount','bankStatementImport','bankReconciliation','bankTransaction','bankMatchGroup','bankAccountBalance']
+ LOOP
+ EXECUTE format('DROP POLICY IF EXISTS "SELECT" ON "public".%I', t);
+ EXECUTE format('CREATE POLICY "SELECT" ON "public".%I FOR SELECT USING ("companyId" = ANY (get_companies_with_employee_permission(''accounting_view'')::text[]))', t);
+ EXECUTE format('DROP POLICY IF EXISTS "INSERT" ON "public".%I', t);
+ EXECUTE format('CREATE POLICY "INSERT" ON "public".%I FOR INSERT WITH CHECK ("companyId" = ANY (get_companies_with_employee_permission(''accounting_create'')::text[]))', t);
+ EXECUTE format('DROP POLICY IF EXISTS "UPDATE" ON "public".%I', t);
+ EXECUTE format('CREATE POLICY "UPDATE" ON "public".%I FOR UPDATE USING ("companyId" = ANY (get_companies_with_employee_permission(''accounting_update'')::text[]))', t);
+ EXECUTE format('DROP POLICY IF EXISTS "DELETE" ON "public".%I', t);
+ EXECUTE format('CREATE POLICY "DELETE" ON "public".%I FOR DELETE USING ("companyId" = ANY (get_companies_with_employee_permission(''accounting_delete'')::text[]))', t);
+ END LOOP;
+ END $$;
+
+ -- Membership tables have no companyId: scope through the parent group
+ DROP POLICY IF EXISTS "SELECT" ON "public"."bankMatchGroupTransaction";
+ CREATE POLICY "SELECT" ON "public"."bankMatchGroupTransaction" FOR SELECT USING (
+ EXISTS (SELECT 1 FROM "bankMatchGroup" g WHERE g."id" = "groupId"
+ AND g."companyId" = ANY (get_companies_with_employee_permission('accounting_view')::text[]))
+ );
+ DROP POLICY IF EXISTS "INSERT" ON "public"."bankMatchGroupTransaction";
+ CREATE POLICY "INSERT" ON "public"."bankMatchGroupTransaction" FOR INSERT WITH CHECK (
+ EXISTS (SELECT 1 FROM "bankMatchGroup" g WHERE g."id" = "groupId"
+ AND g."companyId" = ANY (get_companies_with_employee_permission('accounting_create')::text[]))
+ );
+ DROP POLICY IF EXISTS "DELETE" ON "public"."bankMatchGroupTransaction";
+ CREATE POLICY "DELETE" ON "public"."bankMatchGroupTransaction" FOR DELETE USING (
+ EXISTS (SELECT 1 FROM "bankMatchGroup" g WHERE g."id" = "groupId"
+ AND g."companyId" = ANY (get_companies_with_employee_permission('accounting_delete')::text[]))
+ );
+ -- Same three policies for bankMatchGroupJournalLine (identical bodies, table name swapped)
+ DROP POLICY IF EXISTS "SELECT" ON "public"."bankMatchGroupJournalLine";
+ CREATE POLICY "SELECT" ON "public"."bankMatchGroupJournalLine" FOR SELECT USING (
+ EXISTS (SELECT 1 FROM "bankMatchGroup" g WHERE g."id" = "groupId"
+ AND g."companyId" = ANY (get_companies_with_employee_permission('accounting_view')::text[]))
+ );
+ DROP POLICY IF EXISTS "INSERT" ON "public"."bankMatchGroupJournalLine";
+ CREATE POLICY "INSERT" ON "public"."bankMatchGroupJournalLine" FOR INSERT WITH CHECK (
+ EXISTS (SELECT 1 FROM "bankMatchGroup" g WHERE g."id" = "groupId"
+ AND g."companyId" = ANY (get_companies_with_employee_permission('accounting_create')::text[]))
+ );
+ DROP POLICY IF EXISTS "DELETE" ON "public"."bankMatchGroupJournalLine";
+ CREATE POLICY "DELETE" ON "public"."bankMatchGroupJournalLine" FOR DELETE USING (
+ EXISTS (SELECT 1 FROM "bankMatchGroup" g WHERE g."id" = "groupId"
+ AND g."companyId" = ANY (get_companies_with_employee_permission('accounting_delete')::text[]))
+ );
+
+ -- Deterministic auto-match core: exact amount + ±7 days + exactly one candidate.
+ -- SECURITY INVOKER: RLS applies for app users; service role bypasses.
+ CREATE OR REPLACE FUNCTION run_bank_matching(bank_account_id TEXT, company_id TEXT, user_id TEXT)
+ RETURNS INTEGER
+ LANGUAGE plpgsql
+ AS $$
+ DECLARE
+ v_gl_account TEXT;
+ v_currency TEXT;
+ v_class TEXT;
+ v_base_currency TEXT;
+ v_sign NUMERIC;
+ v_is_base BOOLEAN;
+ v_matched INTEGER := 0;
+ r RECORD;
+ v_count INTEGER;
+ v_line_id TEXT;
+ v_group_id TEXT;
+ BEGIN
+ SELECT ba."glAccountId", ba."currencyCode", a."class"::text
+ INTO v_gl_account, v_currency, v_class
+ FROM "bankAccount" ba JOIN "account" a ON a."id" = ba."glAccountId"
+ WHERE ba."id" = bank_account_id AND ba."companyId" = company_id;
+ IF v_gl_account IS NULL THEN
+ RAISE EXCEPTION 'Bank account % not found', bank_account_id;
+ END IF;
+
+ SELECT c."code" INTO v_base_currency
+ FROM "currency" c
+ WHERE c."isBaseCurrency" = TRUE
+ AND c."companyGroupId" = (SELECT "companyGroupId" FROM "company" WHERE "id" = company_id);
+
+ v_is_base := (v_currency = v_base_currency);
+ v_sign := CASE WHEN v_class = 'Liability' THEN -1 ELSE 1 END;
+
+ FOR r IN
+ SELECT "id", "amount", "transactionDate"
+ FROM "bankTransaction"
+ WHERE "bankAccountId" = bank_account_id
+ AND "companyId" = company_id
+ AND "status" = 'Unmatched'
+ LOOP
+ SELECT COUNT(*)::int, (array_agg(v."id"))[1]
+ INTO v_count, v_line_id
+ FROM "bankMatchableJournalLine" v
+ WHERE v."accountId" = v_gl_account
+ AND v."companyId" = company_id
+ AND v."groupId" IS NULL
+ AND v."postingDate" BETWEEN r."transactionDate" - 7 AND r."transactionDate" + 7
+ AND (
+ (v_is_base AND v."amount" = v_sign * r."amount")
+ OR (NOT v_is_base AND v."sourceCurrencyCode" = v_currency AND v."sourceAmount" = v_sign * r."amount")
+ );
+
+ IF v_count = 1 THEN
+ INSERT INTO "bankMatchGroup" ("bankAccountId", "matchType", "companyId", "createdBy")
+ VALUES (bank_account_id, 'Auto', company_id, user_id)
+ RETURNING "id" INTO v_group_id;
+ INSERT INTO "bankMatchGroupTransaction" ("groupId", "bankTransactionId") VALUES (v_group_id, r."id");
+ INSERT INTO "bankMatchGroupJournalLine" ("groupId", "journalLineId") VALUES (v_group_id, v_line_id);
+ UPDATE "bankTransaction" SET "status" = 'Matched' WHERE "id" = r."id";
+ v_matched := v_matched + 1;
+ END IF;
+ END LOOP;
+
+ RETURN v_matched;
+ END;
+ $$;
+ ```
+
+3. Commit:
+ ```bash
+ git add packages/database/supabase/migrations/ && git commit -m "feat(accounting): bank reconciliation schema + matching RPC
+
+ Tracking spec: .ai/specs/2026-07-02-bank-reconciliation.md
+
+ Co-Authored-By: Claude Fable 5 <[email protected]>"
+ ```
+
+---
+
+## Task 2: Apply migration locally + verify
+
+**Steps:**
+
+1. ```bash
+ pnpm db:migrate
+ # Expected: applies <ts>_bank-reconciliation.sql, regenerates local types
+ ```
+2. Verify (use the `PORT_DB` from `.env.local`):
+ ```bash
+ psql "postgresql://postgres:[email protected]:$(grep PORT_DB .env.local | cut -d= -f2)/postgres" \
+ -c '\d "bankTransaction"' -c "SELECT run_bank_matching('nope','nope','nope');" 2>&1 | head -30
+ # Expected: table description, then ERROR: Bank account nope not found (function exists + guards)
+ ```
+3. Idempotency: re-run the file directly — must apply cleanly twice:
+ ```bash
+ psql "<same conn>" -f packages/database/supabase/migrations/<ts>_bank-reconciliation.sql
+ # Expected: no errors (IF NOT EXISTS / OR REPLACE / ON CONFLICT guards hold)
+ ```
+4. **Do NOT commit** the regenerated `@carbon/database` types diff (cloud-generated; see Execution notes).
+
+---
+
+## Task 3: Zod validators + enum arrays
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts`
+
+**Steps:**
+
+1. Add at the end of the file (imports `z`/`zfd` already present):
+
+ ```typescript
+ export const bankAccountTypes = ["Checking", "Savings", "Credit Card", "Other"] as const;
+ export const bankTransactionStatuses = ["Pending", "Unmatched", "Matched", "Excluded", "Reconciled"] as const;
+ export const bankReconciliationStatuses = ["Draft", "In Review", "Completed", "Voided"] as const;
+ export const bankStatementFormats = ["CSV", "OFX"] as const; // Phase 3 adds BAI2/MT940/CAMT053
+
+ export const bankAccountValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ bankName: zfd.text(z.string().optional()),
+ accountNumberLastFour: zfd.text(z.string().max(4).optional()),
+ type: z.enum(bankAccountTypes, {
+ errorMap: () => ({ message: "Type is required" }),
+ }),
+ currencyCode: z.string().min(1, { message: "Currency is required" }),
+ glAccountId: z.string().min(1, { message: "GL account is required" }),
+ openingBalance: zfd.numeric(z.number()),
+ openingDate: zfd.text(z.string().optional()),
+ });
+
+ export const bankStatementUploadValidator = z.object({
+ bankAccountId: z.string().min(1),
+ filePath: z.string().min(1, { message: "Upload a file first" }),
+ fileName: z.string().min(1),
+ format: z.enum(bankStatementFormats),
+ columnMappings: zfd.text(z.string().optional()), // JSON: CSV header -> field
+ });
+
+ export const bankMatchValidator = z.object({
+ bankTransactionIds: z.array(z.string().min(1)).min(1, { message: "Select a bank line" }),
+ journalLineIds: z.array(z.string().min(1)).min(1, { message: "Select a GL line" }),
+ });
+
+ export const bankQuickJournalValidator = z.object({
+ bankTransactionId: z.string().min(1),
+ accountId: z.string().min(1, { message: "Account is required" }),
+ memo: zfd.text(z.string().optional()),
+ });
+
+ export const bankReconciliationValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ bankAccountId: z.string().min(1),
+ statementDate: z.string().min(1, { message: "Statement date is required" }),
+ statementEndingBalance: zfd.numeric(z.number()),
+ notes: zfd.text(z.string().optional()),
+ });
+ ```
+
+2. Verify + commit:
+ ```bash
+ pnpm --filter erp exec tsc --noEmit -p . 2>/dev/null || pnpm run typecheck --filter=erp
+ # Expected: no new errors in accounting.models.ts
+ git add apps/erp/app/modules/accounting/accounting.models.ts && git commit -m "feat(accounting): bank reconciliation validators
+
+ Co-Authored-By: Claude Fable 5 <[email protected]>"
+ ```
+
+---
+
+## Task 4: Derived types
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/types.ts`
+
+**Steps:**
+
+1. Add (after the existing `Awaited<ReturnType<...>>` types; service functions arrive in Tasks 5–9 — write these now, they compile once services exist; execute Task 4 after Task 9 if strict ordering is preferred):
+
+ ```typescript
+ import type {
+ getBankAccounts,
+ getBankTransactions,
+ getBankReconciliations,
+ getMatchCandidates,
+ } from "./accounting.service";
+
+ export type BankAccount = NonNullable<
+ Awaited<ReturnType<typeof getBankAccounts>>["data"]
+ >[number];
+ export type BankTransaction = NonNullable<
+ Awaited<ReturnType<typeof getBankTransactions>>["data"]
+ >[number];
+ export type BankReconciliation = NonNullable<
+ Awaited<ReturnType<typeof getBankReconciliations>>["data"]
+ >[number];
+ export type BankMatchCandidate = NonNullable<
+ Awaited<ReturnType<typeof getMatchCandidates>>["data"]
+ >[number];
+ ```
+
+2. Commit with Task 9.
+
+---
+
+## Task 5: Bank account services
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` (append; barrel `index.ts` already re-exports `*` from the service — verify, else add exports)
+
+**Steps:**
+
+1. Append:
+
+ ```typescript
+ export async function getBankAccounts(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: GenericQueryFilters & { search: string | null }
+ ) {
+ let query = client
+ .from("bankAccounts") // view: + glAccountNumber/Name/Class, unmatchedCount, lastReconciledDate
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
+ if (args?.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+ if (args) {
+ query = setGenericQueryFilters(query, args, [{ column: "name", ascending: true }]);
+ }
+ return query;
+ }
+
+ export async function getBankAccount(client: SupabaseClient<Database>, id: string) {
+ return client.from("bankAccounts").select("*").eq("id", id).single();
+ }
+
+ export async function upsertBankAccount(
+ client: SupabaseClient<Database>,
+ bankAccount:
+ | (Omit<z.infer<typeof bankAccountValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof bankAccountValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+ ) {
+ // Validate GL account class/type per bank type (spec: Bank/Cash asset, or Liability for Credit Card)
+ const account = await client
+ .from("account")
+ .select("id, class, accountType")
+ .eq("id", bankAccount.glAccountId)
+ .single();
+ if (account.error || !account.data) {
+ return { data: null, error: { message: "GL account not found" } };
+ }
+ const isCard = bankAccount.type === "Credit Card";
+ const validGl = isCard
+ ? account.data.class === "Liability"
+ : ["Bank", "Cash"].includes(account.data.accountType ?? "");
+ if (!validGl) {
+ return {
+ data: null,
+ error: {
+ message: isCard
+ ? "Credit card accounts must link to a Liability GL account"
+ : "Bank accounts must link to a GL account with type Bank or Cash",
+ },
+ };
+ }
+
+ if ("createdBy" in bankAccount) {
+ return client.from("bankAccount").insert([bankAccount]).select("id").single();
+ }
+ return client
+ .from("bankAccount")
+ .update({ ...sanitize(bankAccount), updatedAt: today(getLocalTimeZone()).toString() })
+ .eq("id", bankAccount.id)
+ .select("id")
+ .single();
+ }
+
+ export async function deactivateBankAccount(
+ client: SupabaseClient<Database>,
+ { id, userId }: { id: string; userId: string }
+ ) {
+ return client
+ .from("bankAccount")
+ .update({ active: false, updatedBy: userId, updatedAt: today(getLocalTimeZone()).toString() })
+ .eq("id", id)
+ .select("id")
+ .single();
+ }
+ ```
+
+ Imports: `z` from `zod`, `bankAccountValidator` from `./accounting.models`, `Json` from `@carbon/database` — all already imported at the top of the service; add any missing.
+
+2. Commit:
+ ```bash
+ git add apps/erp/app/modules/accounting/ && git commit -m "feat(accounting): bank account services
+
+ Co-Authored-By: Claude Fable 5 <[email protected]>"
+ ```
+
+---
+
+## Task 6: Bank transaction services
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts`
+
+**Steps:**
+
+1. Append:
+
+ ```typescript
+ export async function getBankTransactions(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GenericQueryFilters & {
+ bankAccountId: string;
+ status: string | null;
+ search: string | null;
+ }
+ ) {
+ let query = client
+ .from("bankTransaction")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId)
+ .eq("bankAccountId", args.bankAccountId);
+ if (args.status) {
+ query = query.eq("status", args.status as Database["public"]["Enums"]["bankTransactionStatus"]);
+ }
+ if (args.search) {
+ query = query.ilike("description", `%${args.search}%`);
+ }
+ query = setGenericQueryFilters(query, args, [
+ { column: "transactionDate", ascending: false },
+ ]);
+ return query;
+ }
+
+ export async function excludeBankTransaction(
+ client: SupabaseClient<Database>,
+ { id, userId }: { id: string; userId: string }
+ ) {
+ return client
+ .from("bankTransaction")
+ .update({ status: "Excluded", updatedBy: userId, updatedAt: today(getLocalTimeZone()).toString() })
+ .eq("id", id)
+ .eq("status", "Unmatched")
+ .select("id")
+ .single();
+ }
+
+ export async function restoreBankTransaction(
+ client: SupabaseClient<Database>,
+ { id, userId }: { id: string; userId: string }
+ ) {
+ return client
+ .from("bankTransaction")
+ .update({ status: "Unmatched", updatedBy: userId, updatedAt: today(getLocalTimeZone()).toString() })
+ .eq("id", id)
+ .eq("status", "Excluded")
+ .select("id")
+ .single();
+ }
+
+ // Suggestion candidates: amount-equal (class/currency-normalized), ±30 days, unmatched, ranked by date proximity
+ export async function getMatchCandidates(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ bankTransactionId: string
+ ) {
+ const txn = await client
+ .from("bankTransaction")
+ .select("id, amount, transactionDate, bankAccountId")
+ .eq("id", bankTransactionId)
+ .single();
+ if (txn.error || !txn.data) return { data: null, error: txn.error };
+
+ const bankAccount = await client
+ .from("bankAccounts")
+ .select("glAccountId, currencyCode, glAccountClass")
+ .eq("id", txn.data.bankAccountId)
+ .single();
+ if (bankAccount.error || !bankAccount.data) return { data: null, error: bankAccount.error };
+
+ const base = await getBaseCurrency(client, companyId);
+ const isBase = bankAccount.data.currencyCode === base.data?.code;
+ const sign = bankAccount.data.glAccountClass === "Liability" ? -1 : 1;
+ const target = sign * txn.data.amount;
+
+ const from = dateAdd(txn.data.transactionDate, -30);
+ const to = dateAdd(txn.data.transactionDate, 30);
+ const lines = await client
+ .from("bankMatchableJournalLine")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("accountId", bankAccount.data.glAccountId)
+ .is("groupId", null)
+ .gte("postingDate", from)
+ .lte("postingDate", to)
+ .limit(200);
+ if (lines.error) return { data: null, error: lines.error };
+
+ const candidates = (lines.data ?? [])
+ .filter((l) =>
+ isBase
+ ? Number(l.amount) === target
+ : l.sourceCurrencyCode === bankAccount.data.currencyCode &&
+ Number(l.sourceAmount) === target
+ )
+ .sort(
+ (a, b) =>
+ Math.abs(daysBetween(a.postingDate!, txn.data.transactionDate)) -
+ Math.abs(daysBetween(b.postingDate!, txn.data.transactionDate))
+ );
+ return { data: candidates, error: null };
+ }
+ ```
+
+ Add two tiny local date helpers next to them (or reuse existing utils if present — grep `daysBetween` first):
+
+ ```typescript
+ function dateAdd(date: string, days: number): string {
+ const d = new Date(`${date}T00:00:00Z`);
+ d.setUTCDate(d.getUTCDate() + days);
+ return d.toISOString().slice(0, 10);
+ }
+ function daysBetween(a: string, b: string): number {
+ return Math.round(
+ (new Date(`${a}T00:00:00Z`).getTime() - new Date(`${b}T00:00:00Z`).getTime()) / 86400000
+ );
+ }
+ ```
+
+2. Commit (message: `feat(accounting): bank transaction services + match candidates`).
+
+---
+
+## Task 7: Match group create/delete (Kysely transactions)
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.server.ts`
+
+**Steps:**
+
+1. Append (imports of `Kysely`, `KyselyDatabase`, `sql` follow the existing header of this file — `postDepreciationRun` precedent):
+
+ ```typescript
+ export async function createBankMatchGroup(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ bankTransactionIds: string[];
+ journalLineIds: string[];
+ matchType?: "Auto" | "Rule" | "Manual";
+ // Pre-allocated when a tolerance JE may be needed (allocated by the route, Task 19):
+ toleranceJournal?: {
+ journalEntryId: string; // readable JE id from getNextSequence
+ accountingPeriodId: string;
+ bankFeesAccountId: string;
+ companyGroupId: string;
+ };
+ }
+ ) {
+ return db.transaction().execute(async (trx) => {
+ const txns = await trx
+ .selectFrom("bankTransaction")
+ .select(["id", "amount", "bankAccountId", "status", "transactionDate"])
+ .where("id", "in", args.bankTransactionIds)
+ .where("companyId", "=", args.companyId)
+ .execute();
+ if (txns.length !== args.bankTransactionIds.length)
+ throw new Error("Bank transaction not found");
+ if (txns.some((t) => t.status !== "Unmatched"))
+ throw new Error("Only unmatched bank lines can be matched");
+ const bankAccountId = txns[0]?.bankAccountId;
+ if (!bankAccountId || txns.some((t) => t.bankAccountId !== bankAccountId))
+ throw new Error("All bank lines must belong to the same bank account");
+
+ const account = await trx
+ .selectFrom("bankAccount")
+ .innerJoin("account", "account.id", "bankAccount.glAccountId")
+ .select(["bankAccount.glAccountId", "bankAccount.currencyCode", "account.class"])
+ .where("bankAccount.id", "=", bankAccountId)
+ .executeTakeFirstOrThrow();
+
+ const lines = await trx
+ .selectFrom("journalLine")
+ .innerJoin("journal", "journal.id", "journalLine.journalId")
+ .leftJoin("bankMatchGroupJournalLine as m", "m.journalLineId", "journalLine.id")
+ .select(["journalLine.id", "journalLine.amount", "journalLine.sourceAmount", "journalLine.sourceCurrencyCode"])
+ .where("journalLine.id", "in", args.journalLineIds)
+ .where("journalLine.companyId", "=", args.companyId)
+ .where("journalLine.accountId", "=", account.glAccountId)
+ .where("journal.status", "=", "Posted")
+ .where("m.journalLineId", "is", null)
+ .execute();
+ if (lines.length !== args.journalLineIds.length)
+ throw new Error("GL line not found, already matched, or not posted to this bank account");
+
+ const settings = await trx
+ .selectFrom("companySettings")
+ .select(["bankMatchToleranceAmount"])
+ .where("id", "=", args.companyId)
+ .executeTakeFirst();
+ const tolerance = Number(settings?.bankMatchToleranceAmount ?? 0);
+
+ const sign = account.class === "Liability" ? -1 : 1;
+ const bankSum = txns.reduce((s, t) => s + Number(t.amount), 0);
+ const glSum = lines.reduce((s, l) => s + sign * Number(l.amount), 0);
+ const difference = Number((bankSum - glSum).toFixed(6));
+
+ let toleranceJournalId: string | null = null;
+ if (difference !== 0) {
+ if (Math.abs(difference) > tolerance || !args.toleranceJournal) {
+ throw new Error(
+ `Selection does not balance: bank ${bankSum} vs GL ${glSum} (difference ${difference})`
+ );
+ }
+ // Book the difference: bank GL takes `difference` (inflow-signed), bankFees takes the offset.
+ const tj = args.toleranceJournal;
+ const journal = await trx
+ .insertInto("journal")
+ .values({
+ journalEntryId: tj.journalEntryId,
+ description: "Bank match tolerance adjustment",
+ postingDate: txns[0]!.transactionDate,
+ status: "Posted",
+ sourceType: "Manual",
+ accountingPeriodId: tj.accountingPeriodId,
+ postedAt: new Date().toISOString(),
+ postedBy: args.userId,
+ createdBy: args.userId,
+ companyId: args.companyId,
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ toleranceJournalId = journal.id;
+ // bank GL line (class-signed): Asset debit = +, Liability flips
+ await trx
+ .insertInto("journalLine")
+ .values([
+ {
+ journalId: journal.id,
+ accountId: account.glAccountId,
+ description: "Bank match tolerance adjustment",
+ amount: sign * difference,
+ companyId: args.companyId,
+ companyGroupId: tj.companyGroupId,
+ },
+ {
+ // bankFees is an Expense: positive = debit. Outflow difference (negative) = fee expense.
+ journalId: journal.id,
+ accountId: tj.bankFeesAccountId,
+ description: "Bank match tolerance adjustment",
+ amount: -difference,
+ companyId: args.companyId,
+ companyGroupId: tj.companyGroupId,
+ },
+ ])
+ .execute();
+ // The adjustment's bank-GL line joins the group so the group sums exactly
+ const adjLine = await trx
+ .selectFrom("journalLine")
+ .select("id")
+ .where("journalId", "=", journal.id)
+ .where("accountId", "=", account.glAccountId)
+ .executeTakeFirstOrThrow();
+ args.journalLineIds.push(adjLine.id);
+ }
+
+ const group = await trx
+ .insertInto("bankMatchGroup")
+ .values({
+ bankAccountId,
+ matchType: args.matchType ?? "Manual",
+ toleranceJournalId,
+ companyId: args.companyId,
+ createdBy: args.userId,
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("bankMatchGroupTransaction")
+ .values(args.bankTransactionIds.map((id) => ({ groupId: group.id, bankTransactionId: id })))
+ .execute();
+ await trx
+ .insertInto("bankMatchGroupJournalLine")
+ .values(args.journalLineIds.map((id) => ({ groupId: group.id, journalLineId: id })))
+ .execute();
+ await trx
+ .updateTable("bankTransaction")
+ .set({ status: "Matched", updatedBy: args.userId })
+ .where("id", "in", args.bankTransactionIds)
+ .execute();
+ return { groupId: group.id };
+ });
+ }
+
+ export async function deleteBankMatchGroup(
+ db: Kysely<KyselyDatabase>,
+ args: { companyId: string; userId: string; groupId: string }
+ ) {
+ return db.transaction().execute(async (trx) => {
+ const members = await trx
+ .selectFrom("bankMatchGroupTransaction")
+ .innerJoin("bankTransaction", "bankTransaction.id", "bankMatchGroupTransaction.bankTransactionId")
+ .select(["bankTransaction.id", "bankTransaction.status"])
+ .where("bankMatchGroupTransaction.groupId", "=", args.groupId)
+ .where("bankTransaction.companyId", "=", args.companyId)
+ .execute();
+ if (members.length === 0) throw new Error("Match group not found");
+ if (members.some((m) => m.status === "Reconciled"))
+ throw new Error("Cannot unmatch a reconciled line — void the reconciliation first");
+ await trx.deleteFrom("bankMatchGroup").where("id", "=", args.groupId).execute(); // memberships cascade
+ await trx
+ .updateTable("bankTransaction")
+ .set({ status: "Unmatched", updatedBy: args.userId })
+ .where("id", "in", members.map((m) => m.id))
+ .execute();
+ // Note: a tolerance JE, if any, stays posted; user reverses it via the journal UI if desired.
+ });
+ }
+ ```
+
+ Note: keep the small floating-point guard (`toFixed(6)`) — NUMERIC comes back as string from Kysely; `Number(...)` everywhere as shown.
+
+2. Commit (`feat(accounting): bank match group transactions`).
+
+---
+
+## Task 8: Quick-create JE from a bank line
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.server.ts`
+
+**Steps:**
+
+1. Append:
+
+ ```typescript
+ export async function createJournalEntryFromBankTransaction(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ companyGroupId: string;
+ userId: string;
+ bankTransactionId: string;
+ accountId: string; // offset account chosen by the user
+ memo?: string;
+ journalEntryId: string; // pre-allocated readable id (getNextSequence in the route)
+ accountingPeriodId: string; // pre-resolved (getOrCreateAccountingPeriod in the route)
+ }
+ ) {
+ return db.transaction().execute(async (trx) => {
+ const txn = await trx
+ .selectFrom("bankTransaction")
+ .select(["id", "amount", "transactionDate", "description", "bankAccountId", "status"])
+ .where("id", "=", args.bankTransactionId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirstOrThrow();
+ if (txn.status !== "Unmatched") throw new Error("Bank line is not unmatched");
+
+ const account = await trx
+ .selectFrom("bankAccount")
+ .innerJoin("account", "account.id", "bankAccount.glAccountId")
+ .select(["bankAccount.glAccountId", "account.class"])
+ .where("bankAccount.id", "=", txn.bankAccountId)
+ .executeTakeFirstOrThrow();
+ const offset = await trx
+ .selectFrom("account")
+ .select(["id", "class"])
+ .where("id", "=", args.accountId)
+ .executeTakeFirstOrThrow();
+
+ const description = args.memo || txn.description;
+ const journal = await trx
+ .insertInto("journal")
+ .values({
+ journalEntryId: args.journalEntryId,
+ description,
+ postingDate: txn.transactionDate,
+ status: "Posted",
+ sourceType: "Manual",
+ accountingPeriodId: args.accountingPeriodId,
+ postedAt: new Date().toISOString(),
+ postedBy: args.userId,
+ createdBy: args.userId,
+ companyId: args.companyId,
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+
+ const inflow = Number(txn.amount); // account currency == base (FX quick-create deferred; see step note)
+ const bankSign = account.class === "Liability" ? -1 : 1;
+ // Offset line: natural-balance signed for the offset account's class.
+ // Debit/credit space: bank debit = inflow. Offset takes the opposite side.
+ const offsetDebit = -inflow; // inflow>0 → offset is a credit; outflow → offset debit
+ const offsetAmount =
+ offset.class === "Asset" || offset.class === "Expense" ? offsetDebit : -offsetDebit;
+
+ const lines = await trx
+ .insertInto("journalLine")
+ .values([
+ {
+ journalId: journal.id,
+ accountId: account.glAccountId,
+ description,
+ amount: bankSign * inflow,
+ companyId: args.companyId,
+ companyGroupId: args.companyGroupId,
+ },
+ {
+ journalId: journal.id,
+ accountId: offset.id,
+ description,
+ amount: offsetAmount,
+ companyId: args.companyId,
+ companyGroupId: args.companyGroupId,
+ },
+ ])
+ .returning(["id", "accountId"])
+ .execute();
+
+ const bankLine = lines.find((l) => l.accountId === account.glAccountId)!;
+ const group = await trx
+ .insertInto("bankMatchGroup")
+ .values({
+ bankAccountId: txn.bankAccountId,
+ matchType: "Manual",
+ companyId: args.companyId,
+ createdBy: args.userId,
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("bankMatchGroupTransaction")
+ .values({ groupId: group.id, bankTransactionId: txn.id })
+ .execute();
+ await trx
+ .insertInto("bankMatchGroupJournalLine")
+ .values({ groupId: group.id, journalLineId: bankLine.id })
+ .execute();
+ await trx
+ .updateTable("bankTransaction")
+ .set({ status: "Matched", updatedBy: args.userId })
+ .where("id", "=", txn.id)
+ .execute();
+ return { journalId: journal.id, groupId: group.id };
+ });
+ }
+ ```
+
+ Note: quick-create on a **foreign-currency** bank account additionally needs `sourceAmount`/`sourceCurrencyCode` on both lines and a base-converted `amount` (rate from `exchangeRateHistory`). Route (Task 19) blocks quick-create for non-base accounts in this iteration with a clear message ("record a payment or manual JE with FX instead") — smallest correct v1.
+
+2. Commit (`feat(accounting): quick-create journal entry from bank line`).
+
+---
+
+## Task 9: Reconciliation services (list/summary/create/submit)
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts`
+
+**Steps:**
+
+1. Append:
+
+ ```typescript
+ export async function getBankReconciliations(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: GenericQueryFilters & { bankAccountId: string | null }
+ ) {
+ let query = client
+ .from("bankReconciliation")
+ .select("*, bankAccount!inner(name)", { count: "exact" })
+ .eq("companyId", companyId);
+ if (args?.bankAccountId) query = query.eq("bankAccountId", args.bankAccountId);
+ if (args) {
+ query = setGenericQueryFilters(query, args, [{ column: "statementDate", ascending: false }]);
+ }
+ return query;
+ }
+
+ export async function getBankReconciliation(client: SupabaseClient<Database>, id: string) {
+ return client
+ .from("bankReconciliation")
+ .select("*, bankAccount!inner(name, currencyCode, glAccountId)")
+ .eq("id", id)
+ .single();
+ }
+
+ export async function getBankReconciliationSummary(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: { bankAccountId: string; statementDate: string; statementEndingBalance: number }
+ ) {
+ const [account, lastCompleted, scopeLines] = await Promise.all([
+ client.from("bankAccount").select("openingBalance, glAccountId").eq("id", args.bankAccountId).single(),
+ client
+ .from("bankReconciliation")
+ .select("statementEndingBalance, statementDate")
+ .eq("bankAccountId", args.bankAccountId)
+ .eq("status", "Completed")
+ .order("statementDate", { ascending: false })
+ .limit(1)
+ .maybeSingle(),
+ client
+ .from("bankTransaction")
+ .select("id, transactionDate, amount, description, status")
+ .eq("companyId", companyId)
+ .eq("bankAccountId", args.bankAccountId)
+ .in("status", ["Unmatched", "Matched"])
+ .lte("transactionDate", args.statementDate),
+ ]);
+ if (account.error) return { data: null, error: account.error };
+ if (scopeLines.error) return { data: null, error: scopeLines.error };
+
+ const startingBalance = lastCompleted.data
+ ? Number(lastCompleted.data.statementEndingBalance)
+ : Number(account.data.openingBalance);
+ const lines = scopeLines.data ?? [];
+ const clearedTotal = lines.reduce((s, l) => s + Number(l.amount), 0);
+ const difference = Number(
+ (startingBalance + clearedTotal - args.statementEndingBalance).toFixed(6)
+ );
+ const unmatchedLines = lines.filter((l) => l.status === "Unmatched");
+
+ const outstanding = await client
+ .from("bankMatchableJournalLine")
+ .select("id, journalEntryId, postingDate, description, amount")
+ .eq("companyId", companyId)
+ .eq("accountId", account.data.glAccountId)
+ .is("groupId", null)
+ .lte("postingDate", args.statementDate)
+ .order("postingDate", { ascending: false })
+ .limit(100);
+
+ return {
+ data: {
+ startingBalance,
+ clearedTotal,
+ difference,
+ unmatchedLines,
+ outstandingGlLines: outstanding.data ?? [],
+ priorStatementDate: lastCompleted.data?.statementDate ?? null,
+ },
+ error: null,
+ };
+ }
+
+ export async function createBankReconciliation(
+ client: SupabaseClient<Database>,
+ data: z.infer<typeof bankReconciliationValidator> & {
+ reconciliationId: string; // pre-allocated REC- id
+ startingBalance: number;
+ companyId: string;
+ createdBy: string;
+ }
+ ) {
+ // Sequential per account: statementDate must be after the last completed statement
+ const last = await client
+ .from("bankReconciliation")
+ .select("statementDate")
+ .eq("bankAccountId", data.bankAccountId)
+ .eq("status", "Completed")
+ .order("statementDate", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (last.data && data.statementDate <= last.data.statementDate) {
+ return {
+ data: null,
+ error: { message: `Statement date must be after ${last.data.statementDate}` },
+ };
+ }
+ const { id: _id, ...rest } = data;
+ return client.from("bankReconciliation").insert([rest]).select("id").single();
+ }
+
+ export async function submitBankReconciliation(
+ client: SupabaseClient<Database>,
+ { id, userId }: { id: string; userId: string }
+ ) {
+ return client
+ .from("bankReconciliation")
+ .update({
+ status: "In Review",
+ submittedAt: new Date().toISOString(),
+ submittedBy: userId,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", id)
+ .eq("status", "Draft")
+ .select("id")
+ .single();
+ }
+ ```
+
+2. Commit including Task 4's types (`feat(accounting): bank reconciliation services + derived types`).
+
+---
+
+## Task 10: Complete / void reconciliation (Kysely)
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.server.ts`
+
+**Steps:**
+
+1. Append:
+
+ ```typescript
+ export async function completeBankReconciliation(
+ db: Kysely<KyselyDatabase>,
+ args: { companyId: string; userId: string; reconciliationId: string; requireApproval: boolean }
+ ) {
+ return db.transaction().execute(async (trx) => {
+ const rec = await trx
+ .selectFrom("bankReconciliation")
+ .selectAll()
+ .where("id", "=", args.reconciliationId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirstOrThrow();
+
+ if (args.requireApproval) {
+ if (rec.status !== "In Review")
+ throw new Error("Reconciliation must be submitted for review before completion");
+ if (rec.submittedBy === args.userId)
+ throw new Error("The preparer cannot approve their own reconciliation");
+ } else if (rec.status !== "Draft" && rec.status !== "In Review") {
+ throw new Error(`Cannot complete a ${rec.status} reconciliation`);
+ }
+
+ const lines = await trx
+ .selectFrom("bankTransaction")
+ .select(["id", "amount", "status"])
+ .where("companyId", "=", args.companyId)
+ .where("bankAccountId", "=", rec.bankAccountId)
+ .where("status", "in", ["Unmatched", "Matched"])
+ .where("transactionDate", "<=", rec.statementDate)
+ .execute();
+ const unmatched = lines.filter((l) => l.status === "Unmatched");
+ if (unmatched.length > 0)
+ throw new Error(`${unmatched.length} statement lines are still unmatched`);
+
+ const cleared = lines.reduce((s, l) => s + Number(l.amount), 0);
+ const difference = Number(
+ (Number(rec.startingBalance) + cleared - Number(rec.statementEndingBalance)).toFixed(6)
+ );
+ if (difference !== 0)
+ throw new Error(`Reconciliation does not balance (difference ${difference})`);
+
+ await trx
+ .updateTable("bankTransaction")
+ .set({ status: "Reconciled", reconciliationId: rec.id, updatedBy: args.userId })
+ .where("id", "in", lines.map((l) => l.id))
+ .execute();
+ await trx
+ .updateTable("bankReconciliation")
+ .set({
+ status: "Completed",
+ completedAt: new Date().toISOString(),
+ completedBy: args.userId,
+ updatedBy: args.userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .where("id", "=", rec.id)
+ .execute();
+ await trx
+ .insertInto("bankAccountBalance")
+ .values({
+ bankAccountId: rec.bankAccountId,
+ date: rec.statementDate,
+ balance: rec.statementEndingBalance,
+ source: "Statement",
+ companyId: args.companyId,
+ })
+ .onConflict((oc) =>
+ oc.columns(["bankAccountId", "date"]).doUpdateSet({ balance: rec.statementEndingBalance })
+ )
+ .execute();
+ return { id: rec.id };
+ });
+ }
+
+ export async function voidBankReconciliation(
+ db: Kysely<KyselyDatabase>,
+ args: { companyId: string; userId: string; reconciliationId: string }
+ ) {
+ return db.transaction().execute(async (trx) => {
+ const rec = await trx
+ .selectFrom("bankReconciliation")
+ .selectAll()
+ .where("id", "=", args.reconciliationId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirstOrThrow();
+ if (rec.status !== "Completed") throw new Error("Only completed reconciliations can be voided");
+
+ const later = await trx
+ .selectFrom("bankReconciliation")
+ .select("id")
+ .where("bankAccountId", "=", rec.bankAccountId)
+ .where("status", "=", "Completed")
+ .where("statementDate", ">", rec.statementDate)
+ .executeTakeFirst();
+ if (later) throw new Error("Only the latest completed reconciliation can be voided");
+
+ await trx
+ .updateTable("bankTransaction")
+ .set({ status: "Matched", reconciliationId: null, updatedBy: args.userId })
+ .where("reconciliationId", "=", rec.id)
+ .execute();
+ await trx
+ .updateTable("bankReconciliation")
+ .set({
+ status: "Voided",
+ voidedAt: new Date().toISOString(),
+ voidedBy: args.userId,
+ updatedBy: args.userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .where("id", "=", rec.id)
+ .execute();
+ await trx
+ .deleteFrom("bankAccountBalance")
+ .where("bankAccountId", "=", rec.bankAccountId)
+ .where("date", "=", rec.statementDate)
+ .where("source", "=", "Statement")
+ .execute();
+ return { id: rec.id };
+ });
+ }
+ ```
+
+2. Commit (`feat(accounting): reconciliation complete/void transactions`).
+
+---
+
+## Task 11: Populate `journalLine.sourceAmount` in payment posting
+
+**Files:**
+- Modify: `packages/database/supabase/functions/post-payment/build-payment-journal.ts`
+- Modify: `packages/database/supabase/functions/post-payment/post-payment.test.ts`
+
+**Steps:**
+
+1. In `build-payment-journal.ts`, the bank-side line (built from `bankAccount` + `exchangeRate`) currently sets base `amount` only. Add to the bank line object:
+ ```typescript
+ sourceAmount: cashIn ? totalAmount : -totalAmount, // document currency, class-signed like `amount`
+ sourceCurrencyCode: currencyCode,
+ ```
+ Thread `currencyCode` into `BuildPaymentJournalInput` (add `currencyCode: string` to the input type; `index.ts` already has `payment.data.currencyCode` in scope at the call site — pass it through). Non-bank lines (control/discount/FX) stay null.
+2. Update the golden-master tests: every `arBase`/`apBase` fixture gains `currencyCode: "USD"`, and the bank-line assertions add `sourceAmount`/`sourceCurrencyCode` expectations (e.g. AR receipt of 100 → bank line `{ amount: 100, sourceAmount: 100, sourceCurrencyCode: "USD" }`; FX case with `exchangeRate: 1.1` → `amount: 110, sourceAmount: 100`).
+3. Run + commit:
+ ```bash
+ cd packages/database/supabase/functions/post-payment && deno test .
+ # Expected: all tests pass, including new sourceAmount assertions
+ git add packages/database/supabase/functions/post-payment/ && git commit -m "feat(accounting): stamp source-currency amounts on payment bank lines
+
+ Co-Authored-By: Claude Fable 5 <[email protected]>"
+ ```
+
+---
+
+## Task 12: `import-bank-statement` edge function — scaffold + CSV parser
+
+**Files:**
+- Create: `packages/database/supabase/functions/import-bank-statement/parsers/types.ts`
+- Create: `packages/database/supabase/functions/import-bank-statement/parsers/csv.ts`
+- Create: `packages/database/supabase/functions/import-bank-statement/parsers/csv.test.ts`
+
+**Steps:**
+
+1. `parsers/types.ts`:
+ ```typescript
+ export type NormalizedBankTransaction = {
+ transactionDate: string; // yyyy-MM-dd
+ amount: number; // signed, positive = inflow
+ description: string;
+ reference?: string;
+ externalId: string;
+ };
+ export type ParseResult = {
+ transactions: NormalizedBankTransaction[];
+ statementOpeningBalance?: number;
+ statementEndingBalance?: number;
+ };
+ ```
+
+2. `parsers/csv.ts` (complete):
+ ```typescript
+ import { parse } from "https://deno.land/[email protected]/encoding/csv.ts";
+ import type { NormalizedBankTransaction, ParseResult } from "./types.ts";
+
+ export type CsvColumnMappings = {
+ date: string; // header name
+ description: string;
+ amount?: string; // signed single column…
+ debit?: string; // …or a debit/credit pair (debit = money out)
+ credit?: string;
+ reference?: string;
+ };
+
+ function parseDate(value: string): string {
+ const v = value.trim();
+ if (/^\d{4}-\d{2}-\d{2}/.test(v)) return v.slice(0, 10);
+ const mdY = v.match(/^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{4})$/);
+ if (mdY) {
+ const [, m, d, y] = mdY;
+ return `${y}-${m!.padStart(2, "0")}-${d!.padStart(2, "0")}`;
+ }
+ throw new Error(`Unparseable date: ${value}`);
+ }
+
+ function parseAmount(value: string): number {
+ let v = value.trim().replace(/[$,\s]/g, "");
+ if (v === "" || v === "-") return 0;
+ const negative = /^\(.*\)$/.test(v);
+ if (negative) v = v.slice(1, -1);
+ const n = Number(v);
+ if (Number.isNaN(n)) throw new Error(`Unparseable amount: ${value}`);
+ return negative ? -n : n;
+ }
+
+ async function contentHash(parts: string[]): Promise<string> {
+ const data = new TextEncoder().encode(parts.join("|"));
+ const digest = await crypto.subtle.digest("SHA-256", data);
+ return Array.from(new Uint8Array(digest))
+ .map((b) => b.toString(16).padStart(2, "0"))
+ .join("");
+ }
+
+ export async function parseCsvStatement(
+ text: string,
+ mappings: CsvColumnMappings
+ ): Promise<ParseResult> {
+ const rows = (await parse(text, { skipFirstRow: false, lazyQuotes: true })) as string[][];
+ if (rows.length < 2) return { transactions: [] };
+ const headers = rows[0]!.map((h) => h.trim());
+ const col = (name?: string) => (name ? headers.indexOf(name) : -1);
+ const iDate = col(mappings.date);
+ const iDesc = col(mappings.description);
+ const iAmount = col(mappings.amount);
+ const iDebit = col(mappings.debit);
+ const iCredit = col(mappings.credit);
+ const iRef = col(mappings.reference);
+ if (iDate < 0 || iDesc < 0 || (iAmount < 0 && (iDebit < 0 || iCredit < 0))) {
+ throw new Error("Column mappings must include date, description, and amount (or debit + credit)");
+ }
+
+ const occurrences = new Map<string, number>();
+ const transactions: NormalizedBankTransaction[] = [];
+ for (const row of rows.slice(1)) {
+ if (row.every((c) => (c ?? "").trim() === "")) continue;
+ const transactionDate = parseDate(row[iDate] ?? "");
+ const description = (row[iDesc] ?? "").trim();
+ const reference = iRef >= 0 ? (row[iRef] ?? "").trim() || undefined : undefined;
+ const amount =
+ iAmount >= 0
+ ? parseAmount(row[iAmount] ?? "")
+ : parseAmount(row[iCredit] ?? "") - parseAmount(row[iDebit] ?? "");
+ const key = `${transactionDate}|${amount}|${description}|${reference ?? ""}`;
+ const occurrence = (occurrences.get(key) ?? 0) + 1;
+ occurrences.set(key, occurrence);
+ transactions.push({
+ transactionDate,
+ amount,
+ description,
+ reference,
+ externalId: await contentHash([key, String(occurrence)]),
+ });
+ }
+ return { transactions };
+ }
+ ```
+
+3. `parsers/csv.test.ts` — fixtures: (a) signed-amount CSV with `$1,234.56`, `(45.00)` parens-negative, blank row; (b) debit/credit pair CSV; (c) duplicate identical rows keep distinct externalIds; (d) re-parse yields identical externalIds. Assert dates normalize from `6/15/2026`. Run:
+ ```bash
+ cd packages/database/supabase/functions/import-bank-statement && deno test parsers/
+ # Expected: PASS
+ ```
+
+4. Commit (`feat(accounting): bank statement CSV parser`).
+
+---
+
+## Task 13: OFX parser
+
+**Files:**
+- Create: `packages/database/supabase/functions/import-bank-statement/parsers/ofx.ts`
+- Create: `packages/database/supabase/functions/import-bank-statement/parsers/ofx.test.ts`
+
+**Steps:**
+
+1. `parsers/ofx.ts` (complete — tolerant of SGML and XML flavors):
+ ```typescript
+ import type { NormalizedBankTransaction, ParseResult } from "./types.ts";
+
+ function tag(block: string, name: string): string | undefined {
+ const m = block.match(new RegExp(`<${name}>([^<\\r\\n]*)`, "i"));
+ return m?.[1]?.trim() || undefined;
+ }
+
+ function ofxDate(value?: string): string {
+ if (!value || value.length < 8) throw new Error(`Unparseable OFX date: ${value}`);
+ return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}`;
+ }
+
+ export function parseOfxStatement(text: string): ParseResult {
+ const blocks = text.match(/<STMTTRN>[\s\S]*?(<\/STMTTRN>|(?=<STMTTRN>)|$)/gi) ?? [];
+ const transactions: NormalizedBankTransaction[] = blocks.map((block) => {
+ const fitId = tag(block, "FITID");
+ const amount = Number(tag(block, "TRNAMT"));
+ if (!fitId) throw new Error("OFX transaction missing FITID");
+ if (Number.isNaN(amount)) throw new Error("OFX transaction missing TRNAMT");
+ const name = tag(block, "NAME");
+ const memo = tag(block, "MEMO");
+ return {
+ transactionDate: ofxDate(tag(block, "DTPOSTED")),
+ amount, // OFX TRNAMT: positive = credit/inflow — already our convention
+ description: [name, memo].filter(Boolean).join(" — ") || "(no description)",
+ reference: tag(block, "CHECKNUM"),
+ externalId: fitId,
+ };
+ });
+
+ let statementEndingBalance: number | undefined;
+ const ledger = text.match(/<LEDGERBAL>[\s\S]*?(<\/LEDGERBAL>|$)/i)?.[0];
+ if (ledger) {
+ const bal = Number(tag(ledger, "BALAMT"));
+ if (!Number.isNaN(bal)) statementEndingBalance = bal;
+ }
+ return { transactions, statementEndingBalance };
+ }
+ ```
+
+2. `parsers/ofx.test.ts` — fixtures: a minimal SGML OFX (no closing inner tags) and an XML-flavored OFX, each with 3 `STMTTRN` blocks (deposit, check with CHECKNUM, fee) + `LEDGERBAL`. Assert dates, signs, FITIDs, reference, ending balance; assert missing-FITID throws.
+ ```bash
+ deno test parsers/
+ # Expected: PASS (csv + ofx)
+ ```
+
+3. Commit (`feat(accounting): bank statement OFX parser`).
+
+---
+
+## Task 14: Edge function handler + service wrapper
+
+**Files:**
+- Create: `packages/database/supabase/functions/import-bank-statement/index.ts`
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` (append `importBankStatement`)
+
+**Steps:**
+
+1. `index.ts` — mirror `post-payment/index.ts` structure exactly (serve, CORS, zod payload, `getSupabaseServiceRole`, Kysely pool):
+
+ ```typescript
+ import { serve } from "https://deno.land/[email protected]/http/server.ts";
+ import z from "npm:zod@^3.24.1";
+ import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+ import { corsHeaders } from "../lib/headers.ts";
+ import { getSupabaseServiceRole } from "../lib/supabase.ts";
+ import { parseCsvStatement, type CsvColumnMappings } from "./parsers/csv.ts";
+ import { parseOfxStatement } from "./parsers/ofx.ts";
+ import { sql } from "npm:kysely@^0.26.3"; // match the kysely version pinned in ../lib/database.ts
+
+ const pool = getConnectionPool(1);
+ const db = getDatabaseClient<DB>(pool);
+
+ const payloadValidator = z.object({
+ importId: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+ });
+
+ serve(async (req: Request) => {
+ if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });
+ const payload = await req.json();
+ let importId = "";
+ try {
+ const parsed = payloadValidator.parse(payload);
+ importId = parsed.importId;
+ const { companyId, userId } = parsed;
+ const client = await getSupabaseServiceRole(
+ req.headers.get("Authorization"),
+ req.headers.get("carbon-key") ?? "",
+ companyId
+ );
+
+ const importRow = await client
+ .from("bankStatementImport")
+ .select("*")
+ .eq("id", importId)
+ .eq("companyId", companyId)
+ .single();
+ if (importRow.error || !importRow.data) throw new Error("Import not found");
+ const { bankAccountId, filePath, format } = importRow.data;
+
+ const bankAccount = await client
+ .from("bankAccount")
+ .select("id")
+ .eq("id", bankAccountId)
+ .eq("companyId", companyId)
+ .single();
+ if (bankAccount.error) throw new Error("Bank account not found");
+
+ const file = await client.storage.from("private").download(filePath);
+ if (file.error || !file.data) throw new Error("Failed to download statement file");
+ const text = await file.data.text();
+
+ const result =
+ format === "OFX"
+ ? parseOfxStatement(text)
+ : await parseCsvStatement(
+ text,
+ JSON.parse(
+ (importRow.data as { columnMappings?: string }).columnMappings ??
+ (payload.columnMappings ?? "{}")
+ ) as CsvColumnMappings
+ );
+
+ let imported = 0;
+ await db.transaction().execute(async (trx) => {
+ for (const t of result.transactions) {
+ const inserted = await trx
+ .insertInto("bankTransaction")
+ .values({
+ bankAccountId,
+ transactionDate: t.transactionDate,
+ amount: t.amount,
+ description: t.description,
+ reference: t.reference ?? null,
+ externalId: t.externalId,
+ source: "Import",
+ importId,
+ status: "Unmatched",
+ companyId,
+ })
+ .onConflict((oc) => oc.columns(["bankAccountId", "externalId"]).doNothing())
+ .returning("id")
+ .executeTakeFirst();
+ if (inserted) imported++;
+ }
+ await trx
+ .updateTable("bankStatementImport")
+ .set({
+ status: "Completed",
+ importedCount: imported,
+ duplicateCount: result.transactions.length - imported,
+ statementEndingBalance: result.statementEndingBalance ?? null,
+ statementOpeningBalance: result.statementOpeningBalance ?? null,
+ })
+ .where("id", "=", importId)
+ .execute();
+ });
+
+ const matched = await sql<{ run_bank_matching: number }>`
+ SELECT run_bank_matching(${bankAccountId}, ${companyId}, ${userId})
+ `.execute(db);
+
+ return new Response(
+ JSON.stringify({
+ imported,
+ duplicates: result.transactions.length - imported,
+ autoMatched: matched.rows[0]?.run_bank_matching ?? 0,
+ }),
+ { headers: { ...corsHeaders, "Content-Type": "application/json" } }
+ );
+ } catch (err) {
+ if (importId) {
+ try {
+ await db
+ .updateTable("bankStatementImport")
+ .set({ status: "Failed", error: (err as Error).message })
+ .where("id", "=", importId)
+ .execute();
+ } catch (_) { /* best effort */ }
+ }
+ return new Response(JSON.stringify({ error: (err as Error).message }), {
+ status: 500,
+ headers: corsHeaders,
+ });
+ }
+ });
+ ```
+
+ Note: `columnMappings` travels in the POST body (route → edge fn), not on the import row — adjust the two lines above to read `payload.columnMappings` only, and extend `payloadValidator` with `columnMappings: z.string().optional()`. (Keep the import row lean.)
+
+2. Service wrapper in `accounting.service.ts`:
+ ```typescript
+ export async function importBankStatement(
+ client: SupabaseClient<Database>, // pass getCarbonServiceRole() from the route
+ args: { importId: string; companyId: string; userId: string; columnMappings?: string }
+ ) {
+ return client.functions.invoke<{ imported: number; duplicates: number; autoMatched: number }>(
+ "import-bank-statement",
+ { body: args }
+ );
+ }
+ ```
+3. Serve locally + smoke test (crbn stack must already be up — do not start it):
+ ```bash
+ grep -rn "import-bank-statement\|post-payment" packages/database/supabase/config.toml | head -3
+ # If post-payment has a [functions.*] entry, add a matching one for import-bank-statement; if not, none needed.
+ ```
+4. Commit (`feat(accounting): import-bank-statement edge function`).
+
+---
+
+## Task 15: Path helpers + sidebar Banking group
+
+**Files:**
+- Modify: `apps/erp/app/utils/path.ts`
+- Modify: `apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx`
+
+**Steps:**
+
+1. `path.ts` — add alphabetically among the accounting entries:
+ ```typescript
+ bankAccount: (id: string) => generatePath(`${x}/accounting/bank-accounts/${id}`),
+ bankAccountImport: (id: string) => generatePath(`${x}/accounting/bank-accounts/${id}/import`),
+ bankAccounts: `${x}/accounting/bank-accounts`,
+ bankReconciliation: (id: string) => generatePath(`${x}/accounting/reconciliations/${id}`),
+ bankReconciliationPdf: (id: string) => generatePath(`/file/bank-reconciliation/${id}.pdf`),
+ bankReconciliations: `${x}/accounting/reconciliations`,
+ bankReconcile: (id: string) => generatePath(`${x}/accounting/reconcile/${id}`),
+ bankReconcileFinish: (id: string) => generatePath(`${x}/accounting/reconcile/${id}/finish`),
+ newBankAccount: `${x}/accounting/bank-accounts/new`,
+ ```
+2. `useAccountingSubmodules.tsx` — insert a group between `General Ledger` and `Fixed Assets` (icons from `react-icons/lu`; `LuLandmark` + `LuFileCheck` exist — verify with a quick grep in `node_modules/react-icons/lu/index.d.ts` and substitute `LuBanknote`/`LuListChecks` if not):
+ ```typescript
+ {
+ name: t`Banking`,
+ routes: [
+ {
+ name: t`Bank Accounts`,
+ to: path.to.bankAccounts,
+ role: "employee",
+ icon: <LuLandmark />,
+ },
+ {
+ name: t`Reconciliations`,
+ to: path.to.bankReconciliations,
+ role: "employee",
+ icon: <LuFileCheck />,
+ },
+ ],
+ },
+ ```
+ Match the exact route-object fields of the neighboring groups (some include `permission`; copy whatever `Journal Entries` uses).
+3. Commit (`feat(accounting): banking paths + sidebar group`).
+
+---
+
+## Task 16: Bank accounts list route + table
+
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Banking/BankAccountsTable.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Banking/index.ts` (barrel)
+- Create: `apps/erp/app/routes/x+/accounting+/bank-accounts.tsx`
+
+**Steps:**
+
+1. `BankAccountsTable.tsx`: clone the structure of `apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsx` (memoized `Table<T>`, `columns` in `useMemo`, `renderContextMenu`, `New` primary action). Type rows as `BankAccount` from `~/modules/accounting/types`. Columns:
+ - `name` → `Hyperlink` to `path.to.bankReconcile(row.original.id)` (the workspace is the primary drill-in), pinned left, icon `LuLandmark`
+ - `bankName`, `glAccountNumber` + `glAccountName` (combined cell), `currencyCode` (`Enumerable`)
+ - `type` (`Enumerable`, static filter from `bankAccountTypes`)
+ - `unmatchedCount` (plain number — never parenthesized), `lastReconciledDate` (`formatDate`)
+ - `source` badge + `connectionStatus` badge (render nothing when null), `active` boolean
+ Context menu: Reconcile (→ `bankReconcile`), Import Statement (→ `bankAccountImport`), Edit (→ `bankAccount`), Deactivate (permission `update`/`accounting`, `ConfirmDelete`-style confirm posting `intent=deactivate` to the edit route).
+ Primary action: `<New label={t`Bank Account`} to={path.to.newBankAccount} />` gated by `permissions.can("create", "accounting")`.
+2. Route `bank-accounts.tsx`:
+ ```typescript
+ import { requirePermissions } from "@carbon/auth/auth.server";
+ import type { LoaderFunctionArgs } from "react-router";
+ import { Outlet, useLoaderData } from "react-router";
+ import { getBankAccounts } from "~/modules/accounting";
+ import { BankAccountsTable } from "~/modules/accounting/ui/Banking";
+ import { getGenericQueryFilters } from "~/utils/query";
+
+ export const handle = { breadcrumb: "Banking", to: "/x/accounting/bank-accounts" };
+
+ export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, { view: "accounting" });
+ const url = new URL(request.url);
+ const search = url.searchParams.get("search");
+ const { limit, offset, sorts, filters } = getGenericQueryFilters(url.searchParams);
+ const bankAccounts = await getBankAccounts(client, companyId, {
+ search, limit, offset, sorts, filters,
+ });
+ return { bankAccounts: bankAccounts.data ?? [], count: bankAccounts.count ?? 0 };
+ }
+
+ export default function BankAccountsRoute() {
+ const { bankAccounts, count } = useLoaderData<typeof loader>();
+ return (
+ <>
+ <BankAccountsTable data={bankAccounts} count={count} />
+ <Outlet />
+ </>
+ );
+ }
+ ```
+ Mirror the exact loader helper names from `journals.tsx` (`getGenericQueryFilters` signature varies — copy that file's usage verbatim).
+3. Commit (`feat(accounting): bank accounts list`).
+
+---
+
+## Task 17: Bank account form + new/edit drawer routes
+
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Banking/BankAccountForm.tsx`
+- Create: `apps/erp/app/routes/x+/accounting+/bank-accounts.new.tsx`
+- Create: `apps/erp/app/routes/x+/accounting+/bank-accounts.$bankAccountId.tsx`
+
+**Steps:**
+
+1. `BankAccountForm.tsx` — follow the `conventions-forms.md` ModalDrawer skeleton exactly (props `{ initialValues, open?, onClose }`, `useFetcher`, permission-driven `isDisabled`). Fields:
+ ```tsx
+ <Hidden name="id" />
+ <VStack spacing={4}>
+ <Input name="name" label={t`Name`} />
+ <Input name="bankName" label={t`Bank`} />
+ <Input name="accountNumberLastFour" label={t`Account Number (last 4)`} maxLength={4} />
+ <Select name="type" label={t`Type`} options={bankAccountTypes.map((v) => ({ label: v, value: v }))} />
+ <Currency name="currencyCode" label={t`Currency`} />
+ <Account name="glAccountId" label={t`GL Account`} classes={["Asset", "Liability"]} />
+ <Number name="openingBalance" label={t`Opening Balance`} formatOptions={{ style: "decimal", minimumFractionDigits: 2 }} />
+ <DatePicker name="openingDate" label={t`Opening Date`} />
+ <CustomFormFields table="bankAccount" />
+ </VStack>
+ ```
+ (`Account` selector props: copy the exact prop names from its use in `PaymentForm.tsx` — it takes the field name + label; if it lacks a class filter prop, omit and rely on service validation.)
+2. `bank-accounts.new.tsx` — action per the forms rule: `assertIsPost` → `requirePermissions({ create: "accounting" })` → `validator(bankAccountValidator).validate` → `upsertBankAccount(client, { ...data, companyId, createdBy: userId, customFields: setCustomFields(formData) })` → error: `return data({}, await flash(request, error(...)))` → success: `throw redirect(path.to.bankAccounts + ?getParams, await flash(request, success("Bank account created")))`. Default export renders `<BankAccountForm initialValues={{ name: "", type: "Checking", currencyCode: baseCurrency, glAccountId: "", openingBalance: 0 }} onClose={() => navigate(path.to.bankAccounts)} />` (fetch base currency in a small loader).
+3. `bank-accounts.$bankAccountId.tsx` — loader `getBankAccount` (redirect+flash on error), action branches on `intent`: `deactivate` → `deactivateBankAccount`; default → update path of `upsertBankAccount` with `update: "accounting"`. Default export passes loader data to the form.
+4. Commit (`feat(accounting): bank account form + drawers`).
+
+---
+
+## Task 18: Statement import drawer
+
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Banking/BankStatementImportDrawer.tsx`
+- Create: `apps/erp/app/routes/x+/accounting+/bank-accounts.$bankAccountId.import.tsx`
+
+**Steps:**
+
+1. Drawer component (3 steps, state machine like `ImportCSVModal.tsx` but simpler — no enum mappings):
+ - **Step 1 Upload**: `react-dropzone` accepting `.csv,.ofx,.qfx`; on drop, upload to `carbon.storage.from("private").upload(`${companyId}/bank-statements/${nanoid()}.${ext}`, file)` (clone the upload block from `apps/erp/app/components/ImportCSVModal/UploadCSV.tsx`); detect format from extension (`.ofx`/`.qfx` → `OFX`, else `CSV`); for CSV, PapaParse the first 5 rows for headers + preview.
+ - **Step 2 Map (CSV only)**: selects mapping each required field (Date, Description, and Amount **or** Debit+Credit, optional Reference) to a CSV header, previewing first rows — clone the row layout from `FieldMappings.tsx`. OFX skips to step 3.
+ - **Step 3 Confirm**: shows file name + line count; submit via `useFetcher` POST to this route with `filePath`, `fileName`, `format`, `columnMappings` (JSON string). On `fetcher.data` show result (`imported`, `duplicates`, `autoMatched`) with a Done button → navigate to `path.to.bankReconcile(bankAccountId)`.
+2. Route action:
+ ```typescript
+ export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, { create: "accounting" });
+ const { bankAccountId } = params;
+ if (!bankAccountId) throw new Error("bankAccountId not found");
+ const formData = await request.formData();
+ const validation = await validator(bankStatementUploadValidator).validate(formData);
+ if (validation.error) return validationError(validation.error);
+
+ const serviceRole = getCarbonServiceRole();
+ const importRow = await serviceRole
+ .from("bankStatementImport")
+ .insert([{
+ bankAccountId,
+ fileName: validation.data.fileName,
+ filePath: validation.data.filePath,
+ format: validation.data.format,
+ companyId,
+ createdBy: userId,
+ }])
+ .select("id")
+ .single();
+ if (importRow.error) {
+ return data({}, await flash(request, error(importRow.error, "Failed to create import")));
+ }
+ const result = await importBankStatement(serviceRole, {
+ importId: importRow.data.id,
+ companyId,
+ userId,
+ columnMappings: validation.data.columnMappings,
+ });
+ if (result.error) {
+ return data({}, await flash(request, error(result.error, "Import failed")));
+ }
+ return data(result.data, { status: 201 });
+ }
+ ```
+ (`getCarbonServiceRole` import: same as `x+/shared+/import.$tableId.tsx`.)
+3. Commit (`feat(accounting): bank statement import drawer`).
+
+---
+
+## Task 19: Reconcile workspace route (loader + action)
+
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/reconcile.$bankAccountId.tsx`
+
+**Steps:**
+
+1. Loader: `requirePermissions({ view: "accounting" })`; `Promise.all`: `getBankAccount`, `getBankTransactions` (status filter from `?status=`, default `Unmatched`), unmatched GL lines (`bankMatchableJournalLine` where `accountId = glAccountId`, `groupId is null`, order `postingDate desc`, limit 100), `getCompanySettings` (for tolerance display). Redirect+flash if the account is missing.
+2. Action — single route, `intent` field switch (each branch validates its own small schema):
+ ```typescript
+ export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, { update: "accounting" });
+ const { bankAccountId } = params;
+ if (!bankAccountId) throw new Error("bankAccountId not found");
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+ const db = getCarbonServiceRole(); // Kysely handle: use the SAME import the postDepreciationRun caller route uses — grep "postDepreciationRun(" under apps/erp/app/routes and mirror it exactly
+
+ try {
+ switch (intent) {
+ case "match": {
+ const bankTransactionIds = formData.getAll("bankTransactionIds").map(String);
+ const journalLineIds = formData.getAll("journalLineIds").map(String);
+ const validation = bankMatchValidator.safeParse({ bankTransactionIds, journalLineIds });
+ if (!validation.success) {
+ return data({}, await flash(request, error(validation.error, "Select bank and GL lines")));
+ }
+ // Pre-allocate tolerance JE inputs so the server fn can book a within-tolerance difference
+ const [settings, defaults, company] = await Promise.all([
+ getCompanySettings(client, companyId),
+ getDefaultAccounts(client, companyId),
+ getCompany(client, companyId),
+ ]);
+ let toleranceJournal;
+ if (Number(settings.data?.bankMatchToleranceAmount ?? 0) > 0 && defaults.data?.bankFeesAccount) {
+ const [seq, period] = await Promise.all([
+ getNextSequence(client, "journalEntry", companyId),
+ getOrCreateAccountingPeriod(client, companyId, todayIsoDate()),
+ ]);
+ if (seq.data && period.data) {
+ toleranceJournal = {
+ journalEntryId: seq.data,
+ accountingPeriodId: period.data,
+ bankFeesAccountId: defaults.data.bankFeesAccount,
+ companyGroupId: company.data!.companyGroupId,
+ };
+ }
+ }
+ await createBankMatchGroup(db, { companyId, userId, bankTransactionIds, journalLineIds, toleranceJournal });
+ return data({}, await flash(request, success("Matched")));
+ }
+ case "unmatch": {
+ await deleteBankMatchGroup(db, { companyId, userId, groupId: String(formData.get("groupId")) });
+ return data({}, await flash(request, success("Unmatched")));
+ }
+ case "exclude":
+ case "restore": {
+ const fn = intent === "exclude" ? excludeBankTransaction : restoreBankTransaction;
+ const result = await fn(client, { id: String(formData.get("bankTransactionId")), userId });
+ if (result.error) return data({}, await flash(request, error(result.error, "Update failed")));
+ return data({}, await flash(request, success(intent === "exclude" ? "Excluded" : "Restored")));
+ }
+ case "create-journal": {
+ const validation = await validator(bankQuickJournalValidator).validate(formData);
+ if (validation.error) return validationError(validation.error);
+ const account = await getBankAccount(client, bankAccountId);
+ const base = await getBaseCurrency(client, companyId);
+ if (account.data?.currencyCode !== base.data?.code) {
+ return data({}, await flash(request, error(null, "Quick-create is not available for foreign-currency accounts yet — record a payment or manual journal entry instead")));
+ }
+ const txnDate = String(formData.get("transactionDate") ?? todayIsoDate());
+ const [seq, period, company] = await Promise.all([
+ getNextSequence(client, "journalEntry", companyId),
+ getOrCreateAccountingPeriod(client, companyId, txnDate),
+ getCompany(client, companyId),
+ ]);
+ if (seq.error || !seq.data) return data({}, await flash(request, error(seq.error, "Failed to allocate journal id")));
+ if (period.error || !period.data) return data({}, await flash(request, error(period.error, "Accounting period is not open")));
+ await createJournalEntryFromBankTransaction(db, {
+ companyId,
+ companyGroupId: company.data!.companyGroupId,
+ userId,
+ bankTransactionId: validation.data.bankTransactionId,
+ accountId: validation.data.accountId,
+ memo: validation.data.memo,
+ journalEntryId: seq.data,
+ accountingPeriodId: period.data,
+ });
+ return data({}, await flash(request, success("Journal entry posted and matched")));
+ }
+ case "run-matching": {
+ const result = await client.rpc("run_bank_matching", {
+ bank_account_id: bankAccountId,
+ company_id: companyId,
+ user_id: userId,
+ });
+ if (result.error) return data({}, await flash(request, error(result.error, "Matching failed")));
+ return data({}, await flash(request, success(`Auto-matched ${result.data} lines`)));
+ }
+ default:
+ throw new Error(`Unknown intent ${intent}`);
+ }
+ } catch (err) {
+ return data({}, await flash(request, error(err, (err as Error).message)));
+ }
+ }
+ ```
+ Notes for the executor: (a) the `db` Kysely import — grep `postDepreciationRun(` for the calling route and copy its import line; (b) `getOrCreateAccountingPeriod` may have gained a `source` param from the in-flight period-close work — pass `"accounting"` if the signature accepts it; (c) `todayIsoDate()` = `today(getLocalTimeZone()).toString()` from `@internationalized/date`, already used across the module; (d) `getCompanySettings`/`getCompany` live in `~/modules/settings` — copy imports from a route that uses them.
+3. Commit (`feat(accounting): reconcile workspace actions`).
+
+---
+
+## Task 20: Reconcile workspace UI
+
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Banking/ReconcileWorkspace.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Banking/BankTransactionStatus.tsx`
+- Modify: `apps/erp/app/routes/x+/accounting+/reconcile.$bankAccountId.tsx` (default export)
+
+**Steps:**
+
+1. `BankTransactionStatus.tsx`: status badge component cloned from `PaymentStatus` (gray Pending/Unmatched, blue Matched, amber Excluded, green Reconciled).
+2. `ReconcileWorkspace.tsx` — full-page two-pane layout (`grid grid-cols-2 gap-4 h-full`):
+ - **Header**: account name + currency, running totals (`cleared`, `statement lines`, unmatched count — plain numbers), buttons: `Run matching` (fetcher POST `intent=run-matching`), `Import statement` (→ `path.to.bankAccountImport`), `Finish reconciliation` (→ `path.to.bankReconcileFinish`).
+ - **Left pane** (statement lines): status filter tabs (Unmatched / Matched / Excluded / All → `?status=` search param); each row: date, description, reference, signed amount (`tabular-nums`, red negative), status badge; row selection (checkbox, multi); row actions: Exclude/Restore (fetcher), `Add` popover — a small `ValidatedForm` with `<Account name="accountId" />` + `<Input name="memo" />` + hidden `bankTransactionId`/`transactionDate`, submitting `intent=create-journal`.
+ - **Right pane** (unmatched GL lines): date, `journalEntryId`, description, amount; multi-select checkboxes.
+ - **Match bar** (sticky footer): shows Σselected-bank vs Σselected-GL and their difference; `Match` button enabled when both sides have a selection, submits `intent=match` with `bankTransactionIds`/`journalLineIds` repeated fields via `fetcher.submit`.
+ - For a selected Matched line show its group members + `Unmatch` (fetcher `intent=unmatch` with `groupId` — extend the loader to include group memberships for visible Matched lines: query `bankMatchGroupTransaction` + `bankMatchGroupJournalLine` joined for the page of lines).
+ - ERP default sizes (`size="md"`), Lingui `t`/`Trans` for all labels, no parenthesized counts.
+3. Default export wires loader data into the workspace.
+4. Commit (`feat(accounting): reconcile workspace UI`).
+
+---
+
+## Task 21: Finish-reconciliation drawer
+
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/reconcile.$bankAccountId.finish.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Banking/FinishReconciliationDrawer.tsx`
+
+**Steps:**
+
+1. Loader: `requirePermissions({ view: "accounting" })`; reads `?statementDate=&statementEndingBalance=` when present and returns `getBankReconciliationSummary(...)` plus the latest OFX `statementEndingBalance` from `bankStatementImport` (most recent Completed import for the account) as a prefill; also `companySettings.bankRecRequireApproval`.
+2. Drawer: `ValidatedForm` (`bankReconciliationValidator`) with `DatePicker name="statementDate"`, `Number name="statementEndingBalance"`, `TextArea name="notes"`; on change of either key field, refetch summary via `useFetcher` against the loader; render: starting balance, cleared total, **difference** (green 0 / red otherwise), unmatched-lines blocker list, outstanding GL items (collapsed). Submit button label: `Complete reconciliation` or `Submit for review` (per `bankRecRequireApproval`), disabled unless `difference === 0 && unmatchedLines.length === 0`.
+3. Action:
+ ```typescript
+ const validation = await validator(bankReconciliationValidator).validate(formData);
+ if (validation.error) return validationError(validation.error);
+ const summary = await getBankReconciliationSummary(client, companyId, { ...validation.data });
+ if (summary.error || !summary.data) return data({}, await flash(request, error(summary.error, "Failed to compute summary")));
+ const seq = await getNextSequence(client, "bankReconciliation", companyId);
+ if (seq.error || !seq.data) return data({}, await flash(request, error(seq.error, "Failed to allocate reconciliation id")));
+ const created = await createBankReconciliation(client, {
+ ...validation.data,
+ reconciliationId: seq.data,
+ startingBalance: summary.data.startingBalance,
+ companyId,
+ createdBy: userId,
+ });
+ if (created.error || !created.data) return data({}, await flash(request, error(created.error, "Failed to create reconciliation")));
+ const settings = await getCompanySettings(client, companyId);
+ const requireApproval = Boolean(settings.data?.bankRecRequireApproval);
+ if (requireApproval) {
+ const submitted = await submitBankReconciliation(client, { id: created.data.id, userId });
+ if (submitted.error) return data({}, await flash(request, error(submitted.error, "Failed to submit")));
+ throw redirect(path.to.bankReconciliations, await flash(request, success("Submitted for review")));
+ }
+ await completeBankReconciliation(db, { companyId, userId, reconciliationId: created.data.id, requireApproval: false });
+ throw redirect(
+ path.to.bankReconciliation(created.data.id),
+ await flash(request, success("Reconciliation completed"))
+ );
+ ```
+ Wrap the `completeBankReconciliation` call in try/catch → flash the thrown message (it throws on gate failures).
+4. Commit (`feat(accounting): finish reconciliation flow`).
+
+---
+
+## Task 22: Reconciliations list, detail/report, approve/void + PDF
+
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/reconciliations.tsx`
+- Create: `apps/erp/app/routes/x+/accounting+/reconciliations.$reconciliationId.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Banking/BankReconciliationsTable.tsx`
+- Create: `packages/documents/src/pdf/BankReconciliationPDF.tsx` (+ export from the pdf barrel)
+- Create: `apps/erp/app/routes/file+/bank-reconciliation+/$id[.]pdf.tsx`
+
+**Steps:**
+
+1. List route + table: clone the Task 16 pattern. Columns: `reconciliationId` (Hyperlink → detail), bank account name, `statementDate`, `statementEndingBalance` (currency), status badge (Draft gray / In Review amber / Completed green / Voided red), `completedBy`/`completedAt`. Filter by bank account (`?bankAccountId=`).
+2. Detail route (drawer over the list via `<Outlet />`): loader returns `getBankReconciliation`, its reconciled lines (`bankTransaction` where `reconciliationId`), and outstanding GL lines at the statement date (reuse the summary query). Renders the report: header (account, REC id, statement date, preparer/approver), balances block (starting → cleared deposits/withdrawals → ending), reconciled-lines table, outstanding-items table, book-balance tie line. Buttons: `Download PDF` (link to `path.to.bankReconciliationPdf(id)`), `Approve` (visible when status In Review AND `user.id !== submittedBy` AND `permissions.can("update", "accounting")`; fetcher `intent=approve`), `Void` (visible on latest Completed; `intent=void`, `ConfirmDelete`-style confirm).
+ Action: `approve` → `completeBankReconciliation(db, { ..., requireApproval: true })`; `void` → `voidBankReconciliation(db, ...)`; both try/catch → flash.
+3. `BankReconciliationPDF.tsx`: hand-built like `KanbanLabelPDF.tsx` (no template customizer) — `Document`/`Page` from `@react-pdf/renderer`, company header, the same four report blocks as the detail drawer, monospace-aligned amount columns. Props: `{ company, reconciliation, bankAccount, reconciledLines, outstandingLines, locale }`. Export from `packages/documents/src/pdf/index.ts` (match how `KanbanLabelPDF` is exported).
+4. `file+/bank-reconciliation+/$id[.]pdf.tsx`: clone `file+/sales-invoice+/$id[.]pdf.tsx` skeleton — `requirePermissions({ view: "accounting" })`, fetch the same data as the detail loader, `renderToStream(<BankReconciliationPDF ... />)`, drain to Buffer, return `application/pdf` response with `Content-Disposition: inline; filename="{reconciliationId}.pdf"`. Skip the template/sections machinery; call `ensureFont("Inter")` only if the sales-invoice route shows it's required for base fonts.
+5. Commit (`feat(accounting): reconciliation history, approval, and PDF report`).
+
+---
+
+## Task 23: Settings UI (tolerance, approval, bank fees account)
+
+**Files:**
+- Modify: the accounting settings route (grep `accountingEnabled` under `apps/erp/app/routes/x+/settings+/` — the page that edits `companySettings`) — add `Number` field `bankMatchToleranceAmount` and `Boolean` field `bankRecRequireApproval` (with description "Reconciliations must be approved by someone other than the preparer") to its form + validator.
+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts` — add `bankFeesAccount: z.string().min(1)` to `defaultIncomeAcountValidator` (sic — existing name), and `apps/erp/app/routes/x+/accounting+/defaults.tsx` UI — add an `Account` field labeled `Bank Fees` next to `Interest`; extend `updateDefaultIncomeAccounts` field list in `accounting.service.ts`.
+
+**Steps:** mirror the neighboring fields exactly in each file; commit (`feat(accounting): bank rec settings + bank fees default account`).
+
+---
+
+## Task 24: Verification + source sync
+
+**Steps:**
+
+1. Full verification:
+ ```bash
+ pnpm run typecheck # per-package via turbo — expected: pass
+ pnpm run lint # expected: pass
+ cd packages/database/supabase/functions/import-bank-statement && deno test parsers/ && cd -
+ cd packages/database/supabase/functions/post-payment && deno test . && cd -
+ psql "<local conn>" -f packages/database/supabase/migrations/<ts>_bank-reconciliation.sql # idempotency re-check
+ ```
+2. Sync sources (keep-sources-in-sync rule):
+ - Spec `.ai/specs/2026-07-02-bank-reconciliation.md` changelog: PDF on-demand via `file+` route (drop `reportDocumentPath`), tolerance = manual-match-only in Phase 1, reference-agreement removed from the auto-match RPC (returns as Phase 4 suggestion ranking), quick-create blocked on FX accounts pending source-amount support in the quick-create path.
+ - `apps/erp/app/modules/accounting/AGENTS.md`: add the banking tables/services/routes to its inventory.
+ - `.ai/rules/`: no rule tracks banking yet — add a stub section to `.ai/rules/accounting-sync-handlers.md` only if it mentions payments GL specifics; otherwise skip (Phase 2 adds a `bank-feed` rule with Plaid).
+3. Manual UI verification is deliberately deferred (user instruction: don't run the app). Flag in the PR description that agent-browser verification (`/test` skill) has not run and should gate merge per the ui-e2e-verification convention.
+4. Final commit + summary of any deviations discovered during execution.
+
+---
+
+## Self-review checklist (per plan skill)
+
+- [x] Migration follows the newest sibling patterns (single-col PK per ar-ap-payments, `id('prefix')`, audit columns, FK indexes, 4-policy RLS with `::text[]`, idempotent DDL, no NUMERIC precision, randomized timestamp via CLI)
+- [x] Validators use `z` + `zfd`; actions use `validator(schema).validate(formData)`; forms use `ValidatedForm` + `~/components/Form` barrel
+- [x] Services: `(client, ...)` → `{ data, error }`, `companyId` scoping, `setGenericQueryFilters`, Kysely for multi-row transactions
+- [x] No `Response.json`; drawers for detail views; full page only for the workspace; flash on every mutation; `path.to.*` everywhere
+- [x] Deviations from spec/skill defaults are explicit (Execution notes 2–3) — nothing silent
+- [x] Two grep-and-mirror steps remain (Kysely `db` import; settings route filename) — flagged inline rather than guessed
diff --git a/.ai/plans/2026-07-02-budgeting.md b/.ai/plans/2026-07-02-budgeting.md
new file mode 100644
index 0000000000..800e2c7d82
--- /dev/null
+++ b/.ai/plans/2026-07-02-budgeting.md
@@ -0,0 +1,2725 @@
+# GL Budgeting (Phase 1) — Implementation Plan
+
+## Overview
+
+- **Design Spec:** `.ai/specs/2026-07-02-budgeting.md` (status: in-progress, all open questions resolved). This plan covers **Phase 1 — Core budgeting** only. Phases 2 (commitments & budget control) and 3 (reporting integration & consolidation) get their own plan files after Phase 1 ships.
+- **Research:** `.ai/research/budgeting.md`
+- **Prerequisite:** `.ai/plans/2026-07-02-period-closing.md` executed first — Phase 1 relies on `accountingPeriod.fiscalYear`/`periodNumber` (migration `20260702044133`, already drafted) and the `createFiscalYearPeriods` service (period-close plan Task 4).
+- **Tasks:** 17 tasks (~70–90 min of work) + gated verification
+- **Branch:** `feature/budgeting`
+
+**Ground rules for the executor (same as the period-closing plan):**
+
+- Do NOT regenerate or commit `packages/database/src/types.ts` — committed types are cloud-generated. The new `budget`/`budgetLine` tables and `budgetVsActual` RPC are absent from them; access via `(client as any).from("budget")` / `(client as any).rpc("budgetVsActual", ...)` casts (established pattern, e.g. `(client as any).from("itemSamplingPlan")`).
+- Do NOT rebuild the database. Apply the migration with `pnpm db:migrate` only, when the local stack is up (Task 16).
+- Typecheck per package (`pnpm --filter @carbon/erp typecheck`), never whole-repo `tsc --noEmit`.
+- Commit only at the marked checkpoints, after verification passes (check-and-commit gate).
+- UI components use plain strings (the CostCenterForm precedent); only `useAccountingSubmodules.tsx` uses Lingui `t` macros.
+
+**Two deliberate simplifications vs the spec text (spec updated to match):**
+
+1. Copy/seed are **SQL functions in the migration** (atomic INSERT…SELECT, RLS-invoker), not Kysely transactions — avoids `as any` Kysely casts entirely.
+2. Matrix cells write **per-cell from the browser Supabase client** with optimistic state (the QuoteLinePricing precedent): update-by-id when the cell row exists, insert otherwise, delete on zero — no batched route action and no reliance on PostgREST `onConflict` against the NULLS NOT DISTINCT constraint.
+3. Prior-year-profile spreading is delivered by **seed-from-actuals** (it preserves the source year's monthly shape by construction; `p_spread = 'even'` flattens it). Row-level matrix helpers are Fill and Distribute only.
+
+## Dependencies
+
+```
+Task 1–2 (migration: schema, then functions)
+ └─ Task 16 (apply migration) — deferred until stack is up
+Task 3 (models) ─┬─ Task 5 (services) ─┬─ Task 9–10 (list/new/edit/delete/approve routes)
+Task 4 (types) ─┘ ├─ Task 11–12 (matrix component + route)
+Task 6 (path.ts) — needed by 7–14 └─ Task 13 (budget vs actual report)
+Task 7 (BudgetForm) ── Task 9
+Task 8 (BudgetsTable) ── Task 9
+Task 14 (sidebar) — after Task 6
+Task 15 (CSV import) — after Task 1–2 land; independent of UI tasks
+Task 17 (typecheck/lint/AGENTS.md) — last code task
+```
+
+---
+
+## Task 1: Migration — schema (enum, tables, trigger, RLS)
+
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_budgeting.sql`
+
+**Steps:**
+
+1. Create the migration file:
+
+```bash
+pnpm db:migrate:new budgeting
+# Creates packages/database/supabase/migrations/<timestamp>_budgeting.sql
+```
+
+Verify the generated timestamp sorts AFTER `20260702044133_period-close-lifecycle.sql` and its HHMMSS portion is not `000000` (rename with random HHMMSS if needed).
+
+2. Write the schema section:
+
+```sql
+-- Budgeting Phase 1: budget + budgetLine
+-- Amounts are GL-signed (positive = debit), matching journalLine.amount.
+-- Spec: .ai/specs/2026-07-02-budgeting.md
+
+DO $$ BEGIN
+ CREATE TYPE "budgetStatus" AS ENUM ('Draft', 'Approved', 'Archived');
+EXCEPTION WHEN duplicate_object THEN NULL;
+END $$;
+
+CREATE TABLE IF NOT EXISTS "budget" (
+ "id" TEXT NOT NULL DEFAULT id('bud'),
+ "companyId" TEXT NOT NULL,
+
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "fiscalYear" INTEGER NOT NULL,
+ "status" "budgetStatus" NOT NULL DEFAULT 'Draft',
+ "approvedBy" TEXT REFERENCES "user"("id"),
+ "approvedAt" TIMESTAMP WITH TIME ZONE,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ "tags" TEXT[],
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS "budget_companyId_idx" ON "budget" ("companyId");
+CREATE INDEX IF NOT EXISTS "budget_createdBy_idx" ON "budget" ("createdBy");
+CREATE INDEX IF NOT EXISTS "budget_companyId_fiscalYear_idx" ON "budget" ("companyId", "fiscalYear");
+
+DO $$ BEGIN
+ ALTER TABLE "budget" ADD CONSTRAINT "budget_companyId_name_key"
+ UNIQUE ("companyId", "name");
+EXCEPTION WHEN duplicate_table THEN NULL; WHEN duplicate_object THEN NULL;
+END $$;
+
+CREATE TABLE IF NOT EXISTS "budgetLine" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "budgetId" TEXT NOT NULL,
+
+ "accountId" TEXT NOT NULL,
+ "accountingPeriodId" TEXT NOT NULL,
+ "costCenterId" TEXT,
+ "amount" NUMERIC NOT NULL DEFAULT 0,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("budgetId", "companyId") REFERENCES "budget"("id", "companyId") ON DELETE CASCADE,
+ FOREIGN KEY ("accountId") REFERENCES "account"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("accountingPeriodId") REFERENCES "accountingPeriod"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("costCenterId") REFERENCES "costCenter"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS "budgetLine_companyId_idx" ON "budgetLine" ("companyId");
+CREATE INDEX IF NOT EXISTS "budgetLine_budgetId_idx" ON "budgetLine" ("budgetId", "companyId");
+CREATE INDEX IF NOT EXISTS "budgetLine_accountId_idx" ON "budgetLine" ("accountId");
+CREATE INDEX IF NOT EXISTS "budgetLine_accountingPeriodId_idx" ON "budgetLine" ("accountingPeriodId");
+CREATE INDEX IF NOT EXISTS "budgetLine_costCenterId_idx" ON "budgetLine" ("costCenterId");
+CREATE INDEX IF NOT EXISTS "budgetLine_createdBy_idx" ON "budgetLine" ("createdBy");
+
+DO $$ BEGIN
+ ALTER TABLE "budgetLine" ADD CONSTRAINT "budgetLine_cell_key"
+ UNIQUE NULLS NOT DISTINCT ("budgetId", "companyId", "accountId", "accountingPeriodId", "costCenterId");
+EXCEPTION WHEN duplicate_table THEN NULL; WHEN duplicate_object THEN NULL;
+END $$;
+
+-- Hard backstop (period-close trigger pattern): lines writable only in Draft.
+CREATE OR REPLACE FUNCTION check_budget_editable() RETURNS TRIGGER AS $$
+DECLARE v_status "budgetStatus";
+BEGIN
+ SELECT "status" INTO v_status FROM "budget"
+ WHERE "id" = COALESCE(NEW."budgetId", OLD."budgetId")
+ AND "companyId" = COALESCE(NEW."companyId", OLD."companyId");
+ IF v_status IS DISTINCT FROM 'Draft' THEN
+ RAISE EXCEPTION 'Budget is % — copy it to a new draft to revise', v_status;
+ END IF;
+ RETURN COALESCE(NEW, OLD);
+END;
+$$ LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS "budgetLine_check_editable" ON "budgetLine";
+CREATE TRIGGER "budgetLine_check_editable"
+ BEFORE INSERT OR UPDATE OR DELETE ON "budgetLine"
+ FOR EACH ROW EXECUTE FUNCTION check_budget_editable();
+
+-- RLS
+ALTER TABLE "public"."budget" ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."budget";
+CREATE POLICY "SELECT" ON "public"."budget"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+DROP POLICY IF EXISTS "INSERT" ON "public"."budget";
+CREATE POLICY "INSERT" ON "public"."budget"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_create'))::text[])
+);
+DROP POLICY IF EXISTS "UPDATE" ON "public"."budget";
+CREATE POLICY "UPDATE" ON "public"."budget"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])
+);
+DROP POLICY IF EXISTS "DELETE" ON "public"."budget";
+CREATE POLICY "DELETE" ON "public"."budget"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_delete'))::text[])
+);
+
+ALTER TABLE "public"."budgetLine" ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."budgetLine";
+CREATE POLICY "SELECT" ON "public"."budgetLine"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+DROP POLICY IF EXISTS "INSERT" ON "public"."budgetLine";
+CREATE POLICY "INSERT" ON "public"."budgetLine"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_create'))::text[])
+);
+DROP POLICY IF EXISTS "UPDATE" ON "public"."budgetLine";
+CREATE POLICY "UPDATE" ON "public"."budgetLine"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])
+);
+DROP POLICY IF EXISTS "DELETE" ON "public"."budgetLine";
+CREATE POLICY "DELETE" ON "public"."budgetLine"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_delete'))::text[])
+);
+```
+
+3. Do NOT apply yet — application is Task 16.
+
+---
+
+## Task 2: Migration — SQL functions (copy, seed, report)
+
+**Files:**
+- Modify: the Task 1 migration file (append)
+
+**Steps:**
+
+1. Append the copy function. It replaces the target budget's lines with the source's, remapping periods by `periodNumber` across fiscal years and multiplying by the factor. The Task 1 trigger enforces target-is-Draft per row; SECURITY INVOKER keeps RLS in force.
+
+```sql
+CREATE OR REPLACE FUNCTION "copyBudgetLines"(
+ p_company_id TEXT,
+ p_source_budget_id TEXT,
+ p_target_budget_id TEXT,
+ p_adjustment_factor NUMERIC DEFAULT 1,
+ p_created_by TEXT DEFAULT NULL
+) RETURNS INTEGER
+LANGUAGE plpgsql SECURITY INVOKER SET search_path = public
+AS $$
+DECLARE v_count INTEGER;
+BEGIN
+ DELETE FROM "budgetLine"
+ WHERE "budgetId" = p_target_budget_id AND "companyId" = p_company_id;
+
+ INSERT INTO "budgetLine"
+ ("companyId", "budgetId", "accountId", "accountingPeriodId", "costCenterId", "amount", "createdBy")
+ SELECT
+ p_company_id,
+ p_target_budget_id,
+ bl."accountId",
+ tp."id",
+ bl."costCenterId",
+ ROUND(bl."amount" * p_adjustment_factor, 2),
+ COALESCE(p_created_by, bl."createdBy")
+ FROM "budgetLine" bl
+ JOIN "budget" sb ON sb."id" = bl."budgetId" AND sb."companyId" = bl."companyId"
+ JOIN "budget" tb ON tb."id" = p_target_budget_id AND tb."companyId" = p_company_id
+ JOIN "accountingPeriod" sp
+ ON sp."id" = bl."accountingPeriodId" AND sp."companyId" = p_company_id
+ JOIN "accountingPeriod" tp
+ ON tp."companyId" = p_company_id
+ AND tp."fiscalYear" = tb."fiscalYear"
+ AND tp."periodNumber" = sp."periodNumber"
+ WHERE bl."budgetId" = p_source_budget_id
+ AND bl."companyId" = p_company_id
+ AND bl."amount" != 0;
+
+ GET DIAGNOSTICS v_count = ROW_COUNT;
+ RETURN v_count;
+END;
+$$;
+```
+
+2. Append the seed-from-actuals function. Aggregates posted journal lines by account × period-number × cost center (via the CostCenter-type dimension) for the source fiscal year and writes them into the target budget's matching periods. `p_spread = 'source'` keeps the monthly profile; `'even'` divides the annual total evenly across the target FY's periods.
+
+```sql
+CREATE OR REPLACE FUNCTION "seedBudgetLinesFromActuals"(
+ p_company_id TEXT,
+ p_source_fiscal_year INTEGER,
+ p_target_budget_id TEXT,
+ p_adjustment_factor NUMERIC DEFAULT 1,
+ p_spread TEXT DEFAULT 'source', -- 'source' | 'even'
+ p_created_by TEXT DEFAULT NULL
+) RETURNS INTEGER
+LANGUAGE plpgsql SECURITY INVOKER SET search_path = public
+AS $$
+DECLARE v_count INTEGER;
+BEGIN
+ DELETE FROM "budgetLine"
+ WHERE "budgetId" = p_target_budget_id AND "companyId" = p_company_id;
+
+ WITH "costCenterDim" AS (
+ SELECT d."id"
+ FROM "dimension" d
+ JOIN "company" c ON c."companyGroupId" = d."companyGroupId"
+ WHERE c."id" = p_company_id AND d."entityType" = 'CostCenter'
+ LIMIT 1
+ ),
+ "actuals" AS (
+ SELECT
+ jl."accountId",
+ sp."periodNumber",
+ jld."valueId" AS "costCenterId",
+ SUM(jl."amount") AS "amount"
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id" = jl."journalId" AND j."companyId" = p_company_id
+ JOIN "accountingPeriod" sp
+ ON sp."id" = j."accountingPeriodId"
+ AND sp."companyId" = p_company_id
+ AND sp."fiscalYear" = p_source_fiscal_year
+ LEFT JOIN "journalLineDimension" jld
+ ON jld."journalLineId" = jl."id"
+ AND jld."dimensionId" = (SELECT "id" FROM "costCenterDim")
+ WHERE jl."companyId" = p_company_id
+ AND jl."accountId" IS NOT NULL
+ GROUP BY jl."accountId", sp."periodNumber", jld."valueId"
+ ),
+ "shaped" AS (
+ SELECT
+ a."accountId",
+ tp."id" AS "accountingPeriodId",
+ a."costCenterId",
+ CASE
+ WHEN p_spread = 'even' THEN
+ ROUND((SUM(a."amount") OVER (PARTITION BY a."accountId", a."costCenterId"))
+ * p_adjustment_factor
+ / (COUNT(*) OVER (PARTITION BY a."accountId", a."costCenterId")), 2)
+ ELSE ROUND(a."amount" * p_adjustment_factor, 2)
+ END AS "amount"
+ FROM "actuals" a
+ JOIN "budget" tb ON tb."id" = p_target_budget_id AND tb."companyId" = p_company_id
+ JOIN "accountingPeriod" tp
+ ON tp."companyId" = p_company_id
+ AND tp."fiscalYear" = tb."fiscalYear"
+ AND tp."periodNumber" = a."periodNumber"
+ )
+ INSERT INTO "budgetLine"
+ ("companyId", "budgetId", "accountId", "accountingPeriodId", "costCenterId", "amount", "createdBy")
+ SELECT p_company_id, p_target_budget_id, s."accountId", s."accountingPeriodId",
+ s."costCenterId", s."amount", p_created_by
+ FROM "shaped" s
+ WHERE s."amount" != 0;
+
+ GET DIAGNOSTICS v_count = ROW_COUNT;
+ RETURN v_count;
+END;
+$$;
+```
+
+Note: `'even'` divides across the periods that had activity (the partition count). Fully-even 12-way spreads of sparse actuals are refined in the matrix; this matches "flatten what existed".
+
+3. Append the report function:
+
+```sql
+CREATE OR REPLACE FUNCTION "budgetVsActual"(
+ p_company_id TEXT,
+ p_budget_id TEXT,
+ p_cost_center_id TEXT DEFAULT NULL,
+ p_rollup BOOLEAN DEFAULT TRUE,
+ p_untagged BOOLEAN DEFAULT FALSE
+) RETURNS TABLE (
+ "accountId" TEXT,
+ "number" TEXT,
+ "name" TEXT,
+ "class" "glAccountClass",
+ "incomeBalance" "glIncomeBalance",
+ "periodNumber" INTEGER,
+ "budget" NUMERIC,
+ "actual" NUMERIC
+)
+LANGUAGE plpgsql SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH "targetBudget" AS (
+ SELECT b."id", b."companyId", b."fiscalYear"
+ FROM "budget" b
+ WHERE b."id" = p_budget_id AND b."companyId" = p_company_id
+ ),
+ "periods" AS (
+ SELECT ap."id", ap."periodNumber"
+ FROM "accountingPeriod" ap
+ JOIN "targetBudget" tb ON ap."companyId" = tb."companyId"
+ AND ap."fiscalYear" = tb."fiscalYear"
+ ),
+ "costCenterDim" AS (
+ SELECT d."id"
+ FROM "dimension" d
+ JOIN "company" c ON c."companyGroupId" = d."companyGroupId"
+ WHERE c."id" = p_company_id AND d."entityType" = 'CostCenter'
+ LIMIT 1
+ ),
+ "costCenters" AS (
+ -- the selected cost center (+ descendants when p_rollup)
+ WITH RECURSIVE "tree" AS (
+ SELECT cc."id" FROM "costCenter" cc
+ WHERE cc."id" = p_cost_center_id AND cc."companyId" = p_company_id
+ UNION ALL
+ SELECT child."id" FROM "costCenter" child
+ JOIN "tree" t ON child."parentCostCenterId" = t."id"
+ WHERE p_rollup
+ )
+ SELECT "id" FROM "tree"
+ ),
+ "budgetSide" AS (
+ SELECT bl."accountId", p."periodNumber", SUM(bl."amount") AS "amount"
+ FROM "budgetLine" bl
+ JOIN "periods" p ON p."id" = bl."accountingPeriodId"
+ WHERE bl."budgetId" = p_budget_id
+ AND bl."companyId" = p_company_id
+ AND (
+ (p_untagged AND bl."costCenterId" IS NULL)
+ OR (NOT p_untagged AND p_cost_center_id IS NULL)
+ OR (NOT p_untagged AND bl."costCenterId" IN (SELECT "id" FROM "costCenters"))
+ )
+ GROUP BY bl."accountId", p."periodNumber"
+ ),
+ "actualSide" AS (
+ SELECT jl."accountId", p."periodNumber", SUM(jl."amount") AS "amount"
+ FROM "journalLine" jl
+ JOIN "journal" j ON j."id" = jl."journalId" AND j."companyId" = p_company_id
+ JOIN "periods" p ON p."id" = j."accountingPeriodId"
+ WHERE jl."companyId" = p_company_id
+ AND jl."accountId" IS NOT NULL
+ AND (
+ (p_untagged AND NOT EXISTS (
+ SELECT 1 FROM "journalLineDimension" jld
+ WHERE jld."journalLineId" = jl."id"
+ AND jld."dimensionId" = (SELECT "id" FROM "costCenterDim")
+ ))
+ OR (NOT p_untagged AND p_cost_center_id IS NULL)
+ OR (NOT p_untagged AND EXISTS (
+ SELECT 1 FROM "journalLineDimension" jld
+ WHERE jld."journalLineId" = jl."id"
+ AND jld."dimensionId" = (SELECT "id" FROM "costCenterDim")
+ AND jld."valueId" IN (SELECT "id" FROM "costCenters")
+ ))
+ )
+ GROUP BY jl."accountId", p."periodNumber"
+ )
+ SELECT
+ a."id",
+ a."number",
+ a."name",
+ a."class",
+ a."incomeBalance",
+ COALESCE(b."periodNumber", act."periodNumber"),
+ COALESCE(b."amount", 0),
+ COALESCE(act."amount", 0)
+ FROM "budgetSide" b
+ FULL OUTER JOIN "actualSide" act
+ ON act."accountId" = b."accountId" AND act."periodNumber" = b."periodNumber"
+ JOIN "account" a ON a."id" = COALESCE(b."accountId", act."accountId")
+ ORDER BY a."number", COALESCE(b."periodNumber", act."periodNumber");
+END;
+$$;
+```
+
+2. Sanity-read the whole migration once against the spec's Data Model section.
+3. Do NOT apply yet.
+
+**✅ CHECKPOINT: commit** — `git add packages/database/supabase/migrations && git commit -m "feat(accounting): budgeting schema, copy/seed/report functions"`
+
+---
+
+## Task 3: Models — statuses + validators
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts`
+
+**Steps:**
+
+1. Next to `costCenterValidator` (line ~411), add:
+
+```typescript
+export const budgetStatusType = ["Draft", "Approved", "Archived"] as const;
+
+export const budgetValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ description: zfd.text(z.string().optional()),
+ fiscalYear: zfd.numeric(
+ z.number().int().min(2000, { message: "Fiscal year is required" }).max(2200)
+ ),
+ source: z.enum(["none", "budget", "actuals"]).optional(),
+ sourceBudgetId: zfd.text(z.string().optional()),
+ sourceFiscalYear: zfd.numeric(z.number().int().optional()),
+ adjustmentFactor: zfd.numeric(z.number().positive().optional()),
+ spread: z.enum(["source", "even"]).optional()
+});
+
+export const budgetStatusTransitionValidator = z.object({
+ intent: z.enum(["approve", "archive"])
+});
+```
+
+(The `source*` fields only apply on create; the edit form hides them.)
+
+---
+
+## Task 4: Types — manual budget types
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/types.ts`
+
+**Steps:**
+
+1. Below the `CostCenter` types (line ~46), add. These are hand-written because the tables are absent from the cloud-generated DB types:
+
+```typescript
+export type BudgetStatus = (typeof budgetStatusType)[number];
+
+export type Budget = {
+ id: string;
+ companyId: string;
+ name: string;
+ description: string | null;
+ fiscalYear: number;
+ status: BudgetStatus;
+ approvedBy: string | null;
+ approvedAt: string | null;
+ createdBy: string;
+ createdAt: string;
+ updatedBy: string | null;
+ updatedAt: string | null;
+};
+
+export type BudgetLine = {
+ id: string;
+ companyId: string;
+ budgetId: string;
+ accountId: string;
+ accountingPeriodId: string;
+ costCenterId: string | null;
+ amount: number;
+};
+
+export type BudgetVsActualRow = {
+ accountId: string;
+ number: string;
+ name: string;
+ class: string | null;
+ incomeBalance: string | null;
+ periodNumber: number;
+ budget: number;
+ actual: number;
+};
+```
+
+2. Add `budgetStatusType` to this file's imports from `./accounting.models` (match the existing import style at the top of `types.ts`).
+
+---
+
+## Task 5: Services — budget CRUD, lines, RPC wrappers
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts`
+
+**Steps:**
+
+1. Below the cost-center functions (after `upsertCostCenter`, line ~935), add. All `budget`/`budgetLine`/RPC access is cast (`as any`) because the cloud-generated types don't include them:
+
+```typescript
+export async function deleteBudget(
+ client: SupabaseClient<Database>,
+ budgetId: string,
+ companyId: string
+) {
+ return (client as any)
+ .from("budget")
+ .delete()
+ .eq("id", budgetId)
+ .eq("companyId", companyId)
+ .eq("status", "Draft");
+}
+
+export async function getBudget(
+ client: SupabaseClient<Database>,
+ budgetId: string,
+ companyId: string
+): Promise<{ data: Budget | null; error: PostgrestError | null }> {
+ return (client as any)
+ .from("budget")
+ .select("*")
+ .eq("id", budgetId)
+ .eq("companyId", companyId)
+ .single();
+}
+
+export async function getBudgets(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: GenericQueryFilters & { search: string | null }
+) {
+ let query = (client as any)
+ .from("budget")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
+
+ if (args?.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "fiscalYear", ascending: false },
+ { column: "name", ascending: true }
+ ]);
+ }
+
+ return query as unknown as Promise<{
+ data: Budget[] | null;
+ count: number | null;
+ error: PostgrestError | null;
+ }>;
+}
+
+export async function getBudgetsList(
+ client: SupabaseClient<Database>,
+ companyId: string
+): Promise<{ data: Pick<Budget, "id" | "name" | "fiscalYear" | "status">[] | null; error: PostgrestError | null }> {
+ return (client as any)
+ .from("budget")
+ .select("id, name, fiscalYear, status")
+ .eq("companyId", companyId)
+ .order("fiscalYear", { ascending: false })
+ .order("name");
+}
+
+export async function upsertBudget(
+ client: SupabaseClient<Database>,
+ budget:
+ | {
+ name: string;
+ description?: string;
+ fiscalYear: number;
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ }
+ | {
+ id: string;
+ name: string;
+ description?: string;
+ fiscalYear: number;
+ companyId: string;
+ updatedBy: string;
+ customFields?: Json;
+ }
+): Promise<{ data: { id: string } | null; error: PostgrestError | { message: string } | null }> {
+ if ("createdBy" in budget) {
+ // Ensure the fiscal year's periods exist before the matrix needs them.
+ const periods = await (client as any)
+ .from("accountingPeriod")
+ .select("id")
+ .eq("companyId", budget.companyId)
+ .eq("fiscalYear", budget.fiscalYear)
+ .limit(1);
+ if (periods.error) return { data: null, error: periods.error };
+ if (!periods.data || periods.data.length === 0) {
+ const generated = await createFiscalYearPeriods(client, {
+ companyId: budget.companyId,
+ fiscalYear: budget.fiscalYear,
+ userId: budget.createdBy
+ });
+ if (generated.error) return { data: null, error: generated.error };
+ }
+
+ return (client as any).from("budget").insert([budget]).select("id").single();
+ }
+ const { id, ...update } = budget;
+ return (client as any)
+ .from("budget")
+ .update(sanitize(update))
+ .eq("id", id)
+ .eq("companyId", budget.companyId)
+ .eq("status", "Draft")
+ .select("id")
+ .single();
+}
+
+export async function approveBudget(
+ client: SupabaseClient<Database>,
+ args: { budgetId: string; companyId: string; userId: string }
+) {
+ return (client as any)
+ .from("budget")
+ .update({
+ status: "Approved",
+ approvedBy: args.userId,
+ approvedAt: new Date().toISOString(),
+ updatedBy: args.userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", args.budgetId)
+ .eq("companyId", args.companyId)
+ .eq("status", "Draft")
+ .select("id")
+ .single();
+}
+
+export async function archiveBudget(
+ client: SupabaseClient<Database>,
+ args: { budgetId: string; companyId: string; userId: string }
+) {
+ return (client as any)
+ .from("budget")
+ .update({
+ status: "Archived",
+ updatedBy: args.userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", args.budgetId)
+ .eq("companyId", args.companyId)
+ .eq("status", "Approved")
+ .select("id")
+ .single();
+}
+
+export async function getBudgetLines(
+ client: SupabaseClient<Database>,
+ budgetId: string,
+ companyId: string
+): Promise<{ data: BudgetLine[] | null; error: PostgrestError | null }> {
+ return (client as any)
+ .from("budgetLine")
+ .select("id, budgetId, companyId, accountId, accountingPeriodId, costCenterId, amount")
+ .eq("budgetId", budgetId)
+ .eq("companyId", companyId);
+}
+
+export async function copyBudgetLines(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ sourceBudgetId: string;
+ targetBudgetId: string;
+ adjustmentFactor: number;
+ userId: string;
+ }
+) {
+ return (client as any).rpc("copyBudgetLines", {
+ p_company_id: args.companyId,
+ p_source_budget_id: args.sourceBudgetId,
+ p_target_budget_id: args.targetBudgetId,
+ p_adjustment_factor: args.adjustmentFactor,
+ p_created_by: args.userId
+ });
+}
+
+export async function seedBudgetLinesFromActuals(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ sourceFiscalYear: number;
+ targetBudgetId: string;
+ adjustmentFactor: number;
+ spread: "source" | "even";
+ userId: string;
+ }
+) {
+ return (client as any).rpc("seedBudgetLinesFromActuals", {
+ p_company_id: args.companyId,
+ p_source_fiscal_year: args.sourceFiscalYear,
+ p_target_budget_id: args.targetBudgetId,
+ p_adjustment_factor: args.adjustmentFactor,
+ p_spread: args.spread,
+ p_created_by: args.userId
+ });
+}
+
+export async function getBudgetVsActual(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ budgetId: string;
+ costCenterId?: string | null;
+ rollup?: boolean;
+ untagged?: boolean;
+ }
+): Promise<{ data: BudgetVsActualRow[] | null; error: PostgrestError | null }> {
+ return (client as any).rpc("budgetVsActual", {
+ p_company_id: args.companyId,
+ p_budget_id: args.budgetId,
+ p_cost_center_id: args.costCenterId ?? undefined,
+ p_rollup: args.rollup ?? true,
+ p_untagged: args.untagged ?? false
+ });
+}
+
+export async function getAccountingPeriodsForFiscalYear(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ fiscalYear: number
+): Promise<{
+ data: { id: string; periodNumber: number; startDate: string; endDate: string }[] | null;
+ error: PostgrestError | null;
+}> {
+ return (client as any)
+ .from("accountingPeriod")
+ .select("id, periodNumber, startDate, endDate")
+ .eq("companyId", companyId)
+ .eq("fiscalYear", fiscalYear)
+ .order("periodNumber");
+}
+```
+
+2. Add `Budget`, `BudgetLine`, `BudgetVsActualRow` to the file's type imports from `./types` (the file already imports types from there; match style). `createFiscalYearPeriods` is defined in this same file by the period-close plan (Task 4 there) — no import needed.
+
+3. Verify:
+
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | grep -i "budget" | head
+# Expected: no errors mentioning budget files
+```
+
+---
+
+## Task 6: path.ts — budget routes
+
+**Files:**
+- Modify: `apps/erp/app/utils/path.ts`
+
+**Steps:**
+
+1. In the app-routes block near `costCenters` (lines ~572–575), add alphabetically:
+
+```typescript
+budget: (id: string) => generatePath(`${x}/accounting/budgets/${id}`),
+budgets: `${x}/accounting/budgets`,
+budgetVsActual: `${x}/accounting/budget-vs-actual`,
+```
+
+2. Near `deleteCostCenter` (line ~690):
+
+```typescript
+deleteBudget: (id: string) =>
+ generatePath(`${x}/accounting/budgets/delete/${id}`),
+```
+
+3. Near `newCostCenter` (line ~1183):
+
+```typescript
+newBudget: `${x}/accounting/budgets/new`,
+```
+
+4. Near the other edit/approve-style helpers (keep alphabetical placement within the object):
+
+```typescript
+approveBudget: (id: string) =>
+ generatePath(`${x}/accounting/budgets/approve/${id}`),
+editBudget: (id: string) =>
+ generatePath(`${x}/accounting/budgets/edit/${id}`),
+```
+
+---
+
+## Task 7: BudgetForm component
+
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Budgets/BudgetForm.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Budgets/index.ts`
+
+**Steps:**
+
+1. `BudgetForm.tsx` — clone of `CostCenterForm.tsx` with the seed section. The budgets list for "copy from" comes from the list route's loader via `useRouteData`:
+
+```typescript
+import { ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ VStack
+} from "@carbon/react";
+import { useState } from "react";
+import type { z } from "zod";
+import {
+ Hidden,
+ Input,
+ Number as NumberField,
+ Select,
+ Submit,
+ TextArea
+} from "~/components/Form";
+import { usePermissions, useRouteData } from "~/hooks";
+import { path } from "~/utils/path";
+import { budgetValidator } from "../../accounting.models";
+import type { Budget } from "../../types";
+
+type BudgetFormProps = {
+ initialValues: z.infer<typeof budgetValidator>;
+ open?: boolean;
+ onClose: () => void;
+};
+
+const BudgetForm = ({ initialValues, open = true, onClose }: BudgetFormProps) => {
+ const permissions = usePermissions();
+ const routeData = useRouteData<{ budgets: Budget[] }>(path.to.budgets);
+ const budgets = routeData?.budgets ?? [];
+
+ const isEditing = initialValues.id !== undefined;
+ const [source, setSource] = useState<string>(initialValues.source ?? "none");
+ const isDisabled = isEditing
+ ? !permissions.can("update", "accounting")
+ : !permissions.can("create", "accounting");
+
+ return (
+ <ModalDrawerProvider type="drawer">
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={budgetValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.editBudget(initialValues.id!)
+ : path.to.newBudget
+ }
+ defaultValues={initialValues}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Budget
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <VStack spacing={4}>
+ <Input name="name" label="Name" />
+ <NumberField name="fiscalYear" label="Fiscal Year" />
+ <TextArea name="description" label="Description" />
+ {!isEditing && (
+ <>
+ <Select
+ name="source"
+ label="Start From"
+ options={[
+ { value: "none", label: "Empty budget" },
+ { value: "budget", label: "Copy another budget" },
+ { value: "actuals", label: "Prior-year actuals" }
+ ]}
+ onChange={(option) => setSource(option?.value ?? "none")}
+ />
+ {source === "budget" && (
+ <Select
+ name="sourceBudgetId"
+ label="Source Budget"
+ options={budgets.map((b) => ({
+ value: b.id,
+ label: `${b.name} (FY${b.fiscalYear})`
+ }))}
+ />
+ )}
+ {source === "actuals" && (
+ <NumberField
+ name="sourceFiscalYear"
+ label="Actuals From Fiscal Year"
+ />
+ )}
+ {source !== "none" && (
+ <>
+ <NumberField
+ name="adjustmentFactor"
+ label="Adjustment Factor"
+ helperText="1.05 = last year + 5%"
+ />
+ <Select
+ name="spread"
+ label="Spread"
+ options={[
+ { value: "source", label: "Match source periods" },
+ { value: "even", label: "Spread evenly" }
+ ]}
+ />
+ </>
+ )}
+ </>
+ )}
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={() => onClose?.()}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default BudgetForm;
+```
+
+Adjust the `Select`/`NumberField`/`TextArea` imports to the exact names exported from `~/components/Form` (check the barrel; e.g. the number input may be `Number`, `NumberInput`, or `NumberField`, and `helperText` may be `description` — mirror whatever `CostCenterForm`-adjacent forms use).
+
+2. `index.ts`:
+
+```typescript
+import BudgetForm from "./BudgetForm";
+import { BudgetMatrix } from "./BudgetMatrix";
+import { BudgetsTable } from "./BudgetsTable";
+
+export { BudgetForm, BudgetMatrix, BudgetsTable };
+```
+
+(`BudgetMatrix`/`BudgetsTable` are created in Tasks 8 and 11 — create the barrel now, it will typecheck after those land.)
+
+---
+
+## Task 8: BudgetsTable component
+
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Budgets/BudgetsTable.tsx`
+
+**Steps:**
+
+1. Simple row list styled like `CostCentersListView` (header row + bordered rows + actions dropdown). Name navigates to the matrix:
+
+```typescript
+import {
+ Badge,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ IconButton
+} from "@carbon/react";
+import { Link } from "react-router";
+import {
+ LuArchive,
+ LuCheck,
+ LuEllipsisVertical,
+ LuPencil,
+ LuTrash2
+} from "react-icons/lu";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import type { Budget } from "../../types";
+
+const statusVariant = (status: Budget["status"]) => {
+ switch (status) {
+ case "Approved":
+ return "green";
+ case "Archived":
+ return "secondary";
+ default:
+ return "outline";
+ }
+};
+
+export function BudgetsTable({
+ budgets,
+ onEdit,
+ onDelete,
+ onApprove
+}: {
+ budgets: Budget[];
+ onEdit: (id: string) => void;
+ onDelete: (id: string) => void;
+ onApprove: (id: string) => void;
+}) {
+ const permissions = usePermissions();
+ const canUpdate = permissions.can("update", "accounting");
+ const canDelete = permissions.can("delete", "accounting");
+
+ return (
+ <div className="bg-card overflow-hidden h-full">
+ <div className="grid grid-cols-[1fr_120px_120px_auto] items-center border-b border-border bg-card h-11 px-6 gap-3">
+ <span className="text-sm font-medium text-foreground/80">Budget</span>
+ <span className="text-sm font-medium text-foreground/80">
+ Fiscal Year
+ </span>
+ <span className="text-sm font-medium text-foreground/80">Status</span>
+ <span className="text-sm font-medium text-foreground/80">Actions</span>
+ </div>
+ {budgets.map((budget) => (
+ <div
+ key={budget.id}
+ className="grid grid-cols-[1fr_120px_120px_auto] items-center gap-3 border-b border-border px-6 py-3 transition-colors hover:bg-accent/50"
+ >
+ <div className="flex flex-col gap-0 min-w-0">
+ <Link
+ to={path.to.budget(budget.id)}
+ className="text-sm font-medium text-foreground hover:underline truncate"
+ >
+ {budget.name}
+ </Link>
+ {budget.description && (
+ <span className="text-xs text-muted-foreground truncate">
+ {budget.description}
+ </span>
+ )}
+ </div>
+ <span className="text-sm text-foreground">{budget.fiscalYear}</span>
+ <div>
+ <Badge variant={statusVariant(budget.status)}>{budget.status}</Badge>
+ </div>
+ <div className="ml-auto">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="sm"
+ aria-label="Actions"
+ icon={<LuEllipsisVertical />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuItem
+ disabled={budget.status !== "Draft" || !canUpdate}
+ onClick={() => onEdit(budget.id)}
+ >
+ <LuPencil className="mr-2 size-4" />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={budget.status !== "Draft" || !canUpdate}
+ onClick={() => onApprove(budget.id)}
+ >
+ <LuCheck className="mr-2 size-4" />
+ Approve
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={budget.status !== "Approved" || !canUpdate}
+ onClick={() => onApprove(budget.id)}
+ >
+ <LuArchive className="mr-2 size-4" />
+ Archive
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className="text-destructive focus:text-destructive"
+ disabled={budget.status !== "Draft" || !canDelete}
+ onClick={() => onDelete(budget.id)}
+ >
+ <LuTrash2 className="mr-2 size-4" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ ))}
+ {budgets.length === 0 && (
+ <div className="px-6 py-10 text-sm text-muted-foreground">
+ No budgets yet. Create one to start planning.
+ </div>
+ )}
+ </div>
+ );
+}
+```
+
+If `Badge` variants differ (check `packages/react` Badge variants), map to the nearest existing variants — do not invent new ones.
+
+---
+
+## Task 9: Routes — list + new
+
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/budgets.tsx`
+- Create: `apps/erp/app/routes/x+/accounting+/budgets.new.tsx`
+
+**Steps:**
+
+1. `budgets.tsx` (clone of `cost-centers.tsx` shape):
+
+```typescript
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { Heading, HStack } from "@carbon/react";
+import { useCallback } from "react";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, redirect, useLoaderData, useNavigate } from "react-router";
+import { New } from "~/components";
+import { getBudgets } from "~/modules/accounting";
+import { BudgetsTable } from "~/modules/accounting/ui/Budgets";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Budgets",
+ to: path.to.budgets
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const budgets = await getBudgets(client, companyId);
+
+ if (budgets.error) {
+ throw redirect(
+ path.to.accounting,
+ await flash(request, error(budgets.error, "Failed to load budgets"))
+ );
+ }
+
+ return {
+ budgets: budgets.data ?? []
+ };
+}
+
+export default function Route() {
+ const { budgets } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ const handleEdit = useCallback(
+ (id: string) => navigate(path.to.editBudget(id)),
+ [navigate]
+ );
+ const handleDelete = useCallback(
+ (id: string) => navigate(path.to.deleteBudget(id)),
+ [navigate]
+ );
+ const handleApprove = useCallback(
+ (id: string) => navigate(path.to.approveBudget(id)),
+ [navigate]
+ );
+
+ return (
+ <div className="w-full">
+ <div className="flex px-4 py-3 items-center space-x-4 justify-between bg-card border-b border-border w-full">
+ <Heading size="h3">Budgets</Heading>
+ <HStack>
+ <New label="Budget" to={path.to.newBudget} variant="primary" />
+ </HStack>
+ </div>
+ <BudgetsTable
+ budgets={budgets}
+ onEdit={handleEdit}
+ onDelete={handleDelete}
+ onApprove={handleApprove}
+ />
+ <Outlet />
+ </div>
+ );
+}
+```
+
+2. `budgets.new.tsx` (clone of `cost-centers.new.tsx`; after header insert, run the optional seed and land on the matrix):
+
+```typescript
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect, useNavigate } from "react-router";
+import {
+ budgetValidator,
+ copyBudgetLines,
+ seedBudgetLinesFromActuals,
+ upsertBudget
+} from "~/modules/accounting";
+import { BudgetForm } from "~/modules/accounting/ui/Budgets";
+import { setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "accounting"
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(budgetValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const {
+ id: _id,
+ source,
+ sourceBudgetId,
+ sourceFiscalYear,
+ adjustmentFactor,
+ spread,
+ ...d
+ } = validation.data;
+
+ const createBudget = await upsertBudget(client, {
+ ...d,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData)
+ });
+
+ if (createBudget.error || !createBudget.data) {
+ throw redirect(
+ path.to.budgets,
+ await flash(request, error(createBudget.error, "Failed to create budget"))
+ );
+ }
+
+ const budgetId = createBudget.data.id;
+
+ if (source === "budget" && sourceBudgetId) {
+ const copied = await copyBudgetLines(client, {
+ companyId,
+ sourceBudgetId,
+ targetBudgetId: budgetId,
+ adjustmentFactor: adjustmentFactor ?? 1,
+ userId
+ });
+ if (copied.error) {
+ throw redirect(
+ path.to.budget(budgetId),
+ await flash(request, error(copied.error, "Budget created, but copying lines failed"))
+ );
+ }
+ }
+
+ if (source === "actuals" && sourceFiscalYear) {
+ const seeded = await seedBudgetLinesFromActuals(client, {
+ companyId,
+ sourceFiscalYear,
+ targetBudgetId: budgetId,
+ adjustmentFactor: adjustmentFactor ?? 1,
+ spread: spread ?? "source",
+ userId
+ });
+ if (seeded.error) {
+ throw redirect(
+ path.to.budget(budgetId),
+ await flash(request, error(seeded.error, "Budget created, but seeding from actuals failed"))
+ );
+ }
+ }
+
+ throw redirect(
+ path.to.budget(budgetId),
+ await flash(request, success("Budget created"))
+ );
+}
+
+export default function NewBudgetRoute() {
+ const navigate = useNavigate();
+
+ const initialValues = {
+ name: "",
+ fiscalYear: new Date().getFullYear() + 1,
+ source: "none" as const
+ };
+
+ return (
+ <BudgetForm onClose={() => navigate(-1)} initialValues={initialValues} />
+ );
+}
+```
+
+---
+
+## Task 10: Routes — edit, delete, approve/archive
+
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/budgets.edit.$budgetId.tsx`
+- Create: `apps/erp/app/routes/x+/accounting+/budgets.delete.$budgetId.tsx`
+- Create: `apps/erp/app/routes/x+/accounting+/budgets.approve.$budgetId.tsx`
+
+**Steps:**
+
+1. `budgets.edit.$budgetId.tsx` (clone of `cost-centers.$costCenterId.tsx`):
+
+```typescript
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate } from "react-router";
+import { budgetValidator, getBudget, upsertBudget } from "~/modules/accounting";
+import { BudgetForm } from "~/modules/accounting/ui/Budgets";
+import { setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting"
+ });
+
+ const { budgetId } = params;
+ if (!budgetId) throw notFound("Budget ID was not found");
+
+ const budget = await getBudget(client, budgetId, companyId);
+ if (budget.error || !budget.data) {
+ throw redirect(
+ path.to.budgets,
+ await flash(request, error(budget.error, "Failed to get budget"))
+ );
+ }
+
+ return { budget: budget.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "accounting"
+ });
+
+ const { budgetId } = params;
+ if (!budgetId) throw notFound("Budget ID was not found");
+
+ const formData = await request.formData();
+ const validation = await validator(budgetValidator).validate(formData);
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id: _id, source, sourceBudgetId, sourceFiscalYear, adjustmentFactor, spread, ...d } =
+ validation.data;
+
+ const updateBudget = await upsertBudget(client, {
+ id: budgetId,
+ ...d,
+ companyId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData)
+ });
+
+ if (updateBudget.error) {
+ throw redirect(
+ path.to.budgets,
+ await flash(request, error(updateBudget.error, "Failed to update budget"))
+ );
+ }
+
+ throw redirect(
+ path.to.budgets,
+ await flash(request, success("Budget updated"))
+ );
+}
+
+export default function EditBudgetRoute() {
+ const { budget } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ const initialValues = {
+ id: budget.id,
+ name: budget.name,
+ description: budget.description ?? undefined,
+ fiscalYear: budget.fiscalYear
+ };
+
+ return (
+ <BudgetForm
+ onClose={() => navigate(-1)}
+ key={initialValues.id}
+ initialValues={initialValues}
+ />
+ );
+}
+```
+
+2. `budgets.delete.$budgetId.tsx` (clone of `cost-centers.delete.$costCenterId.tsx` — loader fetches via `getBudget(client, budgetId, companyId)`, action requires `delete: "accounting"` and calls `deleteBudget(client, budgetId, companyId)`, component renders `ConfirmDelete` with `action={path.to.deleteBudget(budgetId)}`, `name={budget.name}`, text `Are you sure you want to delete the budget: ${budget.name}? This cannot be undone. Only Draft budgets can be deleted.`, cancel navigates to `path.to.budgets`).
+
+3. `budgets.approve.$budgetId.tsx` — confirm modal driving approve OR archive by current status:
+
+```typescript
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
+import { ConfirmDelete } from "~/components/Modals";
+import { approveBudget, archiveBudget, getBudget } from "~/modules/accounting";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const { budgetId } = params;
+ if (!budgetId) throw notFound("budgetId not found");
+
+ const budget = await getBudget(client, budgetId, companyId);
+ if (budget.error || !budget.data) {
+ throw redirect(
+ path.to.budgets,
+ await flash(request, error(budget.error, "Failed to get budget"))
+ );
+ }
+
+ return { budget: budget.data };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "accounting"
+ });
+
+ const { budgetId } = params;
+ if (!budgetId) throw notFound("budgetId not found");
+
+ const budget = await getBudget(client, budgetId, companyId);
+ if (budget.error || !budget.data) {
+ throw redirect(
+ path.to.budgets,
+ await flash(request, error(budget.error, "Failed to get budget"))
+ );
+ }
+
+ const transition =
+ budget.data.status === "Draft"
+ ? await approveBudget(client, { budgetId, companyId, userId })
+ : await archiveBudget(client, { budgetId, companyId, userId });
+
+ if (transition.error) {
+ throw redirect(
+ path.to.budgets,
+ await flash(request, error(transition.error, "Failed to update budget status"))
+ );
+ }
+
+ throw redirect(
+ path.to.budgets,
+ await flash(
+ request,
+ success(
+ budget.data.status === "Draft" ? "Budget approved" : "Budget archived"
+ )
+ )
+ );
+}
+
+export default function ApproveBudgetRoute() {
+ const { budgetId } = useParams();
+ const { budget } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!budget || !budgetId) return null;
+
+ const isDraft = budget.status === "Draft";
+
+ return (
+ <ConfirmDelete
+ action={path.to.approveBudget(budgetId)}
+ name={budget.name}
+ text={
+ isDraft
+ ? `Approve the budget: ${budget.name}? Approved budgets are locked — revise by copying to a new draft.`
+ : `Archive the budget: ${budget.name}?`
+ }
+ onCancel={() => navigate(path.to.budgets)}
+ />
+ );
+}
+```
+
+If `ConfirmDelete` hardcodes destructive copy/styling, check `~/components/Modals` for a generic `Confirm` and use that instead — same props shape.
+
+**✅ CHECKPOINT: commit** — models, types, services, paths, form, table, CRUD routes: `git add -A && git commit -m "feat(accounting): budget CRUD (models, services, routes, UI)"`
+
+---
+
+## Task 11: BudgetMatrix component
+
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Budgets/BudgetMatrix.tsx`
+
+**Steps:**
+
+1. Grid = `Table/Thead/Tbody/Tr/Td` with `EditableNumberCell` per period cell, per the QuoteLinePricing precedent: optimistic local state keyed by cell, update-by-id / insert / delete-on-zero via the browser client (`useCarbon`), toast on failure. Amounts stored GL-signed; displayed natural per account class.
+
+```typescript
+import { useCarbon } from "@carbon/auth";
+import {
+ Badge,
+ Button,
+ HStack,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr,
+ toast
+} from "@carbon/react";
+import { useCallback, useMemo, useState } from "react";
+import { Link } from "react-router";
+import { LuDownload, LuUpload } from "react-icons/lu";
+import { EditableNumberCell } from "~/components/EditableNumberCell";
+import { ImportCSVModal } from "~/components/ImportCSVModal";
+import { path } from "~/utils/path";
+import type { Budget, BudgetLine } from "../../types";
+
+type MatrixAccount = {
+ id: string;
+ number: string | null;
+ name: string | null;
+ class: string | null;
+ incomeBalance: string | null;
+};
+
+type MatrixPeriod = { id: string; periodNumber: number };
+
+// GL-signed storage: debit-normal classes store entered value as-is;
+// credit-normal classes store the negation. Display reverses it.
+const isDebitNormal = (accountClass: string | null) =>
+ accountClass === "Asset" || accountClass === "Expense";
+const toStored = (value: number, accountClass: string | null) =>
+ isDebitNormal(accountClass) ? value : -value;
+const toDisplay = (amount: number, accountClass: string | null) =>
+ isDebitNormal(accountClass) ? amount : -amount;
+
+const cellKey = (accountId: string, periodId: string) =>
+ `${accountId}:${periodId}`;
+
+export function BudgetMatrix({
+ budget,
+ accounts,
+ periods,
+ lines,
+ costCenters,
+ companyId,
+ userId
+}: {
+ budget: Budget;
+ accounts: MatrixAccount[];
+ periods: MatrixPeriod[];
+ lines: BudgetLine[];
+ costCenters: { id: string; name: string }[];
+ companyId: string;
+ userId: string;
+}) {
+ const { carbon } = useCarbon();
+ const isEditable = budget.status === "Draft";
+
+ // null = company-level cells
+ const [costCenterId, setCostCenterId] = useState<string | null>(null);
+ const [showImport, setShowImport] = useState(false);
+ const [classFilter, setClassFilter] = useState<"Income Statement" | "All">(
+ "Income Statement"
+ );
+ const [search, setSearch] = useState("");
+
+ // cells for the active cost-center slice
+ const [cells, setCells] = useState<
+ Record<string, { id: string | null; amount: number }>
+ >(() => buildCells(lines, null));
+
+ function buildCells(all: BudgetLine[], cc: string | null) {
+ const next: Record<string, { id: string | null; amount: number }> = {};
+ for (const line of all) {
+ if ((line.costCenterId ?? null) !== cc) continue;
+ next[cellKey(line.accountId, line.accountingPeriodId)] = {
+ id: line.id,
+ amount: line.amount
+ };
+ }
+ return next;
+ }
+
+ const [allLines, setAllLines] = useState<BudgetLine[]>(lines);
+
+ const switchCostCenter = useCallback(
+ (cc: string | null) => {
+ setCostCenterId(cc);
+ setCells(buildCells(allLines, cc));
+ },
+ [allLines]
+ );
+
+ const visibleAccounts = useMemo(
+ () =>
+ accounts.filter((a) => {
+ if (classFilter === "Income Statement" && a.incomeBalance !== "Income Statement")
+ return false;
+ if (!search) return true;
+ const q = search.toLowerCase();
+ return (
+ (a.number ?? "").toLowerCase().includes(q) ||
+ (a.name ?? "").toLowerCase().includes(q)
+ );
+ }),
+ [accounts, classFilter, search]
+ );
+
+ const writeCell = useCallback(
+ async (account: MatrixAccount, periodId: string, displayValue: number) => {
+ if (!carbon) return;
+ const key = cellKey(account.id, periodId);
+ const existing = cells[key];
+ const stored = toStored(displayValue, account.class);
+
+ // optimistic
+ setCells((prev) => ({
+ ...prev,
+ [key]: { id: existing?.id ?? null, amount: stored }
+ }));
+
+ if (displayValue === 0 && existing?.id) {
+ const del = await (carbon as any)
+ .from("budgetLine")
+ .delete()
+ .eq("id", existing.id)
+ .eq("companyId", companyId);
+ if (del?.error) {
+ toast.error("Failed to clear budget amount");
+ setCells((prev) => ({ ...prev, [key]: existing }));
+ return;
+ }
+ setCells((prev) => {
+ const next = { ...prev };
+ delete next[key];
+ return next;
+ });
+ setAllLines((prev) => prev.filter((l) => l.id !== existing.id));
+ return;
+ }
+
+ if (existing?.id) {
+ const update = await (carbon as any)
+ .from("budgetLine")
+ .update({
+ amount: stored,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", existing.id)
+ .eq("companyId", companyId);
+ if (update?.error) {
+ toast.error("Failed to update budget amount");
+ setCells((prev) => ({ ...prev, [key]: existing }));
+ } else {
+ setAllLines((prev) =>
+ prev.map((l) => (l.id === existing.id ? { ...l, amount: stored } : l))
+ );
+ }
+ } else if (displayValue !== 0) {
+ const insert = await (carbon as any)
+ .from("budgetLine")
+ .insert({
+ budgetId: budget.id,
+ companyId,
+ accountId: account.id,
+ accountingPeriodId: periodId,
+ costCenterId,
+ amount: stored,
+ createdBy: userId
+ })
+ .select("id")
+ .single();
+ if (insert?.error || !insert?.data) {
+ toast.error("Failed to save budget amount");
+ setCells((prev) => {
+ const next = { ...prev };
+ delete next[key];
+ return next;
+ });
+ } else {
+ const newLine: BudgetLine = {
+ id: insert.data.id,
+ companyId,
+ budgetId: budget.id,
+ accountId: account.id,
+ accountingPeriodId: periodId,
+ costCenterId,
+ amount: stored
+ };
+ setCells((prev) => ({
+ ...prev,
+ [key]: { id: newLine.id, amount: stored }
+ }));
+ setAllLines((prev) => [...prev, newLine]);
+ }
+ }
+ },
+ [carbon, cells, companyId, userId, budget.id, costCenterId]
+ );
+
+ const fillRow = useCallback(
+ (account: MatrixAccount) => {
+ const first = cells[cellKey(account.id, periods[0]?.id ?? "")];
+ if (!first) return;
+ const displayValue = toDisplay(first.amount, account.class);
+ for (const period of periods.slice(1)) {
+ void writeCell(account, period.id, displayValue);
+ }
+ },
+ [cells, periods, writeCell]
+ );
+
+ const distributeRow = useCallback(
+ (account: MatrixAccount) => {
+ const first = cells[cellKey(account.id, periods[0]?.id ?? "")];
+ if (!first) return;
+ const annual = toDisplay(first.amount, account.class);
+ const per = Math.round((annual / periods.length) * 100) / 100;
+ for (const period of periods) {
+ void writeCell(account, period.id, per);
+ }
+ },
+ [cells, periods, writeCell]
+ );
+
+ const exportCsv = useCallback(() => {
+ const header = [
+ "budget",
+ "accountNumber",
+ "costCenter",
+ ...periods.map((p) => `period${p.periodNumber}`)
+ ];
+ const ccName = costCenters.find((c) => c.id === costCenterId)?.name ?? "";
+ const rows = visibleAccounts
+ .map((account) => {
+ const values = periods.map((p) => {
+ const cell = cells[cellKey(account.id, p.id)];
+ return cell ? toDisplay(cell.amount, account.class) : "";
+ });
+ if (values.every((v) => v === "")) return null;
+ return [budget.name, account.number ?? "", ccName, ...values];
+ })
+ .filter(Boolean) as (string | number)[][];
+ const csv = [header, ...rows]
+ .map((row) => row.map((v) => `"${String(v).replace(/"/g, '""')}"`).join(","))
+ .join("\n");
+ const blob = new Blob([csv], { type: "text/csv" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `${budget.name}.csv`;
+ a.click();
+ URL.revokeObjectURL(url);
+ }, [budget.name, cells, costCenterId, costCenters, periods, visibleAccounts]);
+
+ return (
+ <div className="w-full">
+ <div className="flex px-4 py-3 items-center gap-2 justify-between bg-card border-b border-border w-full flex-wrap">
+ <HStack>
+ <span className="text-sm font-medium">{budget.name}</span>
+ <Badge variant={budget.status === "Approved" ? "green" : "outline"}>
+ {budget.status}
+ </Badge>
+ <span className="text-sm text-muted-foreground">
+ FY{budget.fiscalYear}
+ </span>
+ </HStack>
+ <HStack>
+ <select
+ className="h-8 rounded-md border border-border bg-card px-2 text-sm"
+ value={costCenterId ?? ""}
+ onChange={(e) => switchCostCenter(e.target.value || null)}
+ >
+ <option value="">Company-level</option>
+ {costCenters.map((cc) => (
+ <option key={cc.id} value={cc.id}>
+ {cc.name}
+ </option>
+ ))}
+ </select>
+ <select
+ className="h-8 rounded-md border border-border bg-card px-2 text-sm"
+ value={classFilter}
+ onChange={(e) =>
+ setClassFilter(e.target.value as "Income Statement" | "All")
+ }
+ >
+ <option value="Income Statement">Income Statement</option>
+ <option value="All">All Accounts</option>
+ </select>
+ <input
+ className="h-8 rounded-md border border-border bg-card px-2 text-sm"
+ placeholder="Search accounts"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ />
+ <Button
+ variant="secondary"
+ leftIcon={<LuDownload />}
+ onClick={exportCsv}
+ >
+ Export
+ </Button>
+ {isEditable && (
+ <Button
+ variant="secondary"
+ leftIcon={<LuUpload />}
+ onClick={() => setShowImport(true)}
+ >
+ Import
+ </Button>
+ )}
+ </HStack>
+ </div>
+
+ {!isEditable && (
+ <div className="px-4 py-2 text-sm bg-muted text-muted-foreground border-b border-border">
+ This budget is {budget.status.toLowerCase()} and read-only. Copy it to
+ a new draft from the <Link className="underline" to={path.to.newBudget}>New Budget</Link> form to revise.
+ </div>
+ )}
+
+ <div className="overflow-auto">
+ <Table>
+ <Thead>
+ <Tr>
+ <Th className="w-[280px] sticky left-0 bg-card z-10">Account</Th>
+ {periods.map((p) => (
+ <Th key={p.id} className="text-right min-w-[110px]">
+ P{p.periodNumber}
+ </Th>
+ ))}
+ <Th className="text-right min-w-[120px]">Total</Th>
+ {isEditable && <Th className="w-[130px]" />}
+ </Tr>
+ </Thead>
+ <Tbody>
+ {visibleAccounts.map((account) => {
+ const rowTotal = periods.reduce((sum, p) => {
+ const cell = cells[cellKey(account.id, p.id)];
+ return sum + (cell ? toDisplay(cell.amount, account.class) : 0);
+ }, 0);
+ return (
+ <Tr key={account.id} className="group">
+ <Td className="sticky left-0 bg-card z-10 border-r border-border">
+ <div className="flex flex-col">
+ <span className="text-sm font-medium">
+ {account.number}
+ </span>
+ <span className="text-xs text-muted-foreground truncate">
+ {account.name}
+ </span>
+ </div>
+ </Td>
+ {periods.map((p) => {
+ const cell = cells[cellKey(account.id, p.id)];
+ const display = cell
+ ? toDisplay(cell.amount, account.class)
+ : 0;
+ return (
+ <Td key={p.id} className="text-right group-hover:bg-muted/50">
+ <EditableNumberCell
+ value={display}
+ formatOptions={{
+ style: "decimal",
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ }}
+ isEditable={isEditable}
+ onChange={(value) =>
+ writeCell(account, p.id, value ?? 0)
+ }
+ />
+ </Td>
+ );
+ })}
+ <Td className="text-right font-medium tabular-nums">
+ {rowTotal.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ })}
+ </Td>
+ {isEditable && (
+ <Td>
+ <HStack spacing={1}>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => fillRow(account)}
+ >
+ Fill
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => distributeRow(account)}
+ >
+ ÷12
+ </Button>
+ </HStack>
+ </Td>
+ )}
+ </Tr>
+ );
+ })}
+ </Tbody>
+ </Table>
+ </div>
+
+ {showImport && (
+ <ImportCSVModal
+ table="budgetLine"
+ onClose={() => setShowImport(false)}
+ />
+ )}
+ </div>
+ );
+}
+```
+
+2. Reconcile against the real precedents while implementing:
+ - `EditableNumberCell` props: match its actual signature (`value`, `formatOptions`, `minValue`, `isEditable`, `onChange`) from `apps/erp/app/components/EditableNumberCell.tsx`.
+ - `useCarbon` import: match wherever `QuoteLinePricing.tsx` gets its `carbon` client from.
+ - `Button` `leftIcon` prop: match the real `@carbon/react` Button API.
+ - Native `<select>`/`<input>` are acceptable here only if no lightweight `Select`/`SearchInput` exists outside form contexts — check `@carbon/react` `Select`/`Combobox` first and prefer it.
+ - "Fill" reads P1 and copies it to P2..P12; "÷12" distributes P1's value as an annual figure. Both are client loops over `writeCell` (sequential awaits are fine at 11–12 requests).
+
+---
+
+## Task 12: Route — matrix page
+
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/budgets_.$budgetId.tsx`
+
+The trailing underscore (`budgets_`) opts out of nesting inside `budgets.tsx` (remix-flat-routes), making the matrix a full page at `/x/accounting/budgets/:budgetId`.
+
+**Steps:**
+
+1. Create:
+
+```typescript
+import { error, notFound } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData } from "react-router";
+import {
+ getAccountingPeriodsForFiscalYear,
+ getBudget,
+ getBudgetLines,
+ getCostCentersList
+} from "~/modules/accounting";
+import { BudgetMatrix } from "~/modules/accounting/ui/Budgets";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Budgets",
+ to: path.to.budgets
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId, companyGroupId, userId } = await requirePermissions(
+ request,
+ {
+ view: "accounting",
+ role: "employee"
+ }
+ );
+
+ const { budgetId } = params;
+ if (!budgetId) throw notFound("Budget ID was not found");
+
+ const budget = await getBudget(client, budgetId, companyId);
+ if (budget.error || !budget.data) {
+ throw redirect(
+ path.to.budgets,
+ await flash(request, error(budget.error, "Failed to get budget"))
+ );
+ }
+
+ const [accounts, periods, lines, costCenters] = await Promise.all([
+ client
+ .from("accounts")
+ .select("id, number, name, class, incomeBalance")
+ .eq("companyGroupId", companyGroupId)
+ .eq("active", true)
+ .eq("directPosting", true)
+ .order("number", { ascending: true }),
+ getAccountingPeriodsForFiscalYear(client, companyId, budget.data.fiscalYear),
+ getBudgetLines(client, budgetId, companyId),
+ getCostCentersList(client, companyId)
+ ]);
+
+ if (accounts.error) {
+ throw redirect(
+ path.to.budgets,
+ await flash(request, error(accounts.error, "Failed to load accounts"))
+ );
+ }
+ if (periods.error || !periods.data || periods.data.length === 0) {
+ throw redirect(
+ path.to.budgets,
+ await flash(
+ request,
+ error(
+ periods.error,
+ `No accounting periods exist for fiscal year ${budget.data.fiscalYear}`
+ )
+ )
+ );
+ }
+
+ return {
+ budget: budget.data,
+ accounts: (accounts.data ?? []).filter((a) => a.id !== null),
+ periods: periods.data,
+ lines: lines.data ?? [],
+ costCenters: costCenters.data ?? [],
+ companyId,
+ userId
+ };
+}
+
+export default function BudgetMatrixRoute() {
+ const { budget, accounts, periods, lines, costCenters, companyId, userId } =
+ useLoaderData<typeof loader>();
+
+ return (
+ <BudgetMatrix
+ budget={budget}
+ accounts={accounts as any}
+ periods={periods}
+ lines={lines}
+ costCenters={costCenters}
+ companyId={companyId}
+ userId={userId}
+ />
+ );
+}
+```
+
+2. Verify the `accounts` view exposes `directPosting` and `companyGroupId` (it selects `account.*` plus category names — check the newest `accounts` view migration). If not, query the `account` table directly with the same columns plus `.eq("companyId", companyId)`.
+
+---
+
+## Task 13: Budget vs Actual report
+
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/budget-vs-actual.tsx`
+
+**Steps:**
+
+1. Create (loader shape below is complete; match the header/filter JSX classNames to `trial-balance.tsx` — read that file first and mirror its layout primitives):
+
+```typescript
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { Badge, Heading, HStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "react-router";
+import {
+ redirect,
+ useLoaderData,
+ useNavigate,
+ useSearchParams
+} from "react-router";
+import {
+ getBudgetsList,
+ getBudgetVsActual,
+ getCostCentersList
+} from "~/modules/accounting";
+import type { BudgetVsActualRow } from "~/modules/accounting";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Budget vs Actual",
+ to: path.to.budgetVsActual
+};
+
+const isDebitNormal = (accountClass: string | null) =>
+ accountClass === "Asset" || accountClass === "Expense";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const budgetId = url.searchParams.get("budgetId");
+ const costCenterId = url.searchParams.get("costCenterId");
+ const fromPeriod = Number(url.searchParams.get("from") ?? 1);
+ const toPeriod = Number(url.searchParams.get("to") ?? 12);
+
+ const [budgets, costCenters] = await Promise.all([
+ getBudgetsList(client, companyId),
+ getCostCentersList(client, companyId)
+ ]);
+
+ if (budgets.error) {
+ throw redirect(
+ path.to.accounting,
+ await flash(request, error(budgets.error, "Failed to load budgets"))
+ );
+ }
+
+ // Default to the most recently approved budget, else the first budget.
+ const defaultBudget =
+ budgets.data?.find((b) => b.status === "Approved") ?? budgets.data?.[0];
+ const selectedBudgetId = budgetId ?? defaultBudget?.id ?? null;
+
+ let rows: BudgetVsActualRow[] = [];
+ let untaggedActual = 0;
+
+ if (selectedBudgetId) {
+ const result = await getBudgetVsActual(client, {
+ companyId,
+ budgetId: selectedBudgetId,
+ costCenterId,
+ rollup: true
+ });
+ if (result.error) {
+ throw redirect(
+ path.to.accounting,
+ await flash(request, error(result.error, "Failed to load budget vs actual"))
+ );
+ }
+ rows = (result.data ?? []).filter(
+ (r) => r.periodNumber >= fromPeriod && r.periodNumber <= toPeriod
+ );
+
+ if (costCenterId) {
+ const untagged = await getBudgetVsActual(client, {
+ companyId,
+ budgetId: selectedBudgetId,
+ untagged: true
+ });
+ untaggedActual = (untagged.data ?? [])
+ .filter((r) => r.periodNumber >= fromPeriod && r.periodNumber <= toPeriod)
+ .reduce((sum, r) => sum + r.actual, 0);
+ }
+ }
+
+ // Aggregate per account over the period range, natural-signed per class.
+ const byAccount = new Map<
+ string,
+ { number: string; name: string; class: string | null; budget: number; actual: number }
+ >();
+ for (const row of rows) {
+ const sign = isDebitNormal(row.class) ? 1 : -1;
+ const entry = byAccount.get(row.accountId) ?? {
+ number: row.number,
+ name: row.name,
+ class: row.class,
+ budget: 0,
+ actual: 0
+ };
+ entry.budget += sign * row.budget;
+ entry.actual += sign * row.actual;
+ byAccount.set(row.accountId, entry);
+ }
+
+ return {
+ budgets: budgets.data ?? [],
+ costCenters: costCenters.data ?? [],
+ selectedBudgetId,
+ costCenterId,
+ fromPeriod,
+ toPeriod,
+ untaggedActual,
+ accounts: Array.from(byAccount.entries()).map(([accountId, v]) => ({
+ accountId,
+ ...v,
+ variance: v.actual - v.budget,
+ variancePercent: v.budget !== 0 ? ((v.actual - v.budget) / Math.abs(v.budget)) * 100 : null
+ }))
+ };
+}
+
+export default function BudgetVsActualRoute() {
+ const {
+ budgets,
+ costCenters,
+ selectedBudgetId,
+ costCenterId,
+ fromPeriod,
+ toPeriod,
+ untaggedActual,
+ accounts
+ } = useLoaderData<typeof loader>();
+ const [searchParams, setSearchParams] = useSearchParams();
+
+ const setParam = (key: string, value: string) => {
+ const next = new URLSearchParams(searchParams);
+ if (value) next.set(key, value);
+ else next.delete(key);
+ setSearchParams(next);
+ };
+
+ const format = (n: number) =>
+ n.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ });
+
+ return (
+ <div className="w-full">
+ <div className="flex px-4 py-3 items-center gap-2 justify-between bg-card border-b border-border w-full flex-wrap">
+ <Heading size="h3">Budget vs Actual</Heading>
+ <HStack>
+ <select
+ className="h-8 rounded-md border border-border bg-card px-2 text-sm"
+ value={selectedBudgetId ?? ""}
+ onChange={(e) => setParam("budgetId", e.target.value)}
+ >
+ {budgets.map((b) => (
+ <option key={b.id} value={b.id}>
+ {b.name} (FY{b.fiscalYear}
+ {b.status === "Approved" ? ", approved" : ""})
+ </option>
+ ))}
+ </select>
+ <select
+ className="h-8 rounded-md border border-border bg-card px-2 text-sm"
+ value={costCenterId ?? ""}
+ onChange={(e) => setParam("costCenterId", e.target.value)}
+ >
+ <option value="">All cost centers</option>
+ {costCenters.map((cc) => (
+ <option key={cc.id} value={cc.id}>
+ {cc.name}
+ </option>
+ ))}
+ </select>
+ <select
+ className="h-8 rounded-md border border-border bg-card px-2 text-sm"
+ value={String(fromPeriod)}
+ onChange={(e) => setParam("from", e.target.value)}
+ >
+ {Array.from({ length: 12 }, (_, i) => i + 1).map((p) => (
+ <option key={p} value={p}>
+ From P{p}
+ </option>
+ ))}
+ </select>
+ <select
+ className="h-8 rounded-md border border-border bg-card px-2 text-sm"
+ value={String(toPeriod)}
+ onChange={(e) => setParam("to", e.target.value)}
+ >
+ {Array.from({ length: 12 }, (_, i) => i + 1).map((p) => (
+ <option key={p} value={p}>
+ To P{p}
+ </option>
+ ))}
+ </select>
+ </HStack>
+ </div>
+
+ {costCenterId && untaggedActual !== 0 && (
+ <div className="px-4 py-2 text-sm bg-muted text-muted-foreground border-b border-border">
+ {format(Math.abs(untaggedActual))} of actuals in this range are not
+ tagged to any cost center and are excluded from this view.
+ </div>
+ )}
+
+ <div className="overflow-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-border h-11">
+ <th className="text-left px-6 font-medium text-foreground/80">
+ Account
+ </th>
+ <th className="text-right px-6 font-medium text-foreground/80">
+ Budget
+ </th>
+ <th className="text-right px-6 font-medium text-foreground/80">
+ Actual
+ </th>
+ <th className="text-right px-6 font-medium text-foreground/80">
+ Variance
+ </th>
+ <th className="text-right px-6 font-medium text-foreground/80">
+ Variance %
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {accounts.map((a) => (
+ <tr
+ key={a.accountId}
+ className="border-b border-border hover:bg-accent/50"
+ >
+ <td className="px-6 py-2">
+ <span className="font-medium">{a.number}</span>{" "}
+ <span className="text-muted-foreground">{a.name}</span>
+ </td>
+ <td className="px-6 py-2 text-right tabular-nums">
+ {format(a.budget)}
+ </td>
+ <td className="px-6 py-2 text-right tabular-nums">
+ {format(a.actual)}
+ </td>
+ <td
+ className={`px-6 py-2 text-right tabular-nums ${
+ a.variance > 0 ? "text-destructive" : ""
+ }`}
+ >
+ {format(a.variance)}
+ </td>
+ <td className="px-6 py-2 text-right tabular-nums">
+ {a.variancePercent === null ? (
+ <Badge variant="outline">No budget</Badge>
+ ) : (
+ `${a.variancePercent.toFixed(1)}%`
+ )}
+ </td>
+ </tr>
+ ))}
+ {accounts.length === 0 && (
+ <tr>
+ <td
+ colSpan={5}
+ className="px-6 py-10 text-muted-foreground text-sm"
+ >
+ No data for this selection.
+ </td>
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ );
+}
+```
+
+Note: "Variance > 0 = over budget" holds for expense accounts in natural sign; for revenue accounts a positive variance means beating plan — refine the color rule to `class === "Expense" && variance > 0` if the simple rule reads wrong during review.
+
+---
+
+## Task 14: Sidebar — accounting submodules
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx`
+
+**Steps:**
+
+1. Add to the **Reports** group (after Trial Balance):
+
+```typescript
+{
+ name: t`Budget vs Actual`,
+ to: path.to.budgetVsActual,
+ role: "employee",
+ icon: <LuTarget />
+},
+```
+
+2. Add to the **General Ledger** group (next to Journal Entries):
+
+```typescript
+{
+ name: t`Budgets`,
+ to: path.to.budgets,
+ role: "employee",
+ icon: <LuWallet />
+},
+```
+
+3. Add `LuTarget` and `LuWallet` to the `react-icons/lu` import list (pick different Lu icons if these collide with existing entries' style).
+
+**✅ CHECKPOINT: commit** — `git add -A && git commit -m "feat(accounting): budget matrix, budget vs actual report, sidebar"`
+
+---
+
+## Task 15: CSV import — budgetLine
+
+Wide format: one row per account (× cost center), one column per period. Columns: `budget` (enum → budget), `accountNumber`, `costCenter` (optional enum), `period1`…`period12`.
+
+**Files:**
+- Modify: `apps/erp/app/modules/shared/imports.models.ts`
+- Modify: `packages/database/supabase/functions/import-csv/index.ts`
+
+**Steps:**
+
+1. In `imports.models.ts`, add to `fieldMappings` (mirror the `workCenter` entry's exact shape, ~line 1401):
+
+```typescript
+budgetLine: {
+ budget: {
+ label: "Budget",
+ required: true,
+ type: "enum",
+ enumData: {
+ description: "The budget to import lines into (must be Draft)",
+ fetcher: async (client, companyId) => {
+ return (client as any)
+ .from("budget")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .eq("status", "Draft")
+ .order("name");
+ }
+ }
+ },
+ accountNumber: { label: "Account Number", required: true, type: "string" },
+ costCenter: {
+ label: "Cost Center",
+ required: false,
+ type: "enum",
+ enumData: {
+ description: "Optional cost center for these amounts",
+ fetcher: async (client, companyId) => {
+ return client
+ .from("costCenter")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .order("name");
+ }
+ }
+ },
+ period1: { label: "Period 1", required: false, type: "number" },
+ period2: { label: "Period 2", required: false, type: "number" },
+ period3: { label: "Period 3", required: false, type: "number" },
+ period4: { label: "Period 4", required: false, type: "number" },
+ period5: { label: "Period 5", required: false, type: "number" },
+ period6: { label: "Period 6", required: false, type: "number" },
+ period7: { label: "Period 7", required: false, type: "number" },
+ period8: { label: "Period 8", required: false, type: "number" },
+ period9: { label: "Period 9", required: false, type: "number" },
+ period10: { label: "Period 10", required: false, type: "number" },
+ period11: { label: "Period 11", required: false, type: "number" },
+ period12: { label: "Period 12", required: false, type: "number" }
+},
+```
+
+2. Add `budgetLine: "accounting"` to `importPermissions` (~line 1589).
+
+3. Add a `budgetLine` entry to `importSchemas` (~line 1654) mirroring the exact zod shape of the `workCenter` entry (column-name strings per field; `budget` and `accountNumber` required, the rest optional).
+
+4. In the edge function, add `"budgetLine"` to the table enum (line ~18–32).
+
+5. Add the case block in the switch (following the `workCenter` block's structure, but resolving references and upserting by cell key — no externalIdMap):
+
+```typescript
+case "budgetLine": {
+ // Resolve referenced entities once.
+ const budgetIds = new Set(
+ mappedRecords.map((r) => r.budget).filter(Boolean)
+ );
+ const budgets = await trx
+ .selectFrom("budget" as any)
+ .select(["id", "fiscalYear", "status"] as any)
+ .where("companyId", "=", companyId)
+ .where("id", "in", [...budgetIds])
+ .execute();
+ const budgetById = new Map(budgets.map((b: any) => [b.id, b]));
+
+ const accountNumbers = new Set(
+ mappedRecords.map((r) => r.accountNumber?.trim()).filter(Boolean)
+ );
+ const accounts = await trx
+ .selectFrom("account")
+ .select(["id", "number"])
+ .where("companyId", "=", companyId)
+ .where("number", "in", [...accountNumbers])
+ .execute();
+ const accountByNumber = new Map(accounts.map((a) => [a.number, a.id]));
+
+ const fiscalYears = new Set(
+ [...budgetById.values()].map((b: any) => b.fiscalYear)
+ );
+ const periods = await trx
+ .selectFrom("accountingPeriod" as any)
+ .select(["id", "fiscalYear", "periodNumber"] as any)
+ .where("companyId", "=", companyId)
+ .where("fiscalYear", "in", [...fiscalYears])
+ .execute();
+ const periodByYearAndNumber = new Map(
+ periods.map((p: any) => [`${p.fiscalYear}:${p.periodNumber}`, p.id])
+ );
+
+ let rowIndex = 0;
+ for (const record of mappedRecords) {
+ rowIndex++;
+ const budget = budgetById.get(record.budget) as any;
+ if (!budget) {
+ summary.errors.push({ row: rowIndex, reason: "Unknown budget" });
+ continue;
+ }
+ if (budget.status !== "Draft") {
+ summary.errors.push({
+ row: rowIndex,
+ reason: `Budget is ${budget.status} — only Draft budgets can be imported into`
+ });
+ continue;
+ }
+ const accountId = accountByNumber.get(record.accountNumber?.trim());
+ if (!accountId) {
+ summary.errors.push({
+ row: rowIndex,
+ reason: `Unknown account number: ${record.accountNumber}`
+ });
+ continue;
+ }
+ const costCenterId = record.costCenter || null;
+
+ for (let periodNumber = 1; periodNumber <= 12; periodNumber++) {
+ const raw = record[`period${periodNumber}`];
+ if (raw === undefined || raw === null || String(raw).trim() === "") {
+ continue;
+ }
+ const amount = parseFloat(String(raw).replace(/[$,]/g, ""));
+ if (Number.isNaN(amount)) {
+ summary.errors.push({
+ row: rowIndex,
+ reason: `Invalid amount in period ${periodNumber}: ${raw}`
+ });
+ continue;
+ }
+ const accountingPeriodId = periodByYearAndNumber.get(
+ `${budget.fiscalYear}:${periodNumber}`
+ );
+ if (!accountingPeriodId) {
+ summary.errors.push({
+ row: rowIndex,
+ reason: `No accounting period ${periodNumber} for fiscal year ${budget.fiscalYear}`
+ });
+ continue;
+ }
+
+ await trx
+ .insertInto("budgetLine" as any)
+ .values({
+ budgetId: budget.id,
+ companyId,
+ accountId,
+ accountingPeriodId,
+ costCenterId,
+ amount,
+ createdBy: userId,
+ createdAt: new Date().toISOString()
+ } as any)
+ .onConflict((oc: any) =>
+ oc.constraint("budgetLine_cell_key").doUpdateSet({
+ amount,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ )
+ .execute();
+ summary.inserted++;
+ }
+ }
+ break;
+}
+```
+
+Adapt variable names (`mappedRecords`, `summary`, `trx`, `companyId`, `userId`) to the exact identifiers in scope in the switch — read the neighboring `workCenter` case first. Note: imported amounts are **GL-signed as stored** (the exported CSV round-trips natural values for display but the export writes natural sign — reconcile by documenting that import expects the same natural sign as export produces and applying the class-based sign flip: resolve each account's `class` in the account query above, then store `isDebitNormal ? amount : -amount` exactly like the matrix. Add `"class"` to the account select and apply the flip.)
+
+6. Enum note: the CSV enum-mapping UI maps CSV values → ids via `enumMappings`, so `record.budget` / `record.costCenter` arrive as ids — verify against how the `workCenter` case treats its `locationId` enum field and match.
+
+**✅ CHECKPOINT: commit** — `git add -A && git commit -m "feat(accounting): budget line CSV import"`
+
+---
+
+## Task 16: Apply migration + SQL smoke test (requires local stack)
+
+**Steps:**
+
+1. With the local stack up (`crbn up` — user runs this; do not rebuild anything):
+
+```bash
+pnpm db:migrate
+# Expected: applies 20260702044133_period-close-lifecycle.sql (if pending) and the budgeting migration without error
+```
+
+2. Smoke-test in psql (get the port from `.env.local` `PORT_DB`):
+
+```sql
+-- Draft-only trigger: create a budget, approve it, try to write a line
+INSERT INTO "budget" ("companyId", "name", "fiscalYear", "createdBy")
+VALUES ('<companyId>', 'Trigger Test', 2027, '<userId>') RETURNING "id";
+-- write a line while Draft: should succeed (needs a real accountId + accountingPeriodId)
+UPDATE "budget" SET "status" = 'Approved' WHERE "name" = 'Trigger Test';
+-- write a line now: should fail with 'Budget is Approved — copy it to a new draft to revise'
+-- cleanup
+DELETE FROM "budget" WHERE "name" = 'Trigger Test';
+```
+
+3. Verify the cell-uniqueness constraint treats NULL cost centers as equal:
+
+```sql
+-- two inserts with the same (budget, account, period, NULL) → second must fail
+```
+
+4. Do NOT run `pnpm db:types` and do NOT commit any types.ts changes.
+
+---
+
+## Task 17: Typecheck, lint, AGENTS.md
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/AGENTS.md` (if the module has one — check; otherwise the root accounting docs reference)
+
+**Steps:**
+
+1. Verify:
+
+```bash
+pnpm --filter @carbon/erp typecheck
+# Expected: passes (pre-existing errors unrelated to budget files are acceptable — compare against main)
+pnpm run lint
+# Expected: no new Biome errors in touched files
+```
+
+2. Update `modules/accounting` AGENTS.md: add the new service functions (`getBudgets`, `getBudget`, `getBudgetsList`, `upsertBudget`, `approveBudget`, `archiveBudget`, `deleteBudget`, `getBudgetLines`, `copyBudgetLines`, `seedBudgetLinesFromActuals`, `getBudgetVsActual`, `getAccountingPeriodsForFiscalYear`), the two tables, the `budgetVsActual`/`copyBudgetLines`/`seedBudgetLinesFromActuals` RPCs, and the routes.
+
+3. Product docs (`docs/content/` Accounting → Budgets page + glossary) are written when the feature ships to users — track as a follow-up, not part of this branch's gate.
+
+**✅ FINAL CHECKPOINT: commit** — `git add -A && git commit -m "feat(accounting): budgeting phase 1 — verification + docs"`
+
+---
+
+## Post-plan verification (acceptance criteria spot-checks)
+
+With the stack up and migration applied, walk the Phase 1 acceptance criteria from the spec:
+
+1. Create "2027 Plan" (FY2027) → periods auto-created, budget appears, matrix opens with 12 period columns.
+2. Enter 5,000 in P1 for an expense account → Fill and ÷12 behave; reload persists; zeroing a cell deletes its row (check `budgetLine` count).
+3. Switch cost center to a real cost center → cells are a separate slice; company-level cells unchanged.
+4. New budget "2027 Stretch" copying "2027 Plan" ×1.1 → lines equal source × 1.1.
+5. Seed from FY2026 actuals (requires posted journals locally; enable accounting per `.ai/` memory: `/x/settings/accounting`) → lines match `journalLine` aggregates.
+6. Approve "2027 Plan" → matrix read-only; SQL insert on its lines fails.
+7. Budget vs Actual → Actual ties to trial balance for the same range; cost-center filter + untagged banner behave.
+8. Export CSV from the matrix → edit a value → import through the modal → cell updated.
+
+UI verification per house rules: boot with `crbn up`, verify via agent-browser before calling Phase 1 done.
diff --git a/.ai/plans/2026-07-02-financial-reporting.md b/.ai/plans/2026-07-02-financial-reporting.md
new file mode 100644
index 0000000000..77c0608cfe
--- /dev/null
+++ b/.ai/plans/2026-07-02-financial-reporting.md
@@ -0,0 +1,1112 @@
+# Financial Reporting — Implementation Plan
+
+> ⚠️ **2026-07-03 delta (readiness roadmap):** the spec gained Posted-only balances (`2026-07-03-public-company-readiness.md` SD-1 → spec §11): add `p_include_drafts BOOLEAN DEFAULT FALSE` to `accountTreeBalancesByCompany` and the redefined `trialBalance` RPC, an "Include drafts" toggle on report filters, and drawer-follows-parent behavior in the drill-down. See `.ai/plans/2026-07-03-public-company-readiness-roadmap.md`.
+
+## Overview
+
+- **Design Spec:** `.ai/specs/2026-07-02-financial-reporting.md` (status: in-progress, all open questions resolved)
+- **Research:** `.ai/research/financial-reporting.md`
+- **Tasks:** 24 tasks + gated verification
+- **Branch:** `feature/financial-reporting`
+
+Scope = the full spec (former Phase 2 folded into v1): statement of cash flows
+(indirect; single-company AND consolidated with FX-effect line), Retained
+Earnings / Net Income split, GL detail report + journal drawer + drill-down
+links, four-column trial balance, comparative columns, CSV export, PDF
+financial statements package, period picker, and saved report views. Still out
+of scope: cash-basis toggle, dimension-filtered statements, PDF customization,
+shared views.
+
+**Ground rules for the executor:**
+
+- Do NOT regenerate or commit `packages/database/src/types.ts` — committed types are cloud-generated. Access new columns (`account.cashFlowActivity`, new `trialBalance` RPC return columns) via `as unknown as` / `(client as any)` casts (established pattern; see the period-closing plan and `(client as any).from("itemSamplingPlan")` in post-receipt).
+- Do NOT rebuild the database. Apply the migration with `pnpm db:migrate` only, when the local stack is up (Task 22).
+- Typecheck per package (`pnpm --filter @carbon/erp typecheck`), never whole-repo `tsc --noEmit` (OOMs).
+- Sign convention (load-bearing): `journalLine.amount` is **class-normal signed** — positive = the account's natural direction (debit for Asset/Expense, credit for Liability/Equity/Revenue). See `packages/utils/src/accounting.ts`. Never assume "positive = debit" globally.
+- Commit only at marked checkpoints after verification passes (check-and-commit gate); never auto-commit.
+
+## Dependencies
+
+```
+Task 1 (migration file) ── Task 22 (apply migration) — deferred until stack is up
+Task 2 (models/types) ─┬─ Task 3 (pure utils + tests)
+ ├─ Task 4 (RE/CYE split service) ── Task 10 (statement tree display + drill links)
+ ├─ Task 5 (cash flow service) ─┬─── Task 8 (cash-flow route/UI)
+ │ └─── Task 16 (rates + consolidated SCF service) ── Task 17 (consolidated SCF UI)
+ └─ Task 6 (GL detail service) ───── Task 9 (general-ledger route/UI)
+Task 7 (path.ts + nav) — independent; needed by Tasks 8, 9, 11
+Task 11 (journal drawer) — after Task 7
+Task 12 (comparatives) — after Task 4
+Task 13 (trial balance UI) — after Tasks 1 (SQL shape), 7
+Task 14 (account form select) — after Task 2
+Task 15 (CSV export buttons) — after Tasks 8, 10, 13
+Task 18 (period picker) — after Task 7 (reads period-closing columns; hides gracefully)
+Task 19 (report views service + resource route) — after Tasks 1 (table), 2
+Task 20 (report views UI in filters) — after Task 19
+Task 21 (PDF package: component + route + buttons) — after Tasks 4, 5, 16
+Task 22 (apply migration) — env-gated, before Task 23
+Task 23 (full gate: typecheck/lint/tests) — after all code tasks
+Task 24 (browser verification /test) — last
+Independent of each other (parallel-safe): 3∥4∥5∥6, 8∥9∥11∥13∥14, 16∥18∥19
+```
+
+## Progress
+
+- [ ] Task 1: Migration — `cashFlowActivity` enum/column, `accounts` view, `reportView` table, four-column `trialBalance` RPC
+- [ ] Task 2: Models & types — cash flow enums, validator field, statement types
+- [ ] Task 3: Pure helpers + unit tests — activity mapping, fiscal year start, cash flow builder
+- [ ] Task 4: Service — Retained Earnings / Net Income split in `getFinancialStatementBalances`
+- [ ] Task 5: Service — `getCashFlowStatement`
+- [ ] Task 6: Service — `getGeneralLedgerLines` + opening balance
+- [ ] Task 7: Paths + accounting nav entries
+- [ ] Task 8: Route + UI — cash flow statement
+- [ ] Task 9: Route + UI — general ledger detail report
+- [ ] Task 10: Statement trees — RE/CYE display, drill links, unclassified warning
+- [ ] Task 11: Route + UI — journal entry drawer
+- [ ] Task 12: Comparative columns on income statement + balance sheet
+- [ ] Task 13: Trial balance — four-column UI + drill links
+- [ ] Task 14: Account form — Cash Flow Activity select
+- [ ] Task 15: CSV export buttons on statement reports
+- [ ] Task 16: Service — currency rates helper + consolidated cash flow
+- [ ] Task 17: Cash flow UI — consolidated mode + FX-effect line
+- [ ] Task 18: Period picker in ReportFilters
+- [ ] Task 19: Report views — models, service, resource route
+- [ ] Task 20: Report views UI — dropdown + save/delete in ReportFilters
+- [ ] Task 21: PDF financial statements package
+- [ ] Task 22: Apply migration locally
+- [ ] Task 23: Full verification gate
+- [ ] Task 24: Browser verification (/test)
+
+---
+
+## Task 1: Migration — `cashFlowActivity` + `accounts` view + four-column `trialBalance` RPC
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_financial-reporting.sql` (via `pnpm db:migrate:new financial-reporting`; if the generated HHMMSS is `000000`, rename the file with a randomized HHMMSS)
+
+**Steps:**
+
+1. `pnpm db:migrate:new financial-reporting`
+2. Write exactly this SQL (forked from the newest `trialBalance` definition in `20260315000001_per-company-balance-rpc.sql`; all statements idempotent):
+
+```sql
+-- Financial reporting: cash flow classification + four-column trial balance
+-- Spec: .ai/specs/2026-07-02-financial-reporting.md
+
+-- 1. Cash flow activity override (QuickBooks Desktop "Classify Cash" pattern).
+-- NULL = derive from accountType at read time.
+DO $$ BEGIN
+ CREATE TYPE "cashFlowActivity" AS ENUM ('Operating', 'Investing', 'Financing');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+ALTER TABLE "account"
+ ADD COLUMN IF NOT EXISTS "cashFlowActivity" "cashFlowActivity";
+
+-- 2. Recreate the accounts view so the new column is exposed
+-- (view is a plain SELECT *; see 20260229000003_chart-of-accounts-tree.sql)
+DROP VIEW IF EXISTS "accounts";
+CREATE VIEW "accounts" WITH(SECURITY_INVOKER=true) AS
+SELECT * FROM "account";
+
+-- 3. Saved report views — personal-preference table mirroring
+-- userModulePreference (20260512174538_menu-customization.sql):
+-- simple PK, owner-scoped RLS, (userId, companyId, report, name) unique.
+-- No createdBy/updatedBy: ownership IS userId (matches precedent).
+CREATE TABLE IF NOT EXISTS "reportView" (
+ "id" TEXT NOT NULL DEFAULT id('rpv'),
+ "userId" TEXT NOT NULL REFERENCES "user"("id") ON DELETE CASCADE,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "report" TEXT NOT NULL CHECK ("report" IN
+ ('balance-sheet', 'income-statement', 'cash-flow', 'trial-balance', 'general-ledger')),
+ "name" TEXT NOT NULL,
+ "params" JSONB NOT NULL DEFAULT '{}',
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "reportView_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "reportView_userId_companyId_report_name_key"
+ UNIQUE ("userId", "companyId", "report", "name")
+);
+
+CREATE INDEX IF NOT EXISTS "reportView_userId_companyId_idx"
+ ON "reportView" ("userId", "companyId");
+
+ALTER TABLE "reportView" ENABLE ROW LEVEL SECURITY;
+
+DO $$ BEGIN
+ CREATE POLICY "SELECT" ON "reportView"
+ FOR SELECT USING ("userId" = auth.uid()::text);
+ CREATE POLICY "INSERT" ON "reportView"
+ FOR INSERT WITH CHECK ("userId" = auth.uid()::text);
+ CREATE POLICY "UPDATE" ON "reportView"
+ FOR UPDATE USING ("userId" = auth.uid()::text);
+ CREATE POLICY "DELETE" ON "reportView"
+ FOR DELETE USING ("userId" = auth.uid()::text);
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- 4. Four-column trial balance. Return shape changes, so DROP first
+-- (CREATE OR REPLACE cannot change an OUT row type).
+DROP FUNCTION IF EXISTS "trialBalance"(TEXT, TEXT, DATE, DATE);
+
+CREATE FUNCTION "trialBalance" (
+ p_company_group_id TEXT,
+ p_company_id TEXT DEFAULT NULL,
+ from_date DATE DEFAULT (now() - INTERVAL '100 year'),
+ to_date DATE DEFAULT now()
+)
+RETURNS TABLE (
+ "accountId" TEXT,
+ "accountNumber" TEXT,
+ "accountName" TEXT,
+ "accountClass" "glAccountClass",
+ "incomeBalance" "glIncomeBalance",
+ "openingDebit" NUMERIC(19, 4),
+ "openingCredit" NUMERIC(19, 4),
+ "periodDebits" NUMERIC(19, 4),
+ "periodCredits" NUMERIC(19, 4),
+ "debitBalance" NUMERIC(19, 4),
+ "creditBalance" NUMERIC(19, 4),
+ "netChange" NUMERIC(19, 4)
+)
+LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH "movements" AS (
+ -- Per-leaf period debit/credit sums. A line is a debit when its sign
+ -- matches the account's natural-debit direction (class-normal signing).
+ SELECT
+ a."id" AS "mAccountId",
+ COALESCE(SUM(
+ CASE WHEN j."postingDate" >= from_date AND j."postingDate" <= to_date
+ AND ((a."class" IN ('Asset', 'Expense') AND jl."amount" > 0)
+ OR (a."class" IN ('Liability', 'Equity', 'Revenue') AND jl."amount" < 0))
+ THEN ABS(jl."amount") ELSE 0 END), 0) AS "periodDebits",
+ COALESCE(SUM(
+ CASE WHEN j."postingDate" >= from_date AND j."postingDate" <= to_date
+ AND ((a."class" IN ('Asset', 'Expense') AND jl."amount" < 0)
+ OR (a."class" IN ('Liability', 'Equity', 'Revenue') AND jl."amount" > 0))
+ THEN ABS(jl."amount") ELSE 0 END), 0) AS "periodCredits"
+ FROM "account" a
+ LEFT JOIN "journalLine" jl ON jl."accountId" = a."id"
+ AND (p_company_id IS NULL OR jl."companyId" = p_company_id)
+ LEFT JOIN "journal" j ON j."id" = jl."journalId"
+ WHERE a."companyGroupId" = p_company_group_id
+ AND a."isGroup" = false
+ AND a."active" = true
+ GROUP BY a."id"
+ )
+ SELECT
+ a."id" AS "accountId",
+ a."number" AS "accountNumber",
+ a."name" AS "accountName",
+ a."class" AS "accountClass",
+ a."incomeBalance",
+ -- Opening = balanceAtDate − netChange, split by class direction
+ CASE
+ WHEN a."class" IN ('Asset', 'Expense') AND (b."balanceAtDate" - b."netChange") > 0 THEN (b."balanceAtDate" - b."netChange")
+ WHEN a."class" IN ('Liability', 'Equity', 'Revenue') AND (b."balanceAtDate" - b."netChange") < 0 THEN ABS(b."balanceAtDate" - b."netChange")
+ ELSE 0::NUMERIC(19, 4)
+ END AS "openingDebit",
+ CASE
+ WHEN a."class" IN ('Liability', 'Equity', 'Revenue') AND (b."balanceAtDate" - b."netChange") >= 0 THEN (b."balanceAtDate" - b."netChange")
+ WHEN a."class" IN ('Asset', 'Expense') AND (b."balanceAtDate" - b."netChange") < 0 THEN ABS(b."balanceAtDate" - b."netChange")
+ ELSE 0::NUMERIC(19, 4)
+ END AS "openingCredit",
+ COALESCE(m."periodDebits", 0)::NUMERIC(19, 4) AS "periodDebits",
+ COALESCE(m."periodCredits", 0)::NUMERIC(19, 4) AS "periodCredits",
+ -- Closing (existing semantics, unchanged)
+ CASE
+ WHEN a."class" IN ('Asset', 'Expense') AND b."balanceAtDate" > 0 THEN b."balanceAtDate"
+ WHEN a."class" IN ('Liability', 'Equity', 'Revenue') AND b."balanceAtDate" < 0 THEN ABS(b."balanceAtDate")
+ ELSE 0::NUMERIC(19, 4)
+ END AS "debitBalance",
+ CASE
+ WHEN a."class" IN ('Liability', 'Equity', 'Revenue') AND b."balanceAtDate" >= 0 THEN b."balanceAtDate"
+ WHEN a."class" IN ('Asset', 'Expense') AND b."balanceAtDate" < 0 THEN ABS(b."balanceAtDate")
+ ELSE 0::NUMERIC(19, 4)
+ END AS "creditBalance",
+ b."netChange"
+ FROM "account" a
+ INNER JOIN "accountTreeBalancesByCompany"(p_company_group_id, p_company_id, from_date, to_date) b
+ ON b."accountId" = a."id"
+ LEFT JOIN "movements" m ON m."mAccountId" = a."id"
+ WHERE a."isGroup" = false
+ AND a."companyGroupId" = p_company_group_id
+ AND a."active" = true
+ AND (b."balanceAtDate" != 0 OR b."netChange" != 0)
+ ORDER BY a."number";
+END;
+$$;
+```
+
+3. Do NOT apply yet — application is Task 22. Do NOT run `pnpm db:types`.
+
+**Verify:**
+```bash
+ls packages/database/supabase/migrations/ | grep financial-reporting
+# Expected: one file, timestamp newer than every existing migration, HHMMSS not 000000
+grep -c "IF NOT EXISTS\|IF EXISTS\|duplicate_object" packages/database/supabase/migrations/*financial-reporting.sql
+# Expected: >= 7 (idempotency guards present, incl. reportView table/index/policies)
+```
+
+**Out of scope:** RLS on existing tables (`account` policies already cover the new column), `accountTreeBalancesByCompany` (unchanged), any backfill of `cashFlowActivity` (NULL = derive from accountType is the design), `createdBy`/`updatedBy` on `reportView` (ownership is `userId`, matching the `userModulePreference` precedent).
+
+---
+
+## Task 2: Models & types — cash flow enums, validator field, statement types
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts` — add `cashFlowActivities`; extend `accountValidator`
+- Modify: `apps/erp/app/modules/accounting/types.ts` — add cash flow / GL detail types
+
+**Steps:**
+
+1. In `accounting.models.ts`, next to the other enum arrays, add:
+
+```typescript
+export const cashFlowActivities = ["Operating", "Investing", "Financing"] as const;
+```
+
+2. Find `accountValidator` and add the optional field (matches other optional enum fields in the same validator):
+
+```typescript
+cashFlowActivity: z.enum(cashFlowActivities).optional(),
+```
+
+3. In `types.ts`, add:
+
+```typescript
+export type CashFlowActivity = (typeof cashFlowActivities)[number];
+
+export type CashFlowLine = {
+ accountId: string;
+ number: string | null;
+ name: string;
+ amount: number; // signed cash effect for the period
+};
+
+export type CashFlowStatement = {
+ netIncome: number;
+ operating: CashFlowLine[]; // excludes the Net Income line
+ investing: CashFlowLine[];
+ financing: CashFlowLine[];
+ unclassified: CashFlowLine[];
+ operatingTotal: number; // netIncome + Σ operating
+ investingTotal: number;
+ financingTotal: number;
+ unclassifiedTotal: number;
+ netChangeInCash: number; // Σ Bank/Cash netChange
+ beginningCash: number;
+ endingCash: number;
+ unreconciledDifference: number; // 0 when the identity holds
+};
+```
+
+(import `cashFlowActivities` from `./accounting.models`). Re-export nothing new from `index.ts` manually — the barrel already does `export * from "./accounting.models"` / `"./types"`; confirm both lines exist.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -5
+# Expected: exits 0 (or only pre-existing errors unrelated to accounting module)
+```
+
+**Out of scope:** UI components, service functions.
+
+---
+
+## Task 3: Pure helpers + unit tests — activity mapping, fiscal year start, cash flow builder
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.utils.ts` — three pure functions
+- Modify: `apps/erp/app/modules/accounting/accounting.utils.test.ts` — tests (precedent: existing tests in this file)
+
+**Steps:**
+
+1. Add to `accounting.utils.ts` (types from `./types`):
+
+```typescript
+// Default cash flow bucket by accountType. NULL/unknown → null (unclassified).
+// "Excluded" = Bank/Cash (the reconciliation target, not a flow line).
+export function getCashFlowActivityForAccountType(
+ accountType: string | null
+): CashFlowActivity | "Excluded" | null {
+ switch (accountType) {
+ case "Bank":
+ case "Cash":
+ return "Excluded";
+ case "Accounts Receivable":
+ case "Inventory":
+ case "Other Current Asset":
+ case "Accumulated Depreciation":
+ case "Accounts Payable":
+ case "Other Current Liability":
+ case "Tax":
+ return "Operating";
+ case "Fixed Asset":
+ case "Other Asset":
+ case "Investments":
+ return "Investing";
+ case "Long Term Liability":
+ case "Equity - No Close":
+ case "Equity - Close":
+ case "Retained Earnings":
+ return "Financing";
+ default:
+ return null;
+ }
+}
+
+// Fiscal year start date (YYYY-MM-DD) for the fiscal year containing asOfDate.
+// startMonth is the month name from fiscalYearSettings ("January".."December");
+// null/undefined falls back to January (calendar year).
+export function getFiscalYearStartDate(
+ startMonth: string | null | undefined,
+ asOfDate: string
+): string;
+
+// Pure indirect-method builder. `accounts` = leaf accounts with
+// { id, number, name, class, incomeBalance, accountType, cashFlowActivity },
+// `balances` = accountId → { balanceAtDate, netChange } for [startDate, endDate].
+// Net income = Σ IS leaves of rootSign(class) × netChange (Revenue +, Expense −).
+// Cash effect of a non-cash BS leaf = class === "Asset" ? -netChange : +netChange.
+// Bucket = account.cashFlowActivity ?? getCashFlowActivityForAccountType(accountType).
+// Excluded (Bank/Cash): beginningCash += balanceAtDate - netChange;
+// netChangeInCash += netChange. Lines with amount === 0 are omitted.
+// unreconciledDifference = (netIncome + operatingΣ + investingΣ + financingΣ
+// + unclassifiedΣ) - netChangeInCash.
+export function buildCashFlowStatement(
+ accounts: CashFlowAccountInput[],
+ balances: Map<string, { balanceAtDate: number; netChange: number }>,
+ ): CashFlowStatement;
+```
+
+Implement both fully (the comment blocks above are the exact semantics; define and export `CashFlowAccountInput` in `types.ts`). For `getFiscalYearStartDate`: map month name → 1–12; FY start = most recent occurrence of that month's 1st on or before `asOfDate` (e.g. startMonth "April", asOfDate "2026-03-31" → "2025-04-01"; asOfDate "2026-04-01" → "2026-04-01"). Use plain string/date math consistent with existing helpers in this file — no new deps.
+
+2. Add tests to `accounting.utils.test.ts` covering:
+ - mapping: each accountType group → expected bucket; `null` → `null`; `"Bank"` → `"Excluded"`.
+ - fiscal year start: January default; mid-year start month before/on/after boundary (the three April cases above).
+ - cash flow builder: the spec's acceptance scenario — cash sale 100 (Bank +100 debit / Revenue +100), credit sale 50 (AR +50 / Revenue +50), depreciation 20 (Expense +20 / AccumDep −20 — class Asset, credit ⇒ negative). Assert: netIncome = 130... **compute carefully**: Revenue netChange = +150 (class-normal), Expense +20 ⇒ netIncome = 150 − 20 = 130. AR (Asset) netChange +50 ⇒ effect −50. AccumDep (Asset) netChange −20 ⇒ effect +20. Operating total = 130 − 50 + 20 = 100. Bank netChange +100 ⇒ netChangeInCash = 100, beginningCash = balanceAtDate − netChange, ending = beginning + 100, unreconciledDifference = 0.
+ - unclassified: an account with `accountType: null` lands in `unclassified` and the identity still holds (difference 0).
+ - override: same account with `cashFlowActivity: "Financing"` moves buckets.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp test -- accounting.utils
+# Expected: all tests pass, including the new describe blocks
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** service functions, any DB access in these helpers (pure functions only).
+
+---
+
+## Task 4: Service — Retained Earnings / Net Income split
+
+**Depends on:** Tasks 2, 3
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` — `getFinancialStatementBalances` (line ~136)
+
+**Steps:**
+
+1. When `args.includeCurrentYearEarnings` is true:
+ a. Fetch fiscal year settings via the existing `getFiscalYearSettings(client, companyId)` (line ~587). If `companyId` is null (consolidated callers pass a concrete id today — balance-sheet.tsx always passes one; if null, fall back to January).
+ b. Compute `fiscalYearStart = getFiscalYearStartDate(settings?.startMonth, endDate)` where `endDate = args.endDate ?? today`.
+ c. Make ONE additional `client.rpc("accountTreeBalancesByCompany", { p_company_group_id, p_company_id, from_date: fiscalYearStart, to_date: endDate })` call. For income-statement **leaf** accounts (`incomeBalance === "Income Statement" && !isGroup`), with `sign = rootSignMultiplier(a.class)`:
+ - `currentYearEarnings = Σ sign × netChange` (FY window)
+ - `priorYearsEarnings = Σ sign × (balanceAtDate − netChange)` (inception → FY start)
+ d. Keep the existing "Net Income" synthetic row (`NET_INCOME_ACCOUNT_ID`) but set its `balance`/`balanceAtDate` to `currentYearEarnings` (its `netChange` stays the report-window IS net change as computed today).
+ e. Find the Retained Earnings account row: leaf with `accountType === "Retained Earnings"` (read via cast: `(a as unknown as { accountType: string | null }).accountType` — the `accounts` view row type may not include it in committed types). If found: add `priorYearsEarnings` to its `balance` and `balanceAtDate`, and set a flag the UI can read (`isComputed: true` — extend the mapped row type locally). Add `priorYearsEarnings + currentYearEarnings` to the equity **group** row exactly where the code adds the single net income today (replacing the current single-line addition — total added to equity must equal old behavior).
+ f. If NO Retained Earnings account exists: legacy behavior — Net Income row carries `balanceAtDate` = all-inception IS total (current code path), and return a `warnings: ["no-retained-earnings-account"]` marker alongside data (extend the return to `{ data, warnings, error }`; callers that ignore `warnings` still compile).
+2. Preserve: `applyRootSignCorrection` still runs last; the Net Income row stays `isSystem: false`, parented to the equity group.
+3. If the equity-group/balance-sheet-root lookup logic (lines ~197–205) doesn't match this description when you read it, STOP and report — do not improvise.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+grep -n "priorYearsEarnings\|getFiscalYearStartDate" apps/erp/app/modules/accounting/accounting.service.ts | head -5
+# Expected: both symbols present in getFinancialStatementBalances
+```
+
+**Out of scope:** UI rendering of the computed rows (Task 10), consolidation path changes (`getConsolidatedBalances` calls this function per company and inherits the split automatically — do not modify it).
+
+---
+
+## Task 5: Service — `getCashFlowStatement`
+
+**Depends on:** Tasks 2, 3
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` — new function after `getFinancialStatementBalances`
+
+**Steps:**
+
+1. Add:
+
+```typescript
+export async function getCashFlowStatement(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyId: string,
+ args: { startDate: string | null; endDate: string | null }
+) {
+ // 1) accounts: client.from("accounts").select("*")
+ // .eq("companyGroupId", companyGroupId).eq("active", true)
+ // .eq("isGroup", false)
+ // 2) balances: client.rpc("accountTreeBalancesByCompany", {...})
+ // from_date: args.startDate ?? getDateNYearsAgo(50)..., to_date: args.endDate ?? today
+ // (same defaults as getFinancialStatementBalances)
+ // 3) build the Map<accountId, {balanceAtDate, netChange}> from the RPC rows
+ // 4) return { data: buildCashFlowStatement(accountInputs, balancesMap), error: null }
+ // accountInputs read cashFlowActivity via cast:
+ // (a as unknown as { cashFlowActivity: CashFlowActivity | null }).cashFlowActivity
+}
+```
+
+Follow the exact fetch/error-handling pattern of `getFinancialStatementBalances` (parallel `Promise.all`, return the first error response untouched). `companyId` is required — this function computes one company in its local currency; Task 16's `getConsolidatedCashFlowStatement` composes it across companies.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+grep -n "export async function getCashFlowStatement" apps/erp/app/modules/accounting/accounting.service.ts
+# Expected: one match
+```
+
+**Out of scope:** consolidation/translation (deferred to Phase 2), route wiring (Task 8).
+
+---
+
+## Task 6: Service — `getGeneralLedgerLines` + opening balance
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` — two new functions
+- Modify: `apps/erp/app/modules/accounting/types.ts` — `GeneralLedgerLine` row type via `Awaited<ReturnType<...>>` pattern if needed
+
+**Steps:**
+
+1. Add a paginated list function (pattern: any list function using `setGenericQueryFilters`, e.g. the journals list in this file):
+
+```typescript
+export async function getGeneralLedgerLines(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GenericQueryFilters & {
+ accountId: string | null;
+ startDate: string | null;
+ endDate: string | null;
+ status: string[] | null; // journal.status values; default ["Posted", "Reversed"]
+ }
+) {
+ let query = client
+ .from("journalLine")
+ .select("*, journal!inner(id, journalEntryId, postingDate, status, sourceType, description)", { count: "exact" })
+ .eq("companyId", companyId);
+ if (args.accountId) query = query.eq("accountId", args.accountId);
+ if (args.startDate) query = query.gte("journal.postingDate", args.startDate);
+ if (args.endDate) query = query.lte("journal.postingDate", args.endDate);
+ query = query.in("journal.status", args.status ?? ["Posted", "Reversed"]);
+ query = setGenericQueryFilters(query, args, [
+ { column: "journal(postingDate)", ascending: true },
+ ]);
+ return query;
+}
+```
+
+If the embedded-resource orderBy syntax (`journal(postingDate)`) fails at runtime/typecheck, order by `createdAt` ascending instead and STOP to note the limitation in the task checklist — do not silently drop ordering. If `journal!inner(...)` embedding fails typecheck because of the composite-key relationship, fall back to two queries (lines page, then `in("id", journalIds)` header fetch) — keep the return shape `{ data, count, error }`.
+
+2. Add the opening-balance helper (single account, for the running-balance row):
+
+```typescript
+export async function getGeneralLedgerOpeningBalance(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyId: string,
+ accountId: string,
+ beforeDate: string // filter-window start; opening = balance through beforeDate - 1 day
+) {
+ // call accountTreeBalancesByCompany with from_date = beforeDate, to_date = beforeDate,
+ // find the account row, return balanceAtDate - netChange (balance strictly before beforeDate)
+}
+```
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** dimension columns on the GL report (future), CSV specifics (shared Table handles it).
+
+---
+
+## Task 7: Paths + accounting nav entries
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/erp/app/utils/path.ts` — after `incomeStatement` (line ~578)
+- Modify: `apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx` — after the Trial Balance entry (line ~55)
+
+**Steps:**
+
+1. `path.ts` additions beside the existing report paths:
+
+```typescript
+cashFlowStatement: `${x}/accounting/cash-flow`,
+generalLedger: `${x}/accounting/general-ledger`,
+journalEntry: (id: string) => `${x}/accounting/journals/${id}`,
+```
+
+(match the exact style of neighbors; `journalEntry` goes in the function-style section if the file separates statics from functions — follow local ordering.)
+
+2. `useAccountingSubmodules.tsx`: add two entries in the same group as Balance Sheet / Income Statement / Trial Balance, matching their object shape exactly:
+ - `name: t`Cash Flow``, `to: path.to.cashFlowStatement`
+ - `name: t`General Ledger``, `to: path.to.generalLedger`
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+grep -n "cashFlowStatement\|generalLedger" apps/erp/app/utils/path.ts
+# Expected: both present
+```
+
+**Out of scope:** MES paths, breadcrumb handles (each route file defines its own).
+
+---
+
+## Task 8: Route + UI — cash flow statement
+
+**Depends on:** Tasks 5, 7
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/cash-flow.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Reports/CashFlowStatement.tsx`
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/index.ts` — export it
+- Copy from (precedent): `apps/erp/app/routes/x+/accounting+/balance-sheet.tsx` (route/loader shape, `ReportFilters` usage) and `apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTable.tsx` (flat report table with totals styling)
+
+**Steps:**
+
+1. Route: copy `balance-sheet.tsx`'s structure. Loader: `requirePermissions(request, { view: "accounting", role: "employee" })`; read `companies`, `startDate`, `endDate` params; resolve `selectedCompanyId` as balance-sheet does. **This task builds the single-company path only**: when `companiesParam === "all"`, temporarily fall back to the session `companyId` (Task 17 replaces this fallback with the consolidated branch — leave a `// TODO(Task 17)` on that line). Call `getCashFlowStatement(client, companyGroupId, selectedCompanyId, { startDate, endDate })`; on error, redirect to `path.to.accounting` with flash (copy the pattern verbatim). `handle.breadcrumb: "Cash Flow"`, `to: path.to.cashFlowStatement`.
+2. `CashFlowStatement.tsx`: render the sections in order — Operating (first line "Net Income", then each `operating` line), Investing, Financing, Unclassified (only when non-empty, with an amber header warning: "N accounts have no cash flow activity — set an account type or override"), then the footer block: Net change in cash / Cash at beginning of period / Cash at end of period / (Unreconciled difference row only when non-zero, styled destructive). Use the table primitives `TrialBalanceTable.tsx` uses (grep its imports — `@carbon/react` `Table`/`Thead`/`Tbody` wrappers) and the same currency formatting helper it uses. Section subtotal rows use the same styling as that table's totals row. Each account line's amount links to `path.to.generalLedger + "?accountId={id}&startDate=...&endDate=..."`; the Net Income line links to `path.to.incomeStatement` with the same window.
+3. `ReportFilters` reuse: pass the same props balance-sheet passes (the "All companies" option stays visible — it resolves to the fallback until Task 17 wires the consolidated branch).
+4. No parenthesized counts anywhere (house style).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** consolidated mode, translation toggle on this report, PDF/print.
+
+---
+
+## Task 9: Route + UI — general ledger detail report
+
+**Depends on:** Tasks 6, 7
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/general-ledger.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/GeneralLedger/GeneralLedgerTable.tsx` (+ `index.ts` barrel in that folder; re-export from `ui/index.ts` if one exists — follow how `ui/Reports` is exported)
+- Copy from (precedent): `apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx` (shared `Table`-based accounting list + its route `journals.tsx` loader pattern)
+
+**Steps:**
+
+1. Route loader: `requirePermissions({ view: "accounting", role: "employee" })`; parse `accountId`, `startDate`, `endDate`, `status` (multi), plus standard table params via the same helper `journals.tsx` uses (`getGenericQueryFilters` — copy its param parsing exactly). Call `getGeneralLedgerLines`. When `accountId` is set AND sort is default (posting date ascending): also call `getGeneralLedgerOpeningBalance` with `beforeDate = startDate ?? epoch` and return `openingBalance`.
+2. `GeneralLedgerTable.tsx`: columns — Posting Date, Journal (the `journal.journalEntryId` readable id, linked to `path.to.journalEntry(journal.id)`), Source (`journal.sourceType`), Description (line description ?? journal description), Debit (`toDisplayDebit(amount, accountClass)`), Credit (`toDisplayCredit(amount, accountClass)`), and — single-account mode only — Running Balance (client-computed: opening + cumulative class-signed amount per row, page-local starting from `openingBalance`; hide the column when paginated past page 1 or sorted non-default). Debit/credit formatting: import from `@carbon/utils` (`toDisplayDebit`/`toDisplayCredit`); account class comes from the account filter's selected account (fetch account row in loader when `accountId` set). Filters row: account combobox (grep for an existing account selector component — `Account` field in `~/components/Form` used by journal entry form; use the same), date range pickers, status filter.
+3. First row (single-account mode): synthetic "Opening balance" row above the data rows showing `openingBalance`.
+4. Underscore rule: no accessorKey may contain `_` (Table export crashes otherwise).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** editing anything (read-only report), dimension/cost-center columns, Draft journals in running balance (excluded by design even when the status filter shows them).
+
+---
+
+## Task 10: Statement trees — RE/CYE display, drill links, unclassified warning
+
+**Depends on:** Tasks 4, 7
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsx` — leaf links, computed-row affordances
+- Modify: `apps/erp/app/routes/x+/accounting+/balance-sheet.tsx` — pass warnings + window params through
+- Modify: `apps/erp/app/routes/x+/accounting+/income-statement.tsx` — pass window params through
+
+**Steps:**
+
+1. `FinancialStatementTree.tsx`: leaf rows (`!isGroup`, real accounts) — wrap the balance amount in a `Link` to `path.to.generalLedger + "?accountId={id}&startDate={window start}&endDate={window end}"` (add `startDate`/`endDate` props to the tree, passed from each route's params; balance sheet passes no startDate → omit the param, GL report then shows inception-to-date). The synthetic Net Income row (`id === NET_INCOME_ACCOUNT_ID`) links to `path.to.incomeStatement` with the fiscal-YTD window instead; give it and the augmented Retained Earnings row (`isComputed` flag from Task 4) a muted "computed" tooltip: Net Income — "Income statement activity for the current fiscal year (computed, not posted)"; Retained Earnings — "Posted balance plus prior fiscal years' net income (computed, not posted)". Use the existing tooltip primitive already imported in the tree or `@carbon/react`'s `Tooltip`.
+2. `balance-sheet.tsx`: surface `warnings` from `getFinancialStatementBalances` — when it contains `"no-retained-earnings-account"`, render an amber alert above the tree: "No Retained Earnings account found — prior-year income is shown inside Net Income. Add an account with type Retained Earnings." (use the alert component `ChartOfAccountsTree.tsx` or another accounting screen already uses; grep `Alert` in `apps/erp/app/modules/accounting/ui/`).
+3. Keep consolidated mode untouched: links render the same; `translatedBalance` display unchanged.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+grep -n "generalLedger" apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsx | head -3
+# Expected: link present
+```
+
+**Out of scope:** comparison columns (Task 12), tree virtualization changes.
+
+---
+
+## Task 11: Route + UI — journal entry drawer
+
+**Depends on:** Task 7
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/journals.$journalId.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryDrawer.tsx` (+ export from that folder's `index.ts`)
+- Copy from (precedent): `apps/erp/app/routes/x+/accounting+/cost-centers.$costCenterId.tsx` (Drawer child-route pattern under a list route) and `apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryForm.tsx` (line rendering primitives)
+
+**Steps:**
+
+1. Route: loader `requirePermissions({ view: "accounting" })`; `getJournalEntry(client, journalId)` (exists, service line ~1665 — verify it returns header + lines; if it returns header only, also call the lines query used by `journals.tsx`'s expanded view or fetch `journalLine` by `journalId` + `companyId`). Render `<JournalEntryDrawer>`; on close, navigate to `path.to.journals` (mirror the cost-centers close behavior). This must be a **Drawer overlay**, not a page (detail-view convention).
+2. Drawer content (read-only): header — journalEntryId, posting date, status badge, source type, description; lines table — account number + name, description, Debit, Credit (`toDisplayDebit`/`toDisplayCredit` with each line's account class — `getJournalEntry`'s select must include the account relation; extend its select if needed), totals row proving debits = credits.
+3. Verify `journals.tsx` renders an `<Outlet />` for child routes; if it does not, add one (same as the cost-centers list route does).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** editing/reversing from the drawer (existing actions stay where they are), dimensions display.
+
+---
+
+## Task 12: Comparative columns on income statement + balance sheet
+
+**Depends on:** Task 4
+**Files:**
+- Modify: `apps/erp/app/routes/x+/accounting+/income-statement.tsx` — `compare` param + second balance call
+- Modify: `apps/erp/app/routes/x+/accounting+/balance-sheet.tsx` — same
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/ReportFilters.tsx` — Compare select
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsx` — comparison + variance columns
+
+**Steps:**
+
+1. `ReportFilters.tsx`: add a `Select` labeled `Compare` with options None / Previous period / Previous year, writing `compare=none|priorPeriod|priorYear` to search params via the existing `setParams` helper (copy the DatePicker param-writing style at lines ~81–90). Render it only when a new optional prop `showCompare` is true (statements pass true; trial balance/cash flow don't pass it).
+2. Window math (small pure helper `getComparisonWindow(compare, startDate, endDate, mode)` in `accounting.utils.ts` + unit tests in `accounting.utils.test.ts`):
+ - income statement (`mode: "range"`): priorPeriod → same-length window ending the day before `startDate`; priorYear → both dates minus one year. Null `startDate` (inception) → comparison disabled (return null).
+ - balance sheet (`mode: "asOf"`): priorPeriod → `endDate` minus one month; priorYear → minus one year. Null `endDate` → treat as today first.
+3. Loaders: when `compare !== none` and a window resolves, run the same data call again with the comparison window — `getFinancialStatementBalances` single-company, `getConsolidatedBalances` consolidated (same branch the route already has) — and return `comparison: { byAccountId: Record<string, number> }` mapping account id → the same field the primary tree displays (`balanceAtDate` for balance sheet, `netChange` for income statement; translated variants in consolidated mode).
+4. `FinancialStatementTree.tsx`: when `comparison` prop present, three extra columns — Comparison, $ Variance (primary − comparison), % Variance (`comparison === 0 ? "—" : (variance / |comparison|) × 100`, one decimal). Computed rows (Net Income, augmented RE) get comparison values only if present in the comparison map (Net Income row: include it in the map by reusing the synthetic row from the comparison call); otherwise render "—". Column headers via the tree's existing header style.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp test -- accounting.utils
+# Expected: getComparisonWindow tests pass (6+ cases incl. nulls)
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** budget comparison (budgeting spec Phase 3 plugs into these columns later), period-boundary snapping (Phase 2), %-of-revenue columns.
+
+---
+
+## Task 13: Trial balance — four-column UI + drill links
+
+**Depends on:** Tasks 1 (SQL shape), 7
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTable.tsx` — column groups + links + totals
+- Modify: `apps/erp/app/routes/x+/accounting+/trial-balance.tsx` — pass window params for links (loader's `getTrialBalance` call is unchanged)
+
+**Steps:**
+
+1. The RPC now returns four extra columns. Committed types won't know them — cast the RPC response rows once at the boundary: `const rows = (data ?? []) as unknown as TrialBalanceRow[]` with `TrialBalanceRow` defined in `types.ts` listing all 12 return fields.
+2. `TrialBalanceTable.tsx`: grouped headers — Opening (Debit | Credit), Period (Debits | Credits), Closing (Debit | Credit) — plus Net Change if currently shown; footer totals per column; assert visually that opening-debit total = opening-credit total and same for period and closing (render the three pairs; no parenthesized numbers). Account number/name cell links to `path.to.generalLedger + "?accountId=...&startDate=...&endDate=..."` using the report's current window.
+3. If `TrialBalanceTree.tsx` (the hierarchical variant) renders the same RPC data, apply the closing-balance columns there unchanged — the tree keeps its existing columns; only the flat table gets the four-column treatment. If the tree breaks typecheck from the row cast, fix the shared type, not the tree's display.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+grep -n "openingDebit\|periodDebits" apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTable.tsx | head -3
+# Expected: new columns rendered
+```
+
+**Out of scope:** changing `getTrialBalance`'s signature, the consolidated trial balance translation logic.
+
+---
+
+## Task 14: Account form — Cash Flow Activity select
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountForm.tsx`
+- Copy from (precedent): the existing `accountType` / class Select fields inside the same form
+
+**Steps:**
+
+1. Add a `Select` (from `~/components/Form`, same import the form already uses) named `cashFlowActivity`, label "Cash Flow Activity", options: `[{ value: "", label: "Default (from account type)" }, ...cashFlowActivities.map(...)]`. Render it only when the form's `incomeBalance` value is `"Balance Sheet"` (mirror however the form conditionally shows other fields; if it doesn't do conditional fields, show it always with the helper text "Used by the cash flow statement; income statement accounts roll into Net Income").
+2. Confirm the route action that persists the form (`charts.new.tsx` / `charts.$accountId.tsx`) passes validator output straight to the upsert — since `accountValidator` gained the field (Task 2), no action change should be needed; the DB write needs a cast only if the generated `account` Insert/Update type rejects the column (`insert([{ ...data } as any])` — match how the period-closing plan handles unknown columns). If the upsert filters fields explicitly, add `cashFlowActivity` to the allowed list.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** bulk-editing activities, CSV import of accounts.
+
+---
+
+## Task 15: CSV export buttons on statement reports
+
+**Depends on:** Tasks 8, 10, 13
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Reports/ExportReportButton.tsx`
+- Modify: `apps/erp/app/routes/x+/accounting+/{balance-sheet,income-statement,cash-flow,trial-balance}.tsx` — render it in the filter row
+- Copy from (precedent): `apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx` (standalone `json2csv` download — Blob + anchor pattern)
+
+**Steps:**
+
+1. `ExportReportButton.tsx`: props `{ rows: Record<string, string | number | null>[]; filename: string }`; on click, `json2csv(rows, { emptyFieldValue: "" })` → Blob → anchor download (copy the ExchangeRateForm mechanics exactly, including the `json-2-csv` import name). Icon button labeled "Export CSV" matching the filter-bar button styling used in `ReportFilters.tsx`.
+2. Each route maps its loaded data to flat rows: statements → `{ number, name, balance/netChange, comparison?, variance? }` per visible account row (indent group rows with two spaces per depth in the name); cash flow → `{ section, name, amount }` + footer rows; trial balance → the 12 RPC columns. Filename: `balance-sheet-{endDate}.csv`, `income-statement-{endDate}.csv`, `cash-flow-{endDate}.csv`, `trial-balance-{endDate}.csv` (fall back to today when endDate is null).
+3. GL detail already exports via the shared `Table` — do not add a second button there.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** PDF export (Phase 2), server-side export, Excel formatting.
+
+---
+
+## Task 16: Service — currency rates helper + consolidated cash flow
+
+**Depends on:** Task 5
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` — two new functions after `getCashFlowStatement`
+- Modify: `apps/erp/app/modules/accounting/types.ts` — extend `CashFlowStatement` with `effectOfExchangeRates?: number`
+
+**Steps:**
+
+1. Rate helper — mirror the exact fallback chain of `translateTrialBalance` in `packages/database/supabase/migrations/20260315000002_exchange-rate-history.sql` (average = `AVG(rate)` over the window; closing = latest `rate` on/before a date; fallbacks average → closing → 1; `translated = local × rate`). Read that migration before implementing; if the rate direction there is not `local × rate = parent`, STOP and report.
+
+```typescript
+export async function getCurrencyRatesForWindow(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ currencyCode: string,
+ args: { startDate: string | null; endDate: string | null }
+) {
+ // Query exchangeRateHistory (companyGroupId + currencyCode):
+ // - average: AVG of rate where effectiveDate in [startDate, endDate]
+ // - closingAtStart: latest rate where effectiveDate <= startDate (window
+ // open; beginning cash is the balance *before* startDate)
+ // - closingAtEnd: latest rate where effectiveDate <= endDate
+ // Apply fallbacks per rate: average ?? closingAtEnd ?? 1; closing ?? 1.
+ // Return { data: { average, closingAtStart, closingAtEnd }, error: null }.
+ // When currencyCode equals the parent/base currency or no rows exist, all 1.
+}
+```
+
+Fetch rows once with `.gte`/`.lte` on `effectiveDate` plus one query for the latest-before-start rate; compute in TS (no new RPC).
+
+2. Consolidated statement:
+
+```typescript
+export async function getConsolidatedCashFlowStatement(
+ client: SupabaseClient<Database>,
+ companyGroupId: string,
+ companyIds: string[],
+ parentCurrency: string,
+ args: { startDate: string | null; endDate: string | null }
+) {
+ // For each company (Promise.all):
+ // - getCashFlowStatement (local currency)
+ // - company.baseCurrencyCode → getCurrencyRatesForWindow
+ // - translate: every section line amount and netIncome × average;
+ // beginningCash × closingAtStart; endingCash × closingAtEnd
+ // Merge section lines across companies by accountId (shared chart), summing
+ // translated amounts; sum netIncome/beginningCash/endingCash.
+ // effectOfExchangeRates = endingCash − beginningCash −
+ // (netIncome + operatingΣ + investingΣ + financingΣ + unclassifiedΣ)
+ // netChangeInCash (displayed) = endingCash − beginningCash.
+ // Return { data: CashFlowStatement & { effectOfExchangeRates }, error }.
+}
+```
+
+Companies list comes from the caller (route already loads `getCompaniesInGroup` — pass `baseCurrencyCode` per company through rather than re-fetching). Do NOT apply `generateEliminations` here — elimination journals are non-cash balanced adjustments; the elimination company's own journals are included when its id is in `companyIds` (same as other statements).
+
+3. Unit-test the pure merge/plug math: extract a pure `mergeTranslatedCashFlows(perCompany: TranslatedCompanyFlow[])` into `accounting.utils.ts` and add tests in `accounting.utils.test.ts`: (a) two same-currency companies (all rates 1) → FX effect exactly 0, sections sum; (b) one foreign company with average 1.1, closingAtStart 1.0, closingAtEnd 1.2 → FX effect = ending×1.2 − beginning×1.0 − flows×1.1 (assert the identity Beginning + flows + FX = Ending in parent currency).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp test -- accounting.utils
+# Expected: mergeTranslatedCashFlows tests pass (same-currency zero-FX case + foreign-rate identity case)
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** eliminations on the SCF (non-cash by construction), historical-rate equity handling (SCF uses average/closing only), caching rates.
+
+---
+
+## Task 17: Cash flow UI — consolidated mode + FX-effect line
+
+**Depends on:** Tasks 8, 16
+**Files:**
+- Modify: `apps/erp/app/routes/x+/accounting+/cash-flow.tsx` — multi-company branch
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/CashFlowStatement.tsx` — FX line + currency label
+- Copy from (precedent): the multi-company branch in `apps/erp/app/routes/x+/accounting+/balance-sheet.tsx` (lines ~47–88: `companiesParam === "all"`, parent currency resolution)
+
+**Steps:**
+
+1. Route: replace Task 8's `// TODO(Task 17)` single-company fallback. Copy balance-sheet's `selectedCompanyIds`/`isMultiCompany`/`parentCurrency` resolution; when `isMultiCompany && parentCurrency`, call `getConsolidatedCashFlowStatement(client, companyGroupId, selectedCompanyIds, parentCurrency, { startDate, endDate })` (pass each company's `baseCurrencyCode` from the already-loaded companies list); else keep the single-company call. Return `parentCurrency` + `isMultiCompany` for display.
+2. `CashFlowStatement.tsx`: accept optional `effectOfExchangeRates` and `currencyCode` props. When `effectOfExchangeRates` is defined, render an "Effect of exchange rate changes on cash" row between the Financing section and the cash reconciliation footer (same row styling as section subtotals). Show the currency code in the header when provided (consolidated = parent currency). In consolidated mode, line-level drill links to the GL detail remain per-account but without a company filter — append no `companyId` param.
+3. The footer identity in consolidated mode: Beginning + Net change (flows) + FX effect = Ending — assert visually by rendering Net change as `endingCash − beginningCash − effectOfExchangeRates` (flows-only) so the four footer rows sum exactly.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+grep -n "effectOfExchangeRates" apps/erp/app/modules/accounting/ui/Reports/CashFlowStatement.tsx | head -2
+# Expected: prop consumed
+```
+
+**Out of scope:** `showTranslated` toggle on single foreign-currency company (BS/IS-only concern), CTA (balance-sheet concept, not SCF).
+
+---
+
+## Task 18: Period picker in ReportFilters
+
+**Depends on:** Task 7
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/ReportFilters.tsx` — Dates | Period mode toggle
+- Modify: `apps/erp/app/routes/x+/accounting+/{balance-sheet,income-statement,cash-flow,trial-balance,general-ledger}.tsx` — loaders pass `periods` data
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` — `getReportingPeriods`
+
+**Steps:**
+
+1. Service (reads period-closing's columns directly so this feature depends only on that MIGRATION, not its services):
+
+```typescript
+export async function getReportingPeriods(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ const result = await client
+ .from("accountingPeriod")
+ .select("id, startDate, endDate")
+ .eq("companyId", companyId)
+ .order("startDate", { ascending: false });
+ if (result.error) return result;
+ // fiscalYear/periodNumber are period-closing columns absent from committed
+ // types — read via cast; rows where either is null are filtered out.
+ const rows = (result.data ?? []) as unknown as {
+ id: string; startDate: string; endDate: string;
+ fiscalYear: number | null; periodNumber: number | null;
+ }[];
+ return { data: rows.filter((r) => r.fiscalYear !== null && r.periodNumber !== null), error: null };
+}
+```
+
+Select `"*"` if the narrowed select rejects unknown columns at runtime — the cast handles the shape either way. If the `accountingPeriod` table has no `fiscalYear` column at all (period-closing migration not applied), PostgREST returns every row with the cast fields `undefined` → the filter yields `[]` → the toggle hides. Confirm this degradation path works; if selecting explicit missing columns errors instead, fall back to `select("*")`.
+
+2. `ReportFilters.tsx`: add a two-option segmented control Dates | Period (render only when a new optional `periods` prop is non-empty). Period mode replaces the two DatePickers with: fiscal year `Select` (distinct `fiscalYear` desc) + period `Select` ("Full year" + periods of that FY as "P{periodNumber} ({MMM})"). On selection, write `startDate`/`endDate` of the chosen period (or FY span for "Full year") via the existing `setParams` call (line ~84 pattern) — nothing else in any loader changes. Track mode in a `mode` search param so it survives navigation; default `dates`.
+3. Each of the five report loaders: call `getReportingPeriods(client, selectedCompanyId ?? companyId)` and pass `periods` to `ReportFilters`. Comparison column header (Task 12's tree): when `mode=period` and a comparison is active, label the comparison column with the computed window's month/period name instead of the raw dates (pure display; reuse the window dates already returned by the loader).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+pnpm --filter @carbon/erp test -- accounting.utils
+# Expected: still green (no util regressions)
+```
+
+**Out of scope:** creating/generating periods (period-closing's `/x/accounting/periods` UI), snapping compare presets to non-monthly calendars (periods are monthly by construction), locking/closing semantics.
+
+---
+
+## Task 19: Report views — models, service, resource route
+
+**Depends on:** Tasks 1 (table), 2
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts` — `reportViewValidator`
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` — three functions
+- Create: `apps/erp/app/routes/x+/accounting+/report-views.tsx` — resource route (action only)
+- Modify: `apps/erp/app/utils/path.ts` — `reportViews: `${x}/accounting/report-views``
+- Copy from (precedent): any small intent-based action route in `x+/accounting+/` (e.g. the delete routes) for the action shape
+
+**Steps:**
+
+1. Validator:
+
+```typescript
+export const reportViewValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ report: z.enum(["balance-sheet", "income-statement", "cash-flow", "trial-balance", "general-ledger"]),
+ name: z.string().min(1, { message: "Name is required" }),
+ params: z.string(), // JSON-stringified search params from the client
+});
+```
+
+2. Service (RLS is owner-scoped, but scope queries defensively anyway). `reportView` is absent from committed types — use `(client as any).from("reportView")` with explicit row typing on the way out (`ReportView` type in `types.ts`: `{ id, userId, companyId, report, name, params: Record<string, string> }`):
+
+```typescript
+getReportViews(client, companyId: string, userId: string, report: string)
+ // select *, eq companyId + userId + report, order name; parse params JSONB
+upsertReportView(client, view: { id?: string; userId: string; companyId: string; report: string; name: string; params: Record<string, string> })
+ // insert or update-by-id; set updatedAt on update
+deleteReportView(client, id: string, userId: string)
+ // delete eq id + userId (defense in depth on top of RLS)
+```
+
+3. Resource route: action only (`assertIsPost`), `requirePermissions(request, { view: "accounting" })` (personal data — the report's own view permission suffices; do NOT require update/create on accounting). `intent` field: `save` → validate with `reportViewValidator`, `JSON.parse(params)` into a record, call `upsertReportView` with `userId` from the session; `delete` → `deleteReportView(client, id, userId)`. Return `{ success: true }` or flash error — plain objects, never `Response.json`.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+grep -n "reportViews" apps/erp/app/utils/path.ts
+# Expected: present
+```
+
+**Out of scope:** sharing views across users, view management screen (dropdown-only in v1), MCP tool exposure.
+
+---
+
+## Task 20: Report views UI — dropdown + save/delete in ReportFilters
+
+**Depends on:** Task 19
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/ui/Reports/ReportFilters.tsx` — views dropdown + save popover
+- Modify: `apps/erp/app/routes/x+/accounting+/{balance-sheet,income-statement,cash-flow,trial-balance,general-ledger}.tsx` — loaders return `reportViews` via `getReportViews`
+- Copy from (precedent): `apps/erp/app/components/Table/components/TableHeader.tsx` saved-views affordance for visual placement; a `DropdownMenu` from `@carbon/react` for the menu itself
+
+**Steps:**
+
+1. `ReportFilters` gains optional props `report: string` and `views: ReportView[]`. When provided, render a "Views" `DropdownMenu` (leftmost in the filter row): one item per saved view (click = `navigate({ search: new URLSearchParams(view.params).toString() })`), each with a delete icon button submitting `intent=delete` + `id` to `path.to.reportViews` via `useFetcher`; a divider; "Save current view…" opening a small popover with a name input that submits `intent=save`, `report`, `name`, and `params = JSON.stringify(Object.fromEntries(currentSearchParams))` to the same route via `ValidatedForm` + `reportViewValidator`.
+2. On successful save/delete, `revalidate` (fetcher completion already triggers loader revalidation; confirm the views list refreshes — if not, call `useRevalidator().revalidate()` on `fetcher.state === "idle" && fetcher.data?.success`).
+3. Each report loader: `getReportViews(client, companyId, userId, "<report-slug>")` and pass through. Keep the dropdown hidden when `views` prop is undefined (e.g. other future consumers of ReportFilters).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+```
+
+**Out of scope:** renaming views inline (delete + re-save covers v1), default/pinned views.
+
+---
+
+## Task 21: PDF financial statements package
+
+**Depends on:** Tasks 4, 5, 16
+**Files:**
+- Create: `packages/documents/src/pdf/FinancialStatementsPDF.tsx`
+- Modify: `packages/documents/src/pdf/index.ts` — barrel export
+- Create: `apps/erp/app/routes/file+/accounting+/financial-statements[.]pdf.tsx`
+- Modify: `apps/erp/app/utils/path.ts` — `financialStatementsPdf` path helper (with query-param builder)
+- Modify: `apps/erp/app/routes/x+/accounting+/{balance-sheet,income-statement,cash-flow}.tsx` — "Download PDF" button beside Export CSV
+- Copy from (precedent): route shape `apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx` (renderToStream → Buffer → `application/pdf` response, `ensureFont` before render); component style `packages/documents/src/pdf/components/Template.tsx` shell per `.ai/rules/pdf-generation-patterns.md` (hand-built tree — NOT block-registry; check how `KanbanLabelPDF.tsx` imports `useTw`/`tw` for styling)
+
+**Steps:**
+
+1. `FinancialStatementsPDF.tsx`: props `{ company: { name, logo? }, currencyCode, startDate, endDate, balanceSheet: StatementRow[], incomeStatement: StatementRow[], cashFlow: CashFlowStatement & { effectOfExchangeRates?: number } }` where `StatementRow = { name, number?, depth, amount, isGroup, isComputed? }` (flattened tree, depth-indented). Render inside `<Template title="Financial Statements" meta={{...}}>`: one section per statement (new `<Page>` per statement via three Template-wrapped pages OR one Template with page breaks — follow whatever `Template.tsx` supports; if Template is single-page-flow only, render three `<Page>` elements inside one `<Document>` manually reusing Template's header/footer components and STOP-note the deviation). Rows: name (indented 8pt per depth), right-aligned amount (`text-[9px]`, `tabular-nums` if supported); group rows bold; computed rows italic with a "(computed)" suffix; section totals with top border. Style exclusively via `useTw()`/`tw` semantic grays.
+2. Route: `requirePermissions(request, { view: "accounting", role: "employee" })`; parse `companies`, `startDate`, `endDate` from the query string; resolve company selection exactly as `balance-sheet.tsx` does; fetch the three datasets with the same service calls the three screens use (`getFinancialStatementBalances` ×2 filtered by `incomeBalance`, or `getConsolidatedBalances` when multi-company; `getCashFlowStatement` / `getConsolidatedCashFlowStatement`); flatten trees to `StatementRow[]` (depth from parent chain, same ordering as the screens); `await ensureFont(...)` (default family) then `renderToStream(<FinancialStatementsPDF ... />)`; drain to Buffer; respond `application/pdf` with `Content-Disposition: inline; filename="{company} - Financial Statements {endDate}.pdf"`.
+3. Buttons: on the three statement routes, an icon-link "Download PDF" beside the Export CSV button, `href = path.to.financialStatementsPdf + "?" + currentSearchParams` opening in a new tab.
+4. Run `pnpm --filter @carbon/documents build` once if `fonts.data.ts` is missing locally (gitignored, generated).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/documents typecheck 2>&1 | tail -3
+# Expected: exit 0
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+grep -n "FinancialStatementsPDF" packages/documents/src/pdf/index.ts
+# Expected: exported
+```
+
+**Out of scope:** document-template customizer integration (`DOCUMENT_PDFS` registration is for customizable/previewable docs — skip it), trial balance / GL detail in the PDF, ZPL/printing, email delivery.
+
+---
+
+## Task 22: Apply migration locally
+
+**Depends on:** Task 1 (and the local stack being up — if `crbn up` isn't running, STOP and ask the user; never rebuild the DB)
+**Files:** none (applies `packages/database/supabase/migrations/*financial-reporting.sql`)
+
+**Steps:**
+
+1. `pnpm db:migrate` (crbn migrate; it may regenerate local types — do NOT commit any `packages/database/src/types.ts` diff; `git checkout -- packages/database/src/types.ts` afterwards if it changed).
+2. Smoke the RPC and column with psql (get `PORT_DB` from `.env.local`):
+
+```bash
+psql "postgresql://postgres:[email protected]:$PORT_DB/postgres" -c \
+ "SELECT column_name FROM information_schema.columns WHERE table_name='account' AND column_name='cashFlowActivity';"
+# Expected: one row
+psql "postgresql://postgres:[email protected]:$PORT_DB/postgres" -c \
+ "SELECT proname, pronargs FROM pg_proc WHERE proname='trialBalance';"
+# Expected: one row, 4 args
+psql "postgresql://postgres:[email protected]:$PORT_DB/postgres" -c \
+ "SELECT relrowsecurity FROM pg_class WHERE relname='reportView';"
+# Expected: one row, t (table exists with RLS enabled)
+```
+
+3. Re-apply idempotency check: run the migration file once more via psql `-f`; expect zero errors.
+
+**Verify:** (the psql outputs above)
+
+**Out of scope:** deploying, seeding data.
+
+---
+
+## Task 23: Full verification gate
+
+**Depends on:** all code tasks (2–21) + Task 22
+**Files:** none
+
+**Steps + Verify:**
+
+```bash
+pnpm --filter @carbon/erp test -- accounting
+# Expected: all accounting tests pass (utils incl. cash-flow/fiscal-year/comparison/merge-translated suites)
+pnpm --filter @carbon/erp typecheck 2>&1 | tail -3
+# Expected: exit 0
+pnpm --filter @carbon/documents typecheck 2>&1 | tail -3
+# Expected: exit 0 (FinancialStatementsPDF)
+pnpm run lint 2>&1 | tail -5
+# Expected: no new errors (Biome clean on changed files)
+git status --porcelain -- packages/database/src/types.ts
+# Expected: empty (committed types untouched)
+```
+
+Then commit via the check-and-commit gate (user-approved checkpoints only).
+
+---
+
+## Task 24: Browser verification (/test)
+
+**Depends on:** Task 23, local stack up, accounting enabled (`/x/settings/accounting` — crbn reset seeds it off)
+**Files:** none
+
+**Steps:**
+
+1. Run the `/test` skill against the feature branch with this scenario list (it will use `/login` + agent-browser; RVF forms submit via `requestSubmit`):
+ - Post (or reuse seeded) journals so there is prior-fiscal-year and current-year revenue; open `/x/accounting/balance-sheet` → Retained Earnings and Net Income are separate rows, equity totals match the trial balance's equity closing total, root ≈ 0.
+ - `/x/accounting/cash-flow` for the current month → sections render; Beginning + Net change = Ending; no Unreconciled difference on seeded data; Unclassified section only if seeded chart has untyped accounts (then the warning shows).
+ - Click a balance-sheet leaf amount → lands on `/x/accounting/general-ledger?accountId=...` with matching total; opening-balance row present; click a line → journal drawer opens with balanced totals.
+ - Income statement with `Compare: Previous year` → three extra columns, sane variance math on one spot-checked account.
+ - Trial balance → Opening/Period/Closing groups each foot to equal debits and credits; Export CSV downloads on all four reports.
+ - Account form: set an Other Current Liability account's Cash Flow Activity to Financing → cash flow statement moves its line.
+ - Cash flow with `Companies: All` → sections in the parent currency, an "Effect of exchange rate changes on cash" row present, and Beginning + Net change + FX effect = Ending (exactly 0 FX when all companies share the currency).
+ - "Download PDF" on the balance sheet → an `application/pdf` response opens containing all three statements; spot-check one total per statement against the screens.
+ - With period-closing's migration applied and periods generated: switch filters to Period mode, pick "FY · P{current}" → dates populate and the report matches the same manual date range; with no periods, the toggle is absent.
+ - Save a view "Board pack" on the income statement (consolidated + prior-year compare), navigate away, reapply from the Views dropdown → identical URL params; delete it → gone from the dropdown.
+2. Capture screenshots of each report for the PR (house rule: net-new UI PRs include agent-browser screenshots).
+
+**Verify:** `/test` playbook passes all scenarios; screenshots saved.
+
+**Out of scope:** performance testing, Xero-sync interactions.
diff --git a/.ai/plans/2026-07-02-period-closing.md b/.ai/plans/2026-07-02-period-closing.md
new file mode 100644
index 0000000000..72cad6dbbc
--- /dev/null
+++ b/.ai/plans/2026-07-02-period-closing.md
@@ -0,0 +1,1434 @@
+# Period Closing — Implementation Plan
+
+> ⚠️ **2026-07-03 delta (readiness roadmap):** the spec gained a posted-record immutability fold-in (`2026-07-03-public-company-readiness.md` MW-1 → spec §Enforcement item 4): extend the drafted migration `20260702044133` with (a) a second SECURITY DEFINER trigger — Posted journals allow only `Posted → Reversed`; journalLines frozen once parent is Posted, all period states — and (b) `journalLine.createdBy`. Add matching acceptance tests. See `.ai/plans/2026-07-03-public-company-readiness-roadmap.md`.
+>
+> ⚠️ **2026-07-04 delta (user direction):** the spec now includes a **NetSuite-style persisted close checklist** (spec §NetSuite-style close checklist), superseding "computed, not persisted". Execute the **Addendum Tasks 17–20** at the end of this plan; Task 13's close drawer becomes the checklist UI (Task 19 amends it); "persisted close-checklist tasks" is removed from the Deferred list.
+
+## Overview
+
+- **Design Spec:** `.ai/specs/2026-07-02-period-closing.md` (status: in-progress, all open questions resolved)
+- **Research:** `.ai/research/period-closing.md`
+- **Tasks:** 16 tasks (~60–75 min of work) + gated verification
+- **Branch:** `feature/period-closing`
+
+**Ground rules for the executor:**
+
+- Do NOT regenerate or commit `packages/database/src/types.ts` — committed types are cloud-generated. Access new columns (`closeStatus`, `fiscalYear`, `periodNumber`, `lockedAt`, `lockedBy`) via `(client.from("accountingPeriod") as any)` / `as unknown as` casts (established pattern, e.g. `(client as any).from("itemSamplingPlan")` in post-receipt).
+- Do NOT rebuild the database. Apply the migration with `pnpm db:migrate` only, when the local stack is up.
+- Typecheck per package (`pnpm --filter @carbon/erp typecheck`), never whole-repo `tsc --noEmit`.
+- Commit only at the marked checkpoints, after verification passes (check-and-commit gate).
+
+## Dependencies
+
+```
+Task 1 (migration, already drafted)
+ └─ Task 15 (apply migration) — deferred until stack is up
+Task 2 (models) ─┬─ Task 3 (getOrCreateAccountingPeriod) ─┬─ Task 5 (postJournalEntry/reverse gates)
+ │ └─ Task 6 (depreciation/disposal routes)
+ ├─ Task 4 (period services) ─── Task 11–13 (routes/UI)
+Task 7 (edge helper) — independent
+Task 8 (audit config) — independent
+Task 9 (status colors) / Task 10 (path.ts) — independent, needed by 11–13
+Task 14 (sidebar) — after Task 10
+Task 16 (typecheck/lint) — last code task
+```
+
+---
+
+## Task 1: Migration (ALREADY DRAFTED — review only)
+
+**Files:**
+- Exists: `packages/database/supabase/migrations/20260702044133_period-close-lifecycle.sql`
+
+Already written this session. Contents: `periodCloseStatus` enum (`Open`/`Locked`/`Closed`); `closeStatus`, `fiscalYear`, `periodNumber`, `lockedAt`, `lockedBy` columns on `accountingPeriod`; backfill of `closeStatus` from `closedAt` and of `fiscalYear`/`periodNumber` from `startDate` + `fiscalYearSettings.startMonth` (FY named by ending calendar year); unique index `(companyId, fiscalYear, periodNumber)` with non-unique fallback; `check_accounting_period_open()` BEFORE trigger on `journal` (blocks INSERT into Closed, re-dating into/out of Closed, Draft→Posted in Closed, DELETE of non-Draft in Closed; allows Posted→Reversed).
+
+**Steps:**
+1. Re-read the file and confirm it matches the spec's Data Model section.
+2. Confirmed already: no views select from `accountingPeriod`, so no view recreation needed.
+3. Do NOT apply yet — application is Task 15.
+
+---
+
+## Task 2: Models — `periodCloseStatuses` + validators
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts`
+- Modify: `apps/erp/app/modules/accounting/types.ts`
+
+**Steps:**
+
+1. In `accounting.models.ts`, next to `journalEntryStatuses` (line ~482), add:
+
+```typescript
+export const periodCloseStatuses = ["Open", "Locked", "Closed"] as const;
+
+export const accountingPeriodTransitionValidator = z.object({
+ intent: z.enum(["lock", "unlock", "close", "reopen"]),
+ periodId: z.string().min(1, { message: "Period is required" })
+});
+
+export const generateFiscalYearPeriodsValidator = z.object({
+ intent: z.literal("generate"),
+ fiscalYear: zfd.numeric(
+ z.number().int().min(2000).max(2200)
+ )
+});
+```
+
+2. In `types.ts`, add (after Task 4's service functions exist):
+
+```typescript
+export type AccountingPeriodListItem = NonNullable<
+ Awaited<ReturnType<typeof getAccountingPeriods>>["data"]
+>[number];
+export type PeriodCloseStatus = (typeof periodCloseStatuses)[number];
+export type PeriodCloseReadiness = NonNullable<
+ Awaited<ReturnType<typeof getPeriodCloseReadiness>>["data"]
+>;
+```
+(Match the file's existing import style for the service/model imports.)
+
+3. Verify barrel: `apps/erp/app/modules/accounting/index.ts` re-exports `*` from models/service/types (it does — no change unless exports are enumerated).
+
+---
+
+## Task 3: Service — extend `getOrCreateAccountingPeriod` with posting source
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` (lines 509–574)
+
+**Steps:**
+
+1. Replace the function with:
+
+```typescript
+type PeriodPostingSource = "operational" | "accounting";
+
+type AccountingPeriodCloseColumns = {
+ closeStatus?: "Open" | "Locked" | "Closed";
+ fiscalYear?: number | null;
+ periodNumber?: number | null;
+};
+
+const MONTH_NUMBER: Record<string, number> = {
+ January: 1, February: 2, March: 3, April: 4, May: 5, June: 6,
+ July: 7, August: 8, September: 9, October: 10, November: 11, December: 12
+};
+
+function fiscalYearAndPeriodFor(
+ date: Date,
+ startMonth: number
+): { fiscalYear: number; periodNumber: number } {
+ const month = date.getMonth() + 1;
+ const year = date.getFullYear();
+ const periodNumber = ((month - startMonth + 12) % 12) + 1;
+ const fiscalYear =
+ startMonth === 1 ? year : month >= startMonth ? year + 1 : year;
+ return { fiscalYear, periodNumber };
+}
+
+export async function getOrCreateAccountingPeriod(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ date: string,
+ source: PeriodPostingSource = "operational"
+): Promise<{ data: string | null; error: { message: string } | null }> {
+ const existing = await getCurrentAccountingPeriod(client, companyId, date);
+
+ if (existing.data) {
+ const closeStatus =
+ (existing.data as unknown as AccountingPeriodCloseColumns).closeStatus ??
+ "Open";
+
+ if (closeStatus === "Closed") {
+ return {
+ data: null,
+ error: {
+ message: "Accounting period is closed. Reopen it before posting."
+ }
+ };
+ }
+
+ if (closeStatus === "Locked" && source === "operational") {
+ return {
+ data: null,
+ error: {
+ message:
+ "Accounting period is locked. Post as an accounting adjustment or unlock the period first."
+ }
+ };
+ }
+
+ if (existing.data.status === "Inactive") {
+ await client
+ .from("accountingPeriod")
+ .update({ status: "Inactive" as const })
+ .eq("companyId", companyId)
+ .eq("status", "Active");
+
+ await client
+ .from("accountingPeriod")
+ .update({ status: "Active" as const })
+ .eq("id", existing.data.id);
+ }
+ return { data: existing.data.id, error: null };
+ }
+
+ // Create a new period for the month of the given date
+ const d = new Date(date);
+ const year = d.getFullYear();
+ const month = d.getMonth(); // 0-indexed
+ const startDate = new Date(year, month, 1).toISOString().split("T")[0];
+ const endDate = new Date(year, month + 1, 0).toISOString().split("T")[0];
+
+ const settings = await getFiscalYearSettings(client, companyId);
+ const startMonth = settings.data?.startMonth
+ ? MONTH_NUMBER[settings.data.startMonth] ?? 1
+ : 1;
+ const { fiscalYear, periodNumber } = fiscalYearAndPeriodFor(d, startMonth);
+
+ await client
+ .from("accountingPeriod")
+ .update({ status: "Inactive" as const })
+ .eq("companyId", companyId)
+ .eq("status", "Active");
+
+ const result = await (client.from("accountingPeriod") as any)
+ .insert({
+ startDate,
+ endDate,
+ companyId,
+ status: "Active" as const,
+ closeStatus: "Open",
+ fiscalYear,
+ periodNumber,
+ createdBy: "system"
+ })
+ .select("id")
+ .single();
+
+ if (result.error) {
+ return {
+ data: null,
+ error: { message: "Failed to create accounting period" }
+ };
+ }
+
+ return { data: result.data.id, error: null };
+}
+```
+
+Notes: the legacy Active/Inactive toggle is intentionally untouched (spec decision). `getFiscalYearSettings` already exists in this file — keep its existing definition.
+
+---
+
+## Task 4: Service — period queries, transitions, generation, readiness
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` (add below `getOrCreateAccountingPeriod`)
+
+**Steps:**
+
+1. Add:
+
+```typescript
+export async function getAccountingPeriods(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return (client.from("accountingPeriod") as any)
+ .select(
+ "id, startDate, endDate, status, closeStatus, fiscalYear, periodNumber, lockedAt, lockedBy, closedAt, closedBy",
+ { count: "exact" }
+ )
+ .eq("companyId", companyId)
+ .order("startDate", { ascending: false }) as Promise<{
+ data:
+ | {
+ id: string;
+ startDate: string;
+ endDate: string;
+ status: "Active" | "Inactive";
+ closeStatus: "Open" | "Locked" | "Closed";
+ fiscalYear: number | null;
+ periodNumber: number | null;
+ lockedAt: string | null;
+ lockedBy: string | null;
+ closedAt: string | null;
+ closedBy: string | null;
+ }[]
+ | null;
+ count: number | null;
+ error: { message: string } | null;
+ }>;
+}
+
+async function getAccountingPeriodById(
+ client: SupabaseClient<Database>,
+ periodId: string,
+ companyId: string
+) {
+ const result = await (client.from("accountingPeriod") as any)
+ .select("id, startDate, endDate, closeStatus, fiscalYear, periodNumber")
+ .eq("id", periodId)
+ .eq("companyId", companyId)
+ .single();
+ return result as {
+ data: {
+ id: string;
+ startDate: string;
+ endDate: string;
+ closeStatus: "Open" | "Locked" | "Closed";
+ fiscalYear: number | null;
+ periodNumber: number | null;
+ } | null;
+ error: { message: string } | null;
+ };
+}
+
+export async function lockAccountingPeriod(
+ client: SupabaseClient<Database>,
+ args: { periodId: string; companyId: string; userId: string }
+) {
+ const period = await getAccountingPeriodById(
+ client,
+ args.periodId,
+ args.companyId
+ );
+ if (period.error || !period.data) {
+ return { data: null, error: period.error ?? { message: "Period not found" } };
+ }
+ if (period.data.closeStatus !== "Open") {
+ return {
+ data: null,
+ error: { message: "Only open periods can be locked" }
+ };
+ }
+ return (client.from("accountingPeriod") as any)
+ .update({
+ closeStatus: "Locked",
+ lockedAt: new Date().toISOString(),
+ lockedBy: args.userId,
+ updatedBy: args.userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", args.periodId)
+ .eq("companyId", args.companyId)
+ .select("id")
+ .single();
+}
+
+export async function unlockAccountingPeriod(
+ client: SupabaseClient<Database>,
+ args: { periodId: string; companyId: string; userId: string }
+) {
+ const period = await getAccountingPeriodById(
+ client,
+ args.periodId,
+ args.companyId
+ );
+ if (period.error || !period.data) {
+ return { data: null, error: period.error ?? { message: "Period not found" } };
+ }
+ if (period.data.closeStatus !== "Locked") {
+ return {
+ data: null,
+ error: { message: "Only locked periods can be unlocked" }
+ };
+ }
+ return (client.from("accountingPeriod") as any)
+ .update({
+ closeStatus: "Open",
+ lockedAt: null,
+ lockedBy: null,
+ updatedBy: args.userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", args.periodId)
+ .eq("companyId", args.companyId)
+ .select("id")
+ .single();
+}
+
+export async function closeAccountingPeriod(
+ client: SupabaseClient<Database>,
+ args: { periodId: string; companyId: string; userId: string }
+) {
+ const period = await getAccountingPeriodById(
+ client,
+ args.periodId,
+ args.companyId
+ );
+ if (period.error || !period.data) {
+ return { data: null, error: period.error ?? { message: "Period not found" } };
+ }
+ if (period.data.closeStatus === "Closed") {
+ return { data: null, error: { message: "Period is already closed" } };
+ }
+
+ // Sequential close: every earlier period must already be Closed
+ const earlierOpen = await (client.from("accountingPeriod") as any)
+ .select("id", { count: "exact", head: true })
+ .eq("companyId", args.companyId)
+ .lt("startDate", period.data.startDate)
+ .neq("closeStatus", "Closed");
+ if ((earlierOpen.count ?? 0) > 0) {
+ return {
+ data: null,
+ error: {
+ message: "Earlier periods must be closed first (sequential close)"
+ }
+ };
+ }
+
+ return (client.from("accountingPeriod") as any)
+ .update({
+ closeStatus: "Closed",
+ closedAt: new Date().toISOString(),
+ closedBy: args.userId,
+ updatedBy: args.userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", args.periodId)
+ .eq("companyId", args.companyId)
+ .select("id")
+ .single();
+}
+
+export async function reopenAccountingPeriod(
+ client: SupabaseClient<Database>,
+ args: { periodId: string; companyId: string; userId: string }
+) {
+ const period = await getAccountingPeriodById(
+ client,
+ args.periodId,
+ args.companyId
+ );
+ if (period.error || !period.data) {
+ return { data: null, error: period.error ?? { message: "Period not found" } };
+ }
+ if (period.data.closeStatus !== "Closed") {
+ return { data: null, error: { message: "Period is not closed" } };
+ }
+
+ // Reverse-sequential reopen: no later period may still be Closed
+ const laterClosed = await (client.from("accountingPeriod") as any)
+ .select("id", { count: "exact", head: true })
+ .eq("companyId", args.companyId)
+ .gt("startDate", period.data.startDate)
+ .eq("closeStatus", "Closed");
+ if ((laterClosed.count ?? 0) > 0) {
+ return {
+ data: null,
+ error: {
+ message: "Later periods must be reopened first (reopen from the most recent close backwards)"
+ }
+ };
+ }
+
+ return (client.from("accountingPeriod") as any)
+ .update({
+ closeStatus: "Open",
+ closedAt: null,
+ closedBy: null,
+ updatedBy: args.userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", args.periodId)
+ .eq("companyId", args.companyId)
+ .select("id")
+ .single();
+}
+
+export async function createFiscalYearPeriods(
+ client: SupabaseClient<Database>,
+ args: { companyId: string; fiscalYear: number; userId: string }
+) {
+ const settings = await getFiscalYearSettings(client, args.companyId);
+ const startMonth = settings.data?.startMonth
+ ? MONTH_NUMBER[settings.data.startMonth] ?? 1
+ : 1;
+
+ // FY is named by its ending calendar year
+ const firstYear = startMonth === 1 ? args.fiscalYear : args.fiscalYear - 1;
+
+ const existing = await (client.from("accountingPeriod") as any)
+ .select("periodNumber")
+ .eq("companyId", args.companyId)
+ .eq("fiscalYear", args.fiscalYear);
+ if (existing.error) return existing;
+ const existingNumbers = new Set(
+ ((existing.data ?? []) as { periodNumber: number | null }[]).map(
+ (p) => p.periodNumber
+ )
+ );
+
+ const rows = [];
+ for (let p = 1; p <= 12; p++) {
+ if (existingNumbers.has(p)) continue;
+ const monthIndex = (startMonth - 1 + (p - 1)) % 12; // 0-indexed
+ const year = firstYear + Math.floor((startMonth - 1 + (p - 1)) / 12);
+ const startDate = new Date(Date.UTC(year, monthIndex, 1));
+ const endDate = new Date(Date.UTC(year, monthIndex + 1, 0));
+ rows.push({
+ companyId: args.companyId,
+ startDate: startDate.toISOString().split("T")[0],
+ endDate: endDate.toISOString().split("T")[0],
+ status: "Inactive",
+ closeStatus: "Open",
+ fiscalYear: args.fiscalYear,
+ periodNumber: p,
+ createdBy: args.userId
+ });
+ }
+
+ if (rows.length === 0) {
+ return { data: [], error: null };
+ }
+
+ return (client.from("accountingPeriod") as any).insert(rows).select("id");
+}
+
+export async function getPeriodCloseReadiness(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ periodId: string
+) {
+ const period = await getAccountingPeriodById(client, periodId, companyId);
+ if (period.error || !period.data) {
+ return { data: null, error: period.error ?? { message: "Period not found" } };
+ }
+ const { startDate, endDate } = period.data;
+
+ const [draftJournals, journalsInPeriod, draftDepreciation, unmatchedIC] =
+ await Promise.all([
+ client
+ .from("journal")
+ .select("id", { count: "exact", head: true })
+ .eq("companyId", companyId)
+ .eq("status", "Draft")
+ .gte("postingDate", startDate)
+ .lte("postingDate", endDate),
+ client
+ .from("journalEntries")
+ .select("id, journalEntryId, totalDebits, totalCredits")
+ .eq("companyId", companyId)
+ .eq("status", "Posted")
+ .gte("postingDate", startDate)
+ .lte("postingDate", endDate),
+ client
+ .from("depreciationRun")
+ .select("id", { count: "exact", head: true })
+ .eq("companyId", companyId)
+ .eq("status", "Draft")
+ .gte("periodEnd", startDate)
+ .lte("periodEnd", endDate),
+ client
+ .from("intercompanyTransaction")
+ .select("id", { count: "exact", head: true })
+ .eq("status", "Unmatched")
+ .or(`sourceCompanyId.eq.${companyId},targetCompanyId.eq.${companyId}`)
+ ]);
+
+ const unbalanced = (journalsInPeriod.data ?? []).filter(
+ (j) =>
+ Math.abs(Number(j.totalDebits ?? 0) - Number(j.totalCredits ?? 0)) > 0.001
+ );
+
+ const blockers: { key: string; label: string; count: number }[] = [];
+ const warnings: { key: string; label: string; count: number }[] = [];
+
+ if ((draftJournals.count ?? 0) > 0) {
+ blockers.push({
+ key: "draftJournals",
+ label: "Draft journal entries dated in this period",
+ count: draftJournals.count ?? 0
+ });
+ }
+ if (unbalanced.length > 0) {
+ blockers.push({
+ key: "unbalancedJournals",
+ label: "Posted journal entries with unequal debits and credits",
+ count: unbalanced.length
+ });
+ }
+ if ((draftDepreciation.count ?? 0) > 0) {
+ warnings.push({
+ key: "draftDepreciation",
+ label: "Draft depreciation runs ending in this period",
+ count: draftDepreciation.count ?? 0
+ });
+ }
+ if ((unmatchedIC.count ?? 0) > 0) {
+ warnings.push({
+ key: "unmatchedIntercompany",
+ label: "Unmatched intercompany transactions involving this company",
+ count: unmatchedIC.count ?? 0
+ });
+ }
+
+ return { data: { blockers, warnings }, error: null };
+}
+```
+
+2. Verify column names before finalizing: `depreciationRun.periodEnd` and `intercompanyTransaction.sourceCompanyId/targetCompanyId/status` (grep the migrations if types complain). Negative-inventory and pending-posting-queue checks are explicitly deferred (spec changelog).
+
+---
+
+## Task 5: Gate `postJournalEntry` (+ stamp period) and `reverseJournalEntry`
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` (lines ~1896–2048)
+
+**Steps:**
+
+1. In `postJournalEntry`, after the balance validation (`if (Math.abs(totalDebit - totalCredit) > 0.001) {...}`) and before the status-flip update, insert:
+
+```typescript
+ // 3. Period gate — manual JEs are accounting-source postings
+ const period = await getOrCreateAccountingPeriod(
+ client,
+ entry.data.companyId,
+ entry.data.postingDate,
+ "accounting"
+ );
+ if (period.error) {
+ return { data: null, error: period.error };
+ }
+```
+
+and change the update payload to stamp the period:
+
+```typescript
+ return client
+ .from("journal")
+ .update({
+ status: "Posted" as const,
+ accountingPeriodId: period.data,
+ postedAt: new Date().toISOString(),
+ postedBy: userId,
+ updatedBy: userId
+ })
+ .eq("id", id)
+ .select("id")
+ .single();
+```
+
+(Renumber the step comments: the status flip becomes step 4.)
+
+2. In `reverseJournalEntry`, before the reversing-entry insert, add:
+
+```typescript
+ const reversalDate = new Date().toISOString().split("T")[0];
+ const period = await getOrCreateAccountingPeriod(
+ client,
+ data.companyId,
+ reversalDate,
+ "accounting"
+ );
+ if (period.error) {
+ return { data: null, error: period.error };
+ }
+```
+
+and in the insert payload use `postingDate: reversalDate,` and add `accountingPeriodId: period.data,`.
+
+---
+
+## Task 6: Pass `source: "accounting"` in depreciation/disposal routes
+
+**Files:**
+- Modify: `apps/erp/app/routes/x+/depreciation-run+/$depreciationRunId.post.tsx`
+- Modify: `apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.dispose.tsx`
+
+**Steps:**
+
+1. In each route, find the existing `getOrCreateAccountingPeriod(client, companyId, <date>)` call and append the fourth argument `"accounting"`.
+2. No other changes — both routes already handle the `{ error }` return with a flash redirect.
+
+---
+
+## Task 7: Edge-function shared helper — enforce close status
+
+**Files:**
+- Modify: `packages/database/supabase/functions/shared/get-accounting-period.ts`
+
+This is the copy used by post-receipt (l.402), post-shipment (l.763), post-purchase-invoice (l.1382), post-payment (l.294). All are **operational** sources; they post as of *today*. It currently checks nothing about closure.
+
+**Steps:**
+
+1. In `getCurrentAccountingPeriod`, immediately after the `currentAccountingPeriod` fetch and before the `status === "Active"` branch, add:
+
+```typescript
+ const closeStatus =
+ (currentAccountingPeriod.data as unknown as {
+ closeStatus?: "Open" | "Locked" | "Closed";
+ } | null)?.closeStatus ?? "Open";
+
+ if (closeStatus === "Closed") {
+ throw new Error(
+ "Accounting period is closed. Reopen it before posting."
+ );
+ }
+ if (closeStatus === "Locked") {
+ throw new Error(
+ "Accounting period is locked. Unlock it before posting operational transactions."
+ );
+ }
+```
+
+2. In the same file, the lazy-creation branch (`insertInto("accountingPeriod")`) should stamp `closeStatus: "Open"` — add it to the `.values({...})` (cast the values object `as any` if the Kysely `DB` type lacks the column).
+
+3. Confirm each of the four edge functions wraps its handler in try/catch that returns a 4xx/5xx with the error message (they do — posting failures surface to the Inngest job, which retries 3× then fails loudly on the document; spec decision).
+
+---
+
+## Task 8: Audit config — register `accountingPeriod` entity
+
+**Files:**
+- Modify: `packages/database/src/audit.config.ts`
+
+**Steps:**
+
+1. Add to `auditConfig.entities` (alphabetical placement near the top-level entities):
+
+```typescript
+ accountingPeriod: {
+ label: "Accounting Period",
+ tables: {
+ accountingPeriod: { role: "root" }
+ }
+ },
+```
+
+2. If the config supports `createFields`, surface `["startDate", "endDate", "closeStatus", "fiscalYear", "periodNumber"]` on the root table in the same style as an existing example. Note `skipFields` already excludes `updatedAt`/`updatedBy`, so lock/close/reopen UPDATE diffs will show `closeStatus`, `lockedAt/By`, `closedAt/By` — exactly the audit trail the spec requires.
+3. Note: audit subscriptions sync when audit logging is (re)enabled in settings (`syncAuditSubscriptions`); no migration needed.
+
+---
+
+## Task 9: Status color map
+
+**Files:**
+- Modify: `packages/utils/src/status-colors.ts`
+
+**Steps:**
+
+1. Check the `StatusColor` union in the same file for the exact allowed values; then next to `JOURNAL_ENTRY_STATUS_COLOR_MAP` (line ~171) add, using the closest available colors to gray/orange/green:
+
+```typescript
+export const PERIOD_CLOSE_STATUS_COLOR_MAP = {
+ Open: "gray",
+ Locked: "orange",
+ Closed: "green"
+} as const satisfies Record<string, StatusColor>;
+```
+
+(If `orange` is not in `StatusColor`, use `yellow`.)
+
+---
+
+## Task 10: Path helpers
+
+**Files:**
+- Modify: `apps/erp/app/utils/path.ts`
+
+**Steps:**
+
+1. Near the other accounting entries (`accountingJournals`, etc., ~line 467–515), add:
+
+```typescript
+ accountingPeriods: `${x}/accounting/periods`,
+ accountingPeriodClose: (id: string) =>
+ generatePath(`${x}/accounting/periods/${id}/close`),
+```
+
+---
+
+## Task 11: UI — `PeriodCloseStatus` badge + `AccountingPeriodsTable`
+
+**Files:**
+- Create: `apps/erp/app/modules/accounting/ui/Periods/PeriodCloseStatus.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Periods/AccountingPeriodsTable.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Periods/index.ts`
+
+**Steps:**
+
+1. `PeriodCloseStatus.tsx` (mirrors `JournalEntryStatus.tsx`):
+
+```typescript
+import { Status } from "@carbon/react";
+import { PERIOD_CLOSE_STATUS_COLOR_MAP } from "@carbon/utils";
+import type { periodCloseStatuses } from "../../accounting.models";
+
+type PeriodCloseStatusProps = {
+ status?: (typeof periodCloseStatuses)[number] | null;
+};
+
+const PeriodCloseStatus = ({ status }: PeriodCloseStatusProps) => {
+ if (!status) return null;
+ const color = PERIOD_CLOSE_STATUS_COLOR_MAP[status];
+ if (!color) return null;
+
+ return <Status color={color}>{status}</Status>;
+};
+
+export default PeriodCloseStatus;
+```
+
+2. `AccountingPeriodsTable.tsx` (pattern: `DepreciationRunTable.tsx`; row actions submit intents to the parent route action via `useFetcher`, Close navigates to the close drawer, Reopen uses a confirm modal):
+
+```typescript
+import { MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import type { ColumnDef } from "@tanstack/react-table";
+import type { ReactNode } from "react";
+import { memo, useCallback, useMemo, useState } from "react";
+import {
+ LuCalendar,
+ LuCalendarCheck,
+ LuHash,
+ LuLock,
+ LuLockOpen,
+ LuRotateCcw,
+ LuStar
+} from "react-icons/lu";
+import { useFetcher, useNavigate } from "react-router";
+import { Table } from "~/components";
+import { Confirm } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import type { AccountingPeriodListItem } from "../../types";
+import PeriodCloseStatus from "./PeriodCloseStatus";
+
+type AccountingPeriodsTableProps = {
+ data: AccountingPeriodListItem[];
+ count: number;
+ primaryAction?: ReactNode;
+};
+
+function periodLabel(row: AccountingPeriodListItem) {
+ if (row.fiscalYear && row.periodNumber) {
+ return `FY${row.fiscalYear} · P${row.periodNumber}`;
+ }
+ return formatDate(row.startDate);
+}
+
+const AccountingPeriodsTable = memo(
+ ({ data, count, primaryAction }: AccountingPeriodsTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const fetcher = useFetcher();
+ const [selectedPeriod, setSelectedPeriod] =
+ useState<AccountingPeriodListItem | null>(null);
+ const reopenModal = useDisclosure();
+
+ const submitIntent = useCallback(
+ (intent: "lock" | "unlock" | "reopen", periodId: string) => {
+ fetcher.submit(
+ { intent, periodId },
+ { method: "post", action: path.to.accountingPeriods }
+ );
+ },
+ [fetcher]
+ );
+
+ const columns = useMemo<ColumnDef<AccountingPeriodListItem>[]>(
+ () => [
+ {
+ accessorKey: "periodNumber",
+ header: "Period",
+ cell: ({ row }) => periodLabel(row.original),
+ meta: { icon: <LuHash /> }
+ },
+ {
+ accessorKey: "startDate",
+ header: "Start",
+ cell: ({ row }) => formatDate(row.original.startDate),
+ meta: { icon: <LuCalendar /> }
+ },
+ {
+ accessorKey: "endDate",
+ header: "End",
+ cell: ({ row }) => formatDate(row.original.endDate),
+ meta: { icon: <LuCalendar /> }
+ },
+ {
+ accessorKey: "closeStatus",
+ header: "Status",
+ cell: ({ row }) => (
+ <PeriodCloseStatus status={row.original.closeStatus} />
+ ),
+ meta: { icon: <LuStar /> }
+ },
+ {
+ accessorKey: "closedAt",
+ header: "Closed",
+ cell: ({ row }) =>
+ row.original.closedAt ? formatDate(row.original.closedAt) : "—",
+ meta: { icon: <LuCalendarCheck /> }
+ }
+ ],
+ []
+ );
+
+ const renderContextMenu = useCallback(
+ (row: AccountingPeriodListItem) => (
+ <>
+ {row.closeStatus === "Open" && (
+ <MenuItem
+ disabled={!permissions.can("update", "accounting")}
+ onClick={() => submitIntent("lock", row.id)}
+ >
+ <MenuIcon icon={<LuLock />} />
+ Lock
+ </MenuItem>
+ )}
+ {row.closeStatus === "Locked" && (
+ <MenuItem
+ disabled={!permissions.can("update", "accounting")}
+ onClick={() => submitIntent("unlock", row.id)}
+ >
+ <MenuIcon icon={<LuLockOpen />} />
+ Unlock
+ </MenuItem>
+ )}
+ {row.closeStatus !== "Closed" && (
+ <MenuItem
+ disabled={!permissions.can("update", "accounting")}
+ onClick={() => navigate(path.to.accountingPeriodClose(row.id))}
+ >
+ <MenuIcon icon={<LuCalendarCheck />} />
+ Close…
+ </MenuItem>
+ )}
+ {row.closeStatus === "Closed" && (
+ <MenuItem
+ disabled={!permissions.can("delete", "accounting")}
+ destructive
+ onClick={() => {
+ setSelectedPeriod(row);
+ reopenModal.onOpen();
+ }}
+ >
+ <MenuIcon icon={<LuRotateCcw />} />
+ Reopen
+ </MenuItem>
+ )}
+ </>
+ ),
+ [navigate, permissions, reopenModal, submitIntent]
+ );
+
+ return (
+ <>
+ <Table<AccountingPeriodListItem>
+ data={data}
+ columns={columns}
+ count={count}
+ primaryAction={primaryAction}
+ renderContextMenu={renderContextMenu}
+ title="Accounting Periods"
+ />
+ {selectedPeriod && (
+ <Confirm
+ isOpen={reopenModal.isOpen}
+ title={`Reopen ${periodLabel(selectedPeriod)}`}
+ text="Reopening allows posting into this period again. The action is recorded in the audit log."
+ confirmText="Reopen"
+ onCancel={() => {
+ reopenModal.onClose();
+ setSelectedPeriod(null);
+ }}
+ onSubmit={() => {
+ submitIntent("reopen", selectedPeriod.id);
+ reopenModal.onClose();
+ setSelectedPeriod(null);
+ }}
+ />
+ )}
+ </>
+ );
+ }
+);
+
+AccountingPeriodsTable.displayName = "AccountingPeriodsTable";
+export default AccountingPeriodsTable;
+```
+
+3. `index.ts`:
+
+```typescript
+export { default as AccountingPeriodsTable } from "./AccountingPeriodsTable";
+export { default as PeriodCloseStatus } from "./PeriodCloseStatus";
+```
+
+4. Verify the `Confirm` modal's props signature against `~/components/Modals` (the depreciation-runs page uses `action=` for a form post; here we use `onSubmit` with a fetcher — if `Confirm` requires `action`, switch to a `fetcher.Form` inside a plain `Modal` following `ConfirmDelete.tsx`).
+
+---
+
+## Task 12: Route — `periods.tsx` (list + intent actions)
+
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/periods.tsx`
+
+**Steps:**
+
+1. Full route:
+
+```typescript
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { Button, VStack } from "@carbon/react";
+import { msg } from "@lingui/core/macro";
+import { LuCirclePlus } from "react-icons/lu";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { Form, Outlet, redirect, useLoaderData } from "react-router";
+import { usePermissions } from "~/hooks";
+import {
+ closeAccountingPeriod,
+ createFiscalYearPeriods,
+ getAccountingPeriods,
+ getPeriodCloseReadiness,
+ lockAccountingPeriod,
+ reopenAccountingPeriod,
+ unlockAccountingPeriod
+} from "~/modules/accounting";
+import { AccountingPeriodsTable } from "~/modules/accounting/ui/Periods";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: msg`Accounting Periods`,
+ to: path.to.accountingPeriods
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "accounting",
+ role: "employee"
+ });
+
+ const periods = await getAccountingPeriods(client, companyId);
+ if (periods.error) {
+ throw redirect(
+ path.to.accounting,
+ await flash(
+ request,
+ error(periods.error, "Failed to load accounting periods")
+ )
+ );
+ }
+
+ const currentYear = new Date().getFullYear();
+ const maxFiscalYear = (periods.data ?? []).reduce(
+ (max, p) => Math.max(max, p.fiscalYear ?? 0),
+ 0
+ );
+ const nextFiscalYear = Math.max(maxFiscalYear + 1, currentYear);
+
+ return {
+ data: periods.data ?? [],
+ count: periods.count ?? 0,
+ nextFiscalYear
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const formData = await request.formData();
+ const intent = String(formData.get("intent"));
+
+ // Reopening a closed period is the highest-privilege operation
+ const scope =
+ intent === "reopen"
+ ? ({ delete: "accounting" } as const)
+ : ({ update: "accounting" } as const);
+ const { client, companyId, userId } = await requirePermissions(
+ request,
+ scope
+ );
+
+ if (intent === "generate") {
+ const fiscalYear = Number(formData.get("fiscalYear"));
+ if (!Number.isInteger(fiscalYear)) {
+ throw redirect(
+ path.to.accountingPeriods,
+ await flash(request, error(null, "Invalid fiscal year"))
+ );
+ }
+ const result = await createFiscalYearPeriods(client, {
+ companyId,
+ fiscalYear,
+ userId
+ });
+ if (result.error) {
+ throw redirect(
+ path.to.accountingPeriods,
+ await flash(request, error(result.error, "Failed to generate periods"))
+ );
+ }
+ throw redirect(
+ path.to.accountingPeriods,
+ await flash(request, success(`Generated periods for FY${fiscalYear}`))
+ );
+ }
+
+ const periodId = String(formData.get("periodId"));
+ if (!periodId) {
+ throw redirect(
+ path.to.accountingPeriods,
+ await flash(request, error(null, "Period is required"))
+ );
+ }
+
+ const args = { periodId, companyId, userId };
+ let result: { data: unknown; error: { message: string } | null };
+ let successMessage: string;
+
+ switch (intent) {
+ case "lock":
+ result = await lockAccountingPeriod(client, args);
+ successMessage = "Period locked";
+ break;
+ case "unlock":
+ result = await unlockAccountingPeriod(client, args);
+ successMessage = "Period unlocked";
+ break;
+ case "close": {
+ const readiness = await getPeriodCloseReadiness(
+ client,
+ companyId,
+ periodId
+ );
+ if (readiness.error) {
+ throw redirect(
+ path.to.accountingPeriods,
+ await flash(
+ request,
+ error(readiness.error, "Failed to check close readiness")
+ )
+ );
+ }
+ if ((readiness.data?.blockers.length ?? 0) > 0) {
+ throw redirect(
+ path.to.accountingPeriods,
+ await flash(
+ request,
+ error(
+ null,
+ `Cannot close: ${readiness.data!.blockers
+ .map((b) => `${b.label} — ${b.count}`)
+ .join("; ")}`
+ )
+ )
+ );
+ }
+ result = await closeAccountingPeriod(client, args);
+ successMessage = "Period closed";
+ break;
+ }
+ case "reopen":
+ result = await reopenAccountingPeriod(client, args);
+ successMessage = "Period reopened";
+ break;
+ default:
+ throw redirect(
+ path.to.accountingPeriods,
+ await flash(request, error(null, "Unknown intent"))
+ );
+ }
+
+ if (result.error) {
+ throw redirect(
+ path.to.accountingPeriods,
+ await flash(request, error(result.error, result.error.message))
+ );
+ }
+
+ throw redirect(
+ path.to.accountingPeriods,
+ await flash(request, success(successMessage))
+ );
+}
+
+export default function AccountingPeriodsRoute() {
+ const { data, count, nextFiscalYear } = useLoaderData<typeof loader>();
+ const permissions = usePermissions();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <AccountingPeriodsTable
+ data={data}
+ count={count}
+ primaryAction={
+ permissions.can("update", "accounting") && (
+ <Form method="post">
+ <input type="hidden" name="intent" value="generate" />
+ <input type="hidden" name="fiscalYear" value={nextFiscalYear} />
+ <Button leftIcon={<LuCirclePlus />} variant="primary" type="submit">
+ Generate FY{nextFiscalYear}
+ </Button>
+ </Form>
+ )
+ }
+ />
+ <Outlet />
+ </VStack>
+ );
+}
+```
+
+---
+
+## Task 13: Route — `periods.$periodId.close.tsx` (close drawer with readiness checklist)
+
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/periods.$periodId.close.tsx`
+
+**Steps:**
+
+1. Full route (loader = readiness; the confirm posts `intent=close` to the parent action; modal-overlay child-route pattern per `payment-terms.new.tsx` / `ConfirmDelete`):
+
+```typescript
+import { notFound } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import {
+ Button,
+ Checkbox,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle
+} from "@carbon/react";
+import { useState } from "react";
+import type { LoaderFunctionArgs } from "react-router";
+import { useFetcher, useLoaderData, useNavigate, useParams } from "react-router";
+import { getPeriodCloseReadiness } from "~/modules/accounting";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ update: "accounting"
+ });
+
+ const { periodId } = params;
+ if (!periodId) throw notFound("periodId not found");
+
+ const readiness = await getPeriodCloseReadiness(client, companyId, periodId);
+ if (readiness.error || !readiness.data) {
+ throw notFound("Could not load close readiness");
+ }
+
+ return { readiness: readiness.data };
+}
+
+export default function ClosePeriodRoute() {
+ const { readiness } = useLoaderData<typeof loader>();
+ const { periodId } = useParams();
+ const navigate = useNavigate();
+ const fetcher = useFetcher();
+ const [acknowledged, setAcknowledged] = useState(false);
+
+ const hasBlockers = readiness.blockers.length > 0;
+ const hasWarnings = readiness.warnings.length > 0;
+ const canClose = !hasBlockers && (!hasWarnings || acknowledged);
+
+ const onClose = () => navigate(path.to.accountingPeriods);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Close Accounting Period</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <div className="flex flex-col gap-4">
+ {!hasBlockers && !hasWarnings && (
+ <p className="text-sm text-muted-foreground">
+ All readiness checks passed. Closing prevents any further
+ posting into this period.
+ </p>
+ )}
+ {readiness.blockers.map((b) => (
+ <div key={b.key} className="text-sm text-destructive">
+ Blocker: {b.label} — {b.count}
+ </div>
+ ))}
+ {readiness.warnings.map((w) => (
+ <div key={w.key} className="text-sm text-orange-500">
+ Warning: {w.label} — {w.count}
+ </div>
+ ))}
+ {hasWarnings && !hasBlockers && (
+ <label className="flex items-center gap-2 text-sm">
+ <Checkbox
+ checked={acknowledged}
+ onCheckedChange={(checked) =>
+ setAcknowledged(checked === true)
+ }
+ />
+ Close anyway — I have reviewed the warnings
+ </label>
+ )}
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <fetcher.Form method="post" action={path.to.accountingPeriods}>
+ <input type="hidden" name="intent" value="close" />
+ <input type="hidden" name="periodId" value={periodId} />
+ <Button
+ type="submit"
+ variant="primary"
+ isDisabled={!canClose || fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Close Period
+ </Button>
+ </fetcher.Form>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
+```
+
+2. Verify `Checkbox` export name/props in `@carbon/react` (grep an existing usage) and adjust the `onCheckedChange` handler to match.
+
+---
+
+## Task 14: Sidebar entry
+
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx`
+
+**Steps:**
+
+1. In the `Configure` group (lines ~98–149), directly above the `Fiscal Year` entry, add:
+
+```typescript
+ {
+ name: t`Accounting Periods`,
+ to: path.to.accountingPeriods,
+ role: "employee",
+ icon: <LuCalendarCheck />
+ },
+```
+
+2. Add `LuCalendarCheck` to the `react-icons/lu` import.
+3. Add `path.to.accountingPeriods` to the `accountingOnlyRoutes` set (lines ~25–33) so the page is gated behind accounting being enabled, matching the other GL pages.
+
+---
+
+## Task 15: Apply migration + SQL verification (requires local stack — coordinate with user)
+
+**Steps:**
+
+1. With the local stack up (`crbn up`):
+ ```bash
+ pnpm db:migrate
+ # Expected: applies 20260702044133_period-close-lifecycle.sql without error
+ ```
+2. Discard the locally regenerated types/swagger (cloud-generated files must not gain a local diff):
+ ```bash
+ git checkout -- packages/database/src/types.ts
+ git status --porcelain # confirm no generated artifacts staged
+ ```
+3. Idempotency check (the deploy runner retries failed files over partial state):
+ ```bash
+ psql postgresql://supabase_admin:postgres@localhost:$PORT_DB/postgres \
+ -f packages/database/supabase/migrations/20260702044133_period-close-lifecycle.sql
+ # Expected: completes cleanly a second time (IF NOT EXISTS / OR REPLACE guards)
+ ```
+4. Trigger smoke test in psql:
+ ```sql
+ -- Close a test period, then attempt a service-role journal insert dated inside it:
+ UPDATE "accountingPeriod" SET "closeStatus" = 'Closed' WHERE "id" = '<test-period-id>';
+ INSERT INTO "journal" ("journalEntryId", "companyId", "postingDate", "createdBy")
+ VALUES ('JE-TEST-000001', '<companyId>', '<date-in-period>', 'system');
+ -- Expected: ERROR: Accounting period is closed for posting date <date>
+ UPDATE "accountingPeriod" SET "closeStatus" = 'Open', "closedAt" = NULL WHERE "id" = '<test-period-id>';
+ ```
+
+---
+
+## Task 16: Typecheck, lint, and gated e2e verification
+
+**Steps:**
+
+1. ```bash
+ pnpm --filter @carbon/erp typecheck
+ pnpm --filter @carbon/database typecheck
+ pnpm --filter @carbon/utils typecheck
+ pnpm run lint
+ # Expected: all pass
+ ```
+2. E2E (requires user go-ahead; stack must be up): use the `/login` + `/test` skills to drive:
+ - `/x/accounting/periods` renders periods grouped list; Generate FY button creates 12 periods.
+ - Lock a period → receipt posting dated today fails with "period is locked"; manual JE posts fine.
+ - Close flow: draft JE in period shows as blocker; after posting the draft, close succeeds; sequential rule blocks closing a later period first.
+ - Reopen requires `delete: accounting`; reopening mid-history is blocked until later periods are open.
+ - Screenshot the periods page and close drawer for the PR (feedback: surface designs with screenshots).
+3. Update the spec: move acceptance-criteria checkboxes as they're verified; add changelog entry; keep spec implementation-accurate.
+
+## Commit checkpoints
+
+- After Tasks 1–8 (backend) pass typecheck: `feat(accounting): period close lifecycle — schema, services, posting gates`
+- After Tasks 9–14 (UI) pass typecheck + lint: `feat(accounting): accounting periods page with lock/close/reopen`
+- Commits only after the check-and-commit gate; PR references `Tracking spec: .ai/specs/2026-07-02-period-closing.md`.
+
+## Deferred (explicit non-goals for v1, per spec)
+
+- Per-subledger AR/AP/Inventory locks; 13th adjustment period; dead-letter UI for closed-period job failures; removal of the legacy Active/Inactive toggle; JournalEntryForm inline period warning (server-side error + flash covers v1). *(Persisted close-checklist tasks were un-deferred 2026-07-04 — see Addendum Tasks 17–20. Negative-inventory readiness is now seeded task 6's auto-check; posting-queue readiness is part of task 1's.)*
+
+---
+
+# Addendum (2026-07-04): NetSuite-style close checklist — Tasks 17–20
+
+Spec reference: `.ai/specs/2026-07-02-period-closing.md` §"NetSuite-style close checklist". Execute after Tasks 1–16 (or fold Task 17's DDL into the Task 1 migration wave if it hasn't been applied yet — preferred).
+
+## Task 17: Migration — checklist tables + seed
+
+**Files:** extend `20260702044133_period-close-lifecycle.sql` if unapplied, else a new randomized-timestamp migration; `packages/database/supabase/functions/lib/seed.data.ts` + `seed-company` for new-company seeding.
+
+1. Create `periodCloseTaskDefinition` + `periodCloseTask` exactly per the spec's SQL sketch (composite PKs, audit columns, `(companyId, accountingPeriodId, definitionId)` unique, indexes on `companyId`, `accountingPeriodId`).
+2. Four standard RLS policies each: SELECT via `get_companies_with_employee_role()`, writes via `get_companies_with_employee_permission('accounting_*')`.
+3. Seed the 9 system definitions (spec table: pending-postings, draft-journals, lock, draft-depreciation, unmatched-ic, negative-inventory, tb-balanced, review-statements, close) for every existing company (`isSystem = true`) and in `seed-company` for new ones. Idempotency-guard all DDL + seeds.
+4. `pnpm run generate:types` before typechecking.
+
+## Task 18: Service — checklist functions + close gating
+
+**Files:** `apps/erp/app/modules/accounting/accounting.service.ts`, `accounting.models.ts`.
+
+1. `getPeriodCloseChecklist(client, companyId, periodId)`: idempotent instantiation from active definitions (insert missing via the unique key, snapshot name/type/sort/required/severity, default assignee), then overlay live results from `getPeriodCloseReadiness` onto Auto tasks (check passes ⇒ effective status Done, `completedBy = null`), return ordered.
+2. `completeCloseTask` / `skipCloseTask` (reject skip on Blocker autos; `skippedReason` required; both stamp user + timestamp) / `addCloseTask` (ad-hoc, `definitionId = null`).
+3. Definition CRUD: `getPeriodCloseTaskDefinitions`, `upsertPeriodCloseTaskDefinition` (system rows: only `sortOrder`/`defaultAssigneeId`/`active` mutable), no hard delete for `isSystem`.
+4. `closeAccountingPeriod` gains the checklist gate: every `required` task Done/Skipped AND no failing Blocker auto-check; on success persist final Auto-task states onto the rows in the same transaction.
+5. Zod validators (`closeTaskCompleteValidator`, `closeTaskSkipValidator` with min-length reason, `periodCloseTaskDefinitionValidator`).
+
+## Task 19: UI — close drawer becomes the checklist; periods row progress
+
+**Files:** amend Task 13's `periods.$periodId.close.tsx`; `AccountingPeriodsTable` from Task 11; new `ui/Periods/PeriodCloseChecklist.tsx`.
+
+1. Drawer renders ordered task rows: status icon (green check / red blocker / amber warning / gray open), name, assignee, per-type affordances — Auto: live state + drill link (draft JEs → journals list filtered; pending docs → posting queue; IC → intercompany match page); Action: Lock/Close buttons wired to the existing parent-route intents; Manual: Complete (notes/evidence optional) + Skip (reason modal). Route action handles `intent: complete | skip | add-task`.
+2. Close button enabled per the Task 18 gate; blockers listed above it when disabled.
+3. `AccountingPeriodsTable` row gains a "6/9" progress chip once a period has instantiated tasks.
+4. Template management: `periods.checklist-settings.tsx` (Drawer) listing definitions with add/reorder/deactivate/default-assignee; `update: "accounting"`.
+
+## Task 20: Verification additions
+
+1. SQL: re-opening the drawer never duplicates tasks (unique-key upsert proven); closing persists Auto states.
+2. E2E per the spec's new acceptance criteria: seeded 9 tasks appear; draft-JE blocker disables Close and its drill link resolves; warning skip requires reason; Blocker skip rejected server-side; custom template task appears in the NEXT period only; close records completedBy/At on manual tasks.
+3. Update the Task 15/16 gates to include these; commit checkpoint: `feat(accounting): NetSuite-style period close checklist`.
diff --git a/.ai/plans/2026-07-03-multi-jurisdiction-tax.md b/.ai/plans/2026-07-03-multi-jurisdiction-tax.md
new file mode 100644
index 0000000000..ce7f08eafa
--- /dev/null
+++ b/.ai/plans/2026-07-03-multi-jurisdiction-tax.md
@@ -0,0 +1,811 @@
+# Multi-Jurisdiction Tax Compliance — implementation plan (Phase 1)
+
+**Spec:** .ai/specs/2026-07-03-multi-jurisdiction-tax.md
+**Research:** .ai/research/multi-jurisdiction-tax.md
+**Branch:** `tax-compliance` (create from `main`)
+
+**Scope:** Phase 1 only — determination (direct assignment), corrected posting, `taxLedger`, memo tax, shipping taxability, PDF tax blocks, liability report. Phases 2 (returns/settlement, use tax) and 3 (Avalara, Xero mapping) get their own plans after Phase 1 ships; their schema hooks (`taxReturnId`, `needsEngineReconciliation` columns) are created now so the ledger never needs an ALTER later.
+
+**Ground rules for every task:** pnpm only (never npm). Never run a whole-repo typecheck (OOMs) — always `pnpm exec turbo run typecheck --filter=@carbon/erp`. Never rebuild the database. Do not commit — /check-and-commit handles commits per task. UI strings use Lingui (`useLingui().t` / `<Trans>` from `@lingui/react/macro`).
+
+## Progress
+
+- [ ] Task 1: Create the Phase 1 migration
+- [ ] Task 2: Regenerate database types
+- [ ] Task 3: Add tax validators and enum arrays to accounting.models.ts (+ memo validator)
+- [ ] Task 4: Add effective-component rate math to accounting.utils.ts with unit tests
+- [ ] Task 5: Add tax CRUD service functions to accounting.service.ts
+- [ ] Task 6: Add resolveLineTaxes + suggestTaxCode with unit-tested core
+- [ ] Task 7: Wire determination into sales-side line creation
+- [ ] Task 8: Wire determination into purchase-side line creation
+- [ ] Task 9: Tax codes routes + table + form (components editor)
+- [ ] Task 10: Tax authorities + tax registrations routes
+- [ ] Task 11: Accounting nav + path.to entries for the Tax group
+- [ ] Task 12: Customer/supplier tax-code assignment UI + taxPercent sunset banner
+- [ ] Task 13: Customer location override select
+- [ ] Task 14: Item "Taxable" switch
+- [ ] Task 15: Line form tax display + override select + audit coverage
+- [ ] Task 16: Shared edge-function tax resolver helper
+- [ ] Task 17: post-sales-invoice — tax split, ledger writes, VOID reversals, shipping taxability
+- [ ] Task 18: post-purchase-invoice — recoverable input tax, reverse charge, ledger writes
+- [ ] Task 19: post-memo — net/tax split + signed ledger rows
+- [ ] Task 20: Sales invoice PDF tax summary, clauses, registration numbers
+- [ ] Task 21: Tax liability report (service + route)
+- [ ] Task 22: Lingui extract + full scoped validation
+- [ ] Task 23: Browser verification via /test
+
+## Dependencies
+
+- Task 1 → 2 → 3 → everything else.
+- Tasks 4–5 after 3; Task 6 needs 4–5.
+- Tasks 7–8 need 6. Tasks 9–11 need 5 (independent of 6–8; 9/10/11 can run in parallel).
+- Tasks 12–14 need 5 (independent of each other; parallel OK).
+- Task 15 needs 6. Task 16 needs 2; Tasks 17–19 need 16 (17/18/19 parallel after 16).
+- Task 20 needs 17 (reads the same resolved data; PDF math is read-side). Task 21 needs 17–18 (ledger rows exist).
+- Task 22 after all code tasks; Task 23 last.
+
+---
+
+## Task 1: Create the Phase 1 migration
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_multi-jurisdiction-tax.sql` (via `pnpm db:migrate:new multi-jurisdiction-tax` — never hand-pick the timestamp; if the generated HHMMSS is `000000`, rename the file with randomized digits)
+
+**Steps:**
+
+1. Run `pnpm db:migrate:new multi-jurisdiction-tax` from the repo root.
+2. Write the following SQL into the generated file. Every statement is idempotency-guarded because the deploy runner retries failed files over partially-committed state.
+
+```sql
+-- ============================== ENUMS ==============================
+DO $$ BEGIN
+ CREATE TYPE "taxCalculationType" AS ENUM ('Normal', 'Reverse Charge');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE TYPE "taxReportingCategory" AS ENUM
+ ('Standard', 'Reduced', 'Zero-Rated', 'Exempt', 'Reverse Charge', 'Export', 'Out of Scope');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+DO $$ BEGIN
+ CREATE TYPE "taxLedgerSource" AS ENUM ('Sales', 'Purchase');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- ============================== TABLES ==============================
+CREATE TABLE IF NOT EXISTS "taxAuthority" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "supplierId" TEXT,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE SET NULL
+);
+CREATE INDEX IF NOT EXISTS "taxAuthority_companyId_idx" ON "taxAuthority" ("companyId");
+CREATE INDEX IF NOT EXISTS "taxAuthority_createdBy_idx" ON "taxAuthority" ("createdBy");
+CREATE INDEX IF NOT EXISTS "taxAuthority_supplierId_idx" ON "taxAuthority" ("supplierId");
+DO $$ BEGIN
+ ALTER TABLE "taxAuthority" ADD CONSTRAINT "taxAuthority_companyId_name_key" UNIQUE ("companyId", "name");
+EXCEPTION WHEN duplicate_table THEN NULL; WHEN duplicate_object THEN NULL; END $$;
+
+CREATE TABLE IF NOT EXISTS "taxCode" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "calculationType" "taxCalculationType" NOT NULL DEFAULT 'Normal',
+ "reportingCategory" "taxReportingCategory" NOT NULL DEFAULT 'Standard',
+ "invoiceMessage" TEXT,
+ "countryId" INTEGER REFERENCES "country"("id"),
+ "state" TEXT,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+CREATE INDEX IF NOT EXISTS "taxCode_companyId_idx" ON "taxCode" ("companyId");
+CREATE INDEX IF NOT EXISTS "taxCode_createdBy_idx" ON "taxCode" ("createdBy");
+CREATE INDEX IF NOT EXISTS "taxCode_countryId_idx" ON "taxCode" ("countryId");
+DO $$ BEGIN
+ ALTER TABLE "taxCode" ADD CONSTRAINT "taxCode_companyId_name_key" UNIQUE ("companyId", "name");
+EXCEPTION WHEN duplicate_table THEN NULL; WHEN duplicate_object THEN NULL; END $$;
+
+CREATE TABLE IF NOT EXISTS "taxCodeComponent" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "taxCodeId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "taxAuthorityId" TEXT,
+ "rate" NUMERIC NOT NULL,
+ "sequence" INTEGER NOT NULL DEFAULT 1,
+ "isCompound" BOOLEAN NOT NULL DEFAULT FALSE,
+ "isRecoverable" BOOLEAN NOT NULL DEFAULT FALSE,
+ "salesTaxAccountId" TEXT,
+ "purchaseTaxAccountId" TEXT,
+ "effectiveDate" DATE,
+ "expirationDate" DATE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("taxCodeId", "companyId") REFERENCES "taxCode"("id", "companyId") ON DELETE CASCADE,
+ FOREIGN KEY ("taxAuthorityId", "companyId") REFERENCES "taxAuthority"("id", "companyId")
+);
+CREATE INDEX IF NOT EXISTS "taxCodeComponent_companyId_idx" ON "taxCodeComponent" ("companyId");
+CREATE INDEX IF NOT EXISTS "taxCodeComponent_taxCodeId_idx" ON "taxCodeComponent" ("taxCodeId");
+CREATE INDEX IF NOT EXISTS "taxCodeComponent_taxAuthorityId_idx" ON "taxCodeComponent" ("taxAuthorityId");
+CREATE INDEX IF NOT EXISTS "taxCodeComponent_createdBy_idx" ON "taxCodeComponent" ("createdBy");
+
+CREATE TABLE IF NOT EXISTS "taxRegistration" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "countryId" INTEGER NOT NULL REFERENCES "country"("id"),
+ "state" TEXT,
+ "registrationNumber" TEXT NOT NULL,
+ "effectiveDate" DATE,
+ "endDate" DATE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+CREATE INDEX IF NOT EXISTS "taxRegistration_companyId_idx" ON "taxRegistration" ("companyId");
+CREATE INDEX IF NOT EXISTS "taxRegistration_countryId_idx" ON "taxRegistration" ("countryId");
+CREATE INDEX IF NOT EXISTS "taxRegistration_createdBy_idx" ON "taxRegistration" ("createdBy");
+
+CREATE TABLE IF NOT EXISTS "taxLedger" (
+ "id" TEXT NOT NULL DEFAULT id('txl'),
+ "companyId" TEXT NOT NULL,
+ "source" "taxLedgerSource" NOT NULL,
+ "documentType" TEXT NOT NULL,
+ "documentId" TEXT NOT NULL,
+ "documentLineId" TEXT,
+ "journalId" TEXT,
+ "postingDate" DATE NOT NULL,
+ "taxCodeId" TEXT,
+ "taxCodeComponentId" TEXT,
+ "componentName" TEXT,
+ "taxAuthorityId" TEXT,
+ "customerId" TEXT,
+ "supplierId" TEXT,
+ "rate" NUMERIC NOT NULL DEFAULT 0,
+ "taxableAmount" NUMERIC NOT NULL DEFAULT 0,
+ "taxAmount" NUMERIC NOT NULL DEFAULT 0,
+ "exemptAmount" NUMERIC NOT NULL DEFAULT 0,
+ "taxExemptionReason" "taxExemptionReason",
+ "exemptionCertificateNumber" TEXT,
+ "currencyCode" TEXT,
+ "exchangeRate" NUMERIC,
+ "taxReturnId" TEXT,
+ "needsEngineReconciliation" BOOLEAN NOT NULL DEFAULT FALSE,
+ "postedToInputAccount" BOOLEAN NOT NULL DEFAULT FALSE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+CREATE INDEX IF NOT EXISTS "taxLedger_companyId_postingDate_idx" ON "taxLedger" ("companyId", "postingDate");
+CREATE INDEX IF NOT EXISTS "taxLedger_companyId_documentId_idx" ON "taxLedger" ("companyId", "documentId");
+CREATE INDEX IF NOT EXISTS "taxLedger_companyId_taxAuthorityId_idx" ON "taxLedger" ("companyId", "taxAuthorityId");
+CREATE INDEX IF NOT EXISTS "taxLedger_companyId_taxReturnId_idx" ON "taxLedger" ("companyId", "taxReturnId");
+CREATE INDEX IF NOT EXISTS "taxLedger_createdBy_idx" ON "taxLedger" ("createdBy");
+
+-- ============================== RLS ==============================
+-- Same block for each of: taxAuthority, taxCode, taxCodeComponent, taxRegistration, taxLedger.
+-- Written out once here for taxAuthority; REPEAT VERBATIM for the other four tables
+-- (replace the table name only).
+ALTER TABLE "public"."taxAuthority" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."taxAuthority";
+CREATE POLICY "SELECT" ON "public"."taxAuthority"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+DROP POLICY IF EXISTS "INSERT" ON "public"."taxAuthority";
+CREATE POLICY "INSERT" ON "public"."taxAuthority"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_create'))::text[])
+);
+DROP POLICY IF EXISTS "UPDATE" ON "public"."taxAuthority";
+CREATE POLICY "UPDATE" ON "public"."taxAuthority"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])
+);
+DROP POLICY IF EXISTS "DELETE" ON "public"."taxAuthority";
+CREATE POLICY "DELETE" ON "public"."taxAuthority"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_delete'))::text[])
+);
+
+-- ============================== COLUMN ADDS ==============================
+ALTER TABLE "item" ADD COLUMN IF NOT EXISTS "taxable" BOOLEAN NOT NULL DEFAULT TRUE;
+ALTER TABLE "customer" ADD COLUMN IF NOT EXISTS "taxCodeId" TEXT;
+ALTER TABLE "customerLocation" ADD COLUMN IF NOT EXISTS "taxCodeId" TEXT;
+ALTER TABLE "supplier" ADD COLUMN IF NOT EXISTS "taxCodeId" TEXT;
+ALTER TABLE "companySettings" ADD COLUMN IF NOT EXISTS "shippingIsTaxable" BOOLEAN NOT NULL DEFAULT FALSE;
+ALTER TABLE "quoteLine" ADD COLUMN IF NOT EXISTS "taxCodeId" TEXT;
+ALTER TABLE "salesOrderLine" ADD COLUMN IF NOT EXISTS "taxCodeId" TEXT;
+ALTER TABLE "salesInvoiceLine" ADD COLUMN IF NOT EXISTS "taxCodeId" TEXT;
+ALTER TABLE "purchaseOrderLine" ADD COLUMN IF NOT EXISTS "taxCodeId" TEXT;
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN IF NOT EXISTS "taxCodeId" TEXT;
+ALTER TABLE "memo" ADD COLUMN IF NOT EXISTS "taxCodeId" TEXT;
+ALTER TABLE "memo" ADD COLUMN IF NOT EXISTS "taxAmount" NUMERIC NOT NULL DEFAULT 0;
+ALTER TABLE "accountDefault" ADD COLUMN IF NOT EXISTS "taxSettlementAccount" TEXT;
+CREATE INDEX IF NOT EXISTS "customer_taxCodeId_idx" ON "customer" ("taxCodeId");
+CREATE INDEX IF NOT EXISTS "customerLocation_taxCodeId_idx" ON "customerLocation" ("taxCodeId");
+CREATE INDEX IF NOT EXISTS "supplier_taxCodeId_idx" ON "supplier" ("taxCodeId");
+```
+
+ Note: authority deletion is blocked by the plain composite FK (NO ACTION) plus a friendly pre-check in Task 5's `deleteTaxAuthority`. If `id('txl')` errors because the `id(prefix)` function signature differs, use bare `id()`. Set `postedToInputAccount = true` on ledger rows whose tax was debited to an input/receivable account (Tasks 18–19) — the liability report aggregates on it.
+
+3. **View recreations.** For each view whose base table gained a column and whose body uses `<alias>.*` or an explicit column list — `customers`, `suppliers`, `quoteLines`, `salesOrderLines`, `salesInvoiceLines`, `purchaseOrderLines`, `purchaseInvoiceLines`, and the memo view(s) from `20260630093809_ar-ap-payments.sql` — do the following, one view at a time:
+ 1. Find the NEWEST migration defining that view: `grep -rln 'CREATE OR REPLACE VIEW "<name>"\|CREATE VIEW "<name>"' packages/database/supabase/migrations/ | sort | tail -1`.
+ 2. Copy that newest body **verbatim** into this migration as `DROP VIEW IF EXISTS "<name>"; CREATE OR REPLACE VIEW "<name>" WITH(SECURITY_INVOKER=true) AS <newest body>;` — dropping first refreshes `*` expansion so the new columns appear.
+ 3. If the body lists columns explicitly (no `<alias>.*`), append the new column(s) (`taxCodeId`, `taxable`, or `taxAmount` as applicable) to the list.
+ 4. If a view's newest definition cannot be located, STOP and report — do not write a view body from memory.
+4. Apply locally: `pnpm db:migrate` (this is applying migrations to the local dev DB, which is allowed; it is not a DB rebuild). If `crbn migrate` fails with a local permission error, validate instead via the rolled-back-transaction method: `psql` as `supabase_admin`, `BEGIN; \i <migration file>; ROLLBACK;` and report that `db:migrate` needs the user.
+
+**Verify:**
+```bash
+pnpm db:migrate
+# Expected: output lists <timestamp>_multi-jurisdiction-tax.sql as applied, exit 0.
+psql "$SUPABASE_DB_URL" -c '\d "taxLedger"' | head -30
+# Expected: columns id, companyId, source, documentType, ..., needsEngineReconciliation present.
+```
+
+**Out of scope:** `taxReturn` / `taxReturnLayout` tables (Phase 2 migration); dropping `customer.taxPercent` (kept as fallback); touching `postingGroup*` anything (dropped tables — do not recreate).
+
+---
+
+## Task 2: Regenerate database types
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `packages/database/src/types.ts` (generated — never hand-edit)
+
+**Steps:**
+1. Run `pnpm run generate:types` from the repo root.
+2. Do NOT commit a 55k-line whole-file rewrite: if the diff includes unrelated per-company table churn (the committed types come from the cloud DB), keep only the hunks for the new tax tables/columns if the repo's convention allows partial staging; otherwise leave the full regenerated file and flag it in the task notes for the user. If the new `taxLedger`/`taxCode` types do NOT appear after generation, STOP and report.
+
+**Verify:**
+```bash
+grep -n '"taxCode"\|"taxLedger"\|"taxAuthority"\|"taxRegistration"' packages/database/src/types.ts | head -5
+# Expected: Row/Insert/Update type entries for the new tables.
+```
+
+**Out of scope:** hand-editing any generated file.
+
+---
+
+## Task 3: Add tax validators and enum arrays to accounting.models.ts (+ memo validator)
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts` — add tax validators + enum arrays
+- Modify: `apps/erp/app/modules/invoicing/invoicing.models.ts` — extend `memoValidator`
+
+**Steps:**
+1. In `accounting.models.ts`, following the existing style (`zfd` from `zod-form-data`, exported `const` arrays for enums — mirror `depreciationMethods` / `fixedAssetStatuses`):
+ - `export const taxCalculationTypes = ["Normal", "Reverse Charge"] as const;`
+ - `export const taxReportingCategories = ["Standard", "Reduced", "Zero-Rated", "Exempt", "Reverse Charge", "Export", "Out of Scope"] as const;`
+ - `taxAuthorityValidator`: `{ id: z.string().optional(), name: z.string().min(1, "Name is required"), supplierId: zfd.text(z.string().optional()) }`
+ - `taxCodeValidator`: `{ id: z.string().optional(), name: z.string().min(1), description: zfd.text(z.string().optional()), calculationType: z.enum(taxCalculationTypes), reportingCategory: z.enum(taxReportingCategories), invoiceMessage: zfd.text(z.string().optional()), countryId: zfd.numeric(z.number().optional()), state: zfd.text(z.string().optional()), active: zfd.checkbox() }`
+ - `taxCodeComponentValidator`: `{ id: z.string().optional(), taxCodeId: z.string().min(1), name: z.string().min(1), taxAuthorityId: zfd.text(z.string().optional()), rate: zfd.numeric(z.number().min(0).max(1)), sequence: zfd.numeric(z.number().int().min(1)).default(1), isCompound: zfd.checkbox(), isRecoverable: zfd.checkbox(), salesTaxAccountId: zfd.text(z.string().optional()), purchaseTaxAccountId: zfd.text(z.string().optional()), effectiveDate: zfd.text(z.string().optional()), expirationDate: zfd.text(z.string().optional()) }` with `.refine` that when both dates present, `expirationDate > effectiveDate`.
+ - `taxRegistrationValidator`: `{ id: z.string().optional(), countryId: zfd.numeric(z.number()), state: zfd.text(z.string().optional()), registrationNumber: z.string().min(1), effectiveDate: zfd.text(z.string().optional()), endDate: zfd.text(z.string().optional()) }`
+ - Export inferred types (`TaxCode`, `TaxCodeComponent`, …) next to the validators, matching file conventions.
+2. In `invoicing.models.ts`, find `memoValidator` and add: `taxCodeId: zfd.text(z.string().optional())`, `taxAmount: zfd.numeric(z.number().min(0)).optional()`. Add a `.refine` that `taxAmount`, when present, is `<= amount`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0, no new errors.
+```
+
+**Out of scope:** UI form components (later tasks); service functions.
+
+---
+
+## Task 4: Add effective-component rate math to accounting.utils.ts with unit tests
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.utils.ts` — pure functions
+- Modify: `apps/erp/app/modules/accounting/accounting.utils.test.ts` — tests (copy style from existing tests in this file)
+
+**Steps:**
+1. Add pure functions (no client, fully unit-testable):
+ - `getEffectiveComponents(components: TaxCodeComponentLike[], date: string): TaxCodeComponentLike[]` — filters `effectiveDate <= date` (or null) AND (`expirationDate` null OR `> date`), sorted by `sequence`.
+ - `computeEffectiveTaxRate(components: TaxCodeComponentLike[]): number` — non-compound components sum on the base; a compound component applies its rate to `base × (1 + sum of prior non-compound rates so far)` in `sequence` order. Return the total effective rate (e.g. GST 5% + compound PST 9.975% → `0.05 + 0.09975 × 1.05 = 0.1547375`).
+ - `computeLineTaxBreakdown(components, taxableBase: number, currencyDecimals: number)` — returns `{ componentId, rate, taxAmount }[]` with **per-line, half-up rounding at `currencyDecimals`** per component, plus `totalTax` = sum of rounded components.
+ Use a structural `TaxCodeComponentLike` type (rate, sequence, isCompound, effectiveDate, expirationDate, id) so the functions work on both app types and edge-function rows.
+2. Tests (use optional chaining on indexed access — `noUncheckedIndexedAccess` is on): single component; two stacked (6.25 + 2 = 8.25 on 100 → 8.25); compound Canada GST+PST example above; effective-date boundary (component expiring 2026-06-30 vs successor effective 2026-07-01, assert rates picked at 2026-06-30 vs 2026-07-01); rounding (rate 0.0825 on 33.33 → component amounts round half-up to 2 decimals and sum consistently).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp test -- accounting.utils
+# Expected: new tests listed and passing, exit 0.
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** DB access; document-level rounding (explicitly not supported).
+
+---
+
+## Task 5: Add tax CRUD service functions to accounting.service.ts
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts`
+- Modify: `apps/erp/app/modules/accounting/index.ts` — barrel exports if not already wildcard
+
+**Steps:**
+1. Following the existing CRUD style in this file (e.g. the payment terms / fixed asset class functions — client first arg, `{data, error}` returned raw, `companyId` scoping on every query, `sanitize` on writes):
+ - `getTaxAuthorities(client, companyId, args?: GenericQueryFilters & { search?: string })` (list w/ `setGenericQueryFilters`), `getTaxAuthoritiesList` (id/name for selects), `getTaxAuthority`, `upsertTaxAuthority`, `deleteTaxAuthority`.
+ - `getTaxCodes(list)`, `getTaxCodesList` (active only, id/name/calculationType), `getTaxCode` (single, `.select("*, taxCodeComponent(*)")`), `upsertTaxCode`, `deleteTaxCode`.
+ - `upsertTaxCodeComponents(client, companyId, taxCodeId, components[], userId)` — delete-and-reinsert components for the code (config tables, low volume) OR per-row upsert matching the house upsert branch style; include audit fields.
+ - `getTaxRegistrations(list)`, `getTaxRegistration`, `upsertTaxRegistration`, `deleteTaxRegistration`.
+ - `getTaxCodeWithEffectiveComponents(client, companyId, taxCodeId, date)` — fetches code + components, applies `getEffectiveComponents`/`computeEffectiveTaxRate` from Task 4, returns `{ taxCode, components, effectiveRate }`.
+2. Block deleting a `taxAuthority` referenced by any `taxCodeComponent` (pre-check count, return an error object with a clear message).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** determination logic (Task 6); routes (Tasks 9–10).
+
+---
+
+## Task 6: Add resolveLineTaxes + suggestTaxCode with unit-tested core
+
+**Depends on:** Tasks 4, 5
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.utils.ts` — pure resolution core
+- Modify: `apps/erp/app/modules/accounting/accounting.utils.test.ts` — tests
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` — thin fetching wrappers
+
+**Steps:**
+1. Pure core in `accounting.utils.ts`:
+ `resolveTaxFromInputs(inputs: { customerTaxExempt?: boolean; customerExemptionReason?: string | null; customerExemptionCertificateNumber?: string | null; itemTaxable?: boolean; locationTaxCodeId?: string | null; partyTaxCodeId?: string | null; legacyTaxPercent?: number | null })` → `{ kind: "exempt" | "nonTaxableItem" | "code" | "legacy" | "none"; taxCodeId: string | null; taxPercent: number | null (null for "code" — computed by caller from components); exemptionReason?; exemptionCertificateNumber? }`. Precedence: exempt → nonTaxableItem → location code → party code → legacy percent → none.
+2. Tests: each precedence rung; exempt customer with a coded location still resolves exempt; taxable item + no codes + legacy 0.05 → legacy.
+3. Service wrappers in `accounting.service.ts`:
+ - `resolveLineTaxes(client, companyId, { source: "sales" | "purchase", customerId?, supplierId?, customerLocationId?, itemId?, date })` — fetches `customerTax` (taxExempt, reason, certificate), `customerLocation.taxCodeId` (when id given), `customer.taxCodeId`/`customer.taxPercent` (or supplier equivalents for purchase), `item.taxable`; runs `resolveTaxFromInputs`; for `kind: "code"` fetches effective components (Task 5) and computes `taxPercent` + `components[]`. Returns `{ data: { taxCodeId, taxPercent, components, kind, exemptionReason, exemptionCertificateNumber }, error }`.
+ - `suggestTaxCode(client, companyId, { countryId?, state? })` — active `taxCode` rows where (`countryId` matches or code's countryId is null) and (`state` matches case-insensitively or code's state is null), ordered most-specific-first (state match > country match); return top 5.
+4. If `customerTax`/`supplierTax` field names differ from the spec's assumption (`taxExempt`, `taxExemptionReason`, `taxExemptionCertificateNumber`), STOP and report — do not guess (check `packages/database/supabase/migrations/20260430000001_tax-status.sql`).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/erp test -- accounting.utils
+# Expected: resolveTaxFromInputs tests pass.
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** call-site wiring (Tasks 7–8); Avalara dispatch (Phase 3 — the wrapper is the seam, keep its signature stable).
+
+---
+
+## Task 7: Wire determination into sales-side line creation
+
+**Depends on:** Task 6
+**Files:**
+- Modify: `apps/erp/app/modules/sales/sales.service.ts` — quote line + sales order line creation/duplication paths
+- Modify: `apps/erp/app/modules/invoicing/invoicing.service.ts` — sales invoice line creation path (if line defaults are set here)
+- Modify: the route actions that create these lines (grep below) if defaulting happens there instead
+
+**Steps:**
+1. Locate every server-side site where a NEW sales-side line's `taxPercent` is defaulted from the customer or copied forward: `grep -n "taxPercent" apps/erp/app/modules/sales/sales.service.ts apps/erp/app/modules/invoicing/invoicing.service.ts apps/erp/app/routes/x+/sales-order+/*.tsx apps/erp/app/routes/x+/quote+/*.tsx apps/erp/app/routes/x+/sales-invoice+/*.tsx` (known site: `sales.service.ts:1937`-area insert). Order→invoice and quote→order copies keep copying the line's stored values (correct — do not re-resolve on conversion).
+2. At each NEW-line creation site, call `resolveLineTaxes` and set both `taxCodeId` and `taxPercent` from the result. Where the caller already receives an explicit `taxPercent` from the form, only default when the field was not user-set (match the existing `?? `-default idiom at each site).
+3. Add a `recalculateLineTaxes` action route for sales orders and sales invoices (new route files following the naming of sibling action-only routes in `apps/erp/app/routes/x+/sales-order+/` — e.g. an `…$orderId.recalculate-taxes.tsx` action-only file): loops document lines, re-runs `resolveLineTaxes` with the current ship-to, updates `taxCodeId`/`taxPercent` on lines NOT manually overridden — track override by comparing stored `taxCodeId` to the resolution result; if there is no reliable way to distinguish a manual override, update all lines and note it in the response flash ("Recalculated N lines").
+4. If the ship-to→`customerLocationId` linkage is not available at line-creation time in a given path (e.g. quotes without a location), pass only `customerId` — the resolver falls back to the customer default.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+pnpm --filter @carbon/erp test
+# Expected: existing sales/invoicing tests still pass.
+```
+
+**Out of scope:** purchase side (Task 8); line form UI (Task 15); changing conversion-copy semantics.
+
+---
+
+## Task 8: Wire determination into purchase-side line creation
+
+**Depends on:** Task 6
+**Files:**
+- Modify: `apps/erp/app/modules/purchasing/purchasing.service.ts` — PO line creation
+- Modify: `apps/erp/app/modules/invoicing/invoicing.service.ts` — purchase invoice line creation
+
+**Steps:**
+1. Same grep approach for purchase lines (`grep -n "taxPercent\|supplierTaxAmount" apps/erp/app/modules/purchasing/purchasing.service.ts apps/erp/app/modules/invoicing/invoicing.service.ts`). Purchase lines keep `supplierTaxAmount` as the authoritative entry — determination only sets `taxCodeId` (identity/recoverability), never overwrites a user-entered `supplierTaxAmount`.
+2. On new PO/purchase-invoice lines, call `resolveLineTaxes({ source: "purchase", supplierId, itemId, date })` and set `taxCodeId` from the result. Do not compute or set `supplierTaxAmount` from the code in this task (the purchase invoice remains supplier-authoritative; a suggested amount display is Task 15's UI concern).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** use-tax accrual (Phase 2); generated `taxPercent`/`taxAmount` columns on purchase lines (they stay GENERATED from supplierTaxAmount — do not touch).
+
+---
+
+## Task 9: Tax codes routes + table + form (components editor)
+
+**Depends on:** Task 5
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/tax-codes.tsx`, `tax-codes.new.tsx`, `tax-codes.$taxCodeId.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Tax/TaxCodesTable.tsx`, `TaxCodeForm.tsx`, `index.ts`
+- Copy from (precedent): `apps/erp/app/routes/x+/accounting+/payment-terms.tsx` + `payment-terms.new.tsx` + `payment-terms.$paymentTermId.tsx`; form fields precedent for account selects: `apps/erp/app/modules/accounting/ui/FixedAssets/AssetClassForm.tsx:134-169` (`<Account>` from `~/components/Form`)
+
+**Steps:**
+1. Clone the payment-terms route trio: list route (loader `getTaxCodes` + `requirePermissions(request, { view: "accounting" })`), `new` and `$taxCodeId` as Drawer overlay routes rendered via the list route's `<Outlet />` (Drawer pattern per the payment-terms precedent — never cards below the table).
+2. `TaxCodeForm` (ValidatedForm + `validator(taxCodeValidator)`): name, description, calculationType select, reportingCategory select, invoiceMessage textarea, country select (existing country select component — grep `~/components/Form` for `Country`; if none exists, use a plain `Select` fed by a countries loader), state input, active checkbox.
+3. Components editor inside the drawer, below the code fields: a row list (add/remove/reorder by sequence) with per-row: name, authority select (from `getTaxAuthoritiesList`), rate (percent input storing 0..1 — follow how `taxPercent` inputs elsewhere convert, grep `taxPercent` in `apps/erp/app/modules/sales/ui/`), isCompound + isRecoverable checkboxes, `<Account>` selects for salesTaxAccountId/purchaseTaxAccountId, effective/expiration date pickers. Submit posts components as a JSON field or repeated fields to the same action, which calls `upsertTaxCode` + `upsertTaxCodeComponents` in sequence. Show a computed effective-rate preview (`computeEffectiveTaxRate` on the current rows) in the drawer footer, formatted as a percent — plain number, no parentheses.
+4. Table columns: name, effective rate (computed), calculation type, reporting category, active; row actions edit/delete gated by `permissions.can("update", "accounting")` per the payment-terms precedent.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** Xero TaxType select (Phase 3); nav registration (Task 11).
+
+---
+
+## Task 10: Tax authorities + tax registrations routes
+
+**Depends on:** Task 5
+**Files:**
+- Create: `apps/erp/app/routes/x+/accounting+/tax-authorities.tsx`, `tax-authorities.new.tsx`, `tax-authorities.$taxAuthorityId.tsx`
+- Create: `apps/erp/app/routes/x+/accounting+/tax-registrations.tsx`, `tax-registrations.new.tsx`, `tax-registrations.$taxRegistrationId.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Tax/TaxAuthoritiesTable.tsx`, `TaxAuthorityForm.tsx`, `TaxRegistrationsTable.tsx`, `TaxRegistrationForm.tsx` (export from `ui/Tax/index.ts`)
+- Copy from (precedent): the same payment-terms trio as Task 9
+
+**Steps:**
+1. Authorities: name + optional supplier select (grep `~/components/Form` for the `Supplier` select component used in purchasing forms). Delete action surfaces the referenced-by-components error from Task 5 as a flash error.
+2. Registrations: country select, state, registrationNumber, effective/end dates.
+3. Cross-warnings on the registrations list route loader: compute (a) active tax codes whose `countryId`/`state` match no active registration, and (b) registrations matching no active code; render each as an `Alert`-style banner above the table (grep `packages/react/src` for the existing `Alert` component).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** Avalara nexus mirror (Phase 3).
+
+---
+
+## Task 11: Accounting nav + path.to entries for the Tax group
+
+**Depends on:** Tasks 9, 10 (routes exist)
+**Files:**
+- Modify: `apps/erp/app/utils/path.ts` — add entries
+- Modify: `apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx` — add a "Tax" group
+
+**Steps:**
+1. `path.ts`, mirroring the paymentTerms trio exactly (list/new/id + generatePath): `taxCodes`, `newTaxCode`, `taxCode(id)`, `taxAuthorities`, `newTaxAuthority`, `taxAuthority(id)`, `taxRegistrations`, `newTaxRegistration`, `taxRegistration(id)`, `taxLiability` (report route, Task 21).
+2. `useAccountingSubmodules.tsx`: add a "Tax" group containing Tax Codes, Tax Authorities, Tax Registrations, Tax Liability, following the existing group structure (Reports / General Ledger / Fixed Assets / Configure). Place Tax Liability under the Reports group if groups are semantic rather than positional — match how Fixed Assets pages are grouped and keep all four tax entries together in one "Tax" group. Use `msg`-style breadcrumb/label conventions already present in the file.
+3. Update Tasks 9/10 routes to use the new `path.to` helpers if they hardcoded URLs.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** MES nav (tax is ERP-only).
+
+---
+
+## Task 12: Customer/supplier tax-code assignment UI + taxPercent sunset banner
+
+**Depends on:** Tasks 5, 6
+**Files:**
+- Modify: `apps/erp/app/modules/sales/ui/Customer/CustomerTaxForm.tsx` — Tax Code select + suggestion + conditional taxPercent
+- Modify: `apps/erp/app/routes/x+/customer+/$customerId.tax.tsx` — loader/action
+- Modify: `apps/erp/app/modules/purchasing/ui/Supplier/SupplierTaxForm.tsx` + `apps/erp/app/routes/x+/supplier+/$supplierId.tax.tsx` — same changes
+- Modify: `apps/erp/app/modules/sales/sales.models.ts` + `purchasing.models.ts` — add `taxCodeId` to the tax validators
+- Modify: `apps/erp/app/modules/sales/sales.service.ts` + `purchasing.service.ts` — persist `customer.taxCodeId` / `supplier.taxCodeId` in the update functions used by those routes
+
+**Steps:**
+1. Add a Tax Code select (options from `getTaxCodesList`, loaded in the route loader) to `CustomerTaxForm`; persist to `customer.taxCodeId` via the route action (extend `updateCustomerTax` or the customer update it delegates to — follow where `taxId`/`taxPercent` are saved today).
+2. Suggestion: in the loader, fetch the customer's primary location address (via `customerLocation`/`address`); call `suggestTaxCode` with its `countryId`/`state`; when the customer has no `taxCodeId` and suggestions exist, render a dismissible inline hint ("This address looks like {state}: apply {code name}?") with an apply button that sets the select value. No document-time inference anywhere.
+3. Sunset banner (OQ 4): in the loader, check whether the company has any party with a `taxCodeId` (one `select id, limit 1` on customer + supplier where `taxCodeId is not null`). If yes, hide the `taxPercent` input and render a banner: "Flat tax percent is deprecated — assign tax codes instead." If no, keep today's `taxPercent` field.
+4. Mirror all of 1–3 for the supplier form/route.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** bulk assignment (do NOT build a new bulk-update route in this task — if the customers table already has a bulk-update action route analogous to `apps/erp/app/routes/x+/items+/update.tsx`, add `taxCodeId` to it; if it does not exist, note that in the task result and leave bulk for a follow-up).
+
+---
+
+## Task 13: Customer location override select
+
+**Depends on:** Task 5
+**Files:**
+- Modify: `apps/erp/app/modules/sales/ui/Customer/CustomerLocationForm.tsx` — Tax Code override select
+- Modify: the customer-location route(s) that render this form (grep `CustomerLocationForm` under `apps/erp/app/routes/x+/customer+/`) — loader provides `getTaxCodesList`, action persists `customerLocation.taxCodeId`
+- Modify: `apps/erp/app/modules/sales/sales.models.ts` — location validator gains `taxCodeId`
+
+**Steps:**
+1. Add an optional "Tax Code (override)" select under the address block in `CustomerLocationForm` (empty option = "Inherit from customer"). Persist through the location upsert service (grep `insertCustomerLocation` / `updateCustomerLocation` in `sales.service.ts`).
+2. On address change in this form, surface the same `suggestTaxCode` hint as Task 12 (reuse the hint component — extract it to `apps/erp/app/modules/accounting/ui/Tax/TaxCodeSuggestion.tsx` and export it if Task 12 inlined it).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** supplier locations (purchase determination uses the supplier default only in Phase 1).
+
+---
+
+## Task 14: Item "Taxable" switch
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/items/ui/Parts/PartProperties.tsx` — Boolean property
+- Modify: sibling properties panels that expose the same block: grep `Requires Inspection\|requiresInspection` under `apps/erp/app/modules/items/ui/` and add the same switch to every panel that has it (Tools, Materials, Consumables, Services as applicable)
+- Modify: `apps/erp/app/routes/x+/items+/update.tsx` — accept the `taxable` field
+- Copy from (precedent): `PartProperties.tsx:600-627` (`<Boolean label="Active" …>` / `<Boolean label="Requires Inspection" …>`)
+
+**Steps:**
+1. Add `<Boolean label="Taxable" name="taxable" variant="small" onChange={(value) => onUpdate("taxable", value)} />` (match the exact `onUpdate`/fetcher submission idiom of the `requiresInspection` switch in each panel).
+2. In `x+/items+/update.tsx`, add `taxable` to the accepted fields (boolean coercion matching how other booleans are parsed there). It is a plain item column — no cascade logic (do NOT touch `deriveItemMethodUpdate` / method-material cascades).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** item views/tables surfacing `taxable` as a column (not needed for Phase 1).
+
+---
+
+## Task 15: Line form tax display + override select + audit coverage
+
+**Depends on:** Tasks 6, 7, 8
+**Files:**
+- Modify: `apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx`
+- Modify: `apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx`
+- Modify: `apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx`
+- Modify: `apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx`
+- Modify: the corresponding line route actions to accept/persist `taxCodeId` (grep each form's `action` route)
+- Modify: `packages/database/src/audit.config.ts` — ensure line tables are audited
+- Copy from (precedent): `SalesInvoiceLineForm.tsx:71-143` (where `taxPercent` already flows into totals math)
+
+**Steps:**
+1. In each line form, add a "Tax Code" select (options via `getTaxCodesList` provided by the parent route loader; empty option = "None / manual"). When a code is selected, set the form's `taxPercent` to the code's effective rate (fetch via a small loader/fetcher call to a `resolveLineTaxes`-backed endpoint or pass the codes list with precomputed effective rates from the loader — prefer precomputed rates in the loader: extend `getTaxCodesList` to include `effectiveRate` computed at `today`). Keep `taxPercent` visible read-only next to the select when a code is chosen; editable when "None / manual".
+2. Persist `taxCodeId` in each line action (the zod line validators in `sales.models.ts` / `invoicing.models.ts` gain `taxCodeId: zfd.text(z.string().optional())`).
+3. Audit coverage (OQ 3): open `packages/database/src/audit.config.ts`; if `salesOrderLine` / `salesInvoiceLine` / `purchaseInvoiceLine` / `quoteLine` are already configured entities, confirm new columns are captured automatically (diff-based) and do nothing. If they are NOT in the config, this is an "Ask First" boundary per `packages/database/AGENTS.md` — STOP on that sub-step and report rather than adding entities unilaterally; the rest of the task proceeds.
+4. Purchase invoice line form additionally shows "Suggested tax: {amount}" (computed from the resolved code's effective rate × line base) next to `supplierTaxAmount` — display only, never auto-overwrites the supplier amount.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** MES line UIs; changing how `taxPercent` totals math works in these forms (it already multiplies correctly).
+
+---
+
+## Task 16: Shared edge-function tax resolver helper
+
+**Depends on:** Task 2
+**Files:**
+- Create: `packages/database/supabase/functions/shared/resolve-taxes.ts`
+- Copy from (precedent): `packages/database/supabase/functions/shared/get-accounting-period.ts` (shared-helper shape), `packages/database/supabase/functions/shared/get-posting-group.ts` (accountDefault fetch)
+
+**Steps:**
+1. Export three functions (Deno imports per the edge-function rule — types from `../lib/types.ts`):
+ - `getEffectiveComponents(components, date)` and `computeComponentTaxes(components, taxableBase, decimals)` — port the Task 4 math VERBATIM (same rounding: per-component, half-up at currency decimals; keep the functions in sync by comment reference to `accounting.utils.ts`).
+ - `getLineTaxContext(client, companyId, { taxCodeId, date })` — fetches the code + components effective at `date`, returns `{ calculationType, reportingCategory, components: [{ id, name, taxAuthorityId, rate, isCompound, isRecoverable, salesTaxAccountId, purchaseTaxAccountId }] }`; returns null when `taxCodeId` is null.
+2. No `requirePermissions` here — callers (posting functions) already hold a service-role client inside their transaction.
+
+**Verify:**
+```bash
+cd packages/database/supabase/functions && deno check shared/resolve-taxes.ts
+# Expected: exit 0 (no type errors). If deno is unavailable locally, verify via the edge-runtime container logs after Task 17 and note it.
+```
+
+**Out of scope:** calling it (Tasks 17–19); Avalara (Phase 3).
+
+---
+
+## Task 17: post-sales-invoice — tax split, ledger writes, VOID reversals, shipping taxability
+
+**Depends on:** Task 16
+**Files:**
+- Modify: `packages/database/supabase/functions/post-sales-invoice/index.ts`
+
+**Steps:**
+1. **Revenue net of tax.** At the line-cost computation ([index.ts:302-306](packages/database/supabase/functions/post-sales-invoice/index.ts)), split: `netLineAmount = qty × unitPrice + shipping + addOn` (NO `× (1 + taxPercent)`), `lineTaxAmount` computed as follows: if the line has `taxCodeId`, fetch context once per distinct code (cache in a Map) via `getLineTaxContext` and use `computeComponentTaxes(components, netTaxableBase, decimals)` where `netTaxableBase` excludes `nonTaxableAddOnCost` exactly as the invoice-totals view does; if no code but `taxPercent > 0`, `lineTaxAmount = round(netTaxableBase × taxPercent)` as a single pseudo-component. All amounts × `invoiceExchangeRate` for base currency, same as existing math.
+2. **Journal lines.** Keep AR debit **gross** (`net + tax`, weighted shipping unchanged). Credit revenue with **net**. For each component (or the pseudo-component), credit `component.salesTaxAccountId ?? accountDefaults.data.salesTaxPayableAccount` with the component tax amount, description `"Sales Tax – " + componentName` (legacy: `"Sales Tax"`). If `accountDefaults.data.salesTaxPayableAccount` is null/empty when needed, throw a clear error ("Sales tax payable account is not configured") — surfaced like other posting errors.
+3. **Exempt/zero lines.** When resolution kind was exempt (line has customer marked exempt — fetch `customerTax` once per invoice) or `item.taxable = false` or effective rate 0: post no tax journal lines, but still write the ledger row (step 4) with `exemptAmount = netTaxableBase`, snapshotting `taxExemptionReason`/`exemptionCertificateNumber` from `customerTax` when customer-exempt.
+4. **taxLedger rows.** Inside the same Kysely transaction that writes journal lines, insert one `taxLedger` row per line per component (and one per exempt/legacy line): source `'Sales'`, documentType `'Sales Invoice'`, documentId, documentLineId, journalId, postingDate (same date the journal uses), taxCodeId, taxCodeComponentId, componentName, taxAuthorityId, customerId, rate, taxableAmount (base ccy), taxAmount, exemptAmount, currencyCode, exchangeRate, createdBy = the posting userId.
+5. **Shipping taxability.** Fetch `companySettings.shippingIsTaxable`; when true and the invoice has document-level (shipment) shipping, tax that shipping at the FIRST line's resolved code context (document-level shipping has one destination); write its own tax journal credit + ledger row with documentLineId null. When false, current behavior (untaxed).
+6. **VOID path.** In the VOID branch (grep `VOID` in this file, ~line 1263/1393): insert negated `taxLedger` rows mirroring the original document's rows (select the original rows by documentId, flip signs of taxableAmount/taxAmount/exemptAmount, stamp the void journalId + posting date).
+7. Line-cost allocation weighting (`lineCostPercentageOfTotalCost`) must keep using GROSS totals so shipping weighting behavior is unchanged — only the revenue/tax credit split changes. Fixed-asset disposal invoice lines and intercompany branches: apply the same AR-gross/revenue-net/tax-credit split where those branches credit revenue/proceeds; if a branch's structure makes the split ambiguous, STOP and report the branch rather than guessing.
+
+**Verify:**
+```bash
+cd packages/database/supabase/functions && deno check post-sales-invoice/index.ts
+# Expected: exit 0.
+# Then, with the local stack running (crbn up) and accounting enabled (/x/settings/accounting):
+# post a sales invoice with taxPercent = 0.0825 via the UI and check:
+psql "$SUPABASE_DB_URL" -c 'SELECT "componentName", "taxableAmount", "taxAmount" FROM "taxLedger" ORDER BY "createdAt" DESC LIMIT 5;'
+# Expected: rows for the posted invoice; journal shows revenue net + "Sales Tax" credit lines (inspect via the UI journal viewer).
+```
+
+**Out of scope:** post-shipment / post-receipt (no tax there); Avalara commit calls (Phase 3); changing COGS/inventory entries.
+
+---
+
+## Task 18: post-purchase-invoice — recoverable input tax, reverse charge, ledger writes
+
+**Depends on:** Task 16
+**Files:**
+- Modify: `packages/database/supabase/functions/post-purchase-invoice/index.ts`
+
+**Steps:**
+1. Per line with a `taxCodeId`, fetch context (Map-cached). Split the line's `taxAmount` (already base currency, GENERATED from `supplierTaxAmount × exchangeRate`) across effective components proportionally by component share of the effective rate (rounding per component, half-up; last component absorbs the residual so the sum equals the line's `taxAmount` exactly).
+2. **Normal + recoverable components:** debit `component.purchaseTaxAccountId ?? accountDefaults.data.purchaseTaxPayableAccount` for the component share; reduce the cost debit by the same amount (cost posts net of recoverable tax); set `postedToInputAccount = true` on those ledger rows. **Normal + non-recoverable (or no code):** current behavior — tax stays in `lineCost` ([index.ts:449-458](packages/database/supabase/functions/post-purchase-invoice/index.ts)), AP gross, `postedToInputAccount = false`. Mixed codes (some components recoverable, some not) split accordingly.
+3. **Reverse Charge codes** (`calculationType = 'Reverse Charge'`): the supplier charged no tax (`supplierTaxAmount` expected 0 — if non-zero, treat as Normal and log a warning into the function's console): compute the notional tax from the code's effective rate on the line base; post Dr `purchaseTaxAccountId ?? accountDefault.purchaseTaxPayableAccount` (recoverable) / Cr `accountDefault.reverseChargeSalesTaxPayableAccount` for the same amount; AP stays net (unchanged). If the reverse-charge account default is missing when needed, throw "Reverse charge sales tax payable account is not configured".
+4. **taxLedger rows** in the same transaction: source `'Purchase'`, documentType `'Purchase Invoice'`, one row per component (recoverable, non-recoverable, and both legs' identity for reverse charge: one row with the input-side amount, `taxAmount` positive; reverse-charge output leg is represented by the same row — do NOT write two rows per component; the settlement report reads reverse-charge codes by `reportingCategory`). Include supplierId, rates, bases (base currency).
+5. **VOID path**: negated ledger rows, mirroring Task 17 step 6.
+
+**Verify:**
+```bash
+cd packages/database/supabase/functions && deno check post-purchase-invoice/index.ts
+# Expected: exit 0.
+psql "$SUPABASE_DB_URL" -c 'SELECT "source", "componentName", "taxAmount", "exemptAmount" FROM "taxLedger" WHERE "source" = '"'"'Purchase'"'"' ORDER BY "createdAt" DESC LIMIT 5;'
+# Expected: purchase rows after posting a purchase invoice with a coded line.
+```
+
+**Out of scope:** use-tax accrual affordance (Phase 2); touching the GENERATED columns; post-receipt.
+
+---
+
+## Task 19: post-memo — net/tax split + signed ledger rows
+
+**Depends on:** Task 16
+**Files:**
+- Modify: `packages/database/supabase/functions/post-memo/index.ts`
+- Modify: `apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx` — tax code select + computed tax display
+- Modify: the memo route(s) that render/submit `MemoForm` (grep `MemoForm` under `apps/erp/app/routes/x+/credits+/`) — loader provides tax codes list; action persists `taxCodeId`/`taxAmount`
+
+**Steps:**
+1. **MemoForm:** add a Tax Code select (options w/ precomputed effective rates from the loader, as in Task 15). When set, compute `taxAmount = round(amount × r / (1 + r))` client-side and show it read-only ("Includes {taxAmount} tax"), submitting both fields; allow manual `taxAmount` edit (validator caps at `amount`). `amount` label/semantics unchanged (gross).
+2. **post-memo edge function:** locate the journal-line construction (memo posts Dr/Cr `reasonAccount` vs AR/AP for `amount`). With a `taxCodeId` and `taxAmount > 0`: keep the AR/AP leg at gross `amount`; post the `reasonAccount` leg at `amount − taxAmount`; post the tax leg per component (proportional split as Task 18 step 1) to `salesTaxAccountId`/`purchaseTaxAccountId` fallback chain by party side, with the sign that mirrors the reason-account leg (Credit memo for a customer: Dr reason net, Dr output tax, Cr AR gross; Debit memo flips; supplier memos mirror on the purchase side using purchase accounts).
+3. **taxLedger rows:** one per component, source by party side (`'Sales'` for customer memos, `'Purchase'` for supplier), documentType `'Memo'`, signed so that a customer Credit memo REDUCES the period's output tax (negative `taxAmount`) and a customer Debit memo increases it; supplier memos mirror, with `postedToInputAccount = true` when the tax leg hits a purchase tax account. `taxableAmount` = signed `(amount − taxAmount)` in base currency (× memo exchangeRate).
+4. Memos with no `taxCodeId` (or `taxAmount = 0`) post byte-identically to today — guard the whole feature behind `taxAmount > 0`.
+5. If `post-memo/index.ts` does not exist or memo posting turns out to live elsewhere (grep `functions.invoke("post-memo"` under `apps/erp/`), STOP and report the actual location before editing.
+
+**Verify:**
+```bash
+cd packages/database/supabase/functions && deno check post-memo/index.ts
+# Expected: exit 0.
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** memo application/settlement logic (`invoiceSettlement`) — signs there are amount-based and unaffected because `amount` semantics are unchanged.
+
+---
+
+## Task 20: Sales invoice PDF tax summary, clauses, registration numbers
+
+**Depends on:** Task 17 (data available), Task 2 (types)
+**Files:**
+- Modify: `packages/documents/src/pdf/SalesInvoicePDF.tsx`
+- Modify: `packages/documents/src/utils/sales-invoice.ts`
+- Modify: the PDF data loader that assembles SalesInvoicePDF props (grep `SalesInvoicePDF` under `apps/erp/app/` and `packages/database/supabase/functions/` to find where props are built — likely the document render route/edge function)
+
+**Steps:**
+1. Extend the PDF props with: `taxSummary: { name: string; rate: number; amount: number }[]` (grouped by component name — built from the lines' tax codes' effective components, or for legacy lines a single "Tax" row), `taxMessages: string[]` (distinct `invoiceMessage` values of codes on the document), `sellerTaxRegistrationNumber: string | null` (active `taxRegistration` matching the company's country, else `company.taxId`), `customerVatNumber: string | null` (from `customerTax.vatNumber`, only when any line's code has reportingCategory `Reverse Charge` or `Export`).
+2. In `SalesInvoicePDF.tsx`, render: the tax summary rows between subtotal and total (one row per component: name, rate as percent, amount — no parentheses around numbers); `taxMessages` as small print under the totals block; registration numbers in the header/footer block where `company.taxId` (or equivalent) renders today — grep this file for existing tax/company-identity display and extend in place.
+3. Keep `getLineTaxesAndFees` math untouched; add a `getTaxSummaryByComponent(lines, codeContexts)` helper in `utils/sales-invoice.ts` used by the props builder.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/documents
+# Expected: exit 0.
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0 (props builder).
+```
+
+**Out of scope:** quote/PO PDFs (follow-up); document template customizer blocks beyond what the invoice template already renders.
+
+---
+
+## Task 21: Tax liability report (service + route)
+
+**Depends on:** Tasks 17, 18
+**Files:**
+- Modify: `apps/erp/app/modules/accounting/accounting.service.ts` — `getTaxLiability`
+- Create: `apps/erp/app/routes/x+/accounting+/tax-liability.tsx`
+- Create: `apps/erp/app/modules/accounting/ui/Tax/TaxLiabilityTable.tsx`
+- Copy from (precedent): `apps/erp/app/routes/x+/accounting+/trial-balance.tsx:27-80` (date-range loader + `ReportFilters`); table CSV export is built into the shared Table per `.ai/rules/table-csv-export.md`
+
+**Steps:**
+1. `getTaxLiability(client, companyId, { startDate, endDate, taxAuthorityId? })` — aggregate `taxLedger` grouped by `taxAuthorityId` + `componentName`: `sum(taxableAmount)`, `sum(exemptAmount)`, `sum(taxAmount) filter (source = 'Sales')` as collected, `sum(taxAmount) filter (source = 'Purchase' AND "postedToInputAccount")` as input tax (the flag is written by Tasks 18–19; capitalized non-recoverable purchase tax appears in the bases but not as input tax). Net = collected − input.
+2. Route with `requirePermissions({ view: "accounting" })`, `ReportFilters` for the date range + an authority filter select, and a grouped table (authority → component rows) with the standard Table (CSV export comes free).
+3. Register `taxLiability` in `path.ts`/nav if not done in Task 11.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/erp
+# Expected: exit 0.
+```
+
+**Out of scope:** returns/settlement (Phase 2); GL cross-tie automation (manual check in Task 23).
+
+---
+
+## Task 22: Lingui extract + full scoped validation
+
+**Depends on:** all code tasks (3–21)
+**Files:**
+- Modify: `packages/locale/locales/*/erp.po` (generated by extract)
+
+**Steps:**
+1. `pnpm lingui:extract` (new UI strings from Tasks 9–15, 20–21 land in the `.po` catalogs). Run `pnpm lingui:clean` if headers churn.
+2. Run the full scoped gate: `pnpm run lint`, `pnpm exec turbo run typecheck --filter=@carbon/erp --filter=@carbon/documents --filter=@carbon/database`, `pnpm --filter @carbon/erp test`.
+
+**Verify:**
+```bash
+pnpm run lint && pnpm exec turbo run typecheck --filter=@carbon/erp --filter=@carbon/documents && pnpm --filter @carbon/erp test
+# Expected: all exit 0.
+```
+
+**Out of scope:** `pnpm translate` (LLM translation pass — user-triggered).
+
+---
+
+## Task 23: Browser verification via /test
+
+**Depends on:** Task 22
+**Files:** none (verification)
+
+**Steps:**
+1. Boot the stack with plain `crbn up` (portless `*.dev`). Enable accounting locally at `/x/settings/accounting` (fresh resets seed `accountingEnabled=false`).
+2. Invoke the `/test` skill with this scenario: (a) create tax authority "Texas Comptroller"; (b) create tax code "TX – Austin" with components State 6.25 + City 2.0, match fields US/TX; (c) open a customer with a TX address — confirm the suggestion hint, assign the code; (d) create a sales order line for that customer — confirm `taxPercent` shows 8.25%; (e) invoice and post it; (f) verify the journal shows revenue net + two Sales Tax credit lines and AR gross; (g) open Tax Liability for today — confirm the two component rows with correct bases; (h) create + post a Credit memo with the code — confirm the liability report nets down; (i) screenshot each step (ValidatedForm submits via `requestSubmit`; blur react-aria number fields first).
+3. Any "Something went wrong"/blank page → capture via the `/error` skill and fix before proceeding.
+
+**Verify:**
+```bash
+# /test run transcript + screenshots; liability report totals match the posted documents:
+# 8.25% of the order line base split 6.25/2.00 across the two component rows, memo negative.
+# Expected: playbook cached under .ai/playbooks/.
+```
+
+**Out of scope:** Phase 2/3 scenarios (returns, use tax, Avalara).
diff --git a/.ai/plans/2026-07-03-public-company-readiness-roadmap.md b/.ai/plans/2026-07-03-public-company-readiness-roadmap.md
new file mode 100644
index 0000000000..c38baafc63
--- /dev/null
+++ b/.ai/plans/2026-07-03-public-company-readiness-roadmap.md
@@ -0,0 +1,149 @@
+# Public-Company Readiness — Program Roadmap
+
+> Spec: `.ai/specs/2026-07-03-public-company-readiness.md` (the audit; findings referenced as MW-*/SD-*/GAP-*/CO-*)
+> Research: `.ai/research/public-company-compliance.md`
+> Status: active program tracker — check items off as workstreams land
+
+## Goal
+
+Carbon becomes an accounting system a CFO adopts at seed and keeps through IPO and beyond as a US-listed multi-national. "Full readiness" is defined by the exit criteria at the bottom of this plan — not by feature count.
+
+## Governing decisions (locked)
+
+1. **Accounting is NOT a switch.** `companySettings.accountingEnabled` is a temporary internal feature flag while the suite is completed. It is never exposed as a customer setting. At GA, accounting is always-on: new companies from creation, existing companies through the one-way cutover event (§Cutover). The flag is then removed from the codebase. (Resolved 2026-07-03.)
+2. **Virtual year-end.** No posted closing entries, ever — the computed Retained Earnings / Net Income split (period-closing + financial-reporting specs) is the permanent model.
+3. **Right the first time.** Because the six Phase-∅ specs are unbuilt, three readiness items were folded into them on 2026-07-03 rather than scheduled as retrofits:
+ - Posted-record immutability + `journalLine.createdBy` → period-closing spec §Enforcement item 4 (same trigger wave as the close backstop).
+ - Posted-only balance defaults (`p_include_drafts DEFAULT FALSE` + report toggle) → financial-reporting spec §11 (the RPCs are being redefined anyway).
+ - Universal `journalLine.sourceAmount`/`sourceCurrencyCode` population (every posting path, base documents included) → bank-reconciliation spec FX section (serves FEC/SAF-T + ASC 830, not just bank matching).
+ Their plan files carry ⚠️ delta banners; update task lists before executing.
+4. **Build vs integrate.** Carbon builds the GL baseline + statutory surfaces + integration feeds; it never builds reconciliation certification, SEC/XBRL, equity/718, tax provision, payroll, or US sales-tax content (research §Ecosystem — even NetSuite doesn't).
+5. **All spec open questions resolved 2026-07-03** (recorded inline in the spec): reversal-only + audited `'Repair'` journal channel; **approvals for manual JEs, payments, and purchase invoices ASAP** on the existing PO approval engine (workstream pulled forward — starts now); forward-only gapless numbering, existing journals never renumbered; rev-rec cut accepted with a contract-validation TODO; auto-reverse unrealized FX; **Avalara first-class** for e-invoicing; detective SoD v1; SOC 2 evidence starts now → SOC 1 after Phase 0; group-scoped books with per-company enablement.
+
+## Phase ∅ — Land this branch (prerequisite for everything)
+
+Suggested order (dependencies noted). Each executes per its own plan.
+
+- [ ] **Period closing** (`.ai/plans/2026-07-02-period-closing.md`) — first: budgeting depends on `fiscalYear`/`periodNumber`; financial reporting's period picker reads them; every later close task assumes the lifecycle. Includes the immutability fold-in (delta banner).
+- [ ] **Financial reporting** (`.ai/plans/2026-07-02-financial-reporting.md`) — includes the Posted-only fold-in (delta banner).
+- [ ] **Bank reconciliation Phase 1** (`.ai/plans/2026-07-02-bank-reconciliation-phase-1.md`) — includes the universal source-currency fold-in (delta banner); lands the `journalLine` FX columns everything in Phase 1 below reads.
+- [ ] **Multi-jurisdiction tax Phase 1** (spec ready; cut plan via `/plan`) — determination, corrected posting, `taxLedger`, liability report.
+- [ ] **Budgeting Phase 1** (`.ai/plans/2026-07-02-budgeting.md`) — after period closing.
+- [ ] **Plaid bank feeds** (bank Phase 2; spec ready).
+- [ ] **Tax Phase 2–3** (returns/settlement/use tax; Avalara + Xero mapping).
+- [ ] **Budgeting Phase 2–3** (commitments + control; IS integration, consolidated BvA).
+- [ ] **Bank Phase 3–4** (full format matrix, rules engine, transfers; intelligence layer).
+
+## Phase 0 — Ledger integrity (the two remaining MWs + numbering)
+
+Cut as three specs via `/spec-writing`, then `/plan` + execute each.
+**Spec B (approvals) is pulled forward — it depends only on the existing
+approval engine, not on Phase ∅, and Brad wants it ASAP. Start it now, in
+parallel with the Phase-∅ workstreams.**
+
+- [ ] **Spec A: Record integrity & audit hardening** (MW-1 remainder, SD-1 remainder)
+ - [ ] Immutability triggers for posted `payment`/`memo`/`invoiceSettlement` (`Posted → Voided` only), completing what the period-closing fold-in does for journals.
+ - [ ] Deferred constraint trigger: Σ(signed `journalLine.amount`) = 0 per journal at COMMIT (±0.01) — every writer, including edge functions.
+ - [ ] Audit coverage extension (`audit.config.ts` — ask-first file, this spec is the ask): `journal`, `journalLine`, `account`, `accountingPeriod`, `payment`, `memo`, `sequence`, `userPermission`, `apiKey`, `approvalRequest`/`approvalRule`, `accountDefault`, `taxCode`/`taxCodeComponent`, `bankAccount`, `paymentTerm`, `customerTax`/`supplierTax`.
+ - [ ] Accounting entities: audit **always-on** (company toggle governs operational entities only) and **synchronous in-transaction** (or transactional outbox) — never PGMQ fire-and-forget.
+ - [ ] Audit tables: append-only (REVOKE UPDATE/DELETE + restrictive policies), per-class retention (≥7 years accounting, 30-day default operational), archive integrity.
+ - [ ] **JE population export** (route + streaming service, no row caps): journal id/line, account, signed amount + debit/credit presentation, posting date, createdAt/postedAt, `createdBy`/`preparedBy`/`approvedBy`, source type, document ref, reversal linkage, source currency/amount, book. This is the SOX AS 2401 / FEC / GoBD / SAF-T substrate.
+ - [ ] **Repair channel** (resolved): a `'Repair'` journal source type — the only sanctioned data-fix path once immutability lands. Permissioned, reason required, correcting-entries only (never in-place edits), itself immutable and audit-logged; the invoice/payment audit's deferred historical-repair work flows through it.
+- [ ] **Spec B: Document approvals & SoD reporting** (MW-2) — **✅ SPEC WRITTEN 2026-07-04**: `.ai/specs/2026-07-04-document-approvals.md` (all four remaining questions resolved before writing) — next: `/plan`, then execute
+ - Scope as spec'd: `approvalDocumentType` += `journalEntry`, `payment`, `purchaseInvoice`, **`memo`** (added by resolution); `'Pending Approval'` status on all four documents; gates placed to survive bypass (JE gate inside `postJournalEntry` covering the MCP path; payment/memo edge functions accept the parked status only with an Approved request in-transaction; `post-purchase-invoice` finally gains a status guard); **no-self-approval** server-side for all types incl. existing POs (`enforceNoSelfApproval` default on, disable = audited standing exception); reversals/voids NOT gated in v1 (audit-logged + approver-notified); opt-in rules, no seeding (SoD report flags companies without a JE rule); escalation reminder job makes `escalationDays` real; `journal.preparedBy/approvedBy/approvalRequestId`; user access report + detective SoD conflict report with standing-exception tracking.
+- [ ] **Spec C: Gapless numbering & legal series** (SD-2) — resolved: forward-only fix, **existing journals are never renumbered** (historical gaps are documented with a cutover date, not rewritten)
+ - [ ] `journalEntryId` keeps the `JE-yyyy-mm-` format but is assigned **inside the posting transaction** from a DB-serialized per-company counter — gapless from the cutover date forward.
+ - [ ] `sequence` rows for accounting documents immutable-after-first-use + audit-logged (kills the rewind→duplicate-number hole).
+ - [ ] `legalSeries` table (entity × country × document type) for customer-facing **sales invoices/credit notes** (the EU/LatAm statutory gapless-series requirement — not journals) — substrate for e-invoicing (Phase 3); backdating flag (postingDate ≪ createdAt) in the JE export.
+- [ ] **Schema seed:** `journal.bookId` (+ `accountingBook` table, seeded `PRIMARY` per group) — lands with Spec A's migration so every later poster/report is book-aware (GAP-5 step 1). Scoping resolved: **group-scoped definitions with per-company enablement** (an `accountingBookCompany` enablement table), mirroring the shared chart-of-accounts pattern.
+- [ ] **Cutover tooling** (§Cutover below) — spec the activation event + opening-balance wizard; required for flag retirement, so it belongs to Phase 0 even though it ships last in it.
+
+## Phase 1 — Close & FX completeness
+
+- [ ] **Unrealized FX revaluation** (SD-4): close task revaluing open FX invoices, unapplied payments/memos, FX bank balances at period-end rate; **SAP-style auto-reversing** entries (post at period end, reverse day 1 next period — self-healing; resolved 2026-07-03) to new `unrealizedExchangeGain/LossAccount` defaults; posts as *accounting* source; joins `getPeriodCloseReadiness`.
+- [ ] **Exchange-rate history feed** (SD-5): daily job appends `exchangeRateHistory` closing rates + derives period averages; consolidated reports warn on missing coverage instead of silently falling back to rate 1.
+- [ ] **Posted CTA** (SD-5): consolidation posts CTA to `accountDefault.currencyTranslationAccount` resolved by id (kill the hardcoded "3200"); CTA rolls forward; translated income statement learns `netChange`.
+- [ ] **Scheduled depreciation** (GAP-4.1): monthly Inngest proposal → Draft depreciation run → approval → post; close-readiness check "depreciation posted for period".
+- [ ] **Accrual engines** (GAP-6): prepaid amortization schedules (AP line → schedule → monthly journal), recurring journal templates, auto-reversing accrual flag on manual JEs — all close-checklist tasks.
+
+## Phase 2 — Subledger completeness
+
+- [ ] **Revenue recognition v1** (GAP-1): deferred revenue schedules + recognition journal; customer deposits/prepayments as liabilities; cost-based percent-of-completion for long-lead jobs (uses existing job costing); contract asset/liability rollforward report. SSP allocation explicitly deferred. **TODO before cutting this spec (resolved with condition): validate the cut against real customer contracts — check current/pipeline customers for bundled obligations that would force SSP allocation earlier.**
+- [ ] **Inventory valuation** (GAP-3): standard-cost input + actual-vs-standard variance posting → inventory revaluation document (`Revaluation` cost-ledger type) → LCNRV write-down run (reversal per book: US no, IAS 2 yes — first multi-book consumer) → GL posting for quantity adjustments → overhead absorption to GL → landed cost.
+- [ ] **Fixed assets completeness** (GAP-4): disposal with proceeds (gain/loss = proceeds − NBV), impairment posting, CIP asset class + capitalization from job/PO costs, component assets.
+- [ ] **Master-data change controls** (SD-6): supplier bank details table + approval-gated changes (prereq for any payment execution), change alerts on `accountDefault`/tax config.
+
+## Phase 3 — Multi-book & statutory
+
+- [ ] **Adjustment books** (GAP-5): NetSuite-style delta books on `bookId`; book-specific depreciation per asset; book columns in reports. First consumers: IAS 2 reversals, statutory depreciation, IFRS 16.
+- [ ] **Leases** (GAP-2): lease master, PV/IBR, ROU + liability effective-interest schedules, operating vs finance (+ IFRS 16 single model per book), monthly JEs, maturity-analysis export.
+- [ ] **Statutory audit files** (GAP-D3): FEC 18-field export (thin layer over the Phase-0 JE export), SAF-T country flavors (taxLedger supplies the tax section), GoBD data-access export; statutory COA alternative-account-number mapping; WORM retention ≥10y + legal hold.
+- [ ] **E-invoicing framework** (GAP-D2): EN 16931 semantic model from Carbon invoices (tax spec's registrations/summary blocks are prereqs); Peppol BIS 3.0 / Factur-X / XRechnung renderers; clearance state machine (Pending → Submitted → Accepted/Rejected → Corrected); inbound structured invoices into AP. **Partner resolved: Avalara as a first-class integration** (Avalara E-Invoicing APIs behind Carbon's adapter interface, same posture as the tax spec's AvaTax connector — the two share `companyIntegration` credentials). France Sept 2026 is the first hard deadline.
+- [ ] **Filing extensions** (GAP-D1): AP withholding tax (treaty rates, certificates), EC Sales List + Intrastat extracts, UK MTD digital-links submission.
+- [ ] **Segments** (GAP-7): server-side enforcement of required dimensions at posting; reserved Segment dimension derived from master data; segment columns on statements; ASU 2023-07 expense detail.
+
+## Phase 4 — Scale-out
+
+- [ ] **Intercompany maturity** (SD-5): matching tolerance + FX-difference posting; IC document mirroring (PO↔SO); netting workbench; ownership % + NCI only when a sub-100% subsidiary is real.
+- [ ] **Integration surface** (GAP-E1): TB API (entity/book/period/dimension), JE export API, **controlled JE import API** (validated, approval- and period-aware, idempotent, audit-stamped — how Carta/payroll/lease/provision entries land), posting/close webhooks. Rides MCP/API-key infra once Phase 0 gates exist.
+- [ ] **Enterprise ITGC** (SD-3 remainder): SAML/OIDC SSO, MFA enforcement policy, session revocation on deactivate + admin session listing, API-key audit events. Preventive SoD enforcement if customer demand.
+
+## ∥ Company program (starts now, runs parallel — CO-1)
+
+- [ ] Staging environment in the deploy pipeline; CODEOWNERS on `packages/database` + posting functions; make `pnpm audit` blocking at high/critical.
+- [ ] PITR/DR with documented RPO/RTO (today's docs say "a backup is not disaster recovery").
+- [ ] SOC 2 Type II: pick auditor, start evidence period (~2 quarters) — procurement gate for any mid-market+ customer.
+- [ ] SOC 1 Type II: scope control objectives (posting integrity, tax calc, depreciation calc, costing calc) + ITGCs; requires the staging/change-management items above. A customer IPO-ing in 2 years needs this period started ~now.
+- [ ] ISO 27001 (EU procurement); country invoicing-software certifications (Portugal AT, France PDP) gated on Phase-3 market entry.
+
+## Cutover — accounting goes always-on
+
+### Now (pre-GA)
+
+- `accountingEnabled` stays as-is mechanically but is treated as an **internal-only** flag: no customer-facing setting, no docs describing accounting as optional (update `docs/content/docs/reference/accounting.mdx` language at GA). Internal/design-partner companies flip it manually as today.
+
+### GA gate (flag retirement criteria)
+
+The flag is removed when ALL of:
+1. Phase ∅ fully landed (close lifecycle, tax posting, statements, bank rec).
+2. Phase 0 fully landed (immutability, approval, audit hardening, numbering, JE export).
+3. Cutover tooling (below) shipped and exercised on at least two internal companies.
+
+### New companies (at GA)
+
+- `seed-company` creates every company with accounting active: COA, accountDefaults, fiscal settings, `PRIMARY` book, current-year periods generated, all Phase-0 controls on. No opening balances needed — the ledger starts at zero on day one.
+
+### Existing companies — cutover runbook (one-way, per company)
+
+1. **Prepare** (any time before): choose cutover date = first day of a fiscal period; complete configuration — accountDefaults (a completeness check must pass: every referenced default account set), tax codes assigned to parties, bank accounts created and GL-linked, fiscal year settings confirmed (they lock at activation).
+2. **Opening balances**: a wizard builds a proposed opening trial balance as a Draft journal (new `sourceType: 'Opening Balance'`, dated cutover date − 1 day):
+ - Inventory: valuation from `costLedger`/`itemCost` as of cutover.
+ - AR/AP: open invoice balances (post-tax-spec: net + tax split).
+ - Fixed assets: cost + accumulated depreciation from the register.
+ - Cash/equity/loans/everything else: manual entry against the wizard's remaining-to-balance line.
+ The journal must balance and must tie: AR/AP tie-out and inventory-valuation-vs-GL checks run against the draft before activation is allowed. If migrating from another GL, the opening TB is keyed from that system's closing TB instead, with the same tie-out checks.
+3. **Activate** (permissioned `accounting_update`, explicit confirmation, one-way): posts the opening journal; stamps `company.accountingActivatedAt/By`; locks `baseCurrencyCode` + fiscal settings; generates the fiscal year's periods; **closes all periods before the cutover date** (the period-close trigger then guarantees pre-history stays empty — no retroactive GL from old operational documents, the opening journal is the only bridge); enables all posting paths.
+4. **First close**: run the first month-end per the close-readiness checklist; if parallel-running an old GL, compare trial balances at month 1 and document differences (this comparison is the audit evidence for the migration).
+5. **Retire the flag**: when every active company has `accountingActivatedAt`, remove `accountingEnabled` reads from the posting functions (one PR — the guards are enumerable), then drop the column in a follow-up migration.
+
+Audit posture: the activation event, opening journal, config locks, and pre-cutover period closes are all audit-logged (Phase 0 makes that trail synchronous and immutable). For a future public company, the cutover date is the start of auditable history in Carbon; anything earlier lives in the prior system's records under the retention policy.
+
+## Definition of full readiness (exit criteria)
+
+**Controls:** period close enforced at DB for all writers; posted records immutable everywhere (journals, lines, payments, memos, settlements); JE approval with system-enforced no-self-approval; always-on synchronous audit trail, append-only, ≥7-year retention, covering all accounting + permission tables; gapless journal + legal document numbering; user-access and SoD-conflict reports; JE population export reconciling opening→closing TB.
+**Statements:** BS/IS/TB/SCF/GL-detail Posted-only with comparatives, consolidated across mixed currencies with real (warned) rates and posted, rolled-forward CTA; budget-vs-actual; PDF/CSV everywhere.
+**GAAP:** deferred revenue + deposits + POC with rollforwards; lease subledger; LCNRV + standard costing + revaluation + landed cost; impairment/CIP/component assets; accrual/prepaid/recurring engines; ≥1 adjustment book proving multi-GAAP; segment-tagged statements.
+**Statutory:** tax returns with settlement per registration; e-invoicing live in target markets with clearance tracking; FEC/SAF-T/GoBD exports; statutory COA mapping; WORM retention + legal hold.
+**Ecosystem:** documented TB/JE-export/JE-import APIs + webhooks; at least one live integration each for close-management, equity, and payroll JE import.
+**Vendor:** SOC 1 Type II issued (SOC 2 + ISO 27001 alongside); staging + PITR/DR with stated RPO/RTO.
+
+## Remaining open questions
+
+**None.** All nine resolved by Brad on 2026-07-03 — recorded inline in the spec's Open Questions section and in Governing decision 5 above. One conditional carry-forward: the rev-rec contract-validation TODO (Phase 2) must be done before that spec is cut.
+
+## Changelog
+
+- 2026-07-03: Created. Governing decisions locked (switch → internal FF + cutover; virtual year-end; three fold-ins applied to unbuilt specs with delta banners on their plans).
+- 2026-07-04: Spec B written (`.ai/specs/2026-07-04-document-approvals.md`) after resolving its four open questions with Brad first (per the reordered spec-writing flow): memos added as a fourth gated document type; reversals/voids not gated in v1; opt-in rules with no seeding; escalation reminder job in v1.
+- 2026-07-03: All nine open questions resolved (Governing decision 5). Approvals workstream (Phase 0 Spec B — JEs + payments + purchase invoices on the existing PO engine) pulled forward to start immediately, in parallel with Phase ∅. Numbering fix confirmed forward-only (no renumbering of history); book scoping = group definitions + per-company enablement; FX = auto-reverse; e-invoicing = Avalara first-class; SoD = detective v1.
diff --git a/.ai/plans/2026-07-04-avalara-integration-foundation.md b/.ai/plans/2026-07-04-avalara-integration-foundation.md
new file mode 100644
index 0000000000..ef7eb76bd6
--- /dev/null
+++ b/.ai/plans/2026-07-04-avalara-integration-foundation.md
@@ -0,0 +1,271 @@
+# Avalara Integration Foundation — Implementation Plan
+
+## Overview
+
+- **Design Spec:** `.ai/specs/2026-07-04-avalara-integration-foundation.md` (status: in-progress; one open question gates Task 5 internals only)
+- **Tracking issue:** crbnos/carbon#1061
+- **Tasks:** 11 tasks + gated verification
+- **Branch:** `feature/avalara-integration-foundation`
+
+**Ground rules for the executor:**
+
+- No DB schema changes beyond one idempotent seed row — do NOT run `pnpm run generate:types` expecting changes, and never commit a regenerated `packages/database/src/types.ts` diff.
+- Do NOT rebuild the database; apply the seed migration with `pnpm db:migrate` only, when the local stack is up.
+- Typecheck per package (`pnpm --filter @carbon/ee typecheck`, `--filter @carbon/erp typecheck`) — whole-repo typecheck OOMs.
+- `config.tsx` must stay browser-safe: no imports of `service.server.ts`, `hooks.server.ts`, or the client (see `packages/ee/AGENTS.md` "Never").
+- Never log or flash the license key; error messages include taxonomy `kind` + Avalara message only.
+- Commit only at the marked checkpoints, after verification passes (check-and-commit gate).
+
+## Dependencies
+
+```
+Task 1 (env vars) ──┬─ Task 3 (client core) ─┬─ Task 4 (avatax surface) ─┬─ Task 6 (hooks + service seam)
+ │ └─ Task 5 (einvoicing surface — OQ-gated)
+ └─ Task 2 (config.tsx registry) ────────────────────┘
+Task 7 (seed migration) — independent; needed before browser verification
+Task 8 (API routes + dynamic options) — after Task 6
+Task 9 (unit tests + sandbox smoke) — after Tasks 4–5
+Task 10 (docs/rules) — after Task 8
+Task 11 (validation gate) — last
+```
+
+---
+
+## Task 1: Env plumbing — `AVALARA_ACCOUNT_ID` / `AVALARA_LICENSE_KEY`
+
+**Files:**
+- Modify: `packages/env/src/index.ts`
+- Modify: `.env.example` (repo root; also check `apps/erp/.env.example` if present)
+
+**Steps:**
+
+1. Next to the `XERO_CLIENT_ID` block (~line 313), add:
+
+```typescript
+export const AVALARA_ACCOUNT_ID = getEnv("AVALARA_ACCOUNT_ID", {
+ isRequired: false
+});
+export const AVALARA_LICENSE_KEY = getEnv("AVALARA_LICENSE_KEY", {
+ isRequired: false,
+ isSecret: true
+});
+```
+
+2. Add `AVALARA_ACCOUNT_ID` to the same server-env aggregation object that lists `XERO_CLIENT_ID` (~line 436) if that object gates availability; do NOT add the license key to anything client-visible.
+3. Add both to the `ProcessEnv` interface declaration at the top of the file (where `XERO_CLIENT_ID: string` is declared, ~line 23).
+4. Trace how `XERO_CLIENT_ID` reaches `@carbon/auth` (the Xero `config.tsx` imports it from there) — mirror the export for the two Avalara vars.
+5. Document both in `.env.example` with a comment: `# Avalara (tax + e-invoicing) — integration hidden unless both set`.
+
+**Verification:** `pnpm --filter @carbon/env typecheck && pnpm --filter @carbon/auth typecheck`
+
+---
+
+## Task 2: Registry entry — `packages/ee/src/avalara/config.tsx`
+
+**Files:**
+- Create: `packages/ee/src/avalara/config.tsx`
+- Modify: `packages/ee/src/index.ts` (import + `integrations` array + re-export `Avalara`)
+
+**Steps:**
+
+1. Model on `packages/ee/src/xero/config.tsx`. `defineIntegration({ id: "avalara", name: "Avalara", category: "Tax & Compliance", active: !!AVALARA_ACCOUNT_ID && !!AVALARA_LICENSE_KEY, logo: Logo, images: [], ... })` — no `oauth` block (Basic auth is env-side). Import env vars from the same source Xero uses (`@carbon/auth`).
+2. `AvalaraSettingsSchema` (zod, reuse the file-local `coerceBoolean` pattern from Xero's config):
+ - `companyCode: z.string().min(1)`
+ - `environment: z.enum(["sandbox", "production"]).default("sandbox")`
+ - `taxDetermination: coerceBoolean.optional().default(false)`
+ - `eInvoicing: coerceBoolean.optional().default(false)`
+ - `avalaraCompanyId: z.coerce.number().optional()` (not a form field; written by install hook)
+3. `settingGroups`: `Connection` ("Which Avalara company and environment this Carbon company uses") and `Features` ("Enable the Avalara capabilities this company consumes").
+4. `settings`: `companyCode` (type `options`, `listOptions: []` — populated dynamically, Xero account-code precedent; `required: true`), `environment` (type `options` with sandbox/production descriptions, default `sandbox`), `taxDetermination` + `eInvoicing` (type `switch`, default `false`, descriptions pointing at #1044/#1054 features).
+5. `actions`: `[{ id: "test-connection", label: "Test Connection", description: "Verify credentials and company code against Avalara", endpoint: "/api/integrations/avalara/test" }]`.
+6. Inline `Logo` SVG component (simple monochrome "A" mark placeholder is fine; note for design pass).
+7. Register in `packages/ee/src/index.ts`: import, add to `integrations` array (alphabetical — before `Email`), add `export { Avalara } from "./avalara/config";`.
+
+**Verification:** `pnpm --filter @carbon/ee typecheck`
+
+---
+
+## Task 3: Client core — auth, base URLs, retry/timeout, error taxonomy
+
+**Files:**
+- Create: `packages/ee/src/avalara/lib/client.ts`
+- Create: `packages/ee/src/avalara/lib/types.ts`
+
+**Steps:**
+
+1. `types.ts`: `namespace Avalara` request/response models — `PingResult`, `CompanyModel`, `TransactionModel` (with `details[]`: jurisdiction, rate, tax, taxableAmount — the shape the tax spec maps to `taxLedger`), `AddressResolutionModel`, `NexusModel`, `ErrorBody` (`error.code`, `error.details[]`), e-invoicing `DocumentSubmitResponse`, `DocumentStatusEvent`, `Mandate`. Keep fields to what the spec's consumers need; do not transcribe the whole AvaTax swagger.
+2. `client.ts`:
+ - `export class AvalaraError extends Error { kind: "auth" | "validation" | "not_found" | "conflict" | "rate_limit" | "transient"; status?: number; avalaraCode?: string; retryable: boolean; details?: unknown }` + `toAvalaraError(status, body)` mapper per the spec's taxonomy table (409 and committed-document conflicts → `conflict`).
+ - Base-URL maps: `AVATAX_BASE = { sandbox: "https://sandbox-rest.avatax.com", production: "https://rest.avatax.com" }`; `EINVOICING_BASE = { sandbox: "https://api.sbx.avalara.com/einvoicing", production: "https://api.avalara.com/einvoicing" }`.
+ - `AvalaraHttp` core: constructor takes `{ environment, accountId, licenseKey }`; `request<T>(surface: "avatax" | "einvoicing", method, path, { body?, timeoutMs?, retryable? })` → `{ data: T | null, error: AvalaraError | null }`. Basic auth header for avatax; `X-Avalara-Client: Carbon; 1.0; REST; v2; carbon` on avatax calls; `avalara-version` header on einvoicing calls; `AbortSignal.timeout(timeoutMs ?? 10_000)`.
+ - Retry loop: max 2 retries with exponential backoff + jitter on `rate_limit` (honor `Retry-After` seconds) and `transient`, only when the call is marked `retryable` (default true for GET, false for POSTs unless the method opts in). Do NOT reuse `accounting/core/utils.ts`'s `HTTPClient` (no retry/timeout; throws `RatelimitError` for Inngest semantics we don't want here) — but keep the same `{ data, error }` return philosophy.
+
+**Verification:** `pnpm --filter @carbon/ee typecheck`
+
+---
+
+## Task 4: AvaTax surface
+
+**Files:**
+- Create: `packages/ee/src/avalara/lib/avatax.ts`
+- Create: `packages/ee/src/avalara/index.ts` (barrel: client, surfaces, types, schema type)
+- Modify: `packages/ee/package.json` (exports: `"./avalara": "./src/avalara/index.ts"`)
+
+**Steps:**
+
+1. `AvataxApi` (constructed with an `AvalaraHttp` + `companyCode`):
+ - `ping()` → `GET /api/v2/utilities/ping`; returns `{ authenticated: boolean, version }` — treat `authenticated: false` as `AvalaraError(kind: "auth")`.
+ - `listCompanies()` → `GET /api/v2/companies?$top=200`; `getCompanyByCode(code)` → same with `$filter=companyCode eq '<escaped>'`, returns the single match or `not_found`.
+ - `createTransaction(model)` → `POST /api/v2/transactions/create` (30s timeout; `retryable: false` when `model.commit === true` — document the caller idempotent-`code` contract from the tax spec in the JSDoc).
+ - `commitTransaction(transactionCode)` → `POST /api/v2/companies/{companyCode}/transactions/{transactionCode}/commit` body `{ commit: true }`.
+ - `voidTransaction(transactionCode, reason = "DocVoided")` → `POST .../void` body `{ code: reason }`.
+ - `resolveAddress(address)` → `POST /api/v2/addresses/resolve`.
+ - `listNexus(avalaraCompanyId)` → `GET /api/v2/companies/{avalaraCompanyId}/nexus`.
+2. Verify each path/verb against the current AvaTax REST v2 docs (developer.avalara.com) before finalizing — record any corrections in the spec changelog.
+
+**Verification:** `pnpm --filter @carbon/ee typecheck`
+
+---
+
+## Task 5: E-invoicing surface (OQ-gated auth)
+
+**Files:**
+- Create: `packages/ee/src/avalara/lib/einvoicing.ts`
+
+**Steps:**
+
+1. FIRST: resolve the spec's open question against current Avalara e-invoicing (ELR) API docs: auth mechanism (Avalara Identity OAuth2 client-credentials vs license key) and current `avalara-version` value. If OAuth2 is confirmed: pause, get Brad's approval to add `AVALARA_CLIENT_ID`/`AVALARA_CLIENT_SECRET` (extends Task 1), implement a token-caching `AuthStrategy` in `client.ts`; tick the spec checkbox with the resolution.
+2. `EinvoicingApi`: `submitDocument(payload, meta)` → `POST /documents`; `getDocumentStatus(documentId)` → `GET /documents/{id}/status`; `listDocuments(query)`; `listMandates()` → `GET /mandates`. Verify exact paths in the same docs pass.
+3. If the OQ answer is delayed, ship the method contract with a `not_configured` `AvalaraError` when e-invoicing creds are absent so the e-invoicing spec (`.ai/specs/2026-07-04-e-invoicing.md`) can compile against the interface — do NOT block Tasks 6–11.
+
+**Verification:** `pnpm --filter @carbon/ee typecheck`
+
+---
+
+## Task 6: Hooks + consumer seam
+
+**Files:**
+- Create: `packages/ee/src/avalara/service.server.ts`
+- Create: `packages/ee/src/avalara/hooks.server.ts`
+- Modify: `packages/ee/src/hooks.server.ts` (register `avalara`)
+- Modify: `packages/ee/package.json` (exports: `"./avalara/hooks.server": "./src/avalara/hooks.server.ts"`)
+
+**Steps:**
+
+1. `service.server.ts` (spec §Consumer contract — the ONLY entry point #1044/#1054 use):
+ - `getAvalaraConfig(client, companyId)` — read `companyIntegration` row `id = 'avalara'`, parse metadata with `AvalaraSettingsSchema` (safeParse; parse failure → error), include `installed = active`.
+ - `getAvalaraClient(client, companyId)` — env creds present + installed + parsed config → `{ data: { avatax: AvataxApi, einvoicing: EinvoicingApi, config } }`; else descriptive error ("Avalara is not configured"/"not installed for this company").
+ - `isAvalaraFeatureEnabled(client, companyId, feature)` — false on any error path, never throws.
+2. `hooks.server.ts` (model: `packages/ee/src/xero/hooks.server.ts`, using `getCarbonServiceRole()`):
+ - `avalaraHealthcheck(companyId, metadata)`: parse metadata; build client from env + metadata directly (healthcheck receives metadata — don't re-read the row); `ping()` authenticated AND `getCompanyByCode(companyCode)` resolves → true; any error → false (log kind, never the key).
+ - `avalaraOnInstall(companyId)`: best-effort resolve `companyCode` → write `avalaraCompanyId` into `companyIntegration.metadata` (merge, don't clobber). No event-system subscriptions (spec decision).
+ - `avalaraOnUninstall(companyId)`: delete the Redis health key `integrations:{companyId}:avalara:health` if the redis client is importable here; otherwise no-op with comment (cache self-expires in 5 min).
+3. Register in `packages/ee/src/hooks.server.ts` `serverHooks` map: `avalara: { onHealthcheck, onInstall, onUninstall }`.
+
+**Verification:** `pnpm --filter @carbon/ee typecheck`
+
+**COMMIT CHECKPOINT 1:** `feat(ee): avalara integration foundation — client, registry entry, lifecycle hooks`
+
+---
+
+## Task 7: Seed migration
+
+**Files:**
+- Create via `pnpm db:migrate:new avalara-integration` → `packages/database/supabase/migrations/<ts>_avalara-integration.sql`
+
+**Steps:**
+
+1. Contents (Jira precedent `20260215000000_add_jira_integration.sql`, plus idempotency guard):
+
+```sql
+INSERT INTO "integration" ("id", "jsonschema")
+VALUES ('avalara', '{"type": "object", "properties": {}}'::json)
+ON CONFLICT ("id") DO NOTHING;
+```
+
+2. Confirm `integration.id` is the PK/unique target (read `20240119095150_integrations.sql`); adjust the conflict target if needed.
+3. Apply only when the local stack is up: `pnpm db:migrate`. No type regeneration expected; `git status` must show no `packages/database/src/types.ts` diff.
+
+**Verification:** `psql ... -c "SELECT id FROM \"integration\" WHERE id = 'avalara'"` returns one row; re-running the migration file is a no-op.
+
+---
+
+## Task 8: API routes + dynamic company options
+
+**Files:**
+- Create: `apps/erp/app/routes/api+/integrations.avalara.test.ts`
+- Create: `apps/erp/app/routes/api+/integrations.avalara.companies.ts`
+- Modify: `apps/erp/app/modules/settings/settings.server.ts` (dynamic options wiring)
+
+**Steps:**
+
+1. `integrations.avalara.test.ts` — action, `requirePermissions(request, { update: "settings" })`: `getAvalaraClient` → `ping()` + `getCompanyByCode()` uncached; flash success `Connected to Avalara — company "<name>" (<environment>)` or the taxonomy-mapped failure (`auth` → "Invalid Avalara credentials", `not_found` → "Company code not found", `transient` → "Avalara unreachable"); redirect back to `path.to.integration("avalara")` (check the exact path helper used by the Xero backfill route and mirror it).
+2. `integrations.avalara.companies.ts` — loader, same permissions: `listCompanies()` → `[{ value: companyCode, label: name }]`.
+3. In `settings.server.ts`, where the Xero integration branch populates dynamic `listOptions` (the `dynamicOptions` path feeding `integrations.$id.tsx`), add the `avalara` branch: when env creds present, populate `companyCode` options from `listCompanies()`; on error leave options empty (field degrades to free entry only if the renderer supports it — otherwise show empty list; do not crash the page).
+4. Grep `path.to` for how existing `api+/integrations.*` endpoints are referenced from config `actions` (Xero's is the literal string `/api/integrations/xero/backfill`) — keep the literal-string convention.
+
+**Verification:** `pnpm --filter @carbon/erp typecheck`
+
+---
+
+## Task 9: Tests — unit + sandbox smoke
+
+**Files:**
+- Create: `packages/ee/src/avalara/lib/client.test.ts`
+- Create: `packages/ee/src/avalara/lib/avatax.test.ts`
+
+**Steps:**
+
+1. Check how existing `@carbon/ee` vitest suites stub `fetch` (grep `vi.stubGlobal("fetch"` / `msw` under `packages/ee`); follow that pattern.
+2. `client.test.ts`: Basic auth + `X-Avalara-Client` headers present; 429 with `Retry-After: 1` retried then succeeds; 400 with AvaTax `error.details[]` → `kind: "validation"`, no retry, details preserved; 503×3 → `kind: "transient"` after max retries; abort at timeout budget → `transient`; POST with `retryable: false` never retried.
+3. `avatax.test.ts` (mocked): `createTransaction(SalesOrder)` sends `type/companyCode/commit:false` and parses `totalTax` + `details[]`; `createTransaction(..., commit: true)` is marked non-retryable; `voidTransaction` hits the companies-scoped path; `getCompanyByCode` escapes quotes in the `$filter`.
+4. Sandbox smoke (spec AC): a `describe.skipIf(!process.env.AVALARA_SANDBOX_SMOKE)` block running live sandbox `ping` + `createTransaction(SalesOrder)` + `resolveAddress` — never runs in CI without the flag; document the flag in the test header.
+
+**Verification:** `pnpm --filter @carbon/ee test` — all pass (smoke skipped).
+
+**COMMIT CHECKPOINT 2:** `feat(erp): avalara settings wiring — seed row, test-connection, dynamic company codes, tests`
+
+---
+
+## Task 10: Docs + rules
+
+**Files:**
+- Create: `.ai/rules/avalara-integration.md` (frontmatter `paths: ["packages/ee/src/avalara/**", "apps/erp/app/routes/api+/integrations.avalara.*"]`)
+- Modify: `packages/ee/AGENTS.md` (exports list + key patterns)
+- Modify: `AGENTS.md` (Task Router → Integrations: `Avalara (tax + e-invoicing substrate)` row)
+
+**Steps:**
+
+1. Rule file: package layout, consumer contract (`getAvalaraClient`/`isAvalaraFeatureEnabled` — consumers never read `companyIntegration` directly), error taxonomy table, env vars, sandbox/production switching, the commit-idempotency contract, pointers to the three specs (#1044 tax Phase 3, #1054 e-invoicing, this foundation).
+2. `packages/ee/AGENTS.md`: add `./avalara` + `./avalara/hooks.server` to Exports; note "Avalara is NOT an accounting-sync provider — no syncers, no `externalIntegrationMapping`".
+
+---
+
+## Task 11: Validation + gated browser verification
+
+**Steps:**
+
+1. ```bash
+ pnpm --filter @carbon/ee typecheck
+ pnpm --filter @carbon/erp typecheck
+ pnpm --filter @carbon/env typecheck
+ pnpm --filter @carbon/ee test
+ pnpm run lint
+ # Expected: all pass
+ ```
+2. Browser verify (requires user go-ahead, stack up, sandbox env vars set; `/auth` + `/test` skills):
+ - Env unset → no Avalara card in `/x/settings/integrations`; env set → card under Tax & Compliance.
+ - Install flow: company-code dropdown lists sandbox companies; save persists metadata (inspect row — NO secrets); health badge goes green; Test Connection flashes company + environment.
+ - Break the license key in env → healthcheck red + Test Connection shows the `auth` message.
+ - Toggle `taxDetermination` on and confirm via a scratch loader/console that `isAvalaraFeatureEnabled` flips.
+ - Screenshot the card + Test Connection result for the PR.
+3. Update the spec: tick acceptance criteria as verified; changelog entry; resolve/annotate the e-invoicing-auth open question with the Task 5 outcome.
+
+**COMMIT CHECKPOINT 3:** `docs(ai): avalara integration rule + agents updates` — PR references `Tracking spec: .ai/specs/2026-07-04-avalara-integration-foundation.md` + `Closes crbnos/carbon#1061`.
+
+## Deferred (explicit non-goals, per spec)
+
+- AvaTax determination connector (#1044 Phase 3: `AvalaraTaxEngine`, `resolveLineTaxes` dispatch, `taxLedger` mapping, outage fallback/reconcile job, nexus-drift UI).
+- E-invoicing flows (#1054: document building, submission orchestration, status jobs, mandate UX).
+- Per-company secret storage (Vault/AES-GCM) — nothing secret per company in v1; Plaid precedent reserved.
+- Custom Avalara logo/design pass; category grouping polish if "Tax & Compliance" renders oddly in the integrations list.
diff --git a/.ai/research/bank-reconciliation.md b/.ai/research/bank-reconciliation.md
new file mode 100644
index 0000000000..50f7938e2d
--- /dev/null
+++ b/.ai/research/bank-reconciliation.md
@@ -0,0 +1,109 @@
+# Bank Reconciliation — Research Notes
+
+> Date: 2026-07-02 · Feeds spec: `.ai/specs/2026-07-02-bank-reconciliation.md`
+
+## Part 1 — Carbon codebase findings
+
+### GL accounts & the bank-account gap
+
+- `account` table (20230330024715_accounts.sql): `id` (xid), `number`, `name`, `class` (Asset/…), `incomeBalance`, `accountType` TEXT — bank accounts are `accountType = 'Bank'` (also `'Cash'`), scoped by `companyGroupId` (accounts are group-shared, not per-company).
+- All modern FK references use `account.id`, never `account.number` (ar-ap-payments migration backfilled legacy number refs).
+- **There is no bank-account master entity** — no bank name, masked account number, per-account currency, or feed linkage. `payment.bankAccount` (TEXT NOT NULL → `account.id`) points straight at the GL account.
+- `accountDefault` (PK = companyId) has `bankCashAccount`, `bankLocalCurrencyAccount`, `bankForeignCurrencyAccount` defaults, plus (new in ar-ap-payments) `realizedExchangeGainAccount` / `realizedExchangeLossAccount`, `customerWriteOffAccount` / `supplierWriteOffAccount` — all → `account.id`.
+
+### AR/AP payments (20260630093809_ar-ap-payments.sql — shipped 2 days ago)
+
+- `payment`: `id` xid, `paymentId` readable (`PAY-%{yyyy}-%{mm}-`, size 6, via `getNextSequence(client, "payment", companyId)`), `paymentType` enum Receipt|Disbursement, `status` Draft|Posted|Voided, exactly-one customerId/supplierId (CHECK), `paymentDate`, `postingDate`, `currencyCode`, `exchangeRate`, `totalAmount >= 0`, `bankAccount` → account.id, `reference`, `memo`, `journalId`, posted/voided audit cols, `companyId`, `customFields`. RLS uses `invoicing_*` permissions.
+- `memo`: credit/debit memos, same lifecycle shape.
+- `invoiceSettlement`: funding source (paymentId XOR memoId) × target (salesInvoice/purchaseInvoice/memo), `appliedAmount`/`discountAmount`/`writeOffAmount`, `sourceExchangeRate`/`targetExchangeRate`, generated `fxGainLossAmount`, `appliedViaPaymentId`.
+- **Posting is base-currency**: `post-payment` edge fn computes `paymentTotalBase = totalAmount * exchangeRate` and inserts `journalLine` rows in base currency (`build-payment-journal.ts`). Voiding posts mirror lines (`amount: -line.amount`) — never deletes.
+
+### Journal structure
+
+- `journal`: `id` = `id('je')`, `journalEntryId` readable (`JE-%{yyyy}-%{mm}-`), `description`, `postingDate`, `status` Draft|Posted|Reversed, `sourceType` enum (Manual, Purchase Receipt/Invoice, Sales Invoice/Shipment, Inventory Adjustment, Payment, Credit Memo, Debit Memo, …), `accountingPeriodId`, `reversalOfId`/`reversedById`, posted audit cols, `companyId`.
+- `journalLine`: `id` xid, `journalId` (CASCADE), `accountId` → account.id, `description`, `amount` **class-signed natural balance** (Asset: positive = debit = cash inflow), `journalLineReference` (uuid), `companyId`, `companyGroupId`. No date on the line — join `journal.postingDate`.
+- `journalLineDimension` for analytics tags.
+- `postJournalEntry(client, id, userId)` validates Draft + balanced then flips to Posted. `reverseJournalEntry` creates a mirror entry.
+- GL lines are stored **in base currency**; multi-currency documents carry `exchangeRate` and post translated amounts. `exchangeRateHistory` table exists ((currencyCode, effectiveDate, companyGroupId) unique).
+
+### Accounting module layout
+
+- One service file: `apps/erp/app/modules/accounting/accounting.service.ts` (~2.5k lines) — bank rec functions must go here (feedback memory: never scatter service/models files). Models → `accounting.models.ts`; heavy Kysely transactions → `accounting.server.ts` (precedent: `postDepreciationRun`).
+- Routes: `apps/erp/app/routes/x+/accounting+/` — list pages (`journals.tsx`, `charts.tsx`, `fixed-assets.tsx`), drawer child routes (`charts.$accountId.tsx`, `journals.new.tsx`) per Drawer-overlay convention.
+- Sidebar: `ui/useAccountingSubmodules.tsx` groups — Reports / General Ledger / Fixed Assets / Configure; gated by `accountingEnabled` setting + `accounting_view`.
+- Periods: `accountingPeriod` with `closedAt`/`closedBy`; `getOrCreateAccountingPeriod(client, companyId, date)` is the posting gate. **Period-closing spec in flight** (2026-07-02) adds `closeStatus` Open|Locked|Closed + close-readiness checklist — bank rec should integrate (readiness warning + reconciliation vs locked periods).
+
+### Integration framework (Xero = precedent)
+
+- Registry: `packages/ee/src/index.ts` `integrations` array; per-integration `packages/ee/src/{id}/config.tsx` (+ `hooks.server.ts` registered in `packages/ee/src/hooks.server.ts` — onInstall/onUninstall/onHealthcheck).
+- `companyIntegration` table: PK (`id`, `companyId`), `metadata` JSON (stores OAuth tokens **plaintext JSONB** — Xero access/refresh tokens live here), `active`. One row per integration per company.
+- `externalIntegrationMapping`: (`entityType`, `entityId`, `integration`, `externalId`, `companyId`) with unique constraints — used for idempotent CSV + Xero sync.
+- OAuth flow: `apps/erp/app/routes/api+/integrations.xero.install.ts` (redirect out) + `integrations.xero.oauth.ts` (callback, token exchange, upsert metadata, onInstall hook).
+- Webhooks: `apps/erp/app/routes/api+/webhook.xero.ts` — HMAC verify against raw body, map tenant → company, fire Inngest event. Env secrets in `packages/env/src/index.ts` via `getEnv(...)`.
+- Inngest: `packages/jobs/src/inngest/functions/integrations/…`; event names `carbon/<task-id>`; app code calls `trigger("task-id", payload)` mapped in `packages/lib/src/trigger.ts` + typed in `packages/lib/src/events.ts`.
+
+### CSV import pipeline (precedent for statement upload)
+
+- Client: `apps/erp/app/components/ImportCSVModal/` — react-dropzone + PapaParse preview → upload to `private` bucket at `${companyId}/imports/${nanoid()}.csv` → FieldMappings UI (column → field, enum mappings) → POST `x+/shared+/import.$tableId.tsx`.
+- Mappings/permissions/schemas: `apps/erp/app/modules/shared/imports.models.ts` (`fieldMappings`, `importPermissions`, `importSchemas`).
+- Edge fn `import-csv`: downloads from bucket, parses (Deno std csv), classifies rows insert/update/skip, transaction-wrapped writes, idempotency via `externalIntegrationMapping` (`integration = "csv"`).
+- Storage: `private` bucket, path convention `${companyId}/…`.
+
+### Plaid status
+
+- Zero Plaid references in repo; no fintech SDKs in any package.json. `PLAID_CLIENT_ID`/`PLAID_SECRET` would follow the `packages/env` `getEnv` pattern (optional → integration hides itself when unset, like Xero).
+
+## Part 2 — Industry research (SAP, NetSuite, Xero/QBO, Plaid, audit practice)
+
+Method: deep-research workflow (fan-out search → fetch → 3-vote adversarial verification). 16 claims survived verification before the session usage limit killed the Xero/Plaid verification passes and synthesis; the "verified" subsection below cites sources, the "model knowledge" subsection is unverified-but-stable public-documentation knowledge, labeled as such.
+
+### Verified claims (adversarially checked, cited)
+
+**SAP Electronic Bank Statement (EBS)** — [help.sap.com](https://help.sap.com/docs/SUPPORT_CONTENT/fiaccounting/3361881808.html)
+- Supported statement formats: SWIFT MT940, MultiCash, BAI, XML; import requires a format code (M = MultiCash, S = MT940, X = XML).
+- ISO 20022 camt mapping: camt.052 = intraday (MT942), **camt.053 = end-of-day statement (MT940 equivalent)**, camt.054 = debit/credit notification (MT900/910). Custom/bank-specific XML needs per-format XSL transformation or BAdI `FIEB_MAPPING_X`.
+- FF.5 (RFEBKA00) imports a single file per run; multi-file needs FEB_FILE_HANDLING (app-server only).
+- Posting configuration is a fixed chain: account symbols → assign G/L accounts → posting-rule keys → posting rules → transaction types → **assign external transaction codes (bank-provided) to posting rules** → assign bank accounts to transaction types. I.e., SAP's "rules engine" is code-driven: the bank's transaction-type code on each statement line selects the posting rule.
+
+**NetSuite** — [docs.oracle.com NetSuite help](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1551275.html), [chapter_4842302228](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_4842302228.html), [section_159010939426](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_159010939426.html)
+- Intelligent Transaction Matching auto-runs **at bank-data import time** (plus manual re-run); matches imported bank lines against account (GL) transactions; manual matching is for exceptions.
+- Two rule tiers: immutable **System Rules** + ordered, user-editable **User Rules**, subdivided into Matching Rules and Auto-Create Rules.
+- Auto-Create Rules (2020.2+) create-and-match transactions from unmatched bank lines — limited to deposits/charges for bank accounts (charges/refunds for credit-card accounts).
+- **Ambiguity refusal**: if a rule finds ≥2 candidate matches for one bank line, NetSuite makes no match; user picks manually.
+- Two-stage flow: **Match Bank Data** page (side-by-side grids; actions: match, mark cleared, exclude, review, submit) → **Reconcile Account Statement** page (operates only on submitted/cleared items; include/exclude → reconcile). Status progression: matched/user-cleared → submitted/cleared → reconciled.
+- Bank feeds via aggregators (Salt Edge named for Europe; US/Canada partner unnamed in docs). File import supports **CAMT.053, MT940, BAI2, OFX/QFX**, manual or automated via SFTP.
+- **Hard 1:1 currency constraint**: bank-feed import fails outright if the GL account currency ≠ connected bank account currency (no conversion).
+
+**Xero** — [central.xero.com](https://central.xero.com/s/article/Bank-reconciliation-in-Xero)
+- Reconciliation UX is a two-sided screen: imported bank statement lines on the left, Xero account transactions on the right; reconciling = pairing them.
+
+### Model knowledge (NOT adversarially verified — usage limit killed these passes; from stable public docs)
+
+**Xero / QuickBooks Online UX (usability benchmark)**
+- Xero statement lines are first-class, immutable rows; per line the user can **Match** (to existing transactions, incl. Find & Match for one-to-many), **Create** (code directly to an account, optionally via bank rules), or **Transfer** (to another bank account). Minor difference between a match and the line can be booked inline as a bank-fee/minor adjustment.
+- Xero bank rules: condition set (payee/description/amount contains-equals) → coding template (account, tax, contact); applied as suggestions on feed lines.
+- QBO: "For Review / Categorized / Excluded" tabs; monthly Reconcile module requires statement ending date + ending balance and blocks completion until difference = $0; "undo reconciliation" restricted (accountant role).
+- Both produce a reconciliation report: statement balance vs book balance, with outstanding (uncleared) payments and deposits listed — the artifact auditors request.
+
+**Plaid** ([plaid.com/docs](https://plaid.com/docs/))
+- Flow: server `POST /link/token/create` (products `["transactions"]`, webhook URL) → client opens Link widget → `onSuccess(public_token, metadata.accounts)` → server `POST /item/public_token/exchange` → `access_token` + `item_id`. One **Item** per institution login; an Item contains N accounts (`account_id`s).
+- `/transactions/sync` is the modern cursor model (replaces `/transactions/get`): returns `added` / `modified` / `removed` arrays + `next_cursor` + `has_more`; loop until `has_more=false`; persist cursor per Item.
+- Webhooks: `SYNC_UPDATES_AVAILABLE` (fire a sync), `INITIAL_UPDATE`/`HISTORICAL_UPDATE` (legacy-model progress signals), `TRANSACTIONS_REMOVED` (legacy removal). Item webhooks: `ERROR` with `ITEM_LOGIN_REQUIRED` → re-auth via Link **update mode** (link_token created with the access_token). Webhook authenticity via JWT in `Plaid-Verification` header (`/webhook_verification_key/get`).
+- **Sign convention: Plaid `amount` is positive for money LEAVING the account** (outflow) — must invert for a positive-=-inflow model.
+- Pending → posted: pending transactions arrive with `pending: true`; the posted version arrives as a new transaction carrying `pending_transaction_id`, and the pending one appears in `removed`.
+- `transaction_id` is unique per Item — safe dedupe key. Sandbox: `user_good`/`pass_good`, `/sandbox/item/fire_webhook`. Pricing: subscription per connected Item/account per month for Transactions (order ~$0.30/connected account/mo at scale; production access requires Plaid approval).
+
+**Accounting practice / audit**
+- The audit artifact is the **statement-based reconciliation report**: statement ending balance + deposits in transit − outstanding checks = adjusted bank balance ≟ GL book balance; bank-only items (fees, interest, NSF) are posted as adjusting entries *before* completing.
+- Continuous matching (feeds) and periodic statement tie-out are complementary: match continuously, close out per statement. Un-reconciliation should be restricted (latest-first) and audited. Reconciliation adjustments must respect period locks (post through the normal journal gates).
+- Segregation of duties: ideally the reconciler is not the person who records cash transactions; at minimum the completed reconciliation records who completed it and when.
+
+### Design takeaways for Carbon
+
+1. Separate **bank account master** from the GL account (SAP house bank / NetSuite financial-institution connection), 1:1 with a GL account.
+2. Statement lines are **immutable imported rows** with a provider-stable external ID for idempotent re-import (OFX FITID / Plaid transaction_id / content hash for CSV).
+3. Match at the **GL (journal line) level**, not the document level — everything that touches the bank GL account is matchable regardless of source (SAP posting area 1, NetSuite "account transactions").
+4. Auto-match must be conservative: exact amount + date window + **exactly one candidate** (NetSuite ambiguity refusal); suggestions for the rest.
+5. Two-stage lifecycle: continuous matching + statement-based close-out with ending-balance tie-out (NetSuite Match → Reconcile; QBO difference-must-be-zero).
+6. Mirror NetSuite's hard currency constraint in v1: bank account currency must equal company base currency (Carbon posts GL in base currency only; journalLine has no source-currency amount).
+7. Plaid: store per-Item access tokens + sync cursors in `companyIntegration.metadata` (Xero precedent); webhook-triggered incremental sync + scheduled catch-up; invert amount sign at ingest; keep pending lines out of matching.
diff --git a/.ai/research/budgeting.md b/.ai/research/budgeting.md
new file mode 100644
index 0000000000..8124396700
--- /dev/null
+++ b/.ai/research/budgeting.md
@@ -0,0 +1,322 @@
+# Budgeting in Top ERPs — Research Notes
+
+Research date: 2026-07-02. Focus: how leading ERPs model GL budgets, cost-center
+budgeting, budget versions/scenarios, entry/seeding workflows, and budget-vs-actual
+reporting — with a synthesis for Carbon. Surveyed: SAP (canonical reference),
+NetSuite (accounting-domain competitor), and Microsoft Dynamics 365 Business
+Central (Carbon's accounting module follows BC/NAV patterns: posting groups,
+accounting periods, dimension model).
+
+---
+
+## 1. SAP (ECC CO + S/4HANA)
+
+### Cost center accounting (CO-OM-CCA)
+
+- A **cost center** is an org unit where costs are incurred but revenue is not
+ normally measured (department, team, machine group, service function). Master
+ data: validity dates, category, person responsible, company code, profit
+ center. ([SAP Help — CO-OM-CCA](https://help.sap.com/docs/SUPPORT_CONTENT/ficontrolling/3361881795.html))
+- A mandatory **standard hierarchy** contains every cost center exactly once;
+ unlimited **alternative groups** for reporting/allocations.
+ ([SAP Help — Cost Centers and the Standard Hierarchy](https://help.sap.com/docs/SUPPORT_CONTENT/ficontrolling/3361878477.html))
+- **Cost elements** are the GL link: every FI posting to an expense account
+ carries both the GL account and a CO object (cost center, order). In S/4HANA
+ the cost element and GL account are literally merged into one field in the
+ Universal Journal (ACDOCA). ([SAP Press](https://blog.sap-press.com/primary-and-secondary-costs-in-sap-s4hana))
+
+### Plan vs budget — SAP draws a hard line
+
+- **Planning** (KP06) = granular estimate by **version + fiscal year + period +
+ cost center + cost element**, used only for variance reporting. Nothing blocks
+ overspend ("passive" control).
+- **Budgeting** = the approved, binding figure, entered coarsely (per object,
+ classically not per cost element), optionally driving **active availability
+ control** (warnings → email → hard error at tolerance thresholds like 90%/100%).
+- Classic ECC only enforced budgets on internal orders/WBS elements; real cost
+ center budget enforcement arrived in S/4HANA 1909 and is still annual-only,
+ per cost center + GL account group.
+ ([ERPCorp — planning vs budgeting](https://erpcorp.com/sap-controlling-blog/sap-planning/what-is-the-difference-between-planning-and-budgeting-in-sap-controlling),
+ [SAP Community — Cost Center Budget Availability Control](https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/cost-center-budget-availability-control/ba-p/13752625))
+
+### Versions / scenarios
+
+- **Version 0** holds the plan of record *and* actuals; plan/actual comparison
+ always runs inside version 0. Extra versions (1, 2, …) are plan-only what-ifs.
+- S/4HANA replaces versions with **plan categories** in table **ACDOCP** (`PLN`,
+ `BUDGET01`, `BUDGET02`…) — a single plan-data table parallel to the actuals
+ table. ([SAP Learning](https://learning.sap.com/courses/cost-center-and-internal-order-accounting-in-sap-s-4hana/planning-on-cost-centers-and-internal-orders))
+
+### Entry & seeding workflows
+
+- **Distribution keys** spread an annual amount across periods: equal split, by
+ calendar days, percentage progression, proportional to activity, custom.
+ ([SAP Help — Distribution Key](https://help.sap.com/doc/baf2cc53a8b77214e10000000a174cb4/3.6/en-US/f9e8cc53a8b77214e10000000a174cb4.html))
+- **KP97** copy plan→plan, **KP98** copy actuals→plan, then revalue by ±% —
+ "next year = last year + 3%" is a first-class operation. Excel upload is
+ ubiquitous in practice.
+
+### Commitments (second tier)
+
+Purchase requisitions/POs account-assigned to a cost center create
+**commitments**; assigned value = actuals + commitments; available = budget −
+assigned. Commitments reverse as goods receipts/invoices post actuals.
+([SAP Community — Cost Center Commitments](https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/cost-center-commitments-in-sap-s-4hana-cloud/ba-p/13495753))
+
+### Reporting
+
+Canonical daily-use report **S_ALR_87013611 "Cost Centers: Actual/Plan/Variance"**:
+rows = cost elements (grouped), columns = actual, plan, variance, variance %, for
+a cost center (group) × fiscal year × period range × version. Variants add
+commitments, quarterly and prior-year comparisons.
+([Econvera guide](https://econvera.org/2025/09/24/sap-s_alr_87013611-cost-centers-actual-plan-variance-report-a-comprehensive-guide/))
+
+### SAP essentials distilled
+
+Plan lines at **cost center × GL account × period × version**; hard split
+between advisory plan and binding budget; copy+revalue seeding; commitments as
+the purchasing bridge; variance reporting as the primary surface; blocking as an
+opt-in, profile-driven layer.
+
+---
+
+## 2. NetSuite
+
+### Data model
+
+- A **budget** covers one fiscal year and is keyed by a criteria tuple:
+ subsidiary, fiscal year, **budget category**, **account** (required), and
+ optional **department, class, location, customer/project, item** (+ custom
+ segments). Amounts stored **per accounting period** within the year.
+- Storage: `budgets` header (criteria tuple + year + total) +
+ `budgetsMachine` child rows `(budget, period, amount)` — one row per period.
+- **Uniqueness: one budget per {criteria tuple + category + fiscal year}.**
+ CSV import upserts against this key and overwrites the matched record
+ wholesale. Amounts are entered as **positive numbers** for both income and
+ expense.
+ ([Setting Up a Budget](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1503407.html),
+ [SuiteQL Budgets — Tim Dietrich](https://timdietrich.me/blog/netsuite-suiteql-budgets/),
+ [Budgets Machine schema](https://www.netsuitediagnostics.com/posts/budgets-machine/))
+
+### Budget categories = scenarios
+
+The **Multiple Budgets** feature adds named categories ("Original", "Revised",
+"Forecast"); reports pick which category to compare against. Consultant practice:
+keep Original immutable once approved, reforecast in a separate category
+quarterly/monthly. In OneWorld each category is **Global** (root parent currency)
+or **Local** (per-subsidiary currency), with a dedicated **Budget Exchange
+Rates** table for consolidation at plan rates.
+([Multiple Budgets and Budget Categories](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1506174.html),
+[Subsidiary Budgets](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1506361.html))
+
+### Entry mechanisms
+
+1. **Manual grid** (accounts × 12 periods) with **Fill** (copy first period to
+ all) and **Distribute** (divide first period evenly across periods).
+2. **CSV import** (dedicated 2-page assistant; account + year + category +
+ segments + one column per period).
+3. **Copy Budgets**: from prior budget or **from actuals**, with ±% modifier,
+ "Keep Detail" (retain or collapse dimension detail), and Replace toggle.
+4. **NSPB** (separately licensed Oracle EPM product) for driver-based planning,
+ approvals, rolling forecasts — writes back into native budget categories.
+([Importing a Budget](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1505717.html),
+[Copying a Budget](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1505228.html))
+
+### Reporting
+
+**Budget vs. Actual** report = four columns: Amount (actual), Budget Amount,
+Amount Over Budget, % of Budget — with a budget category selector and column
+expansion by period/class/department/location/subsidiary. Budgets with a
+dimension populated line up against actuals carrying the same dimension;
+company-level (blank-dimension) budget rows are NOT apportioned down.
+Gotcha: the "Report by Period" user preference must be enabled or budget
+columns render zero.
+([Budget vs. Actual Report](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2097218.html))
+
+### Enforcement
+
+**Native budgets are reporting-only** ("budgets provide information for reports
+but do not control income and expense"). Enforcement comes from the free
+**Expense Commitments & Budget Validation** SuiteApp: Budget Control records
+with **Warn Only** or **Prevent Save** actions on requisitions/POs/bills,
+threshold warnings (e.g. 90%), consumed = actuals + open commitments.
+([Creating a Budget Control Record](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_161794703618.html))
+
+### Consultant best practices
+
+- Budget monthly even when planned annually; use Distribute/Fill then hand-adjust
+ seasonal accounts.
+- Granularity workhorse: **account × department, monthly**. Avoid
+ over-dimensioning (customer/item budgets explode row counts; revenue plans only).
+- Most real-world entry happens via CSV round-trip (export → Excel → import).
+- Restrict budget entry behind a dedicated permission; native budgets have no
+ approval workflow or change history (a driver for NSPB upsell).
+([Houseblend budgetary control](https://www.houseblend.io/articles/netsuite-budgetary-control-guide),
+[RSM — Using Budgets](https://technologyblog.rsmus.com/technologies/netsuite/using-budgets-in-netsuite/))
+
+---
+
+## 3. Microsoft Dynamics 365 Business Central (NAV heritage)
+
+### Data model — header + entry ledger
+
+- **G/L Budget Name (table 95)** — the header: `Name`, `Description`, `Blocked`
+ boolean, and **Budget Dimension 1–4 Code** (up to 4 budget-specific dimensions
+ chosen per budget). Multiple budgets per year = versions/revisions/forecasts.
+- **G/L Budget Entry (table 96)** — the line ledger: `Entry No.`, `Budget Name`,
+ `G/L Account No.`, **`Date`** (a plain date, not a period FK), signed
+ `Amount`, `Description`, Global Dimension 1–2 codes, Budget Dimension 1–4
+ codes, `Business Unit Code` (consolidation), `Dimension Set ID`, user/date audit.
+- Amounts aggregate on the fly by filtering entries (budget + account + date
+ range + dimension filters) and summing — cells in the matrix are sums of one
+ or more entries; drill-down opens the entry list.
+- Dimensions stored twice: flattened code columns (2 global + 4 budget) for fast
+ filtering, plus a normalized Dimension Set ID.
+([G/L Budget Name](https://learn.microsoft.com/en-us/dynamics365/business-central/application/base-application/table/microsoft.finance.generalledger.budget.g-l-budget-name),
+[G/L Budget Entry](https://learn.microsoft.com/en-us/dynamics365/business-central/application/base-application/table/microsoft.finance.generalledger.budget.g-l-budget-entry))
+
+### Entry UX — the budget matrix
+
+**Budget page**: matrix with configurable axes — Show as Lines / Show as Columns
+each pick from `G/L Account | Period | Business Unit | Global Dim 1/2 | Budget
+Dim 1–4`; View by Day/Week/Month/Quarter/Year/Accounting Period; rounding factor;
+filters per dimension + account category + income/balance. Editing a cell writes
+G/L Budget Entries through a buffer. **Excel export → edit → import (Add or
+Replace modes)** is a first-class workflow Microsoft explicitly recommends for
+distributing budget entry to department owners.
+([Create Budgets](https://learn.microsoft.com/en-us/dynamics365/business-central/finance-how-create-budgets))
+
+### Copy G/L Budget (report 96)
+
+Source = **G/L Entry (actuals)** or **G/L Budget Entry** (another budget), with:
+**Adjustment Factor** (e.g. 1.1 = +10%), **Rounding Method**, **Date Change
+Formula** (`1Y` shifts last year's actuals into next year), **Date Compression**
+(compress day-level actuals to one entry per month), closing-entry filter.
+"Copy last year's actuals forward, +X%, rounded, shifted 1Y" is the heart of the
+annual cycle.
+([Copy G/L Budget](https://learn.microsoft.com/en-us/dynamics365/business-central/application/base-application/report/microsoft.finance.generalledger.budget.copy-g-l-budget))
+
+### Budget vs actual analysis
+
+1. **G/L Balance/Budget page** — per account: actual, budgeted, **Budget %**
+ column; View by period length; filters hit both actual and budget entries.
+2. **Trial Balance/Budget report** — net change/balance vs budget with % of
+ budget columns, dimension-filterable.
+3. **Financial reports (account schedules)** — column definitions with Ledger
+ Entry Type = Ledger Entries | **Budget Entries**, a **Budget Filter** (which
+ budget name feeds the budget columns), and formula columns for variance.
+ Shipped column layouts: `ACT/BUD`, `BUDGANALYS`, `CVC YTDBUD`.
+4. **Analysis views** with "Include Budgets" — pre-aggregated dimension cubes
+ comparing actual vs budget across any 4 dimensions.
+([Analyze Actual vs Budget](https://learn.microsoft.com/en-us/dynamics365/business-central/bi-how-analyze-actual-versus-budget),
+[Column definitions](https://learn.microsoft.com/en-us/dynamics365/business-central/bi-column-definitions))
+
+### Cost Accounting module (parallel subledger, NAV 2013+)
+
+A GL-fed managerial ledger: **cost types** (≈ P&L accounts), **cost centers**
+("where") and **cost objects** ("who/what") seeded from designated dimensions;
+GL entries carrying those dimensions transfer to cost entries automatically;
+**cost allocations** (static ratios or dynamic bases like headcount) cascade
+costs; **cost budgets** (`Cost Budget Entry`: cost type, date, amount, cost
+center, cost object) mirror GL budgets with per-cost-center matrix pages and
+GL↔CA budget copy jobs. Invariant: every cost entry has exactly one of cost
+center or cost object. Powerful but a distinct subsystem most SMB customers
+never enable.
+([About Cost Accounting](https://learn.microsoft.com/en-us/dynamics365/business-central/finance-about-cost-accounting),
+[Cost Budget Entry](https://learn.microsoft.com/en-us/dynamics365/business-central/application/base-application/table/microsoft.costaccounting.budget.cost-budget-entry))
+
+### Enforcement & period interaction — verified
+
+- **Standard BC has no budget enforcement** — no checks on purchase documents,
+ no encumbrance. Budget control is a Dynamics 365 Finance (different product)
+ feature; in BC it's ISV/AppSource territory.
+- Budget entries are plain dates with **no FK to accounting periods**; periods
+ matter only as a reporting interval. Closing a fiscal year does **not** lock
+ budgets. Practical rule: date budget entries on period start dates.
+([Budget control = D365 Finance](https://learn.microsoft.com/en-us/dynamics365/finance/budgeting/budget-control-overview-configuration),
+[Accounting periods](https://learn.microsoft.com/en-us/dynamics365/business-central/finance-accounting-periods-and-fiscal-years))
+
+---
+
+## 4. Key Consensus Patterns
+
+### 1. The budget line is account × period × dimension(s), grouped under a named budget
+- **SAP**: version + fiscal year + period + cost center + cost element.
+- **NetSuite**: category + fiscal year + account + dept/class/location, child
+ rows per period.
+- **BC**: budget name + account + date + dimension codes.
+- **Rationale**: monthly granularity at account × org-unit is the reporting
+ workhorse everywhere; anything finer (customer/item) is for revenue plans only.
+
+### 2. Multiple named budgets per fiscal year (versions/scenarios)
+- SAP versions/plan categories; NetSuite budget categories (Original/Revised/
+ Forecast); BC budget names. Keep the original immutable once approved;
+ reforecast in a new version. No approval workflow in any base product.
+
+### 3. Budgets are reporting-only by default; enforcement is opt-in
+- SAP: passive plan checks by default, active availability control is opt-in
+ config (and cost-center AVC only arrived in 2019, annual-only).
+- NetSuite: native budgets never block; SuiteApp adds warn/block on purchasing.
+- BC: no enforcement at all in the base product.
+- **Rationale**: hard blocks frustrate operations; warn-at-threshold on
+ purchasing documents is the common middle ground when control is wanted.
+
+### 4. Copy/seed + spread are first-class operations
+- Copy prior budget or copy actuals, apply ±% adjustment factor (all three).
+- Spread annual amounts across periods: SAP distribution keys, NetSuite
+ Fill/Distribute, BC even entry. Equal-split is the baseline; fancier keys are
+ optional.
+
+### 5. Spreadsheet round-trip is the real entry path
+- All three treat Excel/CSV export → edit → import as the primary bulk-entry
+ mechanism; the in-app matrix is for refinement.
+
+### 6. Variance reporting is the daily-use surface
+- Columns: Actual, Budget, Variance (absolute), Variance % — by account rows,
+ filterable/pivotable by period and dimension, with a budget/version picker.
+- Dimension matching: budget rows tagged with a dimension compare against
+ actuals tagged the same; blank-dimension budgets are company-level and are
+ not apportioned.
+
+### 7. Budgets are decoupled from period close
+- BC explicitly: closing a year doesn't lock budgets; entries are dated, not
+ period-FK'd. NetSuite similar. Budgets are forward-looking planning data, not
+ books of record — they stay editable after close (new versions capture
+ reforecasts).
+
+---
+
+## 5. Recommended Approach for Carbon
+
+Carbon already has the hard parts: chart of accounts (`account`, hierarchical),
+first-class accounting periods (`accountingPeriod` gaining
+`fiscalYear`/`periodNumber` via the period-close spec), **cost centers**
+(`costCenter`, hierarchical), a generic dimension system
+(`dimension`/`dimensionValue` incl. entityType `CostCenter`), GL lines tagged via
+`journalLineDimension`, and reporting RPCs (`trialBalance`,
+`accountTreeBalancesByCompany`).
+
+1. **Follow the NetSuite/BC hybrid**: a `budget` header (name, fiscal year,
+ status) + `budgetLine` rows keyed by **account × accounting period × optional
+ cost center**, one row per cell (NetSuite-style buckets, not BC's additive
+ entry ledger — simpler, upsertable, fits a matrix UI). Multiple budgets per
+ fiscal year give versions/scenarios for free.
+2. **Cost center as the v1 dimension**, as a direct FK — matching SAP's primary
+ budgeting axis and BC cost accounting's hardwired cost center column. The
+ generic dimension system stays the actuals-side tagging mechanism; variance
+ reporting joins `journalLineDimension` through the CostCenter-type dimension.
+ Generic budget dimensions (BC's Budget Dimension 1–4) can come later without
+ schema upheaval.
+3. **Reporting-only in v1** — consensus default posture in all three ERPs.
+ Leave commitments/availability control as a clearly-marked future layer on
+ purchasing documents (warn at threshold, never hard-block by default).
+4. **Copy/seed as first-class services**: copy from prior budget and seed from
+ actuals, both with an adjustment factor — plus Fill/Distribute helpers in the
+ matrix UI.
+5. **Budget vs Actual report** modeled on NetSuite's four columns (Actual,
+ Budget, Variance, % of Budget) with period columns and a cost-center filter,
+ implemented as an RPC beside `trialBalance`.
+6. **Keep budgets decoupled from period close** (BC/NetSuite precedent), and
+ **CSV round-trip** via Carbon's existing csv-import/table-export infra.
+7. **Don't build**: approval workflows, driver-based planning, budget exchange
+ rates, allocations — that's the NSPB/EPM tier; revisit on demand.
diff --git a/.ai/research/financial-reporting.md b/.ai/research/financial-reporting.md
new file mode 100644
index 0000000000..4eba9a21ec
--- /dev/null
+++ b/.ai/research/financial-reporting.md
@@ -0,0 +1,412 @@
+# Financial Reporting Research: Best Practices Survey
+
+## Summary
+
+Surveyed how SAP S/4HANA, NetSuite, QuickBooks Online, and Xero implement the core
+financial statements package — income statement, balance sheet, trial balance, cash
+flow statement — plus the reporting mechanics around them: account-to-line mapping,
+retained earnings without a hard close, comparative columns, drill-down, and
+consolidated statements. Key findings: (1) every system maps accounts to statement
+lines through account type + hierarchy (SMB) or a dedicated layout object (SAP FSV,
+NetSuite layouts) — nobody hand-builds statements; (2) the modern consensus is **no
+closing entries** — Net Income and Retained Earnings are computed at report time
+(NetSuite reference rows, QBO/Xero virtual rollover; SAP is the outlier with posted
+balance carryforward, and even SAP also computes the current-year result on the fly);
+(3) automated cash flow statements are **indirect method**, derived from net income
+plus balance-sheet account deltas, classified into Operating/Investing/Financing by
+account type with a per-account override; (4) comparative reporting = relative period
+ranges per column plus formula (variance) columns, with balance-sheet accounts always
+cumulative and P&L accounts always periodic; (5) drill-down is a universal two-hop:
+statement amount → account transactions (GL detail) → journal entry. Carbon already
+has trial balance, balance sheet, income statement, and consolidation; the gaps this
+research informs are the cash flow statement, retained-earnings/current-year-earnings
+split, comparative columns, period-based reporting, drill-down, GL detail, and export.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA** — enterprise reference: FSV hierarchies, Universal Journal (ACDOCA)
+ live aggregation, trial balance semantics, balance carryforward, group reporting.
+- **NetSuite** — closest architectural peer: mid-market ERP, multi-subsidiary
+ consolidation with elimination subsidiaries and CTA (the model Carbon already
+ follows), Financial Report Builder, computed retained earnings.
+- **QuickBooks Online** — SMB baseline most Carbon customers migrate from; account
+ type drives everything; simplest useful model of each report.
+- **Xero** — SMB reference for report layouts and drill-down; notable as the
+ direct-method cash flow outlier; Carbon already integrates with Xero.
+
+## Key Consensus Patterns
+
+### 1. Accounts map to statement lines via type + hierarchy; layout designers are an enterprise add-on
+
+- **SAP**: Financial Statement Version (FSV) — a time-dependent tree; leaf nodes hold
+ from/to account intervals with debit/credit indicators; auto-generated special
+ items (Assets, Liabilities+Equity, Net result profit/loss, P+L result, Not
+ assigned). Accounts with balances not assigned to any node surface in a "Not
+ assigned" section rather than silently disappearing.
+- **NetSuite**: reusable statement **layouts** made of Financial Sections whose
+ selection criteria are primarily **account type**; computed rows (Gross Profit,
+ Net Income) are formula/summary rows; one layout serves many reports.
+- **QBO**: no layout object at all — **account type alone** determines statement
+ placement and section order (detail type is organizational only).
+- **Xero**: standard layouts + an "Edit layout" editor (account groups, formula
+ rows); practice-level Report Codes exist for cross-client templates.
+- **Rationale**: the statement structure is derivable from the chart of accounts
+ classification; a custom layout designer is a power feature layered on top, not a
+ prerequisite. An "unassigned accounts" safety net matters more than layout
+ flexibility — a statement that silently omits accounts is worse than an ugly one.
+
+### 2. No closing entries: Net Income and Retained Earnings are computed at report time
+
+- **SAP**: statement programs compute the net result at runtime into special FSV
+ nodes ("Net result: profit/loss" on the BS, "P+L result" on the IS) so the balance
+ sheet balances mid-year with no posting. Year-end **balance carryforward**
+ (FAGLGVTR) then posts P&L balances into retained earnings account(s) (OB53
+ mapping) as period-0 documents — and self-adjusts when late postings hit a closed
+ year.
+- **NetSuite**: never posts closing entries. Balance sheet "Net Income" row = a
+ reference row against the income statement for fiscal-year-start → as-of date;
+ "Retained Earnings" row = cumulative net income from inception → beginning of the
+ report's fiscal year, plus direct postings to the RE account. Year-end close is
+ automatic when all periods close; P&L history is preserved.
+- **QBO**: identical model — "Net Income" = fiscal-YTD computed; "Retained Earnings"
+ = sum of prior years' net income + manual RE postings; the rollover is a virtual
+ "electronic swap" with no visible transactions; RE has no register.
+- **Xero**: identical — "Current Year Earnings" (drills to the P&L) + "Retained
+ Earnings" system account (locked for normal coding).
+- **Rationale**: computing avoids closing-entry bulk postings, keeps P&L history
+ queryable forever, and makes reopening trivial. The universal split is: **Retained
+ Earnings = inception → fiscal-year start (+ direct RE postings); Current Year
+ Earnings = fiscal-year start → as-of date**. Carbon's period-closing spec already
+ chose the computed model; the balance sheet must present the two lines separately,
+ not one merged "Net Income" line.
+
+### 3. Cash flow statement: indirect method, classified by account type, with per-account override
+
+- **SAP**: standard app is **indirect method** (F3076), driven by semantic tags on
+ FSV nodes; strategic successor is finance-owned "Reporting Rules" classifying by
+ account ranges. A direct-method view exists only on the treasury/cash-management
+ side.
+- **NetSuite**: indirect only. Operating starts at Net Income (reference row), then
+ period **changes** in working-capital account balances by account type (AR,
+ inventory, other current assets, AP, other current liabilities); Investing =
+ changes in Fixed Asset + Other Asset accounts; Financing = changes in Long Term
+ Liability + Equity accounts; ends with Net Change in Cash, Beginning Cash,
+ FX effect on cash, Ending Cash. Classification lives in the report layout keyed on
+ account type.
+- **QBO**: indirect, fixed classification by account type (current asset/liability →
+ Operating; fixed/other asset → Investing; long-term liability + equity →
+ Financing). QuickBooks **Desktop** exposes "Classify Cash" — per-account override
+ among O/I/F — and its absence in QBO is a documented pain point (e.g. long-term
+ deferred revenue misfiled under Financing).
+- **Xero**: the outlier — **direct method** from coded cash transactions; an
+ indirect-method report is a top open feature request precisely because accountants
+ need the net-income reconciliation for three-way reporting.
+- **Rationale**: the indirect method is the automation consensus because every input
+ already exists in the GL — net income from the P&L, everything else from
+ balance-sheet deltas; no transaction-level cash tagging needed. Both ASC 230 and
+ IAS 7 permit it, and US GAAP requires an indirect reconciliation even from
+ direct-method filers. Default the O/I/F bucket from account type, exclude cash
+ accounts from the body (their delta is the bottom line), and provide a per-account
+ override — the edge cases (deferred revenue, shareholder loans) are exactly where
+ type-based defaults are wrong. Non-cash addbacks (depreciation) fall out
+ automatically as the delta of accumulated-depreciation accounts.
+
+### 4. Comparative reporting: relative period ranges per column + variance formula columns
+
+- **SAP**: RFBILA00/F.01 takes reporting year+period range and comparison
+ year+period range, outputs both plus absolute and relative difference. Fiori F0708
+ makes End Period / Comparison End Period mandatory filters. The hard semantic
+ rule: **balance sheet accounts are always cumulative (carryforward + periods up to
+ the limit); P&L accounts sum only the selected interval**.
+- **NetSuite**: report columns carry an "Alternate Date/Period Range", either fixed
+ or **relative to the report date** (Previous Period, Last Fiscal Year, This FY to
+ Date), so comparison columns shift automatically; variance and % change are
+ formula columns; Budget vs Actual is the same row layout with Budget Amount +
+ variance formula columns; "View Columns By" generates month-by-month matrix
+ columns (30-column limit).
+- **QBO**: Previous Period / Previous Year / YTD checkbox columns, each with
+ optional $ change and % change; % of Income/Expense/Row/Column; column split by
+ month/quarter/class/location.
+- **Xero**: "Compare with" N previous periods, same-month-last-year, budget columns
+ with variance as value or percent.
+- **Rationale**: comparisons are never snapshots — they are just different period
+ aggregations over the same journal, so they stay correct after reopening/adjusting.
+ Relative ranges (prior period, same period prior year, YTD) cover ~all real use;
+ budget comparison is the same mechanism with the budget as the alternate source
+ (Carbon's budgeting spec Phase 3 already plans exactly this).
+
+### 5. Drill-down: statement amount → account detail (GL register) → journal entry
+
+- **SAP**: FSV node → G/L account balance → line items → journal entry document
+ (F0708 → Display G/L Account Balances → line-item browser → Manage Journal
+ Entries); unbroken because everything aggregates live from ACDOCA.
+- **NetSuite**: statement amount → **Account Detail report** (register style: date,
+ type, document, amount, running balance, Split column) → transaction record.
+ Caveat documented: removing the Amount column breaks drill-down; formula rows are
+ not drillable.
+- **QBO**: amount → Transaction Report filtered to account + period + basis → source
+ transaction.
+- **Xero**: balance → **Account Transactions report** scoped to account + period →
+ transaction; computed rows drill contextually (Current Year Earnings → the P&L).
+- **Rationale**: the two-hop pattern is universal and is what makes statements
+ trustworthy — every number can be decomposed to journal lines. It requires a
+ general-purpose **GL detail / account transactions report** (account + date-range
+ filtered journal line listing with running balance) as the drill target; computed
+ rows (Net Income, RE) drill to the statement that defines them, not to lines.
+
+### 6. Trial balance: opening balance / debit / credit / closing balance, period-driven
+
+- **SAP**: Trial Balance app (F0996) columns are Starting Balance, Debit, Credit,
+ Ending Balance per account over a ledger + company code + period range; opening
+ balance includes period-0 carryforward; "adjusted" trial balance = include special
+ periods 13–16, "unadjusted" = stop at period 12. A Trial Balance Comparison app
+ compares two timeframes.
+- **NetSuite**: as-of-date report, one row per account ordered by account type,
+ footer option for Debit/Credit two-column or single net Total column; P&L accounts
+ show fiscal-YTD activity, balance-sheet accounts life-to-date; computed RE row
+ keeps it balancing at any date. Amounts click through to Account Detail.
+- **QBO/Xero**: trial balance + GL detail live in the "For my accountant" section —
+ they are close/tie-out artifacts, not management reports.
+- **Rationale**: the four-column shape (opening, debit movement, credit movement,
+ closing) is the accountant's working format; Carbon's current two-column
+ (debit/credit of net change) trial balance covers the minimum but the four-column
+ form is what ties periods together and is the standard handoff to external
+ accountants.
+
+### 7. Consolidated statements: account-level rate types, report-time CTA, elimination entity
+
+- **SAP**: aggregation tier simply sums company codes (ACDOCA stores group-currency
+ amounts on every line); formal tier (Group Reporting) maps accounts to FS items,
+ translates CLO (closing) for BS / AVG for P&L with translation difference to a CTA
+ item, and posts IC eliminations via monitors.
+- **NetSuite**: Subsidiary Context selector (single vs consolidated); Consolidated
+ Exchange Rates table with Current/Average/Historical rate types per account
+ (General Rate Type + a separate **Cash Flow Rate Type** for the SCF);
+ system CTA account computed dynamically at report time; eliminations are journal
+ entries posted to a dedicated elimination subsidiary swept during period close.
+- **Rationale**: Carbon already implements exactly the NetSuite model
+ (`consolidatedRate` on account, `translateTrialBalance`, CTA computation,
+ elimination entities) — consolidation is a solved problem for Carbon reporting;
+ new reports (cash flow, comparatives) must simply flow through the same
+ translation path. NetSuite's separate Cash Flow Rate Type flags a subtlety: cash
+ flow lines are period *deltas*, so translating them at the closing rate creates
+ artifacts; the FX effect belongs in an explicit "Effect of exchange rate on cash"
+ line.
+
+### 8. The month-end deliverable: 3 statements + trial balance + GL detail, with export
+
+- **QBO/Xero/close-checklist literature**: the standard package is P&L, Balance
+ Sheet, Cash Flow ("three-way reporting"), supported by Trial Balance and GL detail
+ for tie-out; P&L presented in multiple views (vs budget, vs prior period/year, %
+ of sales). Export to PDF/Excel (Xero adds Google Sheets) is table stakes;
+ manufacturers additionally reconcile inventory/WIP to GL before issuing.
+- **SAP**: the Financial Statements Review Booklet (F8587) bundles B/S, P&L, trial
+ balance, and cash flow into one reviewable package.
+- **Rationale**: financial reporting is consumed as a period-end package tied to the
+ close (Carbon's period-closing spec makes closed periods immutable — reports for a
+ closed period are reproducible). Export matters because the audience (owners,
+ banks, external accountants) lives outside the ERP.
+
+## Answers to Research Questions
+
+1. **How should GL accounts map to statement lines?** By account classification +
+ hierarchy, not a layout designer. QBO proves account type alone suffices at SMB
+ scale; NetSuite's sections are account-type queries; SAP's FSV adds interval
+ mapping for enterprises with many charts. Carbon's `account.parentId` tree +
+ `accountType`/`class`/`incomeBalance` already encode statement placement — no new
+ mapping object is needed. Adopt SAP's "Not assigned" safety net: surface accounts
+ that fail classification instead of dropping them.
+2. **How is retained earnings handled without closing entries?** Computed two-line
+ split, universally: Retained Earnings = inception → current-fiscal-year start
+ (+ direct RE postings); Net Income / Current Year Earnings = FY start → as-of
+ date. NetSuite/QBO/Xero all do this; SAP computes current-year result on the fly
+ and only materializes carryforward at year-end. Requires a designated
+ retained-earnings account (Carbon's `accountType` enum already has "Retained
+ Earnings") and the fiscal-year start from `fiscalYearSettings`.
+3. **Which cash flow method, and how are accounts classified?** Indirect (SAP,
+ NetSuite, QBO; the accounting-automation consensus; Xero's direct method is the
+ documented exception users complain about). Classification: Operating = P&L +
+ current assets/liabilities deltas; Investing = long-term asset deltas; Financing
+ = long-term liability + equity deltas; cash/bank accounts excluded (their delta
+ is the result line). Default from account type; per-account override (QuickBooks
+ Desktop "Classify Cash", SAP semantic tags) is the escape hatch every mature
+ system provides.
+4. **How do comparative columns work?** Per-column relative period ranges (previous
+ period, same period last year, YTD) + variance formula columns ($ and %), with BS
+ accounts cumulative and P&L accounts periodic — recomputed live, never
+ snapshotted. Budget comparison is the same mechanism sourcing the budget matrix
+ (already specced in Carbon's budgeting Phase 3).
+5. **What is the drill-down path?** Statement amount → account-transactions report
+ (account + period filter, running balance) → journal entry. Computed rows drill
+ to their defining statement. This requires a GL detail report as a first-class
+ route.
+6. **What does a standard trial balance look like?** One row per posting account:
+ opening balance, period debits, period credits, closing balance, with
+ debit/credit display driven by account class, computed RE keeping it balanced at
+ any date, and zero-balance suppression. Period-driven (fiscal period selector),
+ not just free dates, once periods exist.
+7. **How do consolidated financial statements work?** Entity selector (single vs
+ consolidated), account-level rate types (Current/Average/Historical), report-time
+ CTA, eliminations as posted journals on an elimination entity — Carbon already
+ implements this model; extend it to the new reports rather than inventing
+ anything.
+
+## Competitor-Specific Details
+
+### SAP S/4HANA
+- FSV special items are auto-generated and program-filled: Assets, Liabilities+
+ Equity, Net result: profit, Net result: loss, P+L result, Not assigned, Notes.
+- D/C indicator: same account can report under Assets when in debit and Liabilities
+ when in credit (bank accounts), paired via contra items — an enterprise nicety
+ Carbon does not need initially.
+- Trial balance "adjusted vs unadjusted" is expressed via special periods 13–16 for
+ audit adjustments; Carbon's analog would be reporting a period before vs after
+ late adjustments, since periods stay reproducible after close.
+- Balance carryforward posts period-0 documents and **self-adjusts** on late
+ postings to closed years — the reason SAP can afford posted carryforward. Systems
+ without that machinery (everyone else) compute instead.
+- Plan/actual comparison rides a separate plan table (ACDOCP) — mirrors Carbon's
+ `budgetLine` as a parallel source joined by account + period.
+
+### NetSuite
+- Row taxonomy worth borrowing conceptually: Financial Section (account-backed),
+ Header/Summary pair, Formula Row, Reference Row (value from another statement —
+ how Net Income and Beginning Cash appear on BS/SCF), Text Row.
+- Budget vs Actual = Amount, Budget Amount, Amount Over Budget, % of Budget columns
+ over the standard income-statement layout.
+- "Report by Period" preference switches financials between date-range and
+ accounting-period semantics — supporting both is the mature end state.
+- Consolidated statements include the elimination subsidiary automatically; CTA is
+ dynamic at report time; drill-down warns that formula rows aren't drillable.
+- Trial balance docs warn TB vs Account Detail can differ subtly due to P&L
+ date-range and computed-RE handling — a reconciliation trap to design away.
+
+### QuickBooks Online
+- Account Type list (Bank, AR, Other Current Asset, Fixed Asset, Other Asset, AP,
+ Credit Card, Other Current Liability, Long Term Liability, Equity, Income, COGS,
+ Expense, Other Income, Other Expense) is nearly identical to Carbon's
+ `accountType` enum — Carbon's enum was clearly modeled on it, which makes
+ QBO-style type-driven classification a natural fit.
+- SCF classification is fixed by type in QBO (no override) and users hit real
+ misclassification (long-term deferred revenue → Financing); Desktop's "Classify
+ Cash" per-account override is the fix. Carbon should ship the override on day one.
+- "Close the books" = lock date + optional password; no closing entries — matches
+ Carbon's period-closing Locked status.
+
+### Xero
+- Direct-method SCF is the cautionary tale: cleaner theory, but the missing
+ indirect reconciliation to net income is a top feature request from accountants.
+- Current Year Earnings drills to the P&L — the right behavior for computed rows.
+- Report Codes (practice-level taxonomy mapped over client charts) foreshadow
+ multi-chart standardization — not relevant while Carbon charts are per company
+ group.
+- Export: PDF, Excel, Google Sheets; saved custom reports + report packs for
+ publishing period-end packages.
+
+## Recommended Approach for Carbon
+
+1. **Keep hierarchy-driven statements; no layout designer.** Carbon's account tree +
+ `accountType`/`incomeBalance` already place accounts (QBO model). Add SAP's
+ safety net: any posting account that can't be classified (e.g. no `accountType`
+ or orphaned from the tree) appears in an "Unassigned" section rather than
+ vanishing.
+2. **Split the balance sheet equity into computed "Retained Earnings" + "Current
+ Year Earnings" lines** (NetSuite/Xero naming), replacing the single synthetic
+ Net Income line: RE = income-statement activity from inception → fiscal-year
+ start + direct postings to the Retained Earnings account; CYE = FY start → as-of
+ date. Fiscal-year boundaries come from `fiscalYearSettings.startMonth` /
+ `accountingPeriod.fiscalYear` (period-closing spec). No closing entries, ever —
+ consistent with the period-closing spec's year-end decision.
+3. **Build the cash flow statement indirect-method** (SAP/NetSuite/QBO consensus):
+ Net Income (computed) + deltas of balance-sheet accounts between two dates,
+ bucketed Operating/Investing/Financing. Default the bucket from `accountType`
+ (current assets/liabilities → Operating; fixed/other assets → Investing;
+ long-term liabilities + equity → Financing; Bank/Cash excluded → bottom
+ reconciliation), and add a nullable per-account `cashFlowActivity` override
+ column (QuickBooks Desktop "Classify Cash" pattern). In consolidated view, add an
+ "Effect of exchange rates on cash" line (NetSuite pattern) since translated
+ deltas don't sum cleanly.
+4. **Add comparative columns as relative period ranges + computed variance** —
+ prior period, same period prior year, and YTD for the income statement; prior
+ period / prior year-end for the balance sheet; $ and % variance columns. Honor
+ the universal semantic: BS cumulative, P&L periodic. Once period-closing lands,
+ let reports run by fiscal period (NetSuite "Report by Period") in addition to
+ free date ranges.
+5. **Ship the drill-down chain**: make every statement/trial-balance amount a link
+ into a new **GL detail (account transactions) report** — journal lines filtered
+ by account + date range with running balance and document links — and from each
+ line to the journal entry. Computed rows (CYE, RE) drill to the income statement.
+6. **Upgrade the trial balance to the four-column form** (opening balance, debits,
+ credits, closing balance — SAP F0996 shape) with zero-balance suppression, since
+ it is the accountant handoff artifact.
+7. **Export the package**: CSV/Excel export of every report and a printable PDF
+ financial-statements package (P&L + BS + SCF for a period), consistent with
+ Carbon's existing PDF generation infrastructure. This is the close deliverable
+ (three-way reporting package) every competitor treats as table stakes.
+8. **Reuse the existing consolidation path unchanged** — company selector,
+ `consolidatedRate` translation, report-time CTA, elimination entities — for all
+ new reports; budget-vs-actual columns stay in the budgeting spec (Phase 3) and
+ should reuse the comparative-column mechanism built here.
+
+## Sources
+
+### SAP
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/what-the-fsv-unpacking-standard-financial-statement-versions-in-s-4hana/ba-p/13747219
+- https://community.sap.com/t5/technology-blog-posts-by-members/mastering-financial-statement-design-with-manage-global-hierarchies-in-sap/ba-p/14260213
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/new-gl-and-unassigned-gl-mapping-to-financial-statement-version/ba-p/13540659
+- https://userapps.support.sap.com/sap/support/knowledge/en/2283719 (Trial balance opening/closing balances)
+- https://userapps.support.sap.com/sap/support/knowledge/en/3071770 (Retained earnings logic)
+- https://userapps.support.sap.com/sap/support/knowledge/en/3478671 (Accounts landing in "Not Assigned")
+- https://userapps.support.sap.com/sap/support/knowledge/en/3348991 (F0708/F3084 comparison periods)
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/cash-flow-statement-reporting-rules-vs-semantic-tags/ba-p/14396951
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/s-4hana-finance-balance-carryforward-technical-tip/ba-p/13367327
+- https://fioriappslibrary.hana.ondemand.com/sap/fix/externalViewer/?appId=F3076 (Cash Flow Statement – Indirect Method)
+- https://eursap.eu/blog/an-overview-of-group-reporting-in-sap-s-4-hana-1909
+- https://www.pikon.com/en/blog/fiori-apps-for-finance-in-sap-s4hana/
+- https://help.sap.com/docs/SUPPORT_CONTENT/fiaccounting/3361880573.html (RFBILA00)
+
+### NetSuite
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_N2105415.html (Financial Report Builder)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2115374.html (Financial statement rows)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2110511.html (Financial statement layouts)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2106822.html (Edit Columns page)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2093552.html (Income Statement)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2098310.html (Balance Sheet)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2103273.html (Cash Flow Statement)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2103948.html (Customizing cash flow account sections)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1520986.html (Trial Balance)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2095037.html (Comparative Income Statement)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2097218.html (Budget vs. Actual)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1457773.html (Year-End Closing)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N719130.html (Drill-down)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N278654.html (Consolidated reporting in OneWorld)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1522428.html (Account Detail report)
+- https://www.sikich.com/insight/retained-earnings-concept-in-netsuite/
+
+### QuickBooks
+- https://quickbooks.intuit.com/learn-support/en-us/help-article/chart-accounts/learn-account-detail-types-chart-accounts/L2gCy0rfy_US_en_US
+- https://quickbooks.intuit.com/learn-support/en-us/help-article/financial-reports/view-retained-earnings-account-details/L7d6Ugx58_US_en_US
+- https://quickbooks.intuit.com/learn-support/en-us/help-article/close-books/close-books-quickbooks-online/L59LelyPM_US_en_US
+- https://quickbooks.intuit.com/learn-support/en-us/help-article/financial-reports/run-statement-cash-flows/L7f72hT6Q_US_en_US
+- https://longforsuccess.com/quickbooks-tip-classifying-accounts-for-statement-of-cash-flow/ (Classify Cash)
+- https://quickbooks.intuit.com/learn-support/en-us/reports-and-accounting/how-do-i-make-it-so-long-term-deferred-revenue-account-will-show/00/718506 (misclassification pain)
+- https://quickbooks.intuit.com/learn-support/en-us/help-article/report-management/run-profit-loss-comparison-report/L6GthoBhe_US_en_US
+- https://quickbooks.intuit.com/learn-support/en-us/help-article/report-management/show-active-rows-columns-reports/L0fJtAnS2_US_en_US
+
+### Xero
+- https://central.xero.com/s/article/Create-reusable-custom-report-layouts
+- https://central.xero.com/s/article/Report-codes-for-practices-using-report-templates
+- https://central.xero.com/s/article/Balance-Sheet-New-US (Current Year Earnings)
+- https://central.xero.com/s/article/Locked-and-system-accounts-in-your-chart-of-accounts
+- https://central.xero.com/s/article/Statement-of-Cash-Flows-New (direct method)
+- https://productideas.xero.com/forums/967133-reports-tax/suggestions/44961463-reporting-statement-of-cash-flow-indirect-metho (indirect-method feature request)
+- https://central.xero.com/s/article/Account-Transactions-report-New (drill target)
+- https://central.xero.com/s/article/Export-or-print-a-report
+
+### Standards / general
+- https://www.accountingtools.com/articles/cash-flow-statement-indirect-method
+- https://corporatefinanceinstitute.com/resources/accounting/statement-of-cash-flows/
+- https://openstax.org/books/principles-financial-accounting/pages/16-3-prepare-the-statement-of-cash-flows-using-the-indirect-method
+- https://viewpoint.pwc.com/dt/us/en/pwc/accounting_guides/financial_statement_/financial_statement___18_US/chapter_6_statement__US/64_format_of_the_sta_US.html (ASC 230 format)
+- https://theceosrighthand.co/the-importance-of-the-month-end-reporting-package/
+- https://keitercpa.com/blog/financial-close-checklist/
diff --git a/.ai/research/multi-jurisdiction-tax.md b/.ai/research/multi-jurisdiction-tax.md
new file mode 100644
index 0000000000..bba7394d6b
--- /dev/null
+++ b/.ai/research/multi-jurisdiction-tax.md
@@ -0,0 +1,195 @@
+# Multi-Jurisdiction Tax Compliance Research: Best Practices Survey
+
+## Summary
+
+Surveyed how SAP S/4HANA, NetSuite, Dynamics 365 Business Central, Odoo, Xero, and the external tax engines (Avalara AvaTax, Vertex, Stripe Tax) model tax determination, calculation, GL posting, exemptions, registrations/nexus, and returns across US sales tax and VAT/GST regimes. The industry converges on a small set of structural patterns: a **two-sided classification matrix** (party-side group × item-side group) resolving to a **tax code**; tax codes composed of **components** (one per jurisdiction/authority, each with its own rate and GL account); an immutable **tax subledger** written at posting time that all reporting reads from; **registrations/nexus** gating where tax is calculated at all; and a **pluggable external-engine seam** (estimate on orders, commit at invoice posting). Every surveyed system posts output tax to a liability account separate from revenue and input tax to a recoverable account separate from cost — the two things Carbon's current posting does not do.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA** — enterprise reference; condition-technique determination, BSET tax subledger, external engine interface (TAXUSX)
+- **NetSuite** — mid-market reference; nexus-rooted model, SuiteTax plug-in engine framework, tax control accounts
+- **Dynamics 365 Business Central** — closest SMB architecture to Carbon's existing posting-group matrix; runs *two* parallel tax systems (VAT posting groups + US tax areas/jurisdictions)
+- **Odoo** — SMB reference for a *unified* single-model approach (`account.tax` + fiscal positions + tax grids)
+- **Xero** — Carbon already syncs to Xero; tax rates with summed components, ReportTaxType → return-box mapping
+- **Avalara AvaTax / Vertex / Stripe Tax** — external determination engines; define the integration contract an ERP must expose
+
+## Key Consensus Patterns
+
+### 1. Two-sided classification resolves the tax treatment
+
+- **BC**: `VAT Bus. Posting Group` (customer/vendor) × `VAT Prod. Posting Group` (item/GL account) → `VAT Posting Setup` row (rate, calculation type, accounts). US side: `Tax Area` (party/ship-to) × `Tax Group` (item) → `Tax Detail` rates.
+- **SAP**: customer tax classification × material tax classification (+ departure/destination country) → condition record → tax code.
+- **NetSuite**: nexus (from ship-to + registrations) + item tax schedule → tax code/group.
+- **Odoo**: product default taxes rewritten by the partner's fiscal position (auto-applied by country/VAT-number).
+- **Rationale**: *who/where* you sell to and *what* you sell are independent axes; a matrix keeps N×M treatments maintainable as N+M classifications.
+
+### 2. The tax code is the atomic unit; components carry jurisdictions
+
+- **Xero**: `TaxRate` = list of `TaxComponents` (name, rate, `IsCompound`, `IsNonRecoverable`) that sum to the effective rate — the state+county+city pattern.
+- **BC**: `Tax Area` = set of `Tax Jurisdictions`, each jurisdiction with its own rate (via Tax Detail), its own GL accounts, and a `Report-to Jurisdiction` for rollup.
+- **NetSuite legacy**: `Tax Group` bundles per-authority tax codes; SuiteTax writes one tax-detail line per jurisdiction subnexus.
+- **SAP**: one tax code expands to one condition line per jurisdiction level (`JR1–JR4`/`XR1–XR6`), each with its own account key.
+- **Avalara**: response `details[]` = one entry per jurisdiction per line (jurisCode, type State/County/City/Special, rate, tax).
+- **Rationale**: multi-level US stacking, Canada GST/PST, and single-rate VAT all collapse into "a code with 1..n components."
+
+### 3. An immutable tax subledger is written at posting time
+
+- **BC**: every VAT-relevant posting writes a **VAT Entry** (base, amount, posting groups, VAT date, open/closed) — all reporting and settlement reads VAT entries, not GL.
+- **SAP**: **BSET** segment per document (base, tax, account key, jurisdiction, level).
+- **NetSuite SuiteTax**: per-line Tax Details (type, code, basis, rate, amount).
+- **Avalara**: committed transactions are the return-feeding record; adjust/void create new versions.
+- **Rationale**: rates and config change; posted documents must not. Returns need taxable/exempt *bases*, not just tax amounts — GL alone can't answer "exempt sales to TX in Q2."
+
+### 4. Output and input tax post to dedicated accounts — never into revenue or cost
+
+- **BC**: VAT Posting Setup carries `Sales VAT Account` / `Purchase VAT Account`; US jurisdictions carry `Tax Account (Sales)` / `Tax Account (Purchases)`; non-recoverable purchase tax is explicitly flagged `Expense/Capitalize`.
+- **SAP**: account keys `MWS` (output) / `VST` (input) / `NAV`/`NVV` (non-deductible, posted separately or distributed to cost).
+- **NetSuite**: per-nexus Payables (sales) and Receivables (purchases) tax control accounts.
+- **Xero/Odoo**: account per rate / per repartition line.
+- **Rationale**: collected tax is a liability owed to an authority; recoverable input tax is an asset. Booking either into revenue/cost misstates the P&L and makes remittance untrackable.
+
+### 5. Registrations/nexus gate where tax applies
+
+- **Avalara**: `NexusModel` declarations per jurisdiction — **engine returns zero tax where no nexus is declared**; economic-nexus thresholds (Wayfair $100k/200-txn baseline) are monitored but never self-registered.
+- **Stripe Tax**: registration-based — only calculates where registered.
+- **NetSuite**: nexuses per subsidiary with registration numbers (SuiteTax: multiple, with validity dates); determination fails to a nexus only if a registration exists.
+- **SAP**: plants abroad / RITA for foreign VAT registrations; VAT reg no. (`STCEG`) on master data drives intra-EU treatment.
+- **Rationale**: collecting where unregistered is as bad as not collecting where registered.
+
+### 6. Exemptions are certificates + item taxability + reason codes
+
+- **NetSuite SuiteTax / Avalara**: customer exemption certificates with expiry, scope, reason (entity-use) codes; auto-applied by customer at calc time.
+- **BC**: `Tax Exemption No.` on header; item-side non-taxable Tax Group.
+- **Rationale**: exempt sales still must be *recorded* (returns report exempt bases); an exemption zeroes the rate, it doesn't skip the tax record.
+
+### 7. Reverse charge posts paired entries that net to zero
+
+- **BC**: `VAT Calculation Type = Reverse Charge VAT` → input VAT to Purchase VAT Account + offsetting output to `Reverse Chrg. VAT Acct`.
+- **SAP**: paired condition lines (`MWS`+`VST`, or `ESA`/`ESE` acquisition tax) net zero but both appear in reporting.
+- **Odoo**: intra-EU fiscal position maps to reverse-charge tax whose repartition lines split base/tax into the right grids.
+- **Rationale**: EU B2B purchases (and domestic reverse-charge regimes) require self-assessed output+input VAT reported on both sides of the return.
+
+### 8. Returns are built by mapping codes/components to boxes; settlement is a posted entry
+
+- **BC**: VAT Statement rows (filters by posting groups) map to official return boxes; `Calc. and Post VAT Settlement` nets input vs output into a settlement account and closes VAT entries.
+- **Xero**: `ReportTaxType` enum per rate (~100 values: INPUT, OUTPUT, ECACQUISITIONS, USSALESTAX, REVERSECHARGES…) drives return placement (UK MTD boxes auto-populate).
+- **Odoo**: repartition-line `tag_ids` (tax grids) aggregate into the country return; a closing entry + tax lock date close the period.
+- **NetSuite**: liability reports per agency/nexus; *Pay Sales Tax* / *Pay Tax Liabilities* settle to the agency vendor.
+- **Rationale**: box mapping is per-country configuration layered on top of a category attribute on the tax code — the code itself stays jurisdiction-neutral.
+
+### 9. External engines plug in at one seam; internal tables are the default path
+
+- **NetSuite**: SuiteTax is a plug-in framework — NetSuite's own engine, Avalara, Vertex, Sovos are all engines selectable per nexus.
+- **Odoo**: AvaTax replaces native computation only when the AvaTax fiscal position applies (US/CA/BR).
+- **Xero**: US orgs get Avalara-powered "auto sales tax"; other regions use native rates.
+- **Avalara ERP guide**: estimate with `SalesOrder` (temporary) on quotes/orders; `SalesInvoice` with commit at invoice posting; document `code` = invoice number for idempotency; validate addresses at master-data entry; on outage, flag and reconcile — never commit guessed tax.
+- **Rationale**: rooftop-accurate US determination (13,000+ jurisdictions) is a data-service problem, not an ERP problem. The ERP owns the seam, the records, and the GL.
+
+### 10. Mechanics everyone specifies
+
+- **Rounding**: line-level vs document-level is an explicit setting (Avalara default: line-level for new companies; BC rounds per `VAT Identifier` sum). The two can differ by a penny; authorities tolerate both.
+- **Tax-inclusive pricing**: a document-level mode (Xero `LineAmountTypes` Exclusive/Inclusive/NoTax; BC `Prices Including VAT`; Odoo `price_include`).
+- **Effective-dated rates**: BC Tax Detail and Avalara nexus/rates carry effective dates; NetSuite SuiteTax nexuses have validity dates.
+- **Tax date vs posting date**: BC `VAT Date`, SuiteTax line-level Tax Point Date.
+
+## Answers to Research Questions
+
+1. **Core determination entities** — party-side group × item-side group → tax code (BC posting setup; SAP condition technique; Odoo fiscal positions). Party side is resolved from the **ship-to** (destination) for US sales tax and from country/registration relationships for VAT (SAP/NetSuite/BC all key US determination off ship-to address; SuiteTax additionally weighs ship-from, billing, and registrations).
+2. **US + VAT in one model** — BC keeps two subsystems (VAT posting groups vs tax areas/jurisdictions) bridged by `VAT Calculation Type = Sales Tax`; Odoo/Xero/Avalara prove the unified model: a tax code with 1..n components covers single-rate VAT and stacked US jurisdictions alike; reverse charge is a calculation-type attribute, not a separate system. **A new implementation should unify** (the BC split is NAV legacy).
+3. **GL posting & line storage** — dedicated output-tax liability and input-tax accounts, per component/jurisdiction where needed (consensus #4); per-line tax detail snapshot at posting into a tax subledger (consensus #3). Non-recoverable input tax capitalizes into cost via an explicit flag (BC Expense/Capitalize, Xero IsNonRecoverable, SAP NVV).
+4. **Exemptions & registrations** — certificates on the customer (number, reason, expiry) zero the rate but still write records; item taxability via the item-side group; company registrations with numbers/dates gate calculation and print on documents (consensus #5, #6).
+5. **Returns & rounding** — reporting reads the tax subledger grouped by authority/component (taxable base, exempt base, tax); box mapping is config layered on a reporting-category attribute; settlement is a posted journal entry (consensus #8). Rounding: line-level default (consensus #10).
+6. **External engine contract** — one determination seam; temporary calls for quotes/orders, committed calls at invoice posting keyed by document code; address validation at master entry; nexus declared engine-side mirrors registrations (consensus #9).
+
+## Competitor-Specific Details
+
+### SAP S/4HANA
+Tax codes (`MWSKZ`) within per-country calculation procedures; US jurisdiction code `TXJCD` decomposes into up to 4–6 levels, one condition line per level; account keys (OB40) map to GL per chart of accounts; zero-rated vs exempt are separate 0% codes distinguished only by reporting attributes; deferred (cash-basis) tax via target tax codes; RFUMSV00 builds the VAT return from BSET and posts the net payable.
+
+### NetSuite
+Tax agencies are **vendor records** — remittance is ordinary AP; legacy tax periods are independent of accounting periods (SuiteTax reverts to accounting periods + tax point date); Tax Types carry special behaviors (withholding "does not add to total", "post to item cost" for non-deductible VAT, reverse charge); nexus override is user-visible but permission-gated.
+
+### Dynamics 365 Business Central
+`VAT Identifier` groups posting-setup combinations sharing a rate so document-level VAT rounds per identifier; `Max. VAT Difference Allowed` bounds manual per-line tax overrides; VAT Clauses print per-language legal text justifying zero/reduced rates on invoices; Tax Details support min/max taxable thresholds and effective dates; Canada Provincial Tax Area self-assesses PST when the vendor charged only GST/HST.
+
+### Odoo
+`account.tax.repartition.line` splits each tax's base and amount into GL accounts + report grids separately for invoices vs refunds (factor_percent enables 50/50 GST splits); fiscal localization packages install per-country charts + taxes + return layouts; Tax Lock Date reclassifies late changes into the next open period.
+
+### Xero
+Per-account and per-contact default tax types with line-level override; `LineAmountTypes` is document-level; US system rates are read-only Avalara-managed with system GUIDs — user-defined codes and engine-managed codes coexist in one table.
+
+### Avalara AvaTax
+Document lifecycle Temporary → Saved → Committed → Locked; committed docs feed returns; locked docs (reported on a filed return) are immutable — corrections require offsetting documents with `taxOverride.taxDate` pinned to the original period; `entityUseCode` letter codes standardize exemption reasons; line vs document rounding is a company setting; Managed Returns runs off filing calendars with a monthly reconcile-approve-file cycle.
+
+## Recommended Approach for Carbon
+
+1. **Unify VAT and US sales tax in one model** (Odoo/Xero/Avalara pattern, not BC's dual system): `taxCode` (treatment + reporting category + calculation type) composed of `taxCodeComponent` rows (authority, rate, GL accounts, recoverable/compound flags). Single-rate VAT = one component; Texas 8.25% = two to four components.
+2. **Determination matrix, Carbon-shaped** (BC pattern — Carbon already has the posting-group matrix precedent): party-side `taxArea` (assigned to customers/ship-to locations/suppliers, auto-matchable by country+state) × item-side `taxCategory` (on items) → `taxRule` → `taxCode`. Destination-based: resolve the area from the ship-to address.
+3. **Tax subledger** (BC VAT Entry / SAP BSET pattern): write immutable `taxLedger` rows (base, exempt base, rate, amount, component, authority, journal link) when invoices post; drafts compute live; all reporting reads the ledger.
+4. **Fix posting** (consensus #4): credit revenue net + credit output-tax liability per component on sales; debit recoverable input tax separately from cost on purchases, with a non-recoverable flag preserving capitalize-into-cost (today's behavior) for US purchase tax. Reverse charge = paired entries (activates Carbon's existing dead `reverseChargeSalesTaxPayableAccount` config).
+5. **Registrations** (`taxRegistration`: jurisdiction, number, dates) print on documents and group liability reporting; rule coverage ⇒ collection, mirroring nexus (warn on rule-without-registration).
+6. **Wire the existing exemption metadata** (`customerTax.taxExempt` + certificates, currently display-only) into determination — exempt resolves to a 0% code with reason, still writing ledger rows.
+7. **One determination seam** (`resolveTaxes(...)` service + shared edge-function helper) so an Avalara engine can replace the internal matrix per company later (NetSuite SuiteTax pattern); v1 ships the internal engine only.
+8. **Defer**: return-box statements, settlement posting, tax-inclusive pricing, use-tax accrual, external engine connector, foreign-currency registrations — each has a clean landing zone in this model.
+
+## Sources
+
+### SAP
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/basis-of-tax-procedure-selection-for-us-client/qaq-p/10565870
+- https://sapcodes.com/2016/12/17/tax-determination-in-sap-sd/
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/understand-the-new-account-determination-for-tax-codes-in-s-4-hana-finance/ba-p/13359507
+- https://sap96.com/2024/11/08/assign-gl-accounts-to-tax-account-key-ob40/
+- https://leanx.eu/en/sap/table/bset.html
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/reverse-charge-in-taxation/ba-p/13344984
+- https://help.sap.com/docs/SAP_S4HANA_CLOUD/a624a4a6d1d8473eb95fb42660127cfe/8278b228bc4f4c2ca5b3cb84739f42b0.html (plants abroad / RITA)
+- https://userapps.support.sap.com/sap/support/knowledge/en/2557594 (exemption certificates with external engines)
+- https://saplearners.com/sap-tcode/f-rfumsv25/ (deferred tax transfer)
+- https://knowledge.avalara.com/bundle/wuc0965226643863_wuc0965226643863/page/gws9480803604709.html (SAP↔AvaTax)
+
+### NetSuite
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_0315035511.html (SuiteTax vs legacy)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4283869397.html (Tax types & codes)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4283851663.html (Nexuses)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4283866360.html (Nexus lookup logic)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4283867856.html (Tax details on transactions)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2043102.html (Sales tax liability by agency)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/article_160639676040.html (Exemption certificates)
+- https://timdietrich.me/blog/netsuite-sales-tax-options/
+- https://www.avalara.com/us/en/products/integrations/netsuite/suite-tax-integrations.html
+
+### Dynamics 365 Business Central
+- https://learn.microsoft.com/en-us/dynamics365/business-central/finance-setup-vat
+- https://learn.microsoft.com/en-us/dynamics365/business-central/finance-setup-unrealized-vat
+- https://learn.microsoft.com/en-us/dynamics365/business-central/finance-how-report-vat
+- https://learn.microsoft.com/en-us/dynamics365/business-central/finance-how-setup-vat-statement
+- https://learn.microsoft.com/en-us/dynamics365/business-central/localfunctionality/unitedstates/us-sales-tax
+- https://learn.microsoft.com/en-us/dynamics365/business-central/localfunctionality/unitedstates/how-to-set-up-use-tax-and-purchase-tax
+- https://learn.microsoft.com/en-ca/dynamics365/business-central/localfunctionality/canada/ca-sales-tax
+
+### Odoo
+- https://www.odoo.com/documentation/18.0/applications/finance/accounting/taxes.html
+- https://www.odoo.com/documentation/18.0/applications/finance/accounting/taxes/fiscal_positions.html
+- https://www.odoo.com/documentation/18.0/applications/finance/fiscal_localizations.html
+- https://www.odoo.com/documentation/18.0/applications/finance/accounting/reporting/tax_returns.html
+- https://www.odoo.com/documentation/18.0/applications/finance/accounting/taxes/avatax.html
+- https://github.com/odoo/odoo/blob/18.0/addons/account/models/account_tax.py
+
+### Xero
+- https://developer.xero.com/documentation/api/accounting/taxrates
+- https://developer.xero.com/documentation/api/accounting/types (ReportTaxType enum)
+- https://developer.xero.com/documentation/api/accounting/contacts (per-contact AR/AP tax types)
+- https://github.com/XeroAPI/Xero-NetStandard/blob/master/Xero.NetStandard.OAuth2/Model/Accounting/TaxRate.cs
+- https://www.xero.com/us/media-releases/xero-avalara-launch-auto-sales-tax/
+- https://central.xero.com/s/article/The-VAT-Return
+
+### Tax engines
+- https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Transactions/CreateTransaction/
+- https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Nexus/
+- https://developer.avalara.com/erp-integration-guide/ (when to calculate, address validation, outage fallback)
+- https://developer.avalara.com/avatax/dev-guide/reconciliation/modifying-a-transaction/
+- https://developer.avalara.com/avatax/errors/DocumentCodeConflict/
+- https://help.avalara.com/Frequently_Asked_Questions/Tax_Calculation_FAQ/What_is_the_difference_between_Document_and_Line_level_rounding
+- https://www.avalara.com/blog/en/north-america/2025/06/states-eliminating-economic-nexus-transaction-thresholds.html
+- https://developer.avalara.com/products/returns/
+- https://docs.stripe.com/tax/registrations-api and https://docs.stripe.com/tax/custom
+- https://developer.vertexinc.com/oseries/reference/salepost
diff --git a/.ai/research/period-closing.md b/.ai/research/period-closing.md
new file mode 100644
index 0000000000..745b21c56a
--- /dev/null
+++ b/.ai/research/period-closing.md
@@ -0,0 +1,222 @@
+# Period Closing in Top ERPs — Research Notes
+
+Research date: 2026-07-02. Focus: how leading ERPs model accounting periods, month-end / year-end close, posting validation, and reopening — with a synthesis for a modern mid-market manufacturing ERP.
+
+---
+
+## 1. SAP (S/4HANA and ECC)
+
+### Posting Period Variant (OB52)
+
+SAP does not close periods per se — it controls *which periods accept postings* via a **Posting Period Variant (PPV)** assigned to one or more company codes. The variant is maintained in transaction OB52 ("Open and Close Posting Periods").
+([saponlinetutorials.com](https://www.saponlinetutorials.com/define-variant-for-open-and-close-posting-periods-sap-ob52/), [learntosap.com](https://www.learntosap.com/ficotutorialopenandcloseperiod.html))
+
+Each OB52 row specifies:
+
+- **Account type** — the row applies to a class of accounts:
+ - `+` = valid for all account types (a required baseline row; From/To Account left blank)
+ - `A` = assets, `D` = customers (A/R), `K` = vendors (A/P), `M` = materials, `S` = G/L accounts
+- **Account range** (From Account / To Account) — lets you keep only *specific G/L accounts* open (e.g., only accrual accounts during close).
+- **Three period intervals**:
+ - **Interval 1** (`From per.1` / `To per.1`) — normal posting periods; can carry an **authorization group** so only privileged users (e.g., the close team) may post in it.
+ - **Interval 2** (`From per.2` / `To per.2`) — a second open range, typically the **special periods**, open to everyone or used for the prior period during the close window.
+ - **Interval 3** (`From per.3`) — periods checked for postings transferred **from CO to FI** (controlling-internal postings) — S/4HANA-relevant since CO and FI share the Universal Journal.
+ ([sapsharks.com](https://sapsharks.com/ob52-open-and-close-fi-posting-periods/), [SAP Community](https://community.sap.com/t5/enterprise-resource-planning-q-a/open-and-close-posting-period-ob52/qaq-p/3980255))
+
+Key design consequences:
+- **Granular soft close**: you can close A/P (`K`) and A/R (`D`) while G/L (`S`) remains open — exactly the "lock subledgers first, GL last" pattern.
+- **Role-based exception**: interval 1 + authorization group = "period closed for everyone except accountants in group X." This is the SAP mechanism for controllers posting late adjustments.
+- Mass maintenance exists via program RFOB5200 for orgs with many variants. ([help.sap.com](https://help.sap.com/docs/SUPPORT_CONTENT/fiaccounting/3361878788.html))
+
+### Special periods 13–16
+
+A fiscal year variant has up to 12 normal periods plus up to **4 special periods (13–16)** that all map to the last calendar month of the fiscal year. They exist solely for **year-end adjustments**: audit adjustments in 13, tax adjustments in 14, etc. Posting to a special period requires a posting date in the last normal period, with the special period entered explicitly. This lets SAP produce multiple year-end financial statement versions (pre-audit, post-audit, post-tax) without contaminating December operational numbers. ([saponlinetutorials.com](https://www.saponlinetutorials.com/define-variant-for-open-and-close-posting-periods-sap-ob52/), [sappeers.wordpress.com](https://sappeers.wordpress.com/2011/02/06/open-and-close-posting-periods-ob52/))
+
+### Year-end: balance carryforward (FAGLGVTR)
+
+- SAP posts **no closing entries** to the old year in the classic income-summary sense. Instead, program **FAGLGVTR** (S/4HANA: "Balance Carryforward" job) writes carryforward records into **period 0** of the new fiscal year: balance-sheet account balances carry forward as-is; P&L account balances roll into the configured **retained earnings account**.
+- Crucially, carryforward is **self-maintaining**: once run, any subsequent posting to the old year automatically updates the period-0 carryforward in the new year — so late adjustments never desynchronize opening balances. ([SAP Community](https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/s-4hana-finance-balance-carryforward-technical-tip/ba-p/13367327))
+- Typical year-end sequence: open new-year periods → run carryforward → block old-year normal periods, keep special periods open for adjustments → post audit adjustments in periods 13–16 → close special periods.
+
+### Close orchestration: Financial Closing Cockpit / Advanced Financial Closing
+
+- The **Financial Closing Cockpit (FCC)** — embedded in S/4HANA since 1709 — provides **task list templates** modeling the close as a structured, dependency-ordered set of tasks (transactions, jobs, programs, manual tasks) across company codes; stakeholders execute or monitor their tasks, with status reporting and audit trail. ([help.sap.com](https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/8b1d76cd5e7644caa0553fcf338f3982/3fe49e8767d648a6b1b5edeec8849b8d.html), [SAP Community](https://community.sap.com/t5/financial-management-blog-posts-by-members/sap-s-4hana-financial-closing-cockpit-at-glance/ba-p/13414771))
+- **SAP Advanced Financial Closing (AFC)** is the cloud successor: centrally defined close templates, task dependencies, assignments, approvals, automated job execution across many systems/entities, plus close analytics (cycle-time, bottlenecks). ([IBM](https://www.ibm.com/think/insights/advanced-financial-closing-and-sap-s4hana), [sap-press.com](https://blog.sap-press.com/improving-financial-close-with-sap-s/4hana-finance-tools))
+
+### Soft vs hard close in SAP terms
+
+"Soft close" = OB52 rows tightened progressively (subledger account types closed, G/L restricted to an authorization group). "Hard close" = all account types closed for the period for everyone. Nothing is irreversible — OB52 can always be reopened by someone with config access, so auditability relies on change logs of the variant.
+
+---
+
+## 2. NetSuite
+
+### Accounting period setup
+
+- Periods are **first-class records** (not just date checks): fiscal calendars generate a year of period records with format **standard calendar months, 4-week, or 4-4-5** ([Oracle docs — Manage Accounting Periods](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1445839.html), [Oracle docs — Year-End Closing](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1457773.html)).
+- Periods nest: year → quarter → month; one-day **adjustment periods** can be created that overlap a normal period (used to isolate audit adjustments — the NetSuite analog of SAP special periods).
+- Multiple fiscal calendars are supported so different subsidiaries can have different year-ends.
+
+### The Period Close Checklist
+
+The centerpiece of NetSuite close is a built-in, per-period **checklist** with enforced ordering (tasks show lock icons until prerequisites complete; statuses are Not Started / Partially Done / Complete). Full task list, in order ([Oracle docs — Using the Period Close Checklist](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1455781.html)):
+
+1. **Lock A/R** — blocks A/R-posting transactions in the period
+2. **Lock A/P** — blocks A/P-posting transactions
+3. **Lock Payroll** (if enabled) / **Lock All** shortcut
+4. **Resolve Date/Period Mismatches** (inventory feature) — transactions whose date and assigned period disagree
+5. **Review Negative Inventory** — negative on-hand makes costing unreliable; resolve before close
+6. **Review Inventory Cost Accounting** — ensure costing queue has processed
+7. **Review Inventory Activity** (OneWorld)
+8. **Review Custom GL Plug-in Executions**
+9. **Create Intercompany Adjustments** (OneWorld)
+10. **Revalue Open Foreign Currency Balances** — unrealized FX gain/loss on open balances
+11. **Recognize Revenue** / **Reclassify Revenue** (ARM)
+12. **Calculate Consolidated Exchange Rates** (OneWorld)
+13. **Eliminate Intercompany Transactions** — requires FX revaluation + consolidated rates done first (explicit dependency) ([Oracle docs — Intercompany Elimination](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1498385.html))
+14. **Create Period End Journals** (if feature enabled — materializes consolidation/close as actual journals)
+15. **GL Audit Numbering** — assign and verify **gapless sequence numbers** on GL impact for statutory jurisdictions (last month of period only)
+16. **Close** — final task; period excludes all posting transactions
+
+Notes:
+- **Sequential close**: all prior periods must be closed before a period can be closed; only the earliest open period's checklist is fully actionable. ([Oracle docs — Accounting Period Close](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1452509.html))
+- The lock tasks create a deliberate **"pre-closed state"** so accountants can review stable balances and post adjustments before the hard close. ([Oracle docs — Locking and Unlocking](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1451780.html))
+
+### Period status & posting validation
+
+- Effective statuses: **Open → Locked (per subledger: A/R, A/P, Payroll, or All) → Closed**.
+- Locking is *permission-aware*: users with **Override Period Restrictions** can still post to a locked (not closed) period — this is the controller exception. Closed periods block GL-impacting changes for everyone. ([Oracle docs — Locking and Unlocking](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1451780.html))
+- **Allow Non-G/L Changes** — a per-period flag: users holding the matching permission may edit non-GL-impacting fields (memos, shipping status, etc.) on transactions in a closed period without reopening it. ([Oracle docs — Manage Accounting Periods](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1445839.html))
+- Validation happens **at transaction save time** against the posting period/date's status — there is no batch "post later" escape hatch.
+
+### Reopening
+
+Reopening a closed period **automatically reopens all later closed periods**, and checklist tasks may need to be redone for each; everything is logged. ([Oracle docs — Reopening a Closed Period](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1457543.html))
+
+### Year-end close is implicit
+
+NetSuite posts **no closing entries**. Retained Earnings is a **system-calculated account**: for any balance-sheet date, the system rolls cumulative prior-year net income into Retained Earnings virtually at report time ("Automatic Close" method). Income-statement accounts "reset" each year only in presentation, not via journals. Closing the last period of the year is what finalizes the year. Optionally, the **Period End Journal Entries** feature materializes closing/consolidation as real journals for jurisdictions that require visible closing entries. ([Oracle docs — Year-End Closing](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1457773.html), [Oracle docs — Period End Journal Entries](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1531269686.html), [rsmus.com](https://technologyblog.rsmus.com/technologies/netsuite/month-end-and-year-end-processing-in-netsuite/))
+
+### Multi-book and subsidiary dimensions
+
+- **Extended Accounting Period Close** ("per-book closing") gives each accounting book (e.g., GAAP book vs IFRS book vs tax book) its **own close checklist and period status**, closable/reopenable independently. ([scalenorth.com](https://scalenorth.com/insights/netsuite-close-accounting-period), [Oracle docs](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1455781.html))
+- Base NetSuite closes periods **globally across subsidiaries** (one period record for all of OneWorld); intercompany elimination and consolidated-rate tasks are how subsidiary consolidation enters the checklist. True subsidiary-independent close is a known limitation people work around with fiscal calendars per subsidiary.
+
+---
+
+## 3. Brief references
+
+### Microsoft Dynamics 365 Business Central
+
+- Posting control is **date-range based, not status based**: General Ledger Setup has **Allow Posting From / Allow Posting To**; the **User Setup** table overrides these per user, so most users are pinned to the current period while the controller keeps a wider window. ([kristenhosman.com](https://www.kristenhosman.com/2024/04/working-with-posting-dates-in-microsoft.html), [erpsoftwareblog.com](https://erpsoftwareblog.com/2022/09/how-to-run-the-close-income-statement-in-microsoft-dynamics-365-business-central/))
+- Year-end: "Close Year" marks fiscal-year periods closed (irreversibly flagged, but you can *still post* to a closed year — entries are marked prior-year), then the **Close Income Statement batch job** generates an explicit closing journal that zeroes P&L accounts into retained earnings, posted on a fictitious **"C" closing date** (e.g., `C12/31/2025`) that sits *between* Dec 31 and Jan 1 so it never distorts real-date balances. Re-run the batch job after late adjustments. ([Microsoft Learn](https://learn.microsoft.com/en-us/dynamics365/business-central/year-close-income-statement), [erpconnectconsulting.com](https://erpconnectconsulting.com/blogs/blog/closing-the-fiscal-year-in-dynamics-365-business-central))
+
+### Microsoft Dynamics 365 Finance (F&O) — worth noting
+
+- Ledger calendar period statuses: **Open / On hold / Permanently closed**. On hold blocks posting but is reversible; permanently closed is designed to be irreversible. ([cittros.com](https://www.cittros.com/insights/close-a-period-for-posting-in-d365-finance), [brightpointinfotech.com](https://brightpointinfotech.com/revert-to-open-permanently-closed-calendar-period-status-in-d365/))
+- Per period, **module-level access** (GL, AP, AR, inventory, projects…) can be set to **All / None / a specific user group** — the cleanest mainstream implementation of "subledger closed for everyone except the close team." ([arcticit.com](https://arcticit.com/how-to-specify-which-users-can-post-to-a-period-in-dynamics-365-finance/))
+- A **Financial period close workspace** provides checklist/task orchestration with assignments and due dates, like a lightweight FCC. ([d365training.com](https://www.d365training.com/post/period-close-in-d365-finance-the-close-workspace))
+
+### Odoo
+
+- No period entities at all — close is implemented as **lock dates** on the company ([Odoo 19 docs — Year-end closing](https://www.odoo.com/documentation/19.0/applications/finance/accounting/reporting/year_end.html), [Odoo forum — Lock Dates FAQ](https://www.odoo.com/forum/help-1/odoo-18-lock-dates-frequently-asked-questions-263564)):
+ - **Sales / Purchase lock dates** — module-specific soft locks
+ - **Tax lock date** — nothing affecting a filed tax return can change on/before it
+ - **Fiscal-year lock date ("everyone" / non-advisers lock date)** — regular users blocked; Adviser-group users may still post
+ - **Hard lock date** — irreversible, for statutory inalterability regimes; cannot be overridden by any role
+- Year-end is implicit like NetSuite: an unallocated-earnings auto-computation, with an optional manual entry to allocate to retained earnings.
+
+### QuickBooks (Online/Desktop)
+
+- Minimal model: a single **closing date** plus optional **closing-date password**; edits to transactions on/before the closing date prompt for the password and are logged in the **"Exceptions to Closing Date"** report (audit trail of post-close changes). Only admins set/change the date. ([Intuit — Close your books](https://quickbooks.intuit.com/learn-support/en-us/help-article/close-books/close-books-quickbooks-online/L59LelyPM_US_en_US), [Intuit — Edit closed books](https://quickbooks.intuit.com/learn-support/en-us/help-article/customer-company-settings/edit-closed-books/L76xHuaZ5_US_en_US))
+- Demonstrates the floor: even the simplest system pairs the lock with a *bypass mechanism + exception report*, not an absolute block.
+
+---
+
+## 4. Synthesis / Recommendations for a modern mid-market manufacturing ERP
+
+### 4.1 Terminology to adopt
+
+| Concept | Recommended term | Why |
+|---|---|---|
+| Period record | **Accounting Period** (a.k.a. fiscal period) | NetSuite/D365 standard; avoids confusion with MRP "planning periods" |
+| Container | **Fiscal Year** with generated periods | universal |
+| Status while posting allowed | **Open** | universal |
+| Subledger-restricted state | **Locked** (per ledger: AR / AP / Inventory / Payroll / All) | NetSuite's term; "soft close" as the colloquial description |
+| Fully closed | **Closed** | universal; reversible with permission + audit |
+| Optional irreversible state | **Permanently Closed** (or Odoo-style **hard lock date**) | only if statutory inalterability is ever needed; D365/Odoo precedent |
+| Year-end adjustment window | **Adjustment Period** | NetSuite term; clearer than SAP's numeric "special periods" |
+
+Status lifecycle: `Open → Locked(subledger…) → Closed → (Reopened → …) [→ Permanently Closed]`.
+
+### 4.2 Period entity model
+
+- `fiscalYear` (companyId, start/end, calendar type) → `accountingPeriod` rows generated from a **fiscal calendar** (calendar-month first; design the generator so 4-4-5/4-week and 52/53-week calendars are a data question, not a schema question — NetSuite precedent).
+- Period record: `id, companyId, fiscalYearId, number, startDate, endDate, status, arLocked, apLocked, inventoryLocked, isAdjustmentPeriod, closedAt, closedBy, reopenedAt/By (history table better)`.
+- Support NetSuite-style **one-day adjustment periods** at year-end rather than SAP's periods 13–16 — same purpose (multiple statement versions: pre-audit / post-audit), simpler model. Alternatively BC's "C-date" trick if closing entries are ever materialized.
+- Periods are **per company** (multi-tenant: companyId scoping as usual). If consolidation entities arrive later, follow D365/SAP: close per legal entity, orchestrate across entities via the checklist layer — do NOT copy NetSuite's global-close limitation.
+
+### 4.3 Soft close vs hard close
+
+Adopt the industry-consensus two-stage model:
+
+1. **Soft close = module locks.** Lock subledgers **first** (AP, AR, payroll, then inventory/WIP after costing runs settle), keeping GL open for adjustments. This is SAP account-type rows, NetSuite Lock A/R–A/P–All, D365 module access, Odoo sales/purchase lock dates — every serious ERP converges here. For manufacturing specifically, inventory close must wait for: date/period mismatch resolution, negative-inventory cleanup, and the costing queue (NetSuite tasks 4–7 map directly to a manufacturing checklist). ([Oracle docs](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1455781.html), [mayantechs.com](https://www.mayantechs.com/post/mastering-gl-and-subledger-reconciliation-in-epicor-kinetic))
+2. **Hard close = period status Closed.** Blocks all GL-impacting postings; only reachable after subledger locks and checklist completion.
+
+Ordering rule: **subledgers → inventory/costing → FX revaluation → intercompany/eliminations → GL close** (NetSuite's checklist order is the best public template).
+
+### 4.4 Close checklist / orchestration
+
+- Model the close as a **per-period task list** (template → instance), NetSuite-style, with:
+ - task **dependencies** (task locked until prerequisites complete — e.g., eliminations require FX revaluation),
+ - **assignments and status** (Not Started / In Progress / Complete) per task — the SAP AFC / D365 close-workspace pattern,
+ - a mix of **system tasks** (lock AR = one click that flips a flag and validates) and **manual/review tasks** (reconcile inventory to GL).
+- Some tasks are conditional on enabled features (multicurrency → revaluation; multi-entity → eliminations) — NetSuite handles this by hiding inapplicable tasks; do the same.
+- Enforce **sequential close** (cannot close period N until N−1 closed) — NetSuite rule; prevents opening-balance ambiguity.
+
+### 4.5 Year-end handling
+
+**Recommend the implicit / virtual close (NetSuite/Odoo model), not explicit closing entries:**
+- Retained Earnings is a **system account**; reports compute it as prior-years' cumulative net income at read time. No income-summary journals to generate, reverse, or desynchronize.
+- Closing the last period of the fiscal year *is* the year-end close — no separate batch job.
+- If materialized opening balances are ever needed for performance, copy SAP's **self-healing carryforward**: period-0 balance rows per account that are *automatically updated* when a prior-year posting occurs ([SAP Community](https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/s-4hana-finance-balance-carryforward-technical-tip/ba-p/13367327)) — never a one-shot job that goes stale (BC's re-run-the-batch-job model is a known footgun).
+- Keep the door open for an optional "materialize closing journals" feature (NetSuite Period End Journals) for statutory jurisdictions, but don't build it first.
+
+### 4.6 Reopening rules and audit trail
+
+- **Closed is reversible** with a dedicated permission; **reopening period N reopens nothing silently** — either block if later periods are closed, or (NetSuite model) cascade-reopen all later periods explicitly and tell the user. Cascading is more honest than allowing an island of closed-after-open.
+- Every status transition (lock/unlock/close/reopen) writes an **audit record**: who, when, prior status, reason (free text). QuickBooks' "Exceptions to Closing Date" report is the minimum bar: any bypass posting into a locked period must be queryable.
+- Consider a NetSuite-style **"allow non-GL changes"** flag so operational edits (memos, references, shipment status) don't force a reopen.
+
+### 4.7 Role-based exceptions
+
+Two-tier override, combining the best of each system:
+- Permission **`accounting.postToLockedPeriod`** (NetSuite "Override Period Restrictions" / SAP authorization group / Odoo adviser lock): may post to a **Locked** period; postings are flagged in the audit trail.
+- **Closed** periods reject postings from everyone through the normal API; reopening (permission `accounting.reopenPeriod`) is required — this keeps "who changed a closed month" answerable from the reopen log alone.
+- Do not implement per-user date ranges (BC User Setup) — period-status + permission is cleaner and matches the rest of the recommended model.
+
+### 4.8 Posting validation enforcement
+
+- **Validate at journal creation time, server-side, in one choke point** (the journal-insert service / a DB trigger or RPC): given `postingDate` (or explicit `accountingPeriodId`) + source module + user permissions →
+ 1. resolve the period (reject if none exists — force calendar generation ahead of time),
+ 2. reject if period **Closed** (no override),
+ 3. reject if the relevant **module lock** (AR/AP/inventory) is set, unless caller has the override permission (then log),
+ 4. reject if period **Open** but date outside period bounds when a period id is passed (NetSuite's date/period mismatch — better to prevent than to reconcile at close).
+- Every posting flow (invoices, receipts, cost postings, manual journals, background jobs) must go through this single validation — NetSuite's lesson is that locks are only trustworthy because *every* GL-impacting save checks them; SAP's is that the check must know *which subledger* the posting comes from.
+
+### 4.9 Manufacturing-specific checklist content (starter template)
+
+1. Lock AP · 2. Lock AR · 3. Resolve date/period mismatches · 4. Review negative inventory · 5. Verify costing/GL-posting queue drained (WIP, variances, overhead absorption) · 6. Reconcile inventory & WIP subledger to GL control accounts · 7. Lock inventory · 8. FX revaluation (if multicurrency) · 9. Intercompany adjustments/eliminations (if multi-entity) · 10. Review GL / post accruals · 11. Close period.
+
+---
+
+## Source index
+
+- SAP OB52 / PPV: https://www.saponlinetutorials.com/define-variant-for-open-and-close-posting-periods-sap-ob52/ · https://sapsharks.com/ob52-open-and-close-fi-posting-periods/ · https://www.learntosap.com/ficotutorialopenandcloseperiod.html · https://community.sap.com/t5/enterprise-resource-planning-q-a/open-and-close-posting-period-ob52/qaq-p/3980255 · https://help.sap.com/docs/SUPPORT_CONTENT/fiaccounting/3361878788.html
+- SAP FCC / AFC / carryforward: https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/8b1d76cd5e7644caa0553fcf338f3982/3fe49e8767d648a6b1b5edeec8849b8d.html · https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/s-4hana-finance-balance-carryforward-technical-tip/ba-p/13367327 · https://www.ibm.com/think/insights/advanced-financial-closing-and-sap-s4hana · https://blog.sap-press.com/improving-financial-close-with-sap-s/4hana-finance-tools
+- NetSuite: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1455781.html · https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1452509.html · https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1451780.html · https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1445839.html · https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1457543.html · https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1457773.html · https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1531269686.html · https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1498385.html · https://scalenorth.com/insights/netsuite-close-accounting-period · https://technologyblog.rsmus.com/technologies/netsuite/month-end-and-year-end-processing-in-netsuite/
+- Business Central: https://learn.microsoft.com/en-us/dynamics365/business-central/year-close-income-statement · https://www.kristenhosman.com/2024/04/working-with-posting-dates-in-microsoft.html · https://erpsoftwareblog.com/2022/09/how-to-run-the-close-income-statement-in-microsoft-dynamics-365-business-central/ · https://erpconnectconsulting.com/blogs/blog/closing-the-fiscal-year-in-dynamics-365-business-central
+- D365 Finance: https://www.cittros.com/insights/close-a-period-for-posting-in-d365-finance · https://arcticit.com/how-to-specify-which-users-can-post-to-a-period-in-dynamics-365-finance/ · https://www.d365training.com/post/period-close-in-d365-finance-the-close-workspace
+- Odoo: https://www.odoo.com/documentation/19.0/applications/finance/accounting/reporting/year_end.html · https://www.odoo.com/forum/help-1/odoo-18-lock-dates-frequently-asked-questions-263564
+- QuickBooks: https://quickbooks.intuit.com/learn-support/en-us/help-article/close-books/close-books-quickbooks-online/L59LelyPM_US_en_US · https://quickbooks.intuit.com/learn-support/en-us/help-article/customer-company-settings/edit-closed-books/L76xHuaZ5_US_en_US
+- Close ordering best practices: https://www.dualentry.com/blog/general-ledger-vs-subledger · https://www.mayantechs.com/post/mastering-gl-and-subledger-reconciliation-in-epicor-kinetic · https://insightsoftware.com/blog/navigating-the-maze-of-the-subledger-close-cycle/
diff --git a/.ai/research/plaid-bank-feeds.md b/.ai/research/plaid-bank-feeds.md
new file mode 100644
index 0000000000..e7f8f9774c
--- /dev/null
+++ b/.ai/research/plaid-bank-feeds.md
@@ -0,0 +1,61 @@
+# Plaid Bank Feeds — Research Notes (Bank Reconciliation Phase 2)
+
+> Date: 2026-07-02 · Feeds spec: `.ai/specs/2026-07-02-plaid-bank-feeds.md`
+> Builds on `.ai/research/bank-reconciliation.md` (Part 2 had Plaid facts from model knowledge only — the deep-research verification pass died at a usage limit). This file re-verifies the load-bearing Plaid mechanics directly against plaid.com/docs (fetched 2026-07-02).
+
+## Verified Plaid API facts
+
+### /transactions/sync — [docs](https://plaid.com/docs/api/products/transactions/)
+
+- First call: cursor null/empty → response carries `next_cursor`; subsequent calls pass it. Cursor is ≤256 chars base64, **valid ≥1 year after the final pagination page**.
+- Response: `added` / `modified` / `removed` arrays + `has_more`; loop with `next_cursor` until `has_more = false`.
+- **`TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION`**: if the Item's data mutates mid-pagination, the **entire loop must restart from the first cursor of the update** — not just the failed page. ⇒ Persist the cursor only after a *complete* loop; buffer pages in memory (or staging) until then.
+- Pending: `pending: true` rows; posted rows carry `pending_transaction_id` linking back; the pending row later appears in `removed`. Pending details may change before settlement.
+- **Amount sign: positive = money OUT of the account** (debit purchases positive; deposits negative) — invert at ingest for Carbon's positive-=-inflow convention.
+- `transactions.days_requested`: default **90**, range 1–730 (**production minimum 30**), and **cannot be changed after the Transactions product is active on the Item** — the backfill window is fixed at link time.
+
+### Webhook verification — [docs](https://plaid.com/docs/api/webhooks/webhook-verification/)
+
+- JWT arrives in the **`Plaid-Verification`** header (treat header name case-insensitively). `alg` MUST be `ES256` — reject anything else.
+- Fetch the public key from **`/webhook_verification_key/get`** using the JWT header's `kid`; cache keys by `kid`.
+- Validate the body via the JWT claim **`request_body_sha256`** against a SHA-256 of the *raw* body using a **constant-time comparison**; reject webhooks with `iat` **older than 5 minutes** (replay protection).
+
+### Transactions webhooks — [docs](https://plaid.com/docs/transactions/webhooks/)
+
+- **`SYNC_UPDATES_AVAILABLE`** is the only webhook a /sync integration needs. Payload: `initial_update_complete` (≥30 days ready), `historical_update_complete` (full `days_requested` history ready).
+- It **only starts firing after `/transactions/sync` is called at least once on the Item** ⇒ prime each Item with an immediate sync right after token exchange.
+- Legacy webhooks (`INITIAL_UPDATE`, `HISTORICAL_UPDATE`, `DEFAULT_UPDATE`, `TRANSACTIONS_REMOVED`) still fire in some paths (e.g. `/transactions/refresh`) — ignore them; act only on `SYNC_UPDATES_AVAILABLE` + `ITEM` webhooks.
+
+### Link update mode (re-auth) — [docs](https://plaid.com/docs/link/update-mode/)
+
+- Create a link_token with the **`access_token`** param (no `products` needed); user re-authenticates in Link.
+- Triggers: **`ITEM_LOGIN_REQUIRED`** error/webhook, **`PENDING_EXPIRATION`** (consent expires within 7 days), **`PENDING_DISCONNECT`**.
+- **The access_token does not change** — no re-exchange after update mode completes.
+
+### /link/token/create — [docs](https://plaid.com/docs/api/link/)
+
+- Required: `client_name` (≤30 chars), `language`, `country_codes` (ISO-3166-1 alpha-2), `user`. `products: ["transactions"]`. Optional `webhook` URL per Item. `transactions.days_requested` set here (see above — immutable later).
+
+### Sandbox — [docs](https://plaid.com/docs/sandbox/)
+
+- Credentials `user_good` / `pass_good` at any sandbox institution.
+- **`/sandbox/public_token/create`** bypasses the Link UI entirely — ideal for automated tests.
+- **`/sandbox/item/fire_webhook`** triggers webhooks on demand (needs a reachable webhook URL).
+- **`/sandbox/item/reset_login`** forces `ITEM_LOGIN_REQUIRED` (tests the re-auth flow). Sandbox Items also auto-enter `ITEM_LOGIN_REQUIRED` 30 days after creation.
+
+## Carbon context (verified this session)
+
+- Integration framework: `packages/ee/src/index.ts` `integrations` array; per-integration `config.tsx` + `hooks.server.ts` (registered in `packages/ee/src/hooks.server.ts`); `companyIntegration` (PK (id, companyId), `metadata` JSON, `active`); OAuth/webhook route precedents `api+/integrations.xero.*` / `api+/webhook.xero.ts`; Inngest `sync-external-accounting` + `accounting-backfill` job precedents; `trigger()` mapping in `packages/lib/src/trigger.ts` + typed events in `packages/lib/src/events.ts`; env via `packages/env` `getEnv` (integration hides itself when unset).
+- **`companyIntegration.id` FKs to an `integration` registry table** — check how Xero's row is seeded (migration vs runtime upsert) and mirror for `plaid`.
+- **Vault: NOT verified.** No `vault`/`pgsodium` references anywhere in `packages/database/supabase/migrations/` or `config.toml`. The master spec's accepted decision (Plaid tokens in Supabase Vault) needs an environment probe (`SELECT 1 FROM vault.secrets LIMIT 0`) across local crbn stack, Docker deploy, and cloud before it's real. Fallback: app-layer AES-256-GCM with a `PLAID_TOKEN_ENCRYPTION_KEY` env secret, same metadata shape (`tokenCiphertext` instead of `tokenSecretId`).
+- Local-dev webhook reachability: portless `*.dev` is local-only — Plaid cannot deliver webhooks to a dev machine. Dev loop = manual "Sync now" + scheduled catch-up; webhook path testable against a deployed env (or tunnel) with `/sandbox/item/fire_webhook`.
+- Phase 1 already shipped (or ships) everything the feed lands on: `bankAccount` (plaidItemId/plaidAccountId/connectionStatus/lastSyncedAt), `bankTransaction` (externalId unique per account, `pendingExternalId`, `needsReview`, Pending status), `bankAccountBalance`, `run_bank_matching` RPC.
+
+## Design takeaways
+
+1. Cursor persistence is transactional-per-loop: never store `next_cursor` from a partial loop (mutation restart rule).
+2. Prime `/transactions/sync` immediately post-exchange or webhooks never fire.
+3. Webhook route = pure verifier + dispatcher (JWT verify, dedupe, fire Inngest event); all real work in the job — Xero webhook precedent already works this way.
+4. Backfill window is a connect-time, per-Item, irreversible choice — surface it in the connect UI (90 default / 180 / 365 / 730).
+5. Re-auth = banner → update-mode link token → done (no re-exchange, no remapping).
+6. Sandbox supports fully automated e2e (public_token/create → exchange → sync → reset_login → update mode) without a browser Link flow.
diff --git a/.ai/research/public-company-compliance.md b/.ai/research/public-company-compliance.md
new file mode 100644
index 0000000000..fca4254be1
--- /dev/null
+++ b/.ai/research/public-company-compliance.md
@@ -0,0 +1,246 @@
+# Public-Company Compliance Research: Best Practices Survey
+
+> Feeds: `.ai/specs/2026-07-03-public-company-readiness.md`
+> Date: 2026-07-03
+> Question: what must an accounting system provide for a CFO to adopt it early and keep it through IPO and beyond, as a US-listed (or dual-listed) company operating in multiple countries?
+
+## Summary
+
+We surveyed the two reference systems (SAP S/4HANA for enterprise patterns, NetSuite as the system most mid-market companies actually IPO on), the regulatory requirements themselves (SOX 404/ICFR, US GAAP standards needing system support, IFRS deltas, SEC reporting chain, multi-country statutory/e-invoicing mandates, vendor assurance), and the bolt-on ecosystem that defines what an ERP is NOT expected to build. Consensus: the load-bearing architecture decisions are (1) an immutable, complete, exportable journal population with preparer/approver metadata — one investment that satisfies SOX AS 2401, France FEC, Germany GoBD, and SAF-T simultaneously; (2) a book/ledger dimension on every journal line for multi-GAAP parallel accounting — the single hardest thing to retrofit; (3) hard period close with permissioned locking; (4) JE approval with system-enforced no-self-approval; (5) functional-currency remeasurement vs. translation as two distinct mechanisms with CTA memory; and (6) a trading-partner stamp on intercompany lines to make eliminations automatable. Everything downstream (recs certification, SEC/XBRL, equity comp, tax provision, payroll) is deliberately left to the ecosystem — even NetSuite does not build those — provided the ERP exposes clean TB/JE extracts and a controlled JE-import surface.
+
+## Competitors Surveyed
+
+- **Oracle NetSuite (OneWorld, Multi-Book, ARM, SuiteTax)** — the system "63% of technology IPOs since 2011" ran; defines the practical mid-market bar for "hold through IPO."
+- **SAP S/4HANA (Universal Journal, Group Reporting, DRC, GRC)** — the enterprise reference for parallel ledgers, currency architecture, consolidation, and country localization.
+- **Regulatory sources** — PCAOB AS 2201/2401 practice, ASC 606/842/718/740/830/280/330/805, IFRS 15/16, IAS 2/16/21, SEC iXBRL rules, EU ViDA + country e-invoicing/SAF-T/FEC/GoBD/MTD regimes, SOC 1/SOC 2/ISO 27001 expectations of a SaaS accounting vendor.
+- **Ecosystem** — BlackLine/FloQast, Workiva, Carta/Shareworks, OneSource/Corptax, Avalara/Vertex, Fastpath/Strongpoint (see §Ecosystem below).
+
+## Key Consensus Patterns
+
+### 1. One immutable journal population is the compliance keystone
+
+- **SAP**: posted documents are immutable; corrections are reversal documents only; master-data changes tracked as change documents (CDHDR/CDPOS, old value → new value); gapless document numbering per company code + fiscal year is a legal requirement in many jurisdictions.
+- **NetSuite**: System Notes capture field-level before/after with user, role, timestamp, and context (UI vs. script vs. web services); GL Audit Numbering assigns a gapless sequence to posted entries as a close task; the JE population is exported via saved search for auditor testing and treated as IPE.
+- **Regulatory**: AS 2401 JE testing requires the complete population with preparer, approver, created/posted timestamps, source, reconcilable to opening and closing trial balances. France FEC prescribes an 18-field flat export of every entry, validated for sequential completeness, delivered within 15 days of an audit notice. Germany GoBD requires "Unveränderbarkeit" (unalterability) with machine-analyzable data access. SAF-T countries (PT/PL/NO/RO) require the same data as standardized XML.
+- **Rationale**: one schema investment — append-only posted journals, reversal-only correction, preparer/approver/timestamps on every entry, gapless numbering, flat full-population export — satisfies four regimes at once.
+
+### 2. Multi-GAAP = a ledger/book dimension on every journal line
+
+- **SAP**: ledger approach — leading ledger 0L + non-leading ledgers per accounting principle (IFRS/local GAAP/tax); ACDOCA's primary key includes the ledger; ordinary postings fan out to all ledgers, valuation postings target a ledger group; extension ledgers store deltas only. Asset accounting: one depreciation area per valuation, each posting to its ledger in real time.
+- **NetSuite**: Multi-Book Accounting — primary book + secondary books with book-specific COA mappings, calendars, base currencies, rev-rec and depreciation rules; Adjustment-Only Books as the lightweight delta variant.
+- **Regulatory**: every foreign subsidiary files statutory accounts under local GAAP while the group consolidates under US GAAP (or IFRS); IFRS 16 vs ASC 842 alone forces the same lease to produce different P&L per book; IAS 2 requires NRV write-down reversals US GAAP forbids. Bolting a book dimension on later is one of the most expensive ERP retrofits.
+- **Rationale**: model "book/ledger" as a first-class posting dimension from the start, even if v1 ships with exactly one book per company. An adjustment-only (delta) book is the pragmatic first parallel book.
+
+### 3. Hard close is a state machine with permissions, not a date check
+
+- **SAP**: posting period variants — open/close intervals per account type (GL/AR/AP/assets/materials) with an authorization group so only designated users post during the closing window; special periods 13–16 layer audit/tax adjustments on period 12 without reopening operations.
+- **NetSuite**: Period Close Checklist with ordered tasks (Lock A/R → Lock A/P → Lock All → eliminations → FX revaluation → rev rec → GL audit numbering → consolidated rates → Close); *locked* (overridable with the Override Period Restrictions permission) vs *closed* (immutable until explicit reopen) are distinct states; reopening cascades — all later closed periods reopen and the checklist redoes.
+- **Regulatory**: auditors test who can post to closed periods and whether close/reopen is permissioned and logged; 10-K/Q deadlines (60/40-day regime as an accelerated filer) require a repeatable 5–10 business-day hard close.
+- **Rationale**: period status must be enforced at the posting engine (DB/edge layer), never only in app code; locked-vs-closed distinction plus a permissioned override is the industry contract; close itself is a checklist entity with owners, dependencies, and evidence.
+
+### 4. JE approval: parked → approved → posted, no self-approval
+
+- **SAP**: Verify General Journal Entries workflow — manual journals park until routed approval (amount/company/account criteria, multi-level); requester ≠ approver enforced; tolerance groups additionally cap posting amounts per user group.
+- **NetSuite**: native JE approval routing or SuiteFlow (up to 3 levels, Pending Approval → Approved before posting), covering JEs, intercompany JEs, statistical journals.
+- **Regulatory**: auditors specifically test whether submitter and approver credentials are the same person and the time gap between them; manual and top-side entries are the mandatory fraud-testing population; system-enforced preparer ≠ approver is the cheapest "IPO-ready" differentiator.
+- **Rationale**: approval must be a posting-state gate in the engine, with amount/account routing, and the system — not policy — blocks self-approval.
+
+### 5. FX: remeasurement and translation are two different machines
+
+- **SAP**: parallel currency amounts (document/local/group) stored on every line at posting time; FAGL_FCV revalues open items and FX balances per valuation area (per ledger) with auto-reverse or delta logic = ASC 830 remeasurement; FAGL_FC_TRANS translates balances for consolidation = translation; Group Reporting posts CTA to dedicated FS items in OCI using per-item translation keys (closing/average/historical).
+- **NetSuite**: subsidiary base (functional) currency immutable once posted; Consolidated Exchange Rates table with Current/Average/Historical rate types, each account tagged with a general rate type and a cash-flow rate type; "Revalue Open Foreign Currency Balances" is a standard close task (unrealized G/L); CTA is a system account posted automatically during consolidation.
+- **Regulatory**: ASC 830/IAS 21 — functional currency per entity; remeasurement gains/losses in net income; translation plug to CTA in OCI; historical-rate memory on equity and non-monetary accounts; CTA rollforward disclosure.
+- **Rationale**: store transaction + base (+ group) amounts per line at posting; run period-end unrealized revaluation of open AR/AP/bank as a close task posting reversible entries; keep consolidation translation separate, driven by per-account rate types, with CTA posted (not a display-time plug) so it rolls forward.
+
+### 6. Intercompany: stamp the partner at entry; eliminate on a dedicated entity
+
+- **SAP**: trading partner stamped on original postings enables automated two-sided eliminations (IC AR/AP, revenue/COGS); ICMR matches continuously during the period; consolidation of investments computes goodwill and NCI from ownership percentages.
+- **NetSuite**: intercompany framework — paired IC customer/vendor records, IC JEs with per-subsidiary balancing and auto due-to/due-from, "Eliminate" line flag, elimination subsidiaries per parent node, netting workbench and settlements.
+- **Rationale**: Carbon already has the right skeleton (partner ID on journal lines, elimination entities, matching RPC). The consensus additions: tolerance-based matching (not exact-amount), FX-difference handling on IC pairs, document-level mirroring (IC PO↔SO), netting, and ownership percentages for NCI when below-100% subsidiaries appear.
+
+### 7. Tax is an engine with jurisdictions, codes, and a liability account — never a flat percent
+
+- **SAP**: per-country tax calculation procedures (condition schemas), 2-char tax codes binding rates + GL accounts, US jurisdiction codes, external-engine mode (TAXUSX → Vertex/Avalara).
+- **NetSuite**: SuiteTax — nexus determination per subsidiary registration, line-level rules, per-nexus pluggable third-party engines, exemption certificates.
+- **Regulatory**: VAT place-of-supply/reverse-charge/zero-rating logic, multiple concurrent registrations per entity, VAT returns + EC Sales Lists + Intrastat, withholding tax with treaty rates; output/input tax must post to dedicated liability/receivable accounts to be reportable.
+- **Rationale**: minimum viable structure is taxCode → rates by jurisdiction + validity date, posting to dedicated tax payable/receivable accounts, an external-engine escape hatch for US sales tax, and returns as extracts per registration.
+
+### 8. E-invoicing/statutory is an adapter framework with a submission state machine
+
+- **SAP**: Document and Reporting Compliance — one framework generating legal formats (FatturaPA, CFDI, PEPPOL, SAF-T, FEC, VAT returns) with a per-document submission monitor (55+ countries).
+- **Regulatory timeline pressure**: France issue-mandate Sept 2026 (SMEs 2027); Poland KSeF Feb/Apr 2026; Germany receive since 2025, issue 2027–28; EU ViDA intra-EU DRR July 2030; Italy/Mexico/Brazil/India clearance models already mandatory. Peppol BIS 3.0 / EN 16931 is the safest architectural bet. Gapless legal invoice series per country, rectification-only corrections, digital signatures where mandated, 7–10+ year retention.
+- **Rationale**: the ERP must generate structured invoices per country format, track clearance status (submitted/accepted/rejected/corrected), receive structured supplier invoices, and enforce legal numbering series — typically via a middleware partner (Avalara/Sovos/Pagero) behind one internal adapter interface.
+
+## Answers to Research Questions
+
+1. **What gates "IPO-ready" claims for the ERP itself?** (NetSuite research) — complete JE population export with preparer/approver/timestamps; System-Notes-grade field-level audit trail; gapless GL numbering; JE approval with no self-approval; period close discipline with restricted override/reopen; user-access reports for quarterly reviews; documented SoD matrix over roles; and the vendor's own SOC 1 Type II for ITGC reliance.
+2. **What does even the reference mid-market system NOT build?** — reconciliation certification workbooks (BlackLine/FloQast), SEC drafting/iXBRL (Workiva/DFIN), cap table & ASC 718 expense (Carta/Shareworks), ASC 740 provision (OneSource/Corptax/Bloomberg), US sales-tax rate content and filing (Avalara/Vertex), preventive SoD analysis (Fastpath/Strongpoint), payroll. The ERP's obligation is clean feeds: TB by entity/period/book via API, full JE export, controlled JE import with approval, tax-calc hooks at invoice time.
+3. **How do the references structure multi-entity?** — subsidiary tree with per-entity immutable functional currency; elimination entities per parent node; consolidation = translate (per-account rate types) → eliminate (partner-stamped) → CTA posted; NCI/goodwill only when ownership < 100% enters the picture (SAP C/I; NetSuite does 100% summation like Carbon — NCI is an SAP-tier feature).
+4. **How is period close controlled?** — two-state locked/closed with permissioned override, cascade-on-reopen, ordered close checklist with the FX-revaluation/eliminations/rev-rec/consolidated-rates tasks in it; SAP adds per-account-type windows and special adjustment periods.
+5. **What must the system produce per US GAAP standard?** — 606: performance obligations, SSP allocation, rec schedules, contract asset/liability rollforwards, RPO disclosure; 842/IFRS 16: ROU/liability amortization schedules per book, maturity analysis; 718: import surface for grant-level expense JEs by entity/cost center; 740: TB mapped by legal entity + jurisdiction, book-tax difference detail, taxes paid by jurisdiction (ASU 2023-09); 830: functional currency, remeasurement vs translation, CTA rollforward; 280 (ASU 2023-07): segment dimension incl. significant expense categories, even for single-segment filers; 330: absorption costing, LCNRV write-downs (no reversal under GAAP, reversal required under IAS 2 — book-dependent); 805: fair-value opening balance sheets and measurement-period adjustments.
+6. **What vendor-level assurance is required?** — SOC 1 Type II is non-negotiable (customers' auditors rely on it; without it every customer takes a control gap); SOC 2 Type II and ISO 27001 for procurement; product certification of invoicing in some countries (Portugal AT, France PDP accreditation).
+
+## Ecosystem: Build-vs-Integrate Boundary
+
+**The modern mid-market GL baseline (Sage Intacct / D365 Finance):** dimension-tagged GL (thin COA + ~8 standard dimensions + user-defined) instead of segment-coded accounts; multi-entity with automated due-to/due-from and continuous consolidation incl. auto-eliminations into an elimination entity; automated ASC 830 CTA on shared non-closing equity accounts (Intacct Global Consolidations); multi-book (Intacct: cash/accrual + unlimited user-defined books; D365: 10 posting layers); close workspace with checklists/owners/dependencies and per-module period locking; allocations engine; rev-rec module with SSP allocation and contract-modification recalc. Carbon's dimension-based journal design is already on the right (Intacct-style) side of this divide.
+
+**Market timing:** companies graduate from QuickBooks/Xero at roughly $5–30M revenue / Series B–C, triggered by multi-entity consolidation (the #1 trigger), rev-rec shadow spreadsheets, first audit/diligence, and inventory complexity — Carbon's manufacturing customers hit the inventory trigger earliest. Companies almost never leave NetSuite below ~$500M revenue; they IPO on it and surround it with bolt-ons. Systems must be in place 9–12 months pre-IPO (83% of IPO companies had scalable ERP deployed ≥1 year prior). AI-native GL competitors (Campfire, Rillet, Light, Puzzle — each $40M–$100M+ raised in 2025) all compete on exactly this: modern multi-entity GL + automated rev rec + AI close, with SOC 1/SOC 2 Type II as table stakes; none has manufacturing depth, which is Carbon's wedge.
+
+**ERP-native (Carbon must build):** GL/multi-book, consolidation + eliminations + CTA, period close controls, JE approval/audit trail, AR/AP with payment controls, fixed assets + leases (leases increasingly ERP-native at mid-market), indirect-tax posting structure, deferred revenue/rev-rec schedules, inventory valuation incl. LCNRV, statutory export surfaces (SAF-T/FEC/JE population), dimensions/segments, flux-capable comparative reporting.
+
+**Ecosystem (Carbon integrates, never builds):** reconciliation certification & close orchestration evidence (BlackLine/FloQast — though a native close checklist is expected), SEC/iXBRL (Workiva), equity/718 (Carta), tax provision/740 (OneSource et al.), US sales-tax content/filing (Avalara/Vertex — Carbon builds the hooks), AP payment execution rails (Tipalti/bill.com or bank files), payroll (providers post summarized JEs), FP&A (Adaptive/Pigment), expense (Ramp/Brex).
+
+**Integration surfaces the ERP must expose:** per-entity/period/book trial balance API; full JE-line export (flat, no row caps); controlled JE import API that respects approval workflow and period status (this is how Carta/payroll/provision adjustments land); tax-calculation hook at document pricing/posting time; webhook/event stream for close-status and posting events.
+
+## Competitor-Specific Details
+
+### NetSuite
+Subsidiary cap 250; elimination subsidiaries excluded from cap; CTA a system account; Consolidated Exchange Rates auto-calculated as a close task; Multi-Book provisioned by professional services (i.e., hard to retrofit even for them); SuiteTax enablement irreversible; "Allow Non-G/L Changes" period flag lets memo-level edits in closed periods without GL impact — a nice controlled-flexibility pattern; intercompany netting via a workbench generating paired settlements.
+
+### SAP S/4HANA
+ACDOCA merges GL + subledger analytics so no reconciliation between them can diverge; segment derived from profit center master data (users never key segments); document splitting with zero-balancing per segment for sub-entity balance sheets; extension ledgers for delta books; firefighter break-glass access with session recording and post-hoc review; per-user tolerance groups (amount limits) orthogonal to role permissions; three-layer COA (group ↔ operating ↔ country-statutory alternative account numbers) — do NOT fork the chart per country.
+
+## Recommended Approach for Carbon
+
+1. **Journal integrity first** (SAP immutability + NetSuite System Notes): DB-level append-only posted journals, preparer/approver columns, gapless per-entity numbering, full-population export. Serves SOX + FEC + GoBD + SAF-T at once.
+2. **Hard close as a posting-engine gate** (NetSuite locked/closed states): enforce in the edge functions and RLS, not app code; close checklist entity; permissioned override + logged reopen with cascade.
+3. **JE approval state machine** (SAP parked→posted): approval rules by amount/account; system-enforced preparer ≠ approver; extend the existing approvalRule engine rather than building new.
+4. **Ledger/book dimension on journalLine now, one book per company in v1** (SAP ledger approach, NetSuite adjustment-only books as the first parallel book): schema cost is small today, enormous later.
+5. **Per-line currency memory** (SAP parallel currencies): store transaction currency + amount alongside base on journalLine; unrealized FX revaluation as a close task; post CTA rather than plugging it at display time; write the missing `exchangeRateHistory` feed.
+6. **Tax subledger** (SuiteTax-lite): taxCode/jurisdiction/rate tables, output/input tax posting to liability accounts, exemption enforcement, external-engine hook; returns as extracts.
+7. **E-invoicing adapter framework** (SAP DRC pattern via middleware partner): EN 16931/Peppol core, country adapters, clearance-status state machine, legal numbering series.
+8. **Leave to ecosystem, expose feeds**: recs certification, SEC/XBRL, equity, provision, payroll, payment rails — build the TB/JE APIs and controlled JE import instead.
+
+## Sources
+
+### NetSuite
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N278654.html (Consolidated Reporting in OneWorld)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1405625.html (Consolidated Exchange Rate Types)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1406908.html (Calculating Consolidated Exchange Rates Automatically)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N268563.html (Subsidiaries in OneWorld)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_3831567542.html (Multi-Book Accounting Overview)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_3851620232.html (Chart of Accounts Mapping)
+- https://www.netsuite.com/portal/resource/articles/accounting/multi-book-accounting.shtml (What Is Multi-Book Accounting)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_4328435538.html (Advanced Revenue Management)
+- https://timdietrich.me/blog/netsuite-revenue-recognition-arm/ (ARM data model)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1486393.html (Automated Intercompany Management)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/article_158142795285.html (Intercompany Framework)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/article_158945626309.html (Intercompany Netting)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1455781.html (Period Close Checklist)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1452509.html (Accounting Period Close)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1457543.html (Reopening a Closed Period)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1471271.html (Journal Entry Approval)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_158644279544.html (System Notes)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N557476.html (Line-Level Audit Trail)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_1543968584.html (Fixed Assets Lease Accounting)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_N2126441.html (Fixed Assets Management)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_0315035511.html (SuiteTax vs Legacy Tax)
+- https://technologyblog.rsmus.com/technologies/netsuite/system-audit-functionality-in-netsuite/ (audit functionality)
+- https://technologyblog.rsmus.com/technologies/netsuite/tax-engine-comparison/ (tax engine comparison)
+- https://www.houseblend.io/articles/netsuite-erp-ipo-readiness-guide (IPO readiness)
+- https://www.houseblend.io/articles/netsuite-public-company-compliance (public company compliance)
+- https://www.houseblend.io/articles/netsuite-sec-reporting-workiva-activedisclosure-certent (SEC bolt-ons)
+- https://www.houseblend.io/articles/asc-740-tax-provision-automation-netsuite (ASC 740 gap)
+- https://nuagecg.com/blog/netsuite-sox-compliance-guide/ (SOX guide)
+- https://nuagecg.com/blog/the-netsuite-access-controls-checklist-your-auditor-actually-wants-to-see (access reviews)
+- https://mysuite.tech/blog/netsuite-segregation-of-duties (native SoD limits)
+- https://netwrix.com/en/resources/blog/netsuite-segregation-of-duties/ (SoD)
+- https://www.gofastpath.com/blog/how-to-manage-segregation-of-duties-in-your-netsuite-environment (SoD bolt-ons)
+- https://www.blackline.com/erp-integration/netsuite-integration/ (BlackLine + NetSuite)
+- https://www.ledge.co/content/the-hidden-gaps-in-netsuite-floqast-and-blackline-how-weve-built-ledge-to-solve-them (close-execution gap)
+- https://www.netsuite.com/portal/products/erp/epm.shtml (NetSuite EPM)
+- https://carta.com/equity-management/cap-table/financial-reporting/ (ASC 718 via Carta)
+- https://plative.com/netsuite-for-ipo-success/ (IPO adoption statistics)
+- https://www.mgocpa.com/perspective/how-to-elevate-your-companys-ipe-documentation-to-optimize-sox-compliance/ (IPE documentation)
+
+### SAP S/4HANA
+- https://blog.sap-press.com/what-is-saps-universal-journal (Universal Journal)
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/understanding-the-universal-journal-in-sap-s-4hana/ba-p/13345726
+- https://help.sap.com/docs/SAP_ERP/17ec785ed2294431b933daf9a926af80/4911c9cc2a934a18e10000000a42189b.html (Document Splitting)
+- https://help.sap.com/docs/SAP_ERP/17ec785ed2294431b933daf9a926af80/6b63c7531dc61d4be10000000a174cb4.html (Segment)
+- https://www.iasplus.com/en/standards/ifrs/ifrs8 (IFRS 8)
+- https://blogs.sap.com/2020/10/23/parallel-accounting-account-based-approach-ledger-based-approach-configuration-steps/ (Parallel accounting)
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/in-depth-with-sap-s-4hana-ledger-scoping-q-amp-a/ba-p/13571167 (Ledger scoping)
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/67e323b7117e4c91869c258933f47182/dd214452ab903607e10000000a441470.html (Ledger Approach in Asset Accounting)
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/sap-s-4hana-currency-setup/ba-p/13379639 (Currency setup)
+- https://blog.sap-press.com/defining-currency-types-for-the-general-ledger-in-sap-s4hana (Currency types)
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/651d8af3ea974ad1a4d74449122c620e/8450d7531a4d424de10000000a174cb4.html (Foreign Currency Valuation)
+- https://help.sap.com/docs/SUPPORT_CONTENT/fiaccounting/3361878651.html (FAGL_FC_VAL Delta Logic)
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/fagl-fc-trans-vs-fagl-fc-val/qaq-p/11438393 (Translation vs valuation)
+- https://blog.sap-press.com/what-is-currency-translation-in-sap-s4hana (Group Reporting currency translation)
+- https://eursap.eu/blog/sap-group-reporting-currency-translation-backbone-of-sap-group-reporting (CTA)
+- https://learning.sap.com/learning-journeys/performing-consolidation-with-sap-s-4hana-cloud-for-group-reporting/consolidating-investments_de91a380-d9a9-4781-9adc-43faee325dc4 (Consolidation of investments, NCI)
+- https://sapsharks.com/ob52-open-and-close-fi-posting-periods/ (OB52 posting periods)
+- https://learning.sap.com/courses/customizing-core-settings-in-financial-accounting-in-sap-s4hana/managing-posting-periods (Posting periods)
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/8b1d76cd5e7644caa0553fcf338f3982/3fe49e8767d648a6b1b5edeec8849b8d.html (Financial Closing cockpit)
+- https://blogs.sap.com/2022/03/01/sap-s-4hana-cloud-for-advanced-financial-closing-enhanced-task-list-management/ (AFC)
+- https://pathlock.com/blog/sap-grc/sap-access-control/ (GRC Access Control)
+- https://learning.sap.com/learning-journeys/discovering-the-main-functionalities-of-sap-access-control/building-a-rule-set_b02d61c0-e8aa-48ed-81ae-ea65d320798e (SoD rulesets)
+- https://blogs.sap.com/2020/03/15/verify-general-journal-entries-configuring-the-workflow-in-s-4hana-1909/ (JE verification workflow)
+- https://www.learntosap.com/SAP-CDHDR-CDPOS-Tables.html (Change documents)
+- https://www.stechies.com/types-of-tolerance-groups-in-fi/ (Tolerance groups)
+- https://learning.sap.com/learning-journeys/implementing-record-to-report-in-sap-s-4hana/identifying-the-chart-of-accounts-types (COA types)
+- https://userapps.support.sap.com/sap/support/knowledge/en/3405359 (Local COA)
+- https://blog.sap-press.com/enterprise-structure-elements-for-taxes-within-sap-s4hana (Tax procedures)
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/8999cee59b7c44fdb53fbbb4d703f8e6/44bed153e8b34208e10000000a174cb4.html (Tax jurisdiction)
+- https://blog.sap-press.com/what-is-sap-document-and-reporting-compliance-sap-drc (DRC)
+- https://www.pikon.com/en/blog/statutory-reporting-sap-s4hana-document-and-reporting-compliance/ (DRC statutory)
+
+### Regulatory
+- https://www.gaapdynamics.com/auditing-fraud-risk-journal-entry-testing/ (AS 2401 JE testing)
+- https://www.bakertilly.com/insights/successfully-navigating-sox-404b (SOX 404(b))
+- https://compliancestack.ai/guides/sox-section-404-testing (SOX testing)
+- https://www.sailpoint.com/identity-library/it-general-controls (ITGC)
+- https://support.auditsight.com/hc/en-us/articles/32044532144909-Journal-Entry-Testing-FAQs (JE extracts)
+- https://greenskiesanalytics.com/the-complete-list-of-je-tests/ (JE analytics)
+- https://arch.bdo.com/revenue-recognition-under-asc-606 (ASC 606)
+- https://finquery.com/blog/asc-842-summary-new-lease-accounting-standards/ (ASC 842)
+- https://pro.bloombergtax.com/insights/provision/asc-740-stock-based-compensation/ (740/718 interplay)
+- https://www.bdo.com/insights/tax/improve-transparency-under-asc-740-new-income-tax-disclosures-asu-2023-09 (ASU 2023-09)
+- https://www.equitymethods.com/articles/impact-of-asu-2023-07-on-segment-reporting-for-equity-compensation/ (ASU 2023-07)
+- https://www.gaapdynamics.com/overview-of-foreign-currency-translation-under-asc-830/ (ASC 830)
+- https://viewpoint.pwc.com/dt/us/en/pwc/accounting_guides/foreign_currency/foreign_currency__2_US/chapter_1_framework__US/13_framework_for_the_US.html (PwC FX framework)
+- https://www.houseblend.io/articles/asc-330-inventory-valuation-write-downs (ASC 330 / LCNRV)
+- https://kpmg.com/us/en/articles/2023/ifrs-vs-us-gaap-component-approach.html (IAS 16 components)
+- https://www.wallstreetprep.com/knowledge/us-gaap-vs-ifrs-differences-similarities-examples-pdf-cheat-sheet/ (GAAP vs IFRS)
+- https://www.mayerbrown.com/-/media/files/perspectives-events/publications/2025/12/2026-sec-filing-deadlines-and-financial-statement-staleness-dates.pdf (SEC deadlines)
+- https://www.sec.gov/divisions/corpfin/guidance/interactivedatainterp (iXBRL)
+- https://www.law.cornell.edu/cfr/text/17/240.13a-15 (disclosure controls)
+- https://www.workiva.com/solutions/financial-close-reporting (Workiva model)
+- https://www.e-invoice.app/blog/global-e-invoicing-compliance-2026 (e-invoicing mandates)
+- https://www.fiskaly.com/blog/e-invoicing-mandates-in-europe-2026 (EU mandates)
+- https://tradeshift.com/resources/compliance-fr/france-e-invoicing-update-2026-tradeshift-pa-multinationals/ (France 2026)
+- https://ecosio.com/en/blog/germany-e-invoicing-explained/ (Germany)
+- https://taxation-customs.ec.europa.eu/taxation/vat/vat-digital-age-vida_en (ViDA)
+- https://www.vatupdate.com/2025/05/18/briefing-document-saf-t-implementation-across-europe/ (SAF-T)
+- https://invoicedataextraction.com/blog/france-fec-fichier-ecritures-comptables (FEC)
+- https://www.fiskaly.com/blog/understanding-gobd-compliant-archiving (GoBD)
+- https://www.avalara.com/us/en/vatlive/country-guides/europe/uk/making-tax-digital.html (UK MTD)
+- https://www.fiskaly.com/blog/fiscalization-atcud-qes-in-portugal (Portugal ATCUD/QES)
+- https://linfordco.com/blog/what-is-soc-1-report/ (SOC 1)
+- https://www.dsalta.com/resources/soc-2/sox-compliance-saas-vendors-guide-2026 (SaaS vendor SOX)
+- https://www.a-lign.com/articles/what-is-soc-2-complete-guide (SOC 2)
+
+### Ecosystem / mid-market baseline
+- https://www.sage.com/en-us/sage-business-cloud/intacct/product-capabilities/extended-capabilities/financial-reporting/multi-dimensional-system/ (Intacct dimensions)
+- https://www.sage.com/en-us/sage-business-cloud/intacct/product-capabilities/core-financials/multi-entity/ (Intacct multi-entity)
+- https://www.intacct.com/ia/docs/en_US/help_action/Consolidations/Global_Consolidations/Book_setup/CTA-accts.htm (Intacct CTA accounts)
+- https://www.claconnect.com/en/resources/blogs/sage/sage-intaccts-multi-book-architecture (Intacct multi-book)
+- https://learn.microsoft.com/en-us/dynamics365/finance/general-ledger/financial-dimensions (D365 dimensions)
+- https://learn.microsoft.com/en-us/dynamics365/finance/general-ledger/elimination-rules (D365 eliminations)
+- https://learn.microsoft.com/en-us/dynamics365/finance/general-ledger/financial-period-close-workspace (D365 close workspace)
+- https://www.blackline.com/products/financial-close/ (BlackLine)
+- https://www.floqast.com/integrations (FloQast ERP surface)
+- https://developer.avalara.com/erp-integration-guide/about-this-guide/core-requirements/ (Avalara ERP integration requirements)
+- https://www.glencoyne.com/guides/carta-accounting-sync (Carta JE sync)
+- https://help.tipalti.com/hc/en-us/articles/30710248001303-Synchronization (Tipalti ERP sync)
+- https://docs.ramp.com/developer-api/v1/guides/accounting (Ramp accounting API)
+- https://technologyblog.rsmus.com/netsuite/exporting-full-gl-detail-auditor/ (auditor GL extract)
+- https://quickbooks.intuit.com/learn-support/en-us/help-article/intuit-subscriptions/learn-usage-limits-quickbooks-online/L6THMltE4_US_en_US (QBO limits)
+- https://eightx.co/blog/netsuite-vs-quickbooks-when-to-graduate (graduation thresholds)
+- https://www.brokenrubik.com/blog/netsuite-vs-oracle-fusion-cloud-erp (leaving NetSuite)
+- https://www.pwc.com/us/en/industries/tmt/library/tech-ipo-readiness.html (IPO systems timing)
+- https://techcrunch.com/2025/06/30/tiny-ai-erp-startup-campfire-is-winning-so-many-startups-from-netsuite-accel-led-a-35m-series-a/ (Campfire)
+- https://www.rillet.com/product/enterprise-security (Rillet SOC posture)
+- https://light.inc/ (Light)
+- https://puzzle.io/ (Puzzle)
diff --git a/.ai/skills/README.md b/.ai/skills/README.md
index fd788d3e8d..bc3b9fdc56 100644
--- a/.ai/skills/README.md
+++ b/.ai/skills/README.md
@@ -22,7 +22,7 @@ Questions via `/grill`. `/execute` commits per task via `/check-and-commit`.
/root-cause → (/debugging-difficult-bugs if runtime evidence needed) → /fix → /check-and-commit
```
-**Supervised loop** (single scoped item, doer→gate→judge): `/conductor`.
+**Autonomous loop** (single scoped item, doer→gate→judge, no mid-loop human input, gated PR): `/conductor`.
**Advisory audit** (read-only, produces handoff plans): `/improve`.
@@ -41,7 +41,7 @@ Questions via `/grill`. `/execute` commits per task via `/check-and-commit`.
| `fix` | Minimal fix from a brief + red→green regression test | ready-to-commit change |
| `check-and-commit` | Gate suite, then commit specific files | conventional commit |
| `self-review` | Review your own branch before/at PR time | Must fix / Risks / Suggestions |
-| `conductor` | Supervised doer→gate→judge loop to a gated PR | PR + ledger |
+| `conductor` | Autonomous doer→gate→judge loop to a gated PR (no mid-loop human input) | PR + ledger |
| `improve` | Senior-advisor audit; plans for other agents to execute | `.ai/plans/improve/` |
| `test` | Drive changed flows in the browser; cache playbooks | pass/fail + `.ai/playbooks/{slug}.md` |
| `smoke-test` | Do all core modules load? | pass/fail table |
diff --git a/.ai/skills/conductor/SKILL.md b/.ai/skills/conductor/SKILL.md
index 1f7895a9a4..4b7d74f51a 100644
--- a/.ai/skills/conductor/SKILL.md
+++ b/.ai/skills/conductor/SKILL.md
@@ -1,18 +1,39 @@
---
name: conductor
-description: Supervised loop conductor — drive a single work item (a bug, a usability tweak, a small feature) through a doer→gate→judge→keep-or-revert→ledger cycle to a gated PR, while the human watches. Use when asked to "conduct", "loop on", or build/fix one tightly-scoped item with explicit acceptance criteria. Backed by @carbon/harness and the @carbon/checks gates. Supervised only — never autonomous/overnight, never auto-merged. For multi-phase features prefer /feature.
+description: Autonomous loop conductor — drive a single work item (a bug, a usability tweak, a small feature) through a doer→gate→judge→keep-or-revert→ledger cycle to a gated PR, unattended. Use when asked to "conduct", "loop on", or build/fix one tightly-scoped item with explicit acceptance criteria, and as the inner loop the outer-loop orchestrator dispatches headless. Backed by @carbon/harness and the @carbon/checks gates. Autonomous means: never call /grill or block on human input mid-loop; the gated PR is the supervision point — never auto-merged. For multi-phase features with human design gates prefer /feature.
---
-# conductor — supervised doer→gate→judge loop
+# conductor — autonomous doer→gate→judge loop
Iterate on one work item until its acceptance criteria are met and provable,
-with the human watching and giving final approval. Ship a **gated PR** — never
-merge. Architecture context: `.ai/docs/loop-system.md`; the deterministic
-helpers live in `packages/harness` (see its `AGENTS.md`).
+**without human input mid-loop** — this skill runs unattended (the outer loop
+dispatches it headless via cron; see `.ai/docs/outer-loop.md`). Human review
+happens exactly once, at the end: ship a **gated PR** — never merge.
+Architecture context: `.ai/docs/loop-system.md`; the deterministic helpers
+live in `packages/harness` (see its `AGENTS.md`).
-**Announce at start:** "Using the conductor skill — supervised loop on
+**Announce at start:** "Using the conductor skill — autonomous loop on
{work item}."
+## Autonomous decision protocol — no mid-loop questions
+
+The loop never waits on a human. Concretely:
+
+- **Never invoke `/grill`** or any interactive interview from inside a loop.
+ If a sub-skill offers a supervised question gate (e.g. spec-writing Step 5),
+ use its **autonomous mode** instead.
+- A decision that would normally go to the user is resolved in this order:
+ (1) codebase precedent, (2) the research file / competitor consensus,
+ (3) your own recommended answer. Record every such call in the ledger entry
+ (`reason`) and collect them into an **"Assumed decisions"** section of the
+ PR body — the human reviews them there, not mid-loop.
+- **BLOCKED, not guessed** — some calls are never made autonomously (the root
+ `AGENTS.md` Ask-First list): production-critical schema changes, auth/RBAC/
+ multi-tenancy changes, public contract changes, scope reductions, new
+ production dependencies. Hitting one of these → record BLOCKED in the
+ outcome with the question stated crisply, and stop. Same for a visual proof
+ the stack can't provide.
+
## Step 0: Isolated worktree off origin/main — always first
```bash
diff --git a/.ai/skills/feature/SKILL.md b/.ai/skills/feature/SKILL.md
index 1f1535781e..e299b98ac8 100644
--- a/.ai/skills/feature/SKILL.md
+++ b/.ai/skills/feature/SKILL.md
@@ -16,7 +16,7 @@ skill adds no logic of its own — each phase's rules live in its own skill.
| # | Phase | Skill | Artifact | Gate before next phase |
|---|-------|-------|----------|-------------------------|
| 1 | Research | `/research` | `.ai/research/{slug}.md` | none |
-| 2 | Design + spec | `/spec-writing` | `.ai/specs/{date}-{slug}.md` | 🛑 every Open Question resolved by the user |
+| 2 | Design + spec | `/spec-writing` | `.ai/specs/{date}-{slug}.md` | 🛑 open questions grilled with the user BEFORE the spec is written; spec final only when all are resolved |
| 3 | Plan | `/plan` | `.ai/plans/{date}-{slug}.md` | 🛑 user approves the plan |
| 4 | Build | `/execute` | commits on the feature branch | all tasks verified + committed |
| 5 | Browser verify | `/test` | pass/fail table + playbooks | every user-facing flow passes |
diff --git a/.ai/skills/grill/SKILL.md b/.ai/skills/grill/SKILL.md
index 88fcedbe37..5033723a6e 100644
--- a/.ai/skills/grill/SKILL.md
+++ b/.ai/skills/grill/SKILL.md
@@ -1,6 +1,6 @@
---
name: grill
-description: Interview the user relentlessly, one question at a time, to stress-test a plan, spec, or design until every open decision is resolved — recommended answer per question, answers cross-checked against the codebase and the @carbon/glossary domain terms, resolutions written back to the artifact as they land. Use when the user says "grill me", wants to stress-test a design or plan, or a spec's Open Questions need resolving (spec-writing Step 7 invokes this). Do not use to author the artifact itself — use /spec-writing for specs, /plan for implementation plans.
+description: Interview the user relentlessly, one question at a time, to stress-test a plan, spec, or design until every open decision is resolved — recommended answer per question, answers cross-checked against the codebase and the @carbon/glossary domain terms, resolutions written back to the artifact as they land. Use when the user says "grill me", wants to stress-test a design or plan, or a spec-in-design's open questions need resolving (spec-writing Step 5 invokes this BEFORE the spec is written). SUPERVISED ONLY — never invoke from an automated loop (conductor, headless/outer-loop runs); autonomous flows use spec-writing's autonomous mode instead. Do not use to author the artifact itself — use /spec-writing for specs, /plan for implementation plans.
---
# grill — stress-test a design by interviewing its author
@@ -10,6 +10,12 @@ open decision resolved with the human one branch at a time, each resolution
written to its canonical home, and every contradiction between the user's
answers and the codebase surfaced along the way.
+**Supervised only.** This skill exists to interview a human; there is no
+autonomous variant. Inside an automated loop (conductor, headless/outer-loop
+runs) do NOT invoke it — spec-writing's autonomous mode (recommendation-based
+resolutions recorded as `**Autonomous:**`, Ask-First territory → BLOCKED) is
+the substitute.
+
**Announce at start:** "Using the grill skill — stress-testing {target}."
## Step 1: Identify the target and its write destination
@@ -17,6 +23,7 @@ answers and the codebase surfaced along the way.
| Grilling | Questions come from | Resolutions written to |
|----------|--------------------|------------------------|
| A spec (`.ai/specs/…`) | its Open Questions section, plus anything fuzzy in Design Decisions | inline in the spec: `- [x] {Question} — **Answer:** {decision and rationale}`, plus a changelog entry when done |
+| A spec **in design** (spec-writing Step 5 — no file yet) | the question list assembled in spec-writing Step 4 | carried into the spec's Open Questions section (pre-checked, with answers) when the spec is written in Step 6 |
| A plan (`.ai/plans/…`) | ambiguous or risky tasks, missing acceptance criteria | the affected task in the plan file |
| An idea in chat (no artifact) | the whole decision tree of the idea | `.ai/runs/{YYYY-MM-DD}-grill-{slug}.md` — create it when the first decision lands |
diff --git a/.ai/skills/spec-writing/SKILL.md b/.ai/skills/spec-writing/SKILL.md
index 8f8fe39511..46d65bb71d 100644
--- a/.ai/skills/spec-writing/SKILL.md
+++ b/.ai/skills/spec-writing/SKILL.md
@@ -1,22 +1,24 @@
---
name: spec-writing
-description: Design a feature and write its spec at .ai/specs/{YYYY-MM-DD}-{slug}.md, with competitor research, explicit design decisions, and an Open Questions hard stop. Use when designing or brainstorming a new feature, a new module, a data-model change, or any change touching 3+ files or crossing modules. Do not use for small bug fixes or one-file refactors, and do not start implementation from this skill — implementation starts only after every open question is resolved.
+description: Design a feature and write its spec at .ai/specs/{YYYY-MM-DD}-{slug}.md, with competitor research and explicit design decisions. Open questions are resolved with the user BEFORE the spec is written — the interview comes first, the document second. Use when designing or brainstorming a new feature, a new module, a data-model change, or any change touching 3+ files or crossing modules. Do not use for small bug fixes or one-file refactors, and do not start implementation from this skill — implementation starts only after the spec is written with every question resolved.
---
<!-- Workflow pattern inspired by Open Mercato (MIT License)
https://github.com/open-mercato/open-mercato
Copyright (c) 2025-2026 Open Mercato contributors -->
-# spec-writing — design a feature, produce a spec, stop at open questions
+# spec-writing — research, grill the open questions, THEN write the spec
Input: a feature request. Output: a complete spec at
-`.ai/specs/{YYYY-MM-DD}-{slug}.md` whose **Open Questions section is a hard
-stop** — implementation must not start while any question is unresolved.
+`.ai/specs/{YYYY-MM-DD}-{slug}.md` written **after** every open question has
+been resolved with the user. The interview happens before the document exists,
+so the spec is written once, around real answers — not written around guesses
+and reworked after the fact.
The spec is the single design artifact. Do not write separate "design docs" in
other locations.
-**Announce at start:** "Using the spec-writing skill — designing {feature} and
-drafting the spec."
+**Announce at start:** "Using the spec-writing skill — designing {feature};
+I'll bring you the open questions before writing the spec."
## When to write a spec
@@ -58,7 +60,7 @@ Invoke `/research {feature}`. This is mandatory for ERP-domain features
invent domain logic. Findings land in `.ai/research/{slug}.md`; cite that file
from the spec.
-## Step 4: Make the design decisions
+## Step 4: Make the design decisions — and separate the questions
For each significant decision (data model shape, status lifecycle, workflow,
integration point):
@@ -66,11 +68,15 @@ integration point):
1. State the question.
2. Cite what the research found ("SAP and NetSuite both…").
3. List 2–3 options with one-line trade-offs.
-4. Pick one and say why. If you cannot pick, it is an Open Question — do not
- write "TBD" as a decision.
+4. **Decide it yourself if the research + codebase settle it** — record the
+ choice and rationale for the spec's Design Decisions table.
+5. **If you cannot settle it, it is an open question** — genuine domain
+ ambiguity, scope boundaries, data-model alternatives with real trade-offs,
+ product-positioning calls, anything where the user's answer changes what
+ you build. Do NOT pick a placeholder and move on; do NOT write "TBD".
-Run every new or modified entity through this checklist and record the answer in
-the spec's Design Decisions table:
+Run every new or modified entity through this checklist; decided rows go in the
+Design Decisions table, unsettled ones join the question list:
| # | Heuristic | Question to answer |
|---|-----------|--------------------|
@@ -82,80 +88,108 @@ the spec's Design Decisions table:
| 6 | Module layout | One `{module}.service.ts`, one `{module}.models.ts`, barrel `index.ts`? |
| 7 | Backward compatibility | Any FROZEN/STABLE surface touched (see `BACKWARD_COMPATIBILITY.md`)? What is the migration path? |
-## Step 5: Write the spec
+At least one open question is required before proceeding. Zero questions means
+you haven't thought hard enough — re-read the research and the heuristics table.
-Copy `.ai/specs/template.md` to `.ai/specs/{YYYY-MM-DD}-{slug}.md` (today's
-date, kebab-case slug) and fill every section. Rules:
+## Step 5: Grill — resolve the questions with the user BEFORE writing
-- SQL sketches use `id('prefix')`, `companyId`, composite PK, audit columns —
- never `gen_random_uuid()`.
-- Acceptance criteria must be testable: "user creates a PO with 3 lines and sees
- correct totals in the list view", not "works correctly".
-- No `{placeholders}` left in the file; mark inapplicable sections `N/A` with a
- reason.
+> 🛑 HARD STOP: the spec file is not written while any question is unresolved.
-## Step 6: Open Questions — HARD STOP
+Invoke `/grill` on the question list (protocol: `.ai/skills/grill/SKILL.md` —
+the spec doesn't exist yet, so this is its artifact-less mode; resolutions
+carry into the spec's Open Questions section when it is written in Step 6).
+Interview **one question at a time** (group max 2–3 only for single-module,
+no-schema designs). For each question:
-Populate the Open Questions section with every genuine unknown (domain
-ambiguity, scope boundaries, data-model alternatives you couldn't settle,
-performance, UX choices):
+- State the question and **why it matters** (what changes downstream).
+- Give your **recommended answer** with a one-line rationale, plus the
+ alternatives and their trade-offs.
+- Cross-check the user's answer against the codebase before accepting it — if
+ the answer contradicts something real (an existing table, a lesson in
+ `.ai/lessons.md`, a prior spec), say so and re-ask.
+- Record the resolution: `- [x] {Question} — **Answer:** {decision and rationale}`.
-```markdown
-## Open Questions
+The user may batch ("accept all recommendations") — that is their call to make,
+not yours to assume. Never resolve a question yourself to unblock work;
+resolutions come only from a human answer, a research finding, or an explicit
+documented "out of scope for v1" decision.
-> 🛑 HARD STOP: Do not proceed with implementation until these are answered.
+### Autonomous mode (automated loops — conductor, headless/outer-loop runs)
-- [ ] {Question} — {why it matters}
-```
+When this skill runs inside an automated loop with no human available, **do
+not invoke `/grill` and do not block waiting for answers.** Instead:
+
+- Resolve each question in this order: (1) codebase precedent, (2) research /
+ competitor consensus, (3) your recommended answer. Record it inline as
+ `- [x] {Question} — **Autonomous:** {answer + rationale}` so assumed
+ decisions are distinguishable from human ones at a glance.
+- Surface the full list of autonomous resolutions in the spec changelog AND in
+ the loop's "Assumed decisions" PR section — the human reviews them at the
+ PR, not mid-loop.
+- **Ask-First territory is never resolved autonomously** (root `AGENTS.md`:
+ production-critical schema, auth/RBAC/multi-tenancy, public contracts,
+ scope reductions, new production dependencies). A question in that
+ territory → the loop goes BLOCKED with the question stated crisply.
-Rules:
+## Step 6: Write the spec
-- At least one open question is required. Zero questions means you haven't
- thought hard enough — re-read the research and the heuristics table.
-- Never resolve questions yourself to unblock work. They are resolved only by a
- human answer, a research finding, or an explicit documented "out of scope for
- v1" decision.
-- Record each resolution inline: `- [x] {Question} — **Answer:** {decision and rationale}`.
+Only now. Copy `.ai/specs/template.md` to `.ai/specs/{YYYY-MM-DD}-{slug}.md`
+(today's date, kebab-case slug) and fill every section, with the Step-5
+resolutions baked into the design. Rules:
+
+- SQL sketches use `id('prefix')`, `companyId`, composite PK, audit columns —
+ never `gen_random_uuid()`.
+- Acceptance criteria must be testable: "user creates a PO with 3 lines and sees
+ correct totals in the list view", not "works correctly".
+- No `{placeholders}` left in the file; mark inapplicable sections `N/A` with a
+ reason.
+- The Open Questions section records the resolved Q&A (all boxes checked, each
+ with its inline answer) — it is the audit trail of Step 5, not a to-do list.
-## Step 7: Grill — resolve the questions interactively
+## Step 7: New questions discovered while writing
-Show the user the spec path and the list of open questions, then invoke
-`/grill` on the spec (protocol: `.ai/skills/grill/SKILL.md`). The grill
-interviews the user through the questions one at a time (grouped max 2–3 only
-for single-module, no-schema specs), with a recommended answer per question
-and codebase cross-checks, recording each resolution inline as it lands:
-`- [x] {Question} — **Answer:** {decision and rationale}`.
+Writing the spec sometimes surfaces questions Step 4 missed. When that happens:
-Do not say "we can figure these out during implementation." The hard stop
-holds until every box is checked.
+- Add them to the Open Questions section as unchecked items with "why it
+ matters".
+- Take them back to the user (same protocol as Step 5) **before calling the
+ spec final** — the hard stop applies to these too. Do not say "we can figure
+ these out during implementation."
## Step 8: Finalize
-After every question is resolved (checked off during the Step 7 grill): add a
-changelog entry, set status per `.ai/specs/AGENTS.md`. The spec is now ready
-for `/plan` (or `/feature`, which calls it).
+After every question is resolved: add a changelog entry, set status per
+`.ai/specs/AGENTS.md`. The spec is now ready for `/plan` (or `/feature`, which
+calls it).
## Done when
-- [ ] Spec exists at `.ai/specs/{YYYY-MM-DD}-{slug}.md`, every section real content
+- [ ] Every open question was answered by the user BEFORE the spec was written
+ (Step 5), with the resolution recorded inline in the spec
+- [ ] Spec exists at `.ai/specs/{YYYY-MM-DD}-{slug}.md`, every section real content,
+ design reflecting the resolutions (no section contradicts an answer)
- [ ] Research file exists and is linked from the spec
- [ ] Every applicable heuristic (1–7) has a row in Design Decisions — no TBDs
-- [ ] Open Questions has ≥1 entry, each with "why it matters"
-- [ ] Every question resolved through the Step 7 grill at the correct depth,
- with the answer recorded inline — work is stopped until then
+- [ ] Any questions surfaced during writing (Step 7) were also resolved before
+ the spec was called final
## Anti-patterns
+- Writing the spec first and interviewing the user afterward (the old flow —
+ it produces rework: the document gets written around guesses, then edited
+ around answers)
- Writing a design doc anywhere other than `.ai/specs/`
-- Dumping all open questions in one message and accepting batch answers
+- Dumping all open questions in one message and accepting batch answers you
+ assumed rather than the user chose
- Accepting an answer without checking it against the code
- Marking questions resolved without human input
- Skipping `/research` because "I know how ERPs work"
-- "TBD" in the Design Decisions table (that's an Open Question)
+- "TBD" in the Design Decisions table (that's an open question — Step 5 it)
- Vague acceptance criteria ("feature works as expected")
Red flags — thinking any of these means the gate is being defeated; STOP:
+- "I'll draft the spec now and confirm the questions after" (that IS the old flow)
- "I'll mark this question resolved so we can keep moving"
- "zero open questions — the design is clear" (you haven't looked hard enough)
- "we can settle this during implementation"
diff --git a/.ai/specs/2026-07-02-bank-reconciliation.md b/.ai/specs/2026-07-02-bank-reconciliation.md
new file mode 100644
index 0000000000..98112010e4
--- /dev/null
+++ b/.ai/specs/2026-07-02-bank-reconciliation.md
@@ -0,0 +1,496 @@
+# Bank Reconciliation & Cash Management
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-02
+> Research notes: `.ai/research/bank-reconciliation.md`
+
+## TLDR
+
+Carbon can now record cash (`payment`/`memo`/`invoiceSettlement`, shipped 2026-06-30) but cannot prove it: no bank-account master data, no statement ingestion, no reconciliation, no visibility into what the bank actually says. This spec builds a full banking layer in the accounting module — and aims past NetSuite parity, not at it. A `bankAccount` master (depository **and credit card**, base **and foreign currency**) links 1:1 to a GL account; immutable `bankTransaction` statement lines arrive via **Plaid** (Link → `/transactions/sync`, webhook-driven, plus daily balance snapshots) or **file upload in all five industry formats** (CSV, OFX/QFX, BAI2, MT940, CAMT.053 — the NetSuite import matrix). Matching is layered: a conservative deterministic core (exact amount + date window + NetSuite's exactly-one-candidate rule, many-to-many match groups, class-aware sign normalization so credit cards work), a **bank rules engine** (condition → coding, suggest or auto-post — NetSuite auto-create rules), configurable **tolerance auto-adjustment** (Xero's minor adjustment), **cross-account transfer detection**, and an **intelligence layer** that leapfrogs the incumbents: counterparty resolution against existing pgvector embeddings, LLM-suggested coding for unrecognized lines, and one-click "memorize as rule". Foreign-currency accounts are supported properly by adding source-currency amount columns to `journalLine` (the root-cause fix, not a workaround). The close-out is statement-based with a difference-must-be-zero gate, an optional **preparer→approver workflow** (segregation of duties), a generated **PDF reconciliation report** for the audit binder, and a one-click auto-complete when a period fully ties. A cash position page shows bank-vs-GL drift per account daily — so reconciliation drift surfaces the day it happens, not at month-end. Ships in four independently valuable phases.
+
+## Problem Statement
+
+A controller using Carbon today cannot answer "does our GL cash balance match the bank?" without exporting the journal to a spreadsheet:
+
+- The month-end close (period-close lifecycle spec, in flight) has no cash-verification step. A check recorded at $4,530 that cleared at $4,350, a duplicate ACH, or an unrecorded bank fee sits silently in the GL bank account forever — discovered, if ever, at year-end audit.
+- `payment.bankAccount` points at a GL `account` row (`accountType = 'Bank'`), but there is no bank-account entity — no bank name, masked number, currency, feed connection, or opening balance. There is nothing to reconcile *against*.
+- There is no ingestion path for bank data (no feed, no statement upload), no matching, no reconciliation artifact for auditors, and no cash visibility beyond a trial-balance line.
+
+Every serious ERP treats this as core accounting: SAP EBS imports MT940/BAI/CAMT.053 and clears GL items via code-driven posting rules; NetSuite pairs aggregator bank feeds and file import (CAMT.053/MT940/BAI2/OFX) with Intelligent Transaction Matching, rule tiers, and a two-stage Match → Reconcile flow; Xero/QBO made match-create-exclude the small-business standard. Meanwhile the modern fintech stack (Ramp, Mercury, Digits) shows what those incumbents lack: live feeds with drift alerts, ML counterparty resolution, and continuous close. Carbon should ship the mid-market ERP core *and* the modern layer — it already has the ingredients (pgvector embeddings with match functions, an AI SDK, an event system, a PDF pipeline).
+
+## Proposed Solution
+
+### Entity model
+
+New tables in the accounting module (full SQL below):
+
+| Entity | Purpose | Identity |
+|--------|---------|----------|
+| `bankAccount` | Master record: name, bank, last-4, type (Checking/Savings/**Credit Card**/Other), currency, **1:1 GL account link**, opening balance, feed linkage + health | `id('bka')` |
+| `bankStatementImport` | One row per uploaded file: format, storage path, counts, statement balances when the format carries them | `id('bsi')` |
+| `bankTransaction` | One immutable statement line: date, signed amount in **account currency** (positive = inflow), description, reference, provider-stable `externalId`, resolved counterparty, status lifecycle | `id('btx')` |
+| `bankMatchGroup` (+ two membership tables) | **Many-to-many** match: N bank lines ↔ M journal lines, with match type (Auto/Rule/Manual), optional tolerance-adjustment journal reference | `id('bmg')` |
+| `bankRule` | Ordered coding rules: conditions (description pattern, direction, amount range, account scope) → action (GL account, counterparty, memo; suggest or auto-post) | `id('brl')` |
+| `bankReconciliation` | Statement close-out: statement date, starting/ending balance, Draft → In Review → Completed → Voided, preparer/approver, generated report path, readable ID (`REC-`) | `id('brc')` |
+| `bankAccountBalance` | Daily balance snapshot per account (from Plaid or statement close) powering the drift view | `xid()` |
+
+The match target is the **journal line**, not the business document: everything that touches the bank GL account — payments, manual JEs, any future source — is a posted `journalLine` on `bankAccount.glAccountId`, so matching covers all sources uniformly (SAP clears at GL level; NetSuite matches "account transactions"). Sign comparison is **class-aware**: for Asset accounts, positive `journalLine.amount` = debit = inflow, matching `bankTransaction.amount` directly; for Liability accounts (credit cards), the comparison inverts (positive = credit = new charge = negative statement direction). One normalization helper, used everywhere, makes credit-card accounts first-class instead of a special case.
+
+### Foreign currency, fixed at the root
+
+Carbon posts journal lines in base currency only, which makes accurate matching against a EUR statement impossible today. Rather than restricting to base-currency accounts (NetSuite's hard constraint — it fails imports on currency mismatch), fix the root cause:
+
+- Add nullable `sourceAmount NUMERIC` + `sourceCurrencyCode TEXT` to `journalLine`. **Population is mandatory for every posting path, not best-effort** (upgraded per the public-company readiness audit, `.ai/specs/2026-07-03-public-company-readiness.md` SD-4: France FEC and SAF-T exports require the transaction-currency amount on every journal line, and ASC 830 remeasurement needs it — retrofitting universal population later means touching every poster twice). Every `post-*` edge function and app-side posting service writes the document currency + amount on every line it creates (base-currency documents write the base amount + base currency code — cheap and explicit); the manual JE form gains optional FX entry defaulting to base. Columns stay nullable only for pre-migration history, which backfills to NULL (unknown, honest).
+- Matching compares in the **bank account's currency**: `sourceAmount` when `sourceCurrencyCode` equals the account currency, base `amount` when the account is base-currency. Lines with no source amount on a foreign-currency account fall back to suggestion-only (rate-converted via `exchangeRateHistory`, ±1% band) — never auto-matched.
+- Existing rows backfill to NULL (unknown), which is honest; history reconciles manually or by suggestion.
+- This also lays the schema groundwork for future FX revaluation of monetary accounts — a known gap that would otherwise force this same migration later.
+
+### Statement line lifecycle
+
+```
+ ┌─ Excluded ─(restore)─┐
+Pending ──(posts)──▶ Unmatched ⇄ Matched ──▶ Reconciled
+ └─(removed by feed: row deleted) (via completed reconciliation;
+ terminal unless rec is voided)
+```
+
+- **Pending** (Plaid): visible, unmatched-able, excluded from tie-outs. Posted replacement swaps in via `pending_transaction_id`; feed-removed pending rows are deleted.
+- **Excluded**: feed noise/duplicates (QBO pattern); restorable; never blocks reconciliation.
+- A feed that removes or restates an already-**Matched** line sets `needsReview` instead of deleting — surfaced prominently, resolved by a human.
+- **Reconciled** lines and their match groups are immutable until their reconciliation is voided.
+
+### Ingestion path 1 — Plaid bank feed
+
+Xero-integration precedent throughout (registry in `packages/ee`, per-Item credentials in `companyIntegration.metadata`, webhook route, Inngest jobs):
+
+1. **Connect**: server action creates a `link_token` (products `["transactions"]`); Plaid Link runs client-side; the exchange route swaps `public_token` → `access_token`/`item_id`, stores the access token in **Supabase Vault**, and appends `{ itemId, tokenSecretId, institutionName, cursor, status }` to `metadata.items[]` (no secret material in metadata). The user maps each Plaid account to a new or existing `bankAccount` (`plaidItemId`/`plaidAccountId`, `source = 'Plaid'`); account type and currency prefill from Plaid metadata.
+2. **Transaction sync**: Inngest `bank-feed-sync` runs the `/transactions/sync` cursor loop (`added`/`modified`/`removed`, until `has_more = false`), upserts on `(bankAccountId, externalId = transaction_id)`, **inverts Plaid's sign** (Plaid positive = outflow), handles pending swaps and removals, persists the cursor, then runs the matching pipeline for affected accounts.
+3. **Balance sync**: the same job records `/accounts/balance` into `bankAccountBalance` (one snapshot/day/account) — this powers the cash position page and drift alerts.
+4. **Triggers**: `api+/webhook.plaid.ts` (JWT-verified via `Plaid-Verification`) fires sync on `SYNC_UPDATES_AVAILABLE` and initial/historical updates; a daily scheduled catch-up covers webhook loss; "Sync now" button for humans.
+5. **Re-auth**: `ITEM_LOGIN_REQUIRED`/`ERROR` set the Item and its accounts to `Requires Reauth`; banner reopens Link in update mode.
+6. **Backfill**: initial window 90 days by default, user-selectable up to Plaid's 24-month maximum at connect time.
+
+### Ingestion path 2 — file upload, full format matrix
+
+**v1 formats: CSV, OFX/QFX, BAI2, MT940, CAMT.053** — the NetSuite import matrix, and (via CAMT.053/MT940) SAP's EBS staples. Parsers are pure functions in the new `import-bank-statement` edge function, one fixture-tested module per format (the `post-payment.test.ts` Deno-test pattern), all emitting one normalized shape: `{ date, signedAmount, description, reference, externalId, balance? }`.
+
+- Upload drawer per bank account: dropzone → format auto-detected by extension/content, CSV gets a column-mapping step (date, amount or debit/credit pair, description, reference) reusing the `ImportCSVModal` mapping UX → edge function downloads from `private/${companyId}/bank-statements/`, parses, dedupes, inserts transactionally, writes counts to `bankStatementImport`, runs the matching pipeline.
+- **Dedupe**: `externalId` = OFX `FITID` / BAI2-MT940-CAMT bank reference when present; CSV falls back to `sha256(date|amount|description|reference)` + occurrence counter (identical legitimate rows within one file stay distinct; overlapping re-uploads skip). Unique on `(bankAccountId, externalId)`; duplicates count, never error.
+- Statement opening/closing balances (MT940 field 60F/62F, BAI2 account trailers, CAMT.053 `Bal`, OFX ledger balance) are stored on the import and prefill the reconciliation drawer — and validate continuity against the previous statement's close.
+
+### Matching pipeline
+
+Layered, in strict order, after every sync/import and on demand. Deterministic layers are authoritative; intelligence only ever *suggests*.
+
+1. **Deterministic auto-match** (Postgres function `run_bank_matching`, callable from app/jobs/edge — RPC precedent: `translateCompanyBalances`): candidates are posted, unmatched journal lines on the account's GL within ±7 days; amount exactly equal in the comparison currency; references must agree when both sides have one. **Exactly one candidate → match** (`matchType = 'Auto'`); two or more → nothing (NetSuite's ambiguity refusal). 1:1 only at this layer.
+2. **Bank rules** (ordered, first-match-wins): a matching rule stamps the suggested coding (account + counterparty + memo) on the line; rules with `autoPost = true` **create-and-match** the JE immediately (NetSuite auto-create; intended for deterministic recurring items — bank fees, interest, loan payments). Auto-posted JEs go through the normal period gates.
+3. **Tolerance adjustment** (off by default): when `companySettings.bankMatchToleranceAmount > 0`, a near-miss within tolerance auto-matches and books the difference to `accountDefault.bankFeesAccount` as a linked adjustment JE referenced on the match group (Xero minor adjustment / SAP tolerance groups). Every adjustment is visible on the group and the report.
+4. **Transfer detection**: opposite-signed lines of equal amount within ±3 days across two of the company's bank accounts propose a transfer — accepting creates one JE (debit receiving GL / credit sending GL) and matches both statement lines to its two legs.
+5. **Intelligence (suggest-only)**:
+ - **Counterparty resolution**: statement descriptors ("AMZN MKTP US*Z1234") resolve to customers/suppliers via the existing pgvector embeddings (384-dim, `match_*` functions already in place) + trigram fallback; resolved counterparties narrow match candidates (payments to that supplier rank first) and prefill quick-create.
+ - **LLM coding suggestions**: for unrecognized lines, an Inngest task proposes GL account + counterparty + memo from the chart of accounts and this account's match history (AI SDK, batch, cached on the line as `suggestion JSONB` with confidence + provenance). One-click accept codes the line; **"memorize as rule"** promotes an accepted suggestion into a `bankRule` prefilled from the line — the QBO "remember this" loop, but explicit and auditable. LLM suggestions sit behind the company's existing AI enablement setting; embeddings-based counterparty resolution ships core (it's near-free).
+ - AI writes nothing to the GL by itself: acceptance is always a human action, and every accepted suggestion records provenance.
+
+Manual matching remains fully general: select N bank lines + M GL lines; the group must sum equal (or within tolerance, booking the adjustment). A GL line can belong to at most one group (a line clears once); suggestions surface in both panes of the workspace.
+
+### Quick-create from a bank line
+
+For lines with no GL counterpart (Xero's Create leg):
+
+- **Journal entry**: popover (GL account + memo, prefilled by rules/AI when available) → creates and posts a balanced JE dated the bank-line date (`sourceType = 'Manual'`, period-gated) and matches it, one transaction.
+- **Payment**: opens the payment form prefilled (type from sign, amount, date, bank GL, resolved counterparty); on post, the payment's bank-side journal line auto-matches the originating statement line.
+- **Transfer**: the transfer-detection flow, invocable manually.
+
+### Reconciliation close-out
+
+- "Finish reconciliation" drawer: statement date + ending balance (prefilled from the newest statement-carrying import). `startingBalance` stamps from the previous completed reconciliation (or the account's opening balance). Continuity mismatch against imported statement balances is flagged.
+- **Gate**: every non-excluded line dated ≤ statement date must be Matched, and `starting + Σ(lines) − ending = 0`. Blockers are listed live; there are no warning-overrides — this is arithmetic.
+- **Workflow**: with `bankRecRequireApproval` off (default), Complete finishes directly. With it on, the preparer **submits** (Draft → In Review) and a different user with `accounting_update` approves (→ Completed) — preparer ≠ approver enforced. Approvers are notified through the existing notifications package.
+- **Auto-complete assist**: when a statement period ties completely with zero human touches (all auto/rule matches), the account row offers one-click "Complete reconciliation through {date}" — continuous-close ergonomics with the same gate and workflow.
+- On completion (single Kysely transaction): lines flip `Reconciled` + `reconciliationId`, a **PDF reconciliation report** renders via `@carbon/documents` (statement balance → cleared summary → outstanding checks / deposits in transit → GL book balance) into the private bucket (`reportDocumentPath`), audit-log entry written.
+- **Sequential per account; void latest-only** (QBO undo model). Voiding reverts lines to Matched, keeps match groups, clears the report reference. Completing/voiding posts nothing to the GL — GL impact only ever comes from underlying journals.
+- Reconciliations get readable IDs (`REC-%{yyyy}-%{mm}-`, existing sequence infrastructure) — they're referenced in audit binders.
+
+### Cash position page
+
+The Banking landing page: per account — feed/statement balance (latest `bankAccountBalance`), GL balance, **drift** (their difference net of unmatched-but-dated items), unmatched count, days since last reconciliation, connection health; 30-day balance sparkline. Drift that exceeds the unmatched explanation is the "your books are wrong" signal, surfaced daily instead of at month-end. (Forecasting is a non-goal — this is observed cash only.)
+
+### Period close interaction
+
+- Quick-create/rule/tolerance JEs post through the existing period gates — nothing new to enforce.
+- The period-close readiness checklist gains a **warning**: "bank accounts with unreconciled statement lines dated in the period" (warning, not blocker — feeds lag). Coordinated with the in-flight `20260702044133_period-close-lifecycle` work.
+
+### Non-goals (v1, explicit)
+
+Money movement of any kind (payment initiation, ACH origination, Plaid Transfer), cash-flow *forecasting*, intraday statements (camt.052/MT942), direct bank APIs (EBICS/FDX), bank-fee contract auditing, sweep/pooling structures, and AI auto-posting without human acceptance.
+
+### Phasing (each independently shippable)
+
+| Phase | Scope | Value shipped |
+|-------|-------|---------------|
+| **1 — Foundations** | Schema (incl. `journalLine` FX columns), bank accounts UI, CSV + OFX import, deterministic matching + match groups, reconcile workspace, close-out + approval + PDF report, period-close warning | Manual bank rec end-to-end, audit-ready |
+| **2 — Plaid** | Link/exchange/webhooks/sync/re-auth, balance snapshots, cash position page, pending handling, transfer detection | Feeds + daily drift visibility |
+| **3 — Depth** | BAI2 + MT940 + CAMT.053 parsers, bank rules engine (suggest + auto-post), tolerance adjustment | Enterprise formats + hands-off recurring items |
+| **4 — Intelligence** | Counterparty resolution (embeddings), LLM coding suggestions, memorize-as-rule | The leapfrog layer |
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Multi-tenancy | Single-column PK (`id('prefix')`/`xid()`) + `companyId` FK + RLS on all new tables; business keys include scoping columns | Matches `payment`/`memo`/`invoiceSettlement` (newest sibling tables) per pattern-recency rule; flagged for review since AGENTS.md documents composite PKs |
+| Match target | `journalLine` on the bank's GL account | SAP/NetSuite precedent; uniform across all posting sources |
+| Match cardinality | N:M **match groups** (group + two membership tables), Σbank = ΣGL (± recorded tolerance); a GL line clears at most once | Deposit batches (M GL : 1 bank) and split settlements (N bank : 1 GL) are both real; per-pair rows can't express group sum invariants |
+| Bank ↔ GL link | `bankAccount.glAccountId` unique per company; account must be `accountType IN ('Bank','Cash')` — or a Liability card account for type Credit Card (service-validated) | SAP house-bank model; prevents two bank accounts sharing GL lines |
+| Currency | Foreign-currency accounts supported via `journalLine.sourceAmount`/`sourceCurrencyCode`; auto-match requires exact source-currency agreement, rate-converted comparison is suggest-only | Root-cause fix over NetSuite's hard restriction; groundwork for FX revaluation |
+| Credit cards | Supported via class-aware sign normalization in one shared helper | First-class, not a special case; Plaid returns credit accounts anyway |
+| Sign convention | `bankTransaction.amount` signed, account currency, positive = inflow; Plaid inverted at ingest | Aligns with Asset-class GL lines; one documented convention |
+| Statement lines | Immutable after import; corrections via Exclude; feed restatements of matched lines set `needsReview` | Xero model; evidential value |
+| Auto-match rule | Exact amount + ±7d + reference agreement + exactly one candidate | NetSuite ambiguity refusal; a wrong auto-match is worse than none |
+| Rules engine | Ordered first-match-wins `bankRule` rows; `autoPost` opt-in per rule; auto-posted JEs period-gated | NetSuite user-rule tiers / Xero bank rules; deterministic and auditable |
+| AI boundary | Intelligence suggests; humans accept; provenance recorded; promotion to rules is explicit | Audit safety — the GL never moves on model output alone |
+| Matching implementation | Deterministic core as Postgres RPC; rules/tolerance/transfer layers in `accounting.server.ts` (Kysely); AI suggestions as Inngest task | One authoritative implementation per layer, callable from app/jobs/edge |
+| Reconciliation model | Continuous matching + statement close-out; Draft → In Review → Completed → Voided; sequential per account; void-latest-only; approval + segregation via `companySettings.bankRecRequireApproval` (default off) | NetSuite two-stage + QBO zero-difference + SOX-friendly control that small shops can ignore |
+| Report artifact | PDF via `@carbon/documents` on completion, stored in private bucket | The thing auditors actually ask for |
+| Plaid credentials | Access tokens in **Supabase Vault**, referenced by secret id from `companyIntegration.metadata.items[]`; cursors + non-secret Item state stay in metadata | Bank credentials warrant stronger handling than the Xero plaintext precedent; a follow-up migrates Xero tokens to the same pattern |
+| Feed sync | Webhook-triggered Inngest + daily scheduled catch-up + manual button; balances snapshotted daily | Xero job pattern; webhook-loss insurance |
+| Service shape | All functions in `accounting.service.ts` / `accounting.server.ts`, `(client, ...)` → `{ data, error }` | Module conventions; no new service/models files |
+| RLS / permissions | `accounting_view/create/update/delete`, simple policy names + `::text[]` casts; no new permission | Existing accounting pattern; reconciliation is the controller's job |
+| Forms / UI | `ValidatedForm` + zod in `accounting.models.ts`; drawers for detail views; **full-page** reconcile workspace | Module conventions; workspace ≠ detail view (Xero/NetSuite precedent) |
+| Readable IDs | `REC-` sequence for reconciliations only | Referenced by auditors; other entities are internal |
+| Backward compatibility | `payment.bankAccount` untouched; `journalLine` gains two nullable columns (additive); no behavior change to existing posting paths beyond populating them | Zero churn on the 2-day-old payments surface |
+
+## Data Model Changes
+
+One idempotent migration (`pnpm db:migrate:new bank-reconciliation`, randomized HHMMSS), then `pnpm run generate:types` before typechecking. Sketch (RLS shown once; every new table gets the same four `accounting_*` policies):
+
+```sql
+DO $$ BEGIN
+ CREATE TYPE "bankAccountType" AS ENUM ('Checking', 'Savings', 'Credit Card', 'Other');
+ CREATE TYPE "bankAccountSource" AS ENUM ('Manual', 'Plaid');
+ CREATE TYPE "bankConnectionStatus" AS ENUM ('Connected', 'Requires Reauth', 'Error');
+ CREATE TYPE "bankTransactionSource" AS ENUM ('Plaid', 'Import');
+ CREATE TYPE "bankTransactionStatus" AS ENUM ('Pending', 'Unmatched', 'Matched', 'Excluded', 'Reconciled');
+ CREATE TYPE "bankMatchType" AS ENUM ('Auto', 'Rule', 'Manual');
+ CREATE TYPE "bankStatementFormat" AS ENUM ('CSV', 'OFX', 'BAI2', 'MT940', 'CAMT053');
+ CREATE TYPE "bankReconciliationStatus" AS ENUM ('Draft', 'In Review', 'Completed', 'Voided');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- Root-cause FX support: source-currency amounts on journal lines (nullable, additive)
+ALTER TABLE "journalLine"
+ ADD COLUMN IF NOT EXISTS "sourceAmount" NUMERIC,
+ ADD COLUMN IF NOT EXISTS "sourceCurrencyCode" TEXT REFERENCES "currencyCode"("code");
+
+CREATE TABLE IF NOT EXISTS "bankAccount" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('bka'),
+ "name" TEXT NOT NULL,
+ "bankName" TEXT,
+ "accountNumberLastFour" TEXT,
+ "type" "bankAccountType" NOT NULL DEFAULT 'Checking',
+ "currencyCode" TEXT NOT NULL REFERENCES "currencyCode"("code"),
+ "glAccountId" TEXT NOT NULL REFERENCES "account"("id") ON DELETE RESTRICT,
+ "openingBalance" NUMERIC NOT NULL DEFAULT 0,
+ "openingDate" DATE,
+ "source" "bankAccountSource" NOT NULL DEFAULT 'Manual',
+ "plaidItemId" TEXT,
+ "plaidAccountId" TEXT,
+ "connectionStatus" "bankConnectionStatus",
+ "lastSyncedAt" TIMESTAMP WITH TIME ZONE,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB
+);
+CREATE UNIQUE INDEX IF NOT EXISTS "bankAccount_glAccount_idx" ON "bankAccount" ("glAccountId", "companyId");
+CREATE UNIQUE INDEX IF NOT EXISTS "bankAccount_plaid_idx" ON "bankAccount" ("plaidAccountId", "companyId")
+ WHERE "plaidAccountId" IS NOT NULL;
+
+ALTER TABLE "bankAccount" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "bankAccount" FOR SELECT USING (
+ "companyId" = ANY (get_companies_with_employee_permission('accounting_view')::text[])
+);
+-- INSERT/UPDATE/DELETE: same shape with accounting_create / accounting_update / accounting_delete
+
+CREATE TABLE IF NOT EXISTS "bankStatementImport" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('bsi'),
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "fileName" TEXT NOT NULL,
+ "filePath" TEXT NOT NULL,
+ "format" "bankStatementFormat" NOT NULL,
+ "status" TEXT NOT NULL DEFAULT 'Pending', -- Pending | Completed | Failed
+ "error" TEXT,
+ "importedCount" INTEGER,
+ "duplicateCount" INTEGER,
+ "statementOpeningBalance" NUMERIC, -- MT940 60F / BAI2 trailer / CAMT Bal / OFX ledger
+ "statementEndingBalance" NUMERIC,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+);
+
+CREATE TABLE IF NOT EXISTS "bankReconciliation" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('brc'),
+ "reconciliationId" TEXT NOT NULL, -- readable: REC-2026-06-000001
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "statementDate" DATE NOT NULL,
+ "startingBalance" NUMERIC NOT NULL,
+ "statementEndingBalance" NUMERIC NOT NULL,
+ "status" "bankReconciliationStatus" NOT NULL DEFAULT 'Draft',
+ "notes" TEXT,
+ "submittedAt" TIMESTAMP WITH TIME ZONE, -- preparer, when approval flow is on
+ "submittedBy" TEXT REFERENCES "user"("id"),
+ "completedAt" TIMESTAMP WITH TIME ZONE,
+ "completedBy" TEXT REFERENCES "user"("id"), -- approver when flow is on, else completer
+ "voidedAt" TIMESTAMP WITH TIME ZONE,
+ "voidedBy" TEXT REFERENCES "user"("id"),
+ "reportDocumentPath" TEXT, -- generated PDF in private bucket
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE
+);
+CREATE UNIQUE INDEX IF NOT EXISTS "bankReconciliation_statement_idx"
+ ON "bankReconciliation" ("bankAccountId", "statementDate") WHERE "status" <> 'Voided';
+CREATE UNIQUE INDEX IF NOT EXISTS "bankReconciliation_readable_idx"
+ ON "bankReconciliation" ("reconciliationId", "companyId");
+
+CREATE TABLE IF NOT EXISTS "bankTransaction" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('btx'),
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "transactionDate" DATE NOT NULL,
+ "amount" NUMERIC NOT NULL, -- signed, account currency, positive = inflow
+ "description" TEXT NOT NULL,
+ "counterparty" TEXT, -- raw descriptor name
+ "counterpartyCustomerId" TEXT, -- resolved (composite FK to customer)
+ "counterpartySupplierId" TEXT, -- resolved (composite FK to supplier)
+ "reference" TEXT,
+ "externalId" TEXT NOT NULL, -- plaid txn id | FITID | bank ref | csv hash
+ "pendingExternalId" TEXT,
+ "source" "bankTransactionSource" NOT NULL,
+ "importId" TEXT REFERENCES "bankStatementImport"("id") ON DELETE SET NULL,
+ "status" "bankTransactionStatus" NOT NULL DEFAULT 'Unmatched',
+ "reconciliationId" TEXT REFERENCES "bankReconciliation"("id") ON DELETE SET NULL,
+ "needsReview" BOOLEAN NOT NULL DEFAULT FALSE,
+ "suggestion" JSONB, -- rule/AI coding suggestion + confidence + provenance
+ "raw" JSONB,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE
+);
+CREATE UNIQUE INDEX IF NOT EXISTS "bankTransaction_external_idx"
+ ON "bankTransaction" ("bankAccountId", "externalId");
+CREATE INDEX IF NOT EXISTS "bankTransaction_account_status_idx"
+ ON "bankTransaction" ("bankAccountId", "status", "transactionDate");
+
+-- N:M match groups
+CREATE TABLE IF NOT EXISTS "bankMatchGroup" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('bmg'),
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "matchType" "bankMatchType" NOT NULL DEFAULT 'Manual',
+ "toleranceJournalId" TEXT REFERENCES "journal"("id"), -- adjustment JE when tolerance applied
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+);
+CREATE TABLE IF NOT EXISTS "bankMatchGroupTransaction" (
+ "groupId" TEXT NOT NULL REFERENCES "bankMatchGroup"("id") ON DELETE CASCADE,
+ "bankTransactionId" TEXT NOT NULL UNIQUE REFERENCES "bankTransaction"("id") ON DELETE CASCADE,
+ PRIMARY KEY ("groupId", "bankTransactionId")
+);
+CREATE TABLE IF NOT EXISTS "bankMatchGroupJournalLine" (
+ "groupId" TEXT NOT NULL REFERENCES "bankMatchGroup"("id") ON DELETE CASCADE,
+ "journalLineId" TEXT NOT NULL UNIQUE REFERENCES "journalLine"("id") ON DELETE RESTRICT,
+ PRIMARY KEY ("groupId", "journalLineId")
+);
+
+-- Rules engine
+CREATE TABLE IF NOT EXISTS "bankRule" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT id('brl'),
+ "name" TEXT NOT NULL,
+ "bankAccountId" TEXT REFERENCES "bankAccount"("id") ON DELETE CASCADE, -- NULL = all accounts
+ "priority" INTEGER NOT NULL DEFAULT 0,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "descriptionPattern" TEXT, -- ILIKE pattern
+ "direction" TEXT, -- 'Inflow' | 'Outflow' | NULL
+ "minAmount" NUMERIC,
+ "maxAmount" NUMERIC,
+ "accountId" TEXT NOT NULL REFERENCES "account"("id"),-- code-to GL account
+ "counterpartyCustomerId" TEXT,
+ "counterpartySupplierId" TEXT,
+ "memoTemplate" TEXT,
+ "autoPost" BOOLEAN NOT NULL DEFAULT FALSE, -- create-and-match JE vs suggest-only
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE
+);
+
+-- Daily balance snapshots (drift view)
+CREATE TABLE IF NOT EXISTS "bankAccountBalance" (
+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT xid(),
+ "bankAccountId" TEXT NOT NULL REFERENCES "bankAccount"("id") ON DELETE CASCADE,
+ "date" DATE NOT NULL,
+ "balance" NUMERIC NOT NULL, -- account currency
+ "source" TEXT NOT NULL, -- 'Plaid' | 'Statement'
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+);
+CREATE UNIQUE INDEX IF NOT EXISTS "bankAccountBalance_day_idx"
+ ON "bankAccountBalance" ("bankAccountId", "date");
+
+-- Company settings & account defaults
+ALTER TABLE "companySettings"
+ ADD COLUMN IF NOT EXISTS "bankMatchToleranceAmount" NUMERIC NOT NULL DEFAULT 0,
+ ADD COLUMN IF NOT EXISTS "bankRecRequireApproval" BOOLEAN NOT NULL DEFAULT FALSE;
+ALTER TABLE "accountDefault"
+ ADD COLUMN IF NOT EXISTS "bankFeesAccount" TEXT REFERENCES "account"("id");
+-- bankFeesAccount backfill: COALESCE to interestAccount fallback so it's never NULL for existing companies
+
+-- Sequence for readable reconciliation IDs (all existing companies)
+-- INSERT INTO "sequence" ("table","name","prefix","next","size","step","companyId") ... 'REC-%{yyyy}-%{mm}-'
+
+-- Matching engine core (deterministic layer)
+CREATE OR REPLACE FUNCTION run_bank_matching(bank_account_id TEXT, company_id TEXT)
+RETURNS TABLE ("matchedCount" INTEGER) ...
+-- exact amount (class/currency-normalized), ±7d, reference agreement, unique-candidate; SECURITY DEFINER
+```
+
+Notes:
+- `journalLine` columns are additive/nullable; posting paths populate go-forward (`post-payment`, `build-payment-journal.ts` first). Views over `journalLine`, if any select-star views exist, get DROP/recreate per convention (verify at implementation).
+- `companySettings`/`accountDefault` changes are guarded/backfilled idempotently (migrations-must-be-idempotent rule).
+- Plaid Item state lives outside these tables: access tokens in Supabase Vault (`vault.create_secret`), secret ids + cursors + institution metadata in `companyIntegration.metadata.items[]`.
+
+## API / Service Changes
+
+Services in `accounting.service.ts` (zod in `accounting.models.ts`; transactions in `accounting.server.ts`), all `(client, ...)` → `{ data, error }`:
+
+```ts
+// Master data
+getBankAccounts(client, companyId) // + unmatched counts, drift, health
+upsertBankAccount(client, data) // validates GL type/class per bank type, 1:1, currency
+deactivateBankAccount(client, { id, companyId, userId })
+
+// Statement lines & matching
+getBankTransactions(client, companyId, { bankAccountId, status?, dateRange?, needsReview? })
+getMatchCandidates(client, companyId, bankTransactionId) // deterministic + counterparty-ranked suggestions
+createBankMatchGroup(client, { bankTransactionIds, journalLineIds, userId }) // Σ=Σ or within tolerance
+deleteBankMatchGroup(client, { groupId, userId }) // blocked when Reconciled
+excludeBankTransaction / restoreBankTransaction(client, { bankTransactionId, userId })
+createJournalEntryFromBankTransaction(client, { bankTransactionId, accountId, memo, userId })
+acceptSuggestion(client, { bankTransactionId, userId }) // applies rule/AI suggestion via the JE path
+createBankRuleFromTransaction(client, { bankTransactionId, ...ruleFields, userId }) // memorize-as-rule
+detectTransfers(client, { companyId }) // proposes cross-account pairs
+runBankMatching(client, { bankAccountId, companyId }) // full pipeline: RPC core → rules → tolerance
+
+// Rules
+getBankRules / upsertBankRule / deleteBankRule / reorderBankRules
+
+// Imports
+createBankStatementImport(client, data) // edge fn import-bank-statement does the work
+
+// Reconciliation
+getBankReconciliations(client, companyId, { bankAccountId? })
+getBankReconciliationSummary(client, companyId, { bankAccountId, statementDate, statementEndingBalance })
+ // → { startingBalance, clearedTotal, difference, unmatchedLines, outstandingGlLines, continuityWarning }
+createBankReconciliation(client, data) // Draft; stamps startingBalance + REC- id
+submitBankReconciliation(client, { reconciliationId, userId }) // → In Review (approval flow on)
+completeBankReconciliation(client, { reconciliationId, userId }) // gate re-validated; preparer≠approver enforced
+voidBankReconciliation(client, { reconciliationId, userId }) // latest-completed only
+
+// Cash position
+getCashPosition(client, companyId) // balances + GL + drift + sparkline data
+```
+
+Plaid provider (`packages/ee/src/plaid/`): `config.tsx` (registry entry, hidden unless `PLAID_CLIENT_ID`/`PLAID_SECRET` set), `hooks.server.ts` (install/uninstall/healthcheck), shared Plaid client + sync used by jobs (Xero syncer precedent).
+
+Routes:
+- `api+/integrations.plaid.link-token.ts`, `api+/integrations.plaid.exchange.ts`, `api+/webhook.plaid.ts` (JWT-verified → `trigger("bank-feed-sync")`).
+- `x+/accounting+/`: `banking.tsx` (cash position landing), `bank-accounts.tsx` + `.new` / `.$bankAccountId` / `.$bankAccountId.import` drawers, `reconcile.$bankAccountId.tsx` (workspace; intents: `match` | `unmatch` | `exclude` | `restore` | `create-journal` | `accept-suggestion` | `memorize-rule` | `transfer` | `run-matching` | `sync`), `reconcile.$bankAccountId.finish.tsx` (drawer), `reconciliations.tsx` + `.$reconciliationId` (history + report + PDF download), `bank-rules.tsx` + drawers.
+
+Jobs: `bank-feed-sync` (`carbon/bank-feed-sync`) + daily scheduled catch-up; `bank-suggest-coding` (`carbon/bank-suggest-coding`, batch LLM suggestions, Phase 4). Registered in `packages/lib/src/trigger.ts` + `events.ts`. Env: `PLAID_CLIENT_ID`, `PLAID_SECRET`, `PLAID_ENV` in `packages/env`.
+
+Edge function: `import-bank-statement` — format parsers (CSV/OFX/BAI2/MT940/CAMT.053) as pure, fixture-tested modules; transaction-wrapped insert; then matching pipeline.
+
+## UI Changes
+
+- **Sidebar**: "Banking" group in `useAccountingSubmodules.tsx` (between General Ledger and Fixed Assets): Cash Position, Bank Accounts, Reconciliations, Bank Rules. Gated by `accountingEnabled` + `accounting_view`.
+- **Cash position** (`/x/accounting/banking`): per-account cards/rows — bank balance, GL balance, drift, unmatched count, days since last rec, connection badge, 30-day sparkline; company-total header.
+- **Bank accounts list**: name, bank, GL account, currency, type, source + connection badges, unmatched count (plain number, no parentheses), last synced/imported. Row actions: Reconcile, Import statement, Sync now, Edit. Header: "New Bank Account", "Connect bank" (Plaid Link; hidden when env unset). Requires-reauth banner.
+- **Reconcile workspace** (full page): left pane statement lines (status filter, `needsReview` filter, inline suggestion chips with accept / memorize-as-rule, Exclude, Add: JE popover / payment / transfer); right pane unmatched GL lines (outstanding checks/deposits view) with multi-select match; header running totals (cleared vs statement), Run matching, Finish reconciliation. Transfer proposals surface as paired-line banners.
+- **Finish drawer**: statement date + ending balance (import prefill + continuity check), live difference, blocker list; Complete (or Submit for review when approval flow on).
+- **Reconciliations**: history list; detail drawer with the report (statement balance → cleared summary → outstanding items → book balance), PDF download, Approve (when In Review, non-preparer only), Void (latest only).
+- **Bank rules**: list + drawer form (conditions, coding, autoPost toggle with an explicit "posts to the GL automatically" warning), drag-reorder priority.
+- **Settings**: tolerance amount + approval toggle on the accounting settings page; `bankFeesAccount` in Default Accounts.
+- Flash messages on all mutations; `ValidatedForm` + zod; ERP `size="md"`.
+
+## Acceptance Criteria
+
+Phase 1
+- [ ] Creating a bank account validates GL account class/type per bank type (Bank/Cash for depository, Liability for Credit Card), enforces 1:1 GL linkage, and allows a non-base currency.
+- [ ] OFX upload with 20 transactions → 20 lines; identical re-upload → 0 new, 20 duplicates reported. CSV with debit/credit columns imports correctly signed; overlapping re-upload dedupes.
+- [ ] A posted supplier payment of −$4,530 within 7 days auto-matches; two same-amount candidates → no auto-match, both suggested (ambiguity refusal).
+- [ ] One $12,000 bank deposit matches three GL lines summing exactly; a mismatched selection is rejected; with tolerance $1.00 configured, an $11,999.40 selection matches and books a $0.60 adjustment JE to `bankFeesAccount`, linked on the group.
+- [ ] Quick-create JE from a bank-fee line posts (period-gated per the close lifecycle) and matches atomically.
+- [ ] Completion is blocked while any non-excluded line ≤ statement date is Unmatched or the difference ≠ 0; on completion lines flip Reconciled, a PDF report lands in the private bucket, and unmatch on reconciled lines is rejected. With approval on, the preparer cannot approve their own reconciliation.
+- [ ] Reconciliations complete sequentially per account; only the latest can be voided; voiding reverts lines to Matched and preserves groups.
+- [ ] A foreign-currency (EUR) bank account matches a EUR payment exactly via `journalLine.sourceAmount`; base-only legacy lines appear as rate-converted suggestions, never auto-matches.
+- [ ] Reconciliation report shows outstanding GL items tying statement balance to GL book balance at the statement date.
+
+Phase 2
+- [ ] Plaid sandbox: connect, map accounts, initial sync (90-day default) with inverted signs; `SYNC_UPDATES_AVAILABLE` triggers incremental sync; pending lines are unmatchable and swap correctly on posting; `ITEM_LOGIN_REQUIRED` → Requires Reauth banner → update-mode relink clears it.
+- [ ] Balance snapshots record daily; cash position shows drift = bank balance − GL balance net of dated unmatched items; a matched-line feed removal sets `needsReview` and surfaces in the workspace.
+- [ ] Two opposite $5,000 lines across two bank accounts within 3 days propose a transfer; accepting creates one JE matched to both lines.
+
+Phase 3
+- [ ] BAI2, MT940, and CAMT.053 fixture files each parse to correct normalized lines (Deno unit tests per parser), including statement opening/closing balances used for continuity checks.
+- [ ] A bank rule ("description ILIKE '%WIRE FEE%'", outflow, autoPost → Bank Fees) auto-creates and matches the JE on the next sync; suggest-only rules stamp suggestions without posting.
+
+Phase 4
+- [ ] "AMZN MKTP" descriptor resolves to supplier Amazon via embeddings; candidates for that line rank Amazon payments first.
+- [ ] An unrecognized line shows an LLM coding suggestion with confidence + provenance; accepting posts the JE; "memorize as rule" creates a prefilled `bankRule`; the GL never changes without explicit acceptance.
+
+All phases
+- [ ] Migration applies idempotently twice; `pnpm run generate:types` then `pnpm run typecheck` and `pnpm run lint` pass.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Vault-backed token storage adds infra surface (pgsodium/Vault across local dev, Docker, cloud) | Med | Supabase ships Vault in all environments; decryption is server-side service-role-only; tokens are read-only Transactions scope (no money movement) either way |
+| `journalLine` schema change on the core GL table | Med | Two nullable, additive columns; no reads change behavior; backfill is NULL (honest "unknown"); coordinated with in-flight period-close work touching the same module |
+| `autoPost` rules write to the GL unattended | Med | Opt-in per rule with explicit UI warning, period-gated, `sourceType='Manual'` journals fully audit-trailed, rule provenance on the match group; rules are deterministic (no AI in the posting path) |
+| Wrong auto-match misstates the reconciliation | Med | Exact+unique-candidate core; tolerance layer books visible adjustments; unmatch until Reconciled; match provenance recorded |
+| LLM suggestion cost/quality at volume | Med | Batch Inngest task, cached on the line, only for lines rules/deterministic layers didn't resolve; suggest-only by design |
+| BAI2/MT940/CAMT.053 parser edge cases (bank dialects) | Med | Pure-function parsers with per-bank fixtures; failures fail the import row loudly, never partial-insert (transaction-wrapped) |
+| Feed restatements/removals of matched lines | Med | `needsReview` flag + workspace surfacing instead of silent deletion |
+| CSV content-hash dedupe misfires on description drift | Med | Occurrence counter for legit same-day duplicates; drift creates a visible duplicate the user Excludes |
+| Approval workflow friction for one-person accounting teams | Low | `bankRecRequireApproval` default off; segregation only enforced when on |
+| Initial Plaid backfill floods history | Low | 90-day default, user-selectable window at connect |
+| Webhook loss → stale feeds | Low | Daily scheduled catch-up + manual sync + drift view makes staleness visible |
+
+## Open Questions
+
+> ✅ All resolved 2026-07-02 — recommendations accepted verbatim by Brad ("accept all"). Implementation may proceed.
+
+- [x] **`journalLine` FX columns** — additive change to the core GL table. — **Answer: Approved.** Add nullable `sourceAmount`/`sourceCurrencyCode`, populated go-forward by posting paths (post-payment first); NULL backfill; suggest-only matching for legacy lines on FX accounts.
+- [x] **Production dependencies** — **Answer:** `plaid` Node SDK in `@carbon/ee` + Plaid Link via script-tag loader (no client package) + hand-rolled, fixture-tested pure parsers for OFX/BAI2/MT940/CAMT.053 (formats are stable and well-specified; libraries in this space are mostly unmaintained).
+- [x] **Token storage** — **Answer: Supabase Vault** for Plaid access tokens (secret id referenced from `companyIntegration.metadata.items[]`); follow-up task migrates Xero tokens to the same pattern. Design decisions, ingestion flow, and risks updated accordingly.
+- [x] **AI feature gating** — **Answer:** embeddings-based counterparty resolution ships core; LLM coding suggestions sit behind the existing per-company AI enablement setting.
+- [x] **Approval defaults** — **Answer:** `bankRecRequireApproval` defaults off; preparer ≠ approver enforced when on; surfaced in settings copy.
+- [x] **Credit-card statement semantics** — **Answer:** cycle-date-driven reconciliation (statement date = cycle close) is sufficient for v1; no statement-period metadata (cycle open/close, payment due) in schema.
+- [x] **Period-close checklist wiring** — **Answer:** land this spec independently of the in-flight period-close implementation; wire the "unreconciled bank lines dated in period" readiness warning as a small follow-up PR once both are merged.
+- [x] **Phase-1 cut line** — **Answer:** approval workflow + PDF reconciliation report stay in Phase 1 — they are what makes the feature audit-credible.
+
+## Changelog
+
+- 2026-07-02: Created — grounded in codebase exploration (ar-ap-payments tables, journal/journalLine structure, Xero integration + CSV import pipelines) and adversarially verified ERP research (SAP EBS formats/posting chain, NetSuite ITM two-stage flow + ambiguity refusal + 1:1 currency constraint, Xero two-sided reconcile); Plaid mechanics from public docs (verification pass hit usage limits). See `.ai/research/bank-reconciliation.md`.
+- 2026-07-02: Expanded scope per review ("more ambitious"): all five statement formats in v1; foreign-currency accounts via `journalLine` source-currency columns (root-cause fix replacing the base-currency restriction); credit-card accounts via class-aware sign normalization; N:M match groups; bank rules engine with opt-in auto-post; tolerance auto-adjustment; cross-account transfer detection; preparer→approver workflow + PDF reconciliation report; cash position page with daily balance snapshots and drift; intelligence layer (embeddings counterparty resolution + LLM coding suggestions + memorize-as-rule). Reorganized into four shippable phases.
+- 2026-07-02: Phase 2 (Plaid feeds + cash position) spec split out to `.ai/specs/2026-07-02-plaid-bank-feeds.md` with directly verified Plaid mechanics; note there that Supabase Vault is unverified in this stack (probe + AES-GCM fallback proposed).
+- 2026-07-02: All open questions resolved — recommendations accepted verbatim ("accept all"): `journalLine` FX columns approved; `plaid` SDK + script-tag Link + hand-rolled parsers; Vault-backed Plaid token storage (Xero migration as follow-up); LLM suggestions behind AI enablement flag, embeddings resolution core; approval default off; CC cycle-date reconciliation; period-close warning wired post-merge; Phase 1 keeps approval + PDF. Status → in-progress; ready for `/plan`.
+- 2026-07-03: `journalLine.sourceAmount`/`sourceCurrencyCode` population upgraded from best-effort to **mandatory on every posting path** per the public-company readiness audit (`2026-07-03-public-company-readiness.md` SD-4, roadmap `.ai/plans/2026-07-03-public-company-readiness-roadmap.md`) — the same columns serve FEC/SAF-T exports and ASC 830 remeasurement, which need universal coverage. Update the bank-reconciliation plan's posting-path tasks accordingly.
diff --git a/.ai/specs/2026-07-02-budgeting.md b/.ai/specs/2026-07-02-budgeting.md
new file mode 100644
index 0000000000..471b807abb
--- /dev/null
+++ b/.ai/specs/2026-07-02-budgeting.md
@@ -0,0 +1,652 @@
+# GL Budgeting with Cost Centers, Commitments & Budget Control
+
+> Status: in-progress
+> Author: Claude (for Brad Barbin)
+> Date: 2026-07-02
+> Research: `.ai/research/budgeting.md` (SAP, NetSuite, Dynamics 365 Business Central)
+> Depends on: `.ai/specs/2026-07-02-period-closing.md` (fiscalYear/periodNumber on `accountingPeriod`, `createFiscalYearPeriods`)
+
+## TLDR
+
+Add full-cycle budgeting to the accounting module in three phases. **Phase 1 —
+Core budgeting:** a `budget` header (a named plan for one fiscal year; multiple
+per year act as versions/scenarios) and `budgetLine` rows keyed by **GL account
+× accounting period × optional cost center**, entered through a spreadsheet-style
+matrix (accounts × periods), seeded by copying a prior budget or prior-year
+actuals with an adjustment factor, round-tripped through CSV, and consumed
+through a Budget vs Actual report (Actual / Budget / Variance / Variance %) with
+cost-center filtering and hierarchy rollup. **Phase 2 — Commitments & budget
+control:** open purchase-order lines coded to an account + cost center (the
+indirect-purchasing columns that already exist) count as committed spend;
+a per-company budget control policy (Warn or Block at a threshold %) checks
+purchasing documents against the designated Approved budget — SAP availability
+control / NetSuite Budget Validation, grounded in Carbon's existing PO
+structures. **Phase 3 — Reporting integration:** budget comparison columns on
+the income statement and consolidated group-level budget vs actual. An
+Approved-budget immutability trigger (period-close-style backstop) makes
+enforcement targets trustworthy.
+
+## Problem Statement
+
+Carbon can record actuals with full analytical detail — journal lines carry
+`accountId` and cost-center tags via `journalLineDimension` (written by every
+`post-*` edge function), purchase order lines already carry `accountId` +
+`costCenterId` for indirect spend — but there is nowhere to record what those
+numbers were *supposed* to be, and nothing that uses the plan to inform or
+control spend. A controller planning FY2027 cannot say "R&D cost center:
+$40k/month of `6100 - Salaries`, $5k/month of `6400 - Software`", cannot see in
+March that R&D is 12% over on software, and cannot have the system warn a buyer
+that the PO they're about to release exhausts the marketing budget.
+
+Today a Carbon customer budgets in a spreadsheet, exports the income statement
+monthly, and reconciles by hand; over-budget spend is discovered after the
+invoice posts. Every competitor ERP we surveyed treats budget-vs-actual
+variance as the daily-use surface of managerial accounting, and both SAP
+(availability control) and NetSuite (Budget Validation SuiteApp) offer
+threshold-based purchasing checks as the control layer. Carbon has all the
+underlying structures — chart of accounts, first-class periods, cost centers,
+dimension-tagged GL, account-coded PO lines — and no budgeting on top of them.
+
+## Proposed Solution
+
+All inside the existing `accounting` module (enforcement hooks touch the
+purchasing release/posting flow in Phase 2). Delivered in three phases, each
+independently shippable.
+
+### Phase 1 — Core budgeting
+
+1. **Budget headers** (`budget`): name-unique-per-company plans, each covering
+ one fiscal year, with lifecycle `Draft → Approved → Archived`. Multiple
+ budgets per fiscal year are the versioning mechanism ("2027 Original",
+ "2027 Reforecast Q2") — NetSuite budget categories / BC budget names / SAP
+ versions. Approving records `approvedBy`/`approvedAt` and freezes lines
+ (DB trigger); revisions happen by copying to a new Draft ("Revise" action),
+ which is how SAP keeps version 0 trustworthy.
+2. **Budget lines** (`budgetLine`): one row per cell —
+ `(budgetId, accountId, accountingPeriodId, costCenterId?)` → `amount`.
+ NetSuite-style period buckets (upsertable cells), not BC's additive entry
+ ledger. `NULL` cost center = company-level line (industry convention:
+ blank-dimension rows are not apportioned down).
+3. **Matrix editor**: accounts × the FY's periods, editable cells (building on
+ the `EditableNumberCell` pattern from `QuoteLinePricing`), cost-center
+ selector, account filters (default: income-statement posting accounts),
+ Fill / Distribute helpers (NetSuite semantics). Prior-year-profile shaping
+ (SAP distribution-key analog) comes from seed-from-actuals, which preserves
+ the source year's monthly curve by construction (`spread: "even"` flattens
+ it); row-level matrix helpers are Fill and Distribute only.
+4. **Seeding services**: copy another budget or seed from a fiscal year's
+ posted actuals, both with an adjustment factor ("last year + 5%"),
+ period-number-mapped across years.
+5. **CSV round-trip**: export from the matrix/report via the existing
+ table-export mechanism; **import via the `import-csv` edge function** (new
+ `budgetLine` entry in its table enum) — research is unanimous that
+ spreadsheet round-trip is the real bulk-entry path.
+6. **Budget vs Actual report**: RPC + route beside the trial balance — columns
+ Actual, Budget, Variance, Variance %, filterable by budget, period range,
+ and cost center, with **cost-center hierarchy rollup** (child cost centers
+ aggregate into parents via `parentCostCenterId`, SAP standard-hierarchy
+ style) and an explicit "untagged actuals" row when filtering by cost center.
+
+### Phase 2 — Commitments & budget control
+
+7. **Commitments**: outstanding amounts of open PO lines that are coded to a
+ GL account (`purchaseOrderLine.accountId`, i.e. indirect/G-L-Account-type
+ lines, with their `costCenterId`) count as committed spend: outstanding =
+ ordered − invoiced, valued at line price. Consumed = actuals + commitments;
+ Available = budget − consumed (SAP assigned-value model). The Budget vs
+ Actual report gains Committed and Available columns.
+8. **Budget control policy** (`budgetControlPolicy`): per-company record
+ designating **which Approved budget enforces**, the action (**Warn** or
+ **Block**), and a **threshold %** (e.g. warn at 90% consumed) — NetSuite
+ Budget Control record shape, SAP tolerance-limit semantics. At most one
+ active policy per company.
+9. **Enforcement hook**: on PO release (and warn-only on purchase invoice
+ posting for invoices without a PO), for each account-coded line, check
+ annual consumed + this document against the designated budget for that
+ account (+ cost center). Warn → flash message + banner, still saves.
+ Block → the release fails with a clear message; users holding
+ `accounting_update` may override with a reason (SAP authorization-group
+ analog), and the override is recorded. Annual check only in v1 — matching
+ S/4HANA cost-center AVC, which is annual-only to this day.
+10. **Approved-budget immutability trigger**: `budgetLine` writes are rejected
+ unless the parent budget is `Draft` (period-close trigger pattern) — an
+ enforcement target that can drift is worse than none.
+
+### Phase 3 — Reporting integration & consolidation
+
+11. **Income statement integration**: an optional "Compare to budget" picker on
+ the existing income statement route adds Budget / Variance columns
+ (BC account-schedule `ACT/BUD` analog) using the same RPC.
+12. **Consolidated budget vs actual**: group-level rollup across companies,
+ translating budget amounts with the same mechanism as actuals
+ (`translateCompanyBalances`) — no separate budget-exchange-rate table
+ (deliberate simplification vs NetSuite; see open question 4).
+
+### What stays out (all phases)
+
+- **Driver-based planning, approval routing/workflows engine, rolling-forecast
+ automation, allocations** — the EPM tier (NSPB / SAC territory).
+- **Generic budget dimensions** (BC Budget Dimension 1–4): budgets slice by
+ cost center only. Carbon's own operational pattern is a hard `costCenterId`
+ column on documents (indirect purchasing) converted to generic dimensions
+ only at GL posting — budgeting follows the same pattern. A
+ `budgetLineDimension` table can be added later without reshaping `budgetLine`.
+- **Budget exchange rates** — consolidation translates at the same rates as
+ actuals.
+- **Xero sync** — budgets are not an `AccountingEntityType`.
+- **Item/quantity budgets, statistical key figures (headcount)** — noted for a
+ future demand-planning intersection.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Multi-tenancy | `companyId` + composite PK `("id", "companyId")` on all three new tables; child FKs include `companyId` | Carbon convention (canonical template `20260609143732_document-template.sql`); budgets are per-company (NetSuite: subsidiary-specific) even though the COA is group-scoped |
+| Data shape | Header + one row per cell (account × period × cost center), upsertable | NetSuite `budgets`/`budgetsMachine` bucket model; avoids BC's additive entry ledger + registers; cells map 1:1 to matrix UI and CSV rows |
+| Period keying | `budgetLine.accountingPeriodId` FK → `accountingPeriod` | Actuals already group by `journal.accountingPeriodId`; period-close spec makes periods first-class (`fiscalYear`, `periodNumber`); budget creation ensures the FY's periods exist via `createFiscalYearPeriods` |
+| Cost center dimension | Nullable `costCenterId` FK column on `budgetLine`; NULL = company-level | Matches Carbon's own operational pattern (`purchaseOrderLine.costCenterId`, `20260503000000_indirect-purchases.sql`) and SAP/BC-cost-accounting's hardwired cost-center axis; keeps variance and commitment SQL simple |
+| Actuals-by-cost-center | Join `journalLineDimension` → `dimension` where `entityType = 'CostCenter'` | Already written by every `post-*` edge function (e.g. `post-purchase-invoice` maps `invoiceLine.costCenterId` → dimension row); budgets introduce no second tagging mechanism |
+| Commitments source | Open `purchaseOrderLine` rows with `accountId` set (indirect lines), outstanding = ordered − invoiced | Columns already exist; SAP commitments are strongest for account-assigned (indirect) POs; inventory PO lines post to balance-sheet accounts that aren't spend-controlled the same way |
+| Enforcement posture | Off by default; per-company opt-in policy with Warn/Block + threshold %; annual check; permission-gated override | Consensus: reporting-only is every ERP's default; opt-in control mirrors NetSuite's SuiteApp and S/4HANA AVC (annual-only); hard blocks need an escape hatch |
+| Sign convention | Store GL-signed amounts (positive = debit, matching `journalLine.amount`); UI enters/displays natural positive per account class | Variance = actual − budget with no CASE logic; income statement already does class-based sign flipping (`applyRootSignCorrection`); BC stores GL-signed too |
+| Status lifecycle | Enum `budgetStatus`: `Draft`, `Approved`, `Archived`; `approvedBy`/`approvedAt` on header; lines writable only in Draft (DB trigger); Approved → Archived only; "Revise" = copy to new Draft | SAP: the budget is the *approved, binding* figure; immutability is what makes enforcement meaningful; copy-to-revise keeps an audit-clean original (NetSuite "keep Original immutable" practice) |
+| Period close interaction | None — budgets stay editable (in Draft) regardless of period `closeStatus` | BC/NetSuite precedent: budgets are planning data, not books of record |
+| RLS | Four standard policies per table; SELECT via `get_companies_with_employee_role()`, writes via `get_companies_with_employee_permission('accounting_<action>')` | Matches `costCenter` (`20260317233050_cost-centers.sql`) |
+| Permission scoping | Reuse `accounting` module permissions | Cost centers, journals, periods all use `accounting_*`; adding a `module` enum value ripples through the permission UI for little gain; the Block-override doubles as the elevated action gate |
+| Service function shape | All in `accounting.service.ts`, `client` first arg, `{ data, error }`; copy/seed run as SQL functions (`copyBudgetLines`, `seedBudgetLinesFromActuals`) wrapped by services calling `client.rpc` | `.ai/rules/conventions-services.md`; SQL functions are atomic and SECURITY INVOKER (RLS applies), and avoid Kysely `as any` casts for tables absent from the cloud-generated types |
+| Module layout | Extend `accounting.models.ts` / `accounting.service.ts`; UI under `modules/accounting/ui/Budgets/`; Phase 2 hook lives in the purchasing release action calling an accounting service | One service/models file per module; cross-module touch is one call site |
+| Form pattern | `ValidatedForm` + `validator(zodSchema)` + route actions for header forms; matrix cells write per-cell from the RLS-gated browser client with optimistic state (update-by-id / insert / delete-on-zero) | `.ai/rules/conventions-forms.md`; the QuoteLinePricing precedent — also sidesteps PostgREST `onConflict` against the NULLS NOT DISTINCT constraint |
+| Reporting | RPC `budgetVsActual(...)` beside `trialBalance` / `accountTreeBalancesByCompany`; Phase 2 extends it with committed | Aggregation belongs in Postgres like every financial report here |
+| Matrix UI | Spreadsheet-style grid built on the `EditableNumberCell` pattern (`QuoteLinePricing.tsx`, `SupplierQuoteLinePricing.tsx`) | Copy the nearest precedent, don't design from concepts |
+| CSV import | New `budgetLine` entry in the `import-csv` edge function table enum + import UI per `.ai/rules/csv-import-system.md`; wide format (one row per account × cost center, `period1`–`period12` columns, natural sign matching export), upserted by cell key | Research unanimous: CSV round-trip is the real entry path; infra exists; wide format is what humans edit in Excel |
+| Backward compatibility | Additive except one call added to the PO release action (Phase 2); no FROZEN/STABLE surface changed | Enforcement is inert until a company activates a policy |
+
+## Data Model Changes
+
+Phase 1 migration (`pnpm db:migrate:new budgeting` — randomized HHMMSS), ordered
+**after** `20260702044133_period-close-lifecycle.sql`; Phase 2 adds a second
+migration for `budgetControlPolicy` + the PO-override audit column. All DDL
+idempotent (guards + `DO $$ ... EXCEPTION` for types) per the deploy-runner
+retry convention.
+
+```sql
+CREATE TYPE "budgetStatus" AS ENUM ('Draft', 'Approved', 'Archived');
+
+CREATE TABLE "budget" (
+ "id" TEXT NOT NULL DEFAULT id('bud'),
+ "companyId" TEXT NOT NULL,
+
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "fiscalYear" INTEGER NOT NULL, -- FY named by ending year, matching accountingPeriod.fiscalYear
+ "status" "budgetStatus" NOT NULL DEFAULT 'Draft',
+ "approvedBy" TEXT REFERENCES "user"("id"),
+ "approvedAt" TIMESTAMP WITH TIME ZONE,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ "tags" TEXT[],
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "budget_companyId_idx" ON "budget" ("companyId");
+CREATE INDEX "budget_createdBy_idx" ON "budget" ("createdBy");
+CREATE INDEX "budget_companyId_fiscalYear_idx" ON "budget" ("companyId", "fiscalYear");
+
+ALTER TABLE "budget" ADD CONSTRAINT "budget_companyId_name_key"
+ UNIQUE ("companyId", "name");
+
+CREATE TABLE "budgetLine" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "budgetId" TEXT NOT NULL,
+
+ "accountId" TEXT NOT NULL,
+ "accountingPeriodId" TEXT NOT NULL,
+ "costCenterId" TEXT, -- NULL = company-level line
+ "amount" NUMERIC NOT NULL DEFAULT 0, -- GL-signed: positive = debit
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("budgetId", "companyId") REFERENCES "budget"("id", "companyId") ON DELETE CASCADE,
+ FOREIGN KEY ("accountId") REFERENCES "account"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("accountingPeriodId") REFERENCES "accountingPeriod"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("costCenterId") REFERENCES "costCenter"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "budgetLine_companyId_idx" ON "budgetLine" ("companyId");
+CREATE INDEX "budgetLine_budgetId_idx" ON "budgetLine" ("budgetId", "companyId");
+CREATE INDEX "budgetLine_accountId_idx" ON "budgetLine" ("accountId");
+CREATE INDEX "budgetLine_accountingPeriodId_idx" ON "budgetLine" ("accountingPeriodId");
+CREATE INDEX "budgetLine_costCenterId_idx" ON "budgetLine" ("costCenterId");
+CREATE INDEX "budgetLine_createdBy_idx" ON "budgetLine" ("createdBy");
+
+-- One cell per (budget, account, period, cost center); PG15 NULLS NOT DISTINCT
+-- makes two NULL-cost-center rows for the same cell collide, as intended.
+ALTER TABLE "budgetLine" ADD CONSTRAINT "budgetLine_cell_key"
+ UNIQUE NULLS NOT DISTINCT ("budgetId", "companyId", "accountId", "accountingPeriodId", "costCenterId");
+
+-- Hard backstop (period-close trigger pattern): lines are writable only while
+-- the budget is Draft.
+CREATE OR REPLACE FUNCTION check_budget_editable() RETURNS TRIGGER AS $$
+DECLARE v_status "budgetStatus";
+BEGIN
+ SELECT "status" INTO v_status FROM "budget"
+ WHERE "id" = COALESCE(NEW."budgetId", OLD."budgetId")
+ AND "companyId" = COALESCE(NEW."companyId", OLD."companyId");
+ IF v_status IS DISTINCT FROM 'Draft' THEN
+ RAISE EXCEPTION 'Budget is % — copy it to a new draft to revise', v_status;
+ END IF;
+ RETURN COALESCE(NEW, OLD);
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TRIGGER "budgetLine_check_editable"
+ BEFORE INSERT OR UPDATE OR DELETE ON "budgetLine"
+ FOR EACH ROW EXECUTE FUNCTION check_budget_editable();
+```
+
+Phase 2 migration:
+
+```sql
+CREATE TYPE "budgetControlAction" AS ENUM ('Warn', 'Block');
+
+CREATE TABLE "budgetControlPolicy" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+
+ "budgetId" TEXT NOT NULL, -- must reference an Approved budget (service-enforced)
+ "action" "budgetControlAction" NOT NULL DEFAULT 'Warn',
+ "thresholdPercent" NUMERIC NOT NULL DEFAULT 100,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("budgetId", "companyId") REFERENCES "budget"("id", "companyId") ON DELETE CASCADE
+);
+
+CREATE UNIQUE INDEX "budgetControlPolicy_one_active_per_company"
+ ON "budgetControlPolicy" ("companyId") WHERE "active";
+-- + companyId/budgetId/createdBy indexes and the standard four RLS policies
+
+-- Override audit on the purchase order (Block overrides are recorded):
+ALTER TABLE "purchaseOrder" ADD COLUMN IF NOT EXISTS "budgetOverrideReason" TEXT;
+ALTER TABLE "purchaseOrder" ADD COLUMN IF NOT EXISTS "budgetOverrideBy" TEXT REFERENCES "user"("id");
+```
+
+RLS — identical pattern to `costCenter` for all three tables (shown once):
+
+```sql
+ALTER TABLE "public"."budget" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."budget"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+CREATE POLICY "INSERT" ON "public"."budget"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_create'))::text[])
+);
+CREATE POLICY "UPDATE" ON "public"."budget"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])
+);
+CREATE POLICY "DELETE" ON "public"."budget"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_delete'))::text[])
+);
+-- ...same four for "budgetLine" and "budgetControlPolicy"
+```
+
+### Budget vs Actual RPC (sketch — final SQL in the implementation plan)
+
+```sql
+CREATE OR REPLACE FUNCTION "budgetVsActual"(
+ p_company_id TEXT,
+ p_budget_id TEXT,
+ p_cost_center_id TEXT DEFAULT NULL, -- NULL = company-wide; when set, includes descendant cost centers (recursive CTE on parentCostCenterId)
+ p_rollup BOOLEAN DEFAULT TRUE
+) RETURNS TABLE (
+ "accountId" TEXT,
+ "number" TEXT,
+ "name" TEXT,
+ "periodNumber" INTEGER,
+ "budget" NUMERIC,
+ "actual" NUMERIC,
+ "committed" NUMERIC -- Phase 2; 0 until then
+) LANGUAGE sql SECURITY INVOKER AS $$
+ -- budget side: budgetLine ⋈ accountingPeriod (periodNumber); cost-center
+ -- filter includes the cost center's subtree when p_rollup; NULL-costCenter
+ -- rows are company-level and included only when p_cost_center_id IS NULL;
+ -- actual side: journalLine ⋈ journal (accountingPeriodId → the budget's
+ -- fiscalYear periods), grouped by accountId + periodNumber, summing
+ -- journalLine.amount (signed); cost-center restriction goes through
+ -- journalLineDimension jld ⋈ dimension d ON d."entityType" = 'CostCenter'
+ -- AND jld."valueId" IN (subtree ids);
+ -- committed side (Phase 2): open purchaseOrderLine rows with accountId set,
+ -- outstanding = ordered − invoiced, valued at line price, bucketed to the
+ -- period of the PO's promised/order date;
+ -- FULL OUTER JOIN the sides on (accountId, periodNumber).
+$$;
+```
+
+Notes:
+- Actuals aggregate by `journalLine.accountId` (never the legacy `accountNumber`).
+- Security-invoker, called via `client.rpc(...)` so RLS applies — same as
+ `trialBalance` / `accountTreeBalancesByCompany`.
+- Variance, Variance %, and Available are computed in the loader/UI,
+ sign-corrected per account class exactly like the income statement.
+
+After each migration: `pnpm run generate:types` before any typechecking.
+
+## API / Service Changes
+
+All in `apps/erp/app/modules/accounting/accounting.models.ts` and
+`accounting.service.ts`, exported through the module barrel.
+
+### Models (zod)
+
+```typescript
+export const budgetStatusType = ["Draft", "Approved", "Archived"] as const;
+export const budgetControlActionType = ["Warn", "Block"] as const;
+
+export const budgetValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ description: zfd.text(z.string().optional()),
+ fiscalYear: zfd.numeric(z.number().int().min(2000).max(2100)),
+});
+
+export const budgetLinesValidator = z.object({
+ budgetId: z.string().min(1),
+ costCenterId: zfd.text(z.string().optional()), // applies to all cells in the payload
+ lines: z.array(
+ z.object({
+ accountId: z.string().min(1),
+ accountingPeriodId: z.string().min(1),
+ amount: z.number(),
+ })
+ ),
+});
+
+export const copyBudgetValidator = z.object({
+ targetBudgetId: z.string().min(1),
+ source: z.enum(["budget", "actuals"]),
+ sourceBudgetId: zfd.text(z.string().optional()),
+ sourceFiscalYear: zfd.numeric(z.number().int().optional()),
+ adjustmentFactor: zfd.numeric(z.number().positive().default(1)),
+ spread: z.enum(["source", "even"]).default("source"),
+});
+
+export const budgetControlPolicyValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ budgetId: z.string().min(1),
+ action: z.enum(budgetControlActionType),
+ thresholdPercent: zfd.numeric(z.number().min(1).max(200).default(100)),
+ active: zfd.checkbox(),
+});
+```
+
+### Service functions
+
+Supabase-client functions (return `{ data, error }`, never throw):
+
+| Function | Phase | Notes |
+|---|---|---|
+| `getBudgets(client, companyId, args)` | 1 | List with `setGenericQueryFilters`, `.select("*", { count: "exact" })`, scoped `.eq("companyId", companyId)` |
+| `getBudget(client, budgetId, companyId)` | 1 | Single header |
+| `getBudgetsList(client, companyId, fiscalYear?)` | 1 | id/name pairs for pickers |
+| `upsertBudget(client, budget)` | 1 | Insert/update header; on insert, ensures the FY's `accountingPeriod` rows exist (calls `createFiscalYearPeriods` when `(companyId, fiscalYear)` has none) |
+| `approveBudget(client, { budgetId, companyId, userId })` | 1 | Draft → Approved, stamps `approvedBy/approvedAt`; Approved → Archived via `archiveBudget` |
+| `deleteBudget(client, budgetId, companyId)` | 1 | Draft only (service check); lines cascade |
+| `getBudgetLines(client, budgetId, companyId, costCenterId?)` | 1 | Matrix cells; `costCenterId` null-filter distinguishes company-level view |
+| `getAccountingPeriodsForFiscalYear(client, companyId, fiscalYear)` | 1 | The matrix's period columns |
+| `getBudgetVsActual(client, { companyId, budgetId, costCenterId?, rollup? })` | 1 | Wraps `client.rpc("budgetVsActual", ...)` |
+| `getBudgetControlPolicy(client, companyId)` | 2 | Active policy or null |
+| `upsertBudgetControlPolicy(client, policy)` | 2 | Validates the target budget is Approved and same FY coverage |
+| `checkBudgetAvailability(client, { companyId, lines: [{accountId, costCenterId?, amount}] })` | 2 | Returns per-line `{ status: "ok" \| "warning" \| "blocked", budget, consumed, available }` against the policy's budget (annual check); called by the PO release action and invoice posting |
+
+SQL functions (defined in the budgeting migration; atomic, SECURITY INVOKER so
+RLS applies; the Draft-only trigger enforces the target-state rule per row):
+
+| Function | Phase | Notes |
+|---|---|---|
+| `copyBudgetLines(p_company_id, p_source_budget_id, p_target_budget_id, p_adjustment_factor, p_created_by)` | 1 | Replaces the target's lines with the source's, remapping periods by `periodNumber` across fiscal years, × factor — wrapped by `copyBudgetLines(client, args)` in the service |
+| `seedBudgetLinesFromActuals(p_company_id, p_source_fiscal_year, p_target_budget_id, p_adjustment_factor, p_spread, p_created_by)` | 1 | Aggregates posted `journalLine.amount` by `accountId` × source `periodNumber` (× cost center via `journalLineDimension`/`dimension` `entityType = 'CostCenter'`), × factor, into target-FY lines — BC "Copy G/L Budget from G/L Entry" + NetSuite "base on actuals". `p_spread = 'source'` preserves the monthly profile; `'even'` flattens it |
+
+Matrix cell writes happen client-side (per-cell update-by-id / insert /
+delete-on-zero via the browser Supabase client, RLS-gated — the
+QuoteLinePricing precedent). CSV import writes cells inside the `import-csv`
+edge function's Kysely transaction using `ON CONFLICT ON CONSTRAINT
+"budgetLine_cell_key" DO UPDATE`, applying the class-based sign flip so the
+file carries natural-signed amounts matching the export.
+
+### Enforcement hook (Phase 2, purchasing side)
+
+The PO release action (`apps/erp/app/routes/x+/purchase-order+/…release…`) and
+the purchase-invoice posting path call `checkBudgetAvailability` with the
+document's account-coded lines **before** proceeding:
+
+- No active policy, or no account-coded lines → no-op (zero cost when unused).
+- `warning` → proceed; flash warning ("Marketing is at 94% of FY2027 budget for
+ 6400 - Software") and banner on the PO.
+- `blocked` → action returns a form error; a user with `accounting_update` can
+ resubmit with `overrideReason`, which is stored on the PO
+ (`budgetOverrideReason`/`budgetOverrideBy`) and audit-logged.
+
+### Routes (flat routes under `apps/erp/app/routes/x+/accounting+/`)
+
+| Route file | Phase | Purpose / permission |
+|---|---|---|
+| `budgets.tsx` | 1 | List (table + Outlet) — `view: "accounting"` |
+| `budgets.new.tsx` | 1 | Drawer: header + optional "Start from" (copy/seed + factor) — `create: "accounting"` |
+| `budgets_.$budgetId.tsx` | 1 | Full-page matrix editor (trailing underscore opts out of list nesting); cells write client-side, RLS-gated — `view: "accounting"` |
+| `budgets.edit.$budgetId.tsx` | 1 | Drawer over the list for header edits — `update: "accounting"` |
+| `budgets.approve.$budgetId.tsx` | 1 | Confirm modal → approve (Draft) or archive (Approved) — `update: "accounting"` |
+| `budgets.delete.$budgetId.tsx` | 1 | Confirm modal → `deleteBudget` — `delete: "accounting"` |
+| `budget-vs-actual.tsx` | 1 | Report: budget/cost-center/period filters → `getBudgetVsActual` — `view: "accounting"` |
+| `budget-control.tsx` | 2 | Policy settings form — `update: "accounting"` |
+
+Path helpers in `apps/erp/app/utils/path.ts` (`path.to.budgets`,
+`path.to.budget(id)`, `path.to.budgetVsActual`, `path.to.budgetControl`, …);
+sidebar entries beside Cost Centers and Trial Balance. Route actions follow the
+standard shape: `requirePermissions`, `validator(schema).validate(formData)`,
+plain-object returns (never `Response.json`), flash + redirect.
+
+## UI Changes
+
+Components in `apps/erp/app/modules/accounting/ui/Budgets/`, cloned from the
+nearest precedents:
+
+- **BudgetsTable** — standard list table (clone of `CostCentersTable`): Name,
+ Fiscal Year, Status badge, Approved by/at, Updated; row click → matrix. No
+ parenthesized counts.
+- **BudgetForm** — drawer (clone of `CostCenterForm`): Name, Fiscal Year,
+ Description; create-time "Start from" section (None / Copy budget /
+ Prior-year actuals; Adjustment factor; Spread: as-source / even /
+ prior-year profile).
+- **BudgetMatrix** — the flagship new component, built on the
+ `EditableNumberCell` pattern from `QuoteLinePricing.tsx`: rows = posting
+ accounts (active, `directPosting`; default filter Income Statement, toggle
+ for all classes), columns = the FY's periods + row total; toolbar with
+ account search, class/category filter, **Cost center** select
+ (Company-level / each cost center — determines the cell set shown and
+ written), Fill / Distribute / prior-year-profile helpers on the focused
+ row; batched cell saves with optimistic UI; read-only when status ≠ Draft
+ with an "Approved — Revise to edit" banner and a Revise button
+ (copy-to-draft). Cells display natural sign per account class.
+- **BudgetVsActualTable** — report modeled on the trial balance screen:
+ Account, Actual, Budget, Variance, Variance % (+ Committed, Available in
+ Phase 2), period-range and cost-center filters (rollup toggle), budget
+ picker (defaults to the FY's Approved budget), CSV export, "untagged
+ actuals" row when a cost-center filter is active. Sign-corrected like the
+ income statement.
+- **BudgetControlForm** (Phase 2) — settings card: designated budget (Approved
+ only), Warn/Block, threshold %; plus the PO banner/flash strings.
+- **Income statement** (Phase 3) — "Compare to budget" select adds
+ Budget / Variance columns.
+
+i18n via Lingui throughout. Docs: Accounting → Budgets page + glossary entries
+(budget, commitment, budget control) per keep-sources-in-sync; update
+`modules/accounting` AGENTS.md service list.
+
+## Acceptance Criteria
+
+Phase 1:
+
+- [ ] Migration applies on a DB with the period-close migration, is idempotent,
+ and `pnpm run generate:types` + typecheck pass.
+- [ ] Creating budget "2027 Plan" (FY2027) auto-creates FY2027 periods when
+ missing; duplicate name in the same company is rejected with a form error.
+- [ ] Matrix: entering 5,000 in P1 for an expense account and Distribute spreads
+ evenly across periods; seeding from actuals with `spread = 'source'`
+ matches the FY2026 monthly proportions; reload persists; zeroing a cell
+ deletes its row; row totals correct.
+- [ ] Cost-center select on "Machining" writes lines with that `costCenterId`;
+ company-level cells are a distinct set; the cell-uniqueness constraint
+ makes duplicate company-level cells impossible.
+- [ ] Copy budget ×1.1 and seed-from-actuals ×1.05 produce lines equal to
+ source × factor (period-number-mapped across years; cost-center detail
+ preserved).
+- [ ] CSV: export from the matrix opens in a spreadsheet; re-importing an edited
+ file through the import flow updates the matching cells to the file's
+ values (upsert by cell — absent cells are left untouched).
+- [ ] Approving a budget stamps approver/time; direct `budgetLine` writes are
+ then rejected by the trigger (verified via SQL, not just UI); Revise
+ copies to a new Draft.
+- [ ] Budget vs Actual: Actual ties to the trial balance for the same
+ accounts/range; Variance/Variance % sign-corrected per class; cost-center
+ filter restricts actuals via `journalLineDimension` and includes child
+ cost centers when rollup is on; untagged actuals surfaced.
+- [ ] RLS: no `accounting_create` → cannot insert; `accounting_view` only →
+ read-only. `pnpm run typecheck` and `pnpm run lint` pass.
+
+Phase 2:
+
+- [ ] With no active policy, PO release behavior is byte-for-byte unchanged.
+- [ ] Warn policy at 90%: releasing a PO with an account-coded line that pushes
+ consumed (actuals + open commitments + this PO) past 90% of the annual
+ budget for that account+cost center flashes a warning and still releases.
+- [ ] Block policy at 100%: release fails with a per-line message; resubmit with
+ an override reason by a user holding `accounting_update` succeeds and
+ records `budgetOverrideReason`/`budgetOverrideBy` (+ audit log entry).
+- [ ] Budget vs Actual shows Committed (open account-coded PO outstanding) and
+ Available = Budget − Actual − Committed; invoicing a PO line moves its
+ amount from Committed to Actual without double counting.
+- [ ] Policy form rejects a non-Approved budget; only one active policy per
+ company (partial unique index verified).
+
+Phase 3:
+
+- [ ] Income statement with "Compare to budget" shows Budget and Variance
+ columns consistent with the Budget vs Actual report.
+- [ ] Group-level Budget vs Actual aggregates member companies' budgets and
+ actuals translated with the same rates as consolidated actuals.
+- [ ] `modules/accounting` AGENTS.md, product docs, and glossary updated.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Commitments only see account-coded (indirect) PO lines — item lines resolve accounts through posting groups at receipt and are invisible to budget control until then | Med | Documented explicitly in UI/docs ("budget control applies to G/L-coded purchase lines"); posting-group resolution for item lines is a listed future enhancement, not silently missing |
+| Enforcement adds a check to the PO release path — a bug there blocks purchasing | High | Check is behind an active-policy guard (no-op by default); failure mode on internal error is fail-open with a logged warning, never fail-closed; release action covered by tests for no-policy/warn/block/override |
+| Variance by cost center is only as good as dimension tagging (journal lines without CostCenter tags read as untagged) | Med | `post-*` functions already tag when source documents carry `costCenterId`; the report surfaces "untagged actuals" explicitly; docs state the prerequisite |
+| Dependency on period-closing work (`fiscalYear`/`periodNumber`, `createFiscalYearPeriods`) | Med | Migration ordered after `20260702044133`; if that service is delayed, `upsertBudget` generates periods itself from `fiscalYearSettings.startMonth` |
+| The matrix editor is the largest novel UI; `EditableNumberCell` is a cell, not a grid | Med | Build the grid as rows of editable cells like `QuoteLinePricing` (row = account, cells = periods); virtualize with the existing TanStack Virtual dependency if account counts demand it |
+| CSV import's Kysely `ON CONFLICT ON CONSTRAINT` against the `NULLS NOT DISTINCT` unique constraint needs a PG15 verification | Low | Matrix writes avoid upserts entirely (per-cell update-by-id / insert / delete); import fallback is select-then-update per cell |
+| GL-signed storage confuses manual data fixes (revenue budgets stored negative) | Low | Documented in migration comment + models; every UI surface normalizes by class like the income statement |
+| Immutability trigger vs CSV re-import of an Approved budget | Low | Import flow requires Draft (service check mirrors the trigger); error message points to Revise |
+
+## Open Questions
+
+> All questions resolved 2026-07-02 (1–7 by the be-more-ambitious direction +
+> codebase verification; 8–12 by accepted recommendations). Gate cleared —
+> implementation may proceed per `.ai/plans/2026-07-02-budgeting.md`.
+
+- [x] **1. Dimension scope** — **Answer:** cost center only, as a hard
+ `costCenterId` column — matching Carbon's own operational pattern
+ (`purchaseOrderLine.costCenterId`) and keeping commitment/variance SQL
+ simple. Generic budget dimensions (BC 1–4) deferred; schema leaves room
+ for a `budgetLineDimension` table.
+- [x] **2. Enforcement scope** — **Answer:** in scope as Phase 2 — opt-in
+ per-company policy (Warn/Block + threshold, annual check, permission-gated
+ override), grounded in the existing indirect-purchasing columns. Off by
+ default, matching industry posture.
+- [x] **3. CSV round-trip** — **Answer:** both export and import in Phase 1,
+ via the existing table-export and `import-csv` infrastructure.
+- [x] **4. Balance-sheet budgeting** — **Answer:** all active `directPosting`
+ accounts are budgetable; matrix defaults to the Income Statement filter.
+- [x] **5. Matrix editor** — **Answer:** required in Phase 1; build on the
+ `EditableNumberCell` / `QuoteLinePricing` precedent.
+- [x] **6. Permission granularity** — **Answer:** reuse `accounting_*`; a
+ dedicated budget module permission would ripple through the `module` enum
+ and permission UI for little gain. The Block override is gated on
+ `accounting_update`.
+- [x] **7. "Active/Approved" semantics** — **Answer:** lifecycle is
+ Draft → Approved (immutable, trigger-enforced) → Archived; multiple
+ Approved budgets per FY allowed; reports default to the FY's most recent
+ Approved budget; the control policy designates its target explicitly.
+- [x] **8. Sequencing on period close** — **Answer:** period-closing lands
+ first — its migration (`20260702044133`) is already in this working tree
+ and budgeting's migration is timestamp-ordered after it. The fallback
+ (budgeting generates periods from `fiscalYearSettings.startMonth`) stays
+ documented in Risks in case `createFiscalYearPeriods` ships late.
+- [x] **9. Commitment reduction basis** — **Answer:** reduce committed on
+ **invoice posting**. Indirect/service lines often aren't received, and
+ invoicing is when actuals hit the GL — so committed→actual hand-off is
+ exact with no double counting. Receipt-based reduction revisited if
+ accrual-on-receipt for account-coded lines is added later.
+- [x] **10. Enforcement points** — **Answer:** PO release (warn or block per
+ policy) + warn-only on purchase-invoice posting (catches no-PO invoices).
+ No checks at line save or quote→PO conversion in Phase 2 — earlier checks
+ are noisier and the release gate is the industry anchor point.
+- [x] **11. Commitment period bucketing** — **Answer:** bucket committed
+ amounts to the PO line's **promised date** period (falling back to the
+ order date when unset). Annual enforcement is unaffected either way.
+- [x] **12. Consolidation translation (Phase 3)** — **Answer:** translate
+ budgets at the same consolidated rates as actuals, reusing
+ `translateCompanyBalances` — no budget-exchange-rate table. Fixed plan
+ rates noted as a future option if FX-variance isolation is requested.
+
+## Changelog
+
+- 2026-07-02: Created. Grounded in `.ai/research/budgeting.md` (SAP CO-OM-CCA /
+ S/4HANA plan categories, NetSuite budgets/budgetsMachine + budget categories,
+ Dynamics 365 BC G/L Budget Name/Entry + Cost Accounting).
+- 2026-07-02: Expanded scope per direction to be more ambitious: three-phase
+ delivery adding commitments + budget control (Warn/Block policy, override
+ audit), Draft→Approved→Archived lifecycle with immutability trigger, CSV
+ import in Phase 1, prior-year-profile spreading, cost-center hierarchy
+ rollup, income-statement integration and group consolidation (Phase 3).
+ Verified enablers in-repo: `purchaseOrderLine.accountId`/`costCenterId`
+ (`20260503000000_indirect-purchases.sql`), `journalLineDimension` written by
+ all `post-*` functions, `EditableNumberCell` grid precedent, extensible
+ `import-csv` table enum. Resolved open questions 1–7 accordingly.
+- 2026-07-02: Resolved open questions 8–12 with the recommended answers
+ (period-close sequencing, invoice-posting commitment reduction, PO-release +
+ invoice-warn enforcement points, promised-date commitment bucketing,
+ consolidated-rate translation). Status → in-progress; Phase 1 implementation
+ plan at `.ai/plans/2026-07-02-budgeting.md`.
+- 2026-07-02: Aligned with the Phase 1 plan after precedent verification:
+ copy/seed are SQL functions (`copyBudgetLines`, `seedBudgetLinesFromActuals`)
+ called via `client.rpc` instead of Kysely transactions; matrix cells write
+ per-cell from the RLS-gated browser client (QuoteLinePricing precedent)
+ instead of a batched route action; prior-year-profile spreading is delivered
+ by seed-from-actuals (`p_spread`), with Fill/Distribute as the row-level
+ matrix helpers; matrix route is `budgets_.$budgetId.tsx` (un-nested); CSV
+ import is wide-format (period1–12 columns) upserting by cell key.
diff --git a/.ai/specs/2026-07-02-financial-reporting.md b/.ai/specs/2026-07-02-financial-reporting.md
new file mode 100644
index 0000000000..c866c2bfe8
--- /dev/null
+++ b/.ai/specs/2026-07-02-financial-reporting.md
@@ -0,0 +1,592 @@
+# Financial Reporting
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-02
+> Research notes: `.ai/research/financial-reporting.md`
+
+## TLDR
+
+Carbon already renders a trial balance, balance sheet, and income statement from
+the account tree via `accountTreeBalancesByCompany`, with multi-company
+consolidation, currency translation, and a computed Net Income equity line. This
+spec completes the financial statements package to the standard every surveyed
+competitor (SAP, NetSuite, QuickBooks, Xero) converges on: a **statement of cash
+flows** (indirect method, classified by `accountType` with a per-account
+override — the QuickBooks Desktop "Classify Cash" pattern), a correct
+**Retained Earnings / Net Income split** on the balance sheet (prior fiscal
+years' income folds into the Retained Earnings row, current fiscal year shows as
+Net Income — the NetSuite/QBO/Xero computed model, no closing entries, exactly
+what the period-closing spec's virtual year-end assumes), **comparative
+columns** (prior period / prior year with $ and % variance, recomputed live,
+never snapshotted), a **general ledger detail report** that makes every
+statement amount drillable (statement → account transactions → journal entry —
+the universal two-hop), a **four-column trial balance** (opening / debits /
+credits / closing — the SAP F0996 shape accountants hand to auditors), and
+**CSV export** on every report. Scope also includes the former Phase 2 items:
+**consolidated cash flow** (flows at average rate, cash at closing rates, an
+explicit "Effect of exchange rate changes on cash" plug), a **PDF financial
+statements package** (BS + IS + SCF in one document via `@carbon/documents`),
+a **period picker** (report by fiscal period, reading the period-closing
+migration's `fiscalYear`/`periodNumber`), and **saved report views** (named
+per-user filter sets). Footprint: one nullable enum column on `account`, one
+new personal-preference table (`reportView`), one extended RPC, one PDF
+component, and service/UI work in the existing accounting module.
+
+## Problem Statement
+
+A controller closing June (per the period-closing spec) cannot produce the
+standard month-end package — three statements plus tie-out reports — from
+Carbon today:
+
+- **No cash flow statement.** The third primary statement doesn't exist in any
+ form. A manufacturer running on Carbon cannot answer "where did cash go"
+ without exporting to a spreadsheet ([accounting routes](apps/erp/app/routes/x+/accounting+/)
+ have `trial-balance`, `balance-sheet`, `income-statement` — nothing else).
+- **The balance sheet conflates retained earnings with current-year income.**
+ `getFinancialStatementBalances` ([accounting.service.ts:196-240](apps/erp/app/modules/accounting/accounting.service.ts))
+ synthesizes a single "Net Income" line from *all* income-statement activity
+ since inception. After the first fiscal year, that line is wrong twice over:
+ prior years' profit should sit in Retained Earnings, and the Net Income line
+ should show only the current fiscal year. Every surveyed competitor splits
+ these (NetSuite: computed RE = inception → FY start; QBO: "electronic swap";
+ Xero: Current Year Earnings). The period-closing spec's year-end design
+ ("no closing entries, retained earnings roll-forward happens at report time")
+ *depends* on this split existing — today the roll-forward has nowhere to go.
+- **Numbers are dead ends.** Statement amounts aren't links. There is no GL
+ detail / account-transactions report to drill into, and no journal-entry
+ detail view (`journals.tsx` lists entries; there is no `journals.$journalId`).
+ An auditor asking "what's in 6100 for June" gets a shrug.
+- **No comparisons.** The income statement shows one period. Prior period,
+ prior year, and variance — the daily-use view in QBO/Xero/NetSuite — require
+ running the report twice and diffing by hand. The budgeting spec (Phase 3)
+ plans budget-vs-actual columns on the income statement and needs the
+ comparison-column mechanism this spec builds.
+- **The trial balance shows only closing balances** (`trialBalance` RPC,
+ [20260315000001_per-company-balance-rpc.sql:66](packages/database/supabase/migrations/20260315000001_per-company-balance-rpc.sql)):
+ debit/credit of `balanceAtDate` plus a net change. The accountant handoff
+ format is four columns — opening balance, period debits, period credits,
+ closing balance (SAP Trial Balance app F0996) — which ties each period to the
+ next.
+- **No export.** Reports render in the app only. The audience for financial
+ statements (owners, banks, external accountants) lives outside the ERP; QBO,
+ Xero, and NetSuite all treat Excel/PDF export as table stakes.
+
+## Proposed Solution
+
+All inside the existing `accounting` module. Grounded in
+`.ai/research/financial-reporting.md`; the sign conventions below follow
+`packages/utils/src/accounting.ts` (`journalLine.amount` is **class-normal
+signed**: positive = the account's natural direction — debit for Asset/Expense,
+credit for Liability/Equity/Revenue).
+
+### 1. Retained Earnings / Net Income split (balance sheet)
+
+Adopt the NetSuite/QBO computed model, which the period-closing spec already
+committed to:
+
+- **Net Income** (existing synthetic `NET_INCOME_ACCOUNT_ID` row) becomes
+ *fiscal-year-to-date only*: income-statement activity from the fiscal year
+ start (derived from `fiscalYearSettings.startMonth` for the report's end
+ date) through the report date.
+- **Retained Earnings** — the posted account row (`accountType = 'Retained
+ Earnings'`) has its *displayed* balance augmented with computed prior-years'
+ net income (inception → fiscal year start). Direct postings to the RE account
+ (dividends, prior-period adjustments) are already in the account's own
+ balance, so displayed RE = posted balance + computed prior years — exactly
+ NetSuite's presentation.
+
+Mechanics: when `includeCurrentYearEarnings` is set, `getFinancialStatementBalances`
+makes one additional `accountTreeBalancesByCompany` call with
+`from_date = fiscalYearStart, to_date = endDate`. For income-statement leaves,
+`netChange` of that window = current-year earnings and
+`balanceAtDate − netChange` = prior-years' earnings. Existing column semantics
+of the report are untouched. Degradation: if the chart has no
+`accountType = 'Retained Earnings'` account, keep today's single Net Income
+line (all-inception) and surface a warning in the report header. The balance
+sheet stays balanced in every case because both lines live inside Equity and
+their sum equals today's single line.
+
+### 2. Statement of cash flows (indirect method)
+
+The automation consensus (SAP F3076, NetSuite, QBO; see research §3): every
+input already exists in the GL — net income from the P&L, everything else from
+balance-sheet deltas. This section defines the single-company computation;
+§7 extends it to consolidated mode.
+
+**Classification.** A new nullable `cashFlowActivity` enum column on `account`
+(`'Operating' | 'Investing' | 'Financing'`) is the per-account override
+(QuickBooks Desktop "Classify Cash"; SAP semantic tags). When NULL, the bucket
+defaults from `accountType`:
+
+| `accountType` | Default bucket |
+|---|---|
+| Bank, Cash | **Excluded** — the reconciliation target, not a flow line |
+| Accounts Receivable, Inventory, Other Current Asset, Accumulated Depreciation, Accounts Payable, Other Current Liability, Tax | Operating |
+| Fixed Asset, Other Asset, Investments | Investing |
+| Long Term Liability, Equity - No Close, Equity - Close, Retained Earnings | Financing |
+| Income, COGS, Expense, Other Income, Other Expense | n/a — rolls into the Net Income line |
+| NULL / anything else | **Unclassified** section (SAP "Not assigned" pattern — surfaced, never dropped) |
+
+Classifying `Accumulated Depreciation` → Operating makes the D&A addback fall
+out automatically (its period delta *is* the addback), fixing the QBO
+known-wart of depreciation landing in Investing.
+
+**Computation** (`getCashFlowStatement`, one `accountTreeBalancesByCompany`
+call over `[startDate, endDate]` + the accounts list):
+
+- Net Income = Σ over income-statement leaves of `rootSignMultiplier(class) × netChange` (identical to the income statement's bottom line).
+- Cash effect of each non-cash balance-sheet leaf = `class === 'Asset' ? −netChange : +netChange` (an asset increase consumes cash; a liability/equity increase provides it — trivially correct under class-normal signing).
+- Sections: Operating (Net Income + adjustments + working-capital changes), Investing, Financing, Unclassified.
+- Beginning cash = Σ over Bank/Cash leaves of `balanceAtDate − netChange`; Net change in cash = Σ of their `netChange`; Ending cash = sum.
+- Tie-out: Net Income + Σ all section effects = net change in cash **by the double-entry identity** — as long as every BS account is bucketed (the Unclassified section preserves the identity while flagging the gap). A mismatch is a data bug and renders as an explicit "Unreconciled difference" line rather than silently forcing the total.
+
+**Route** `cash-flow.tsx` beside the other statements; sectioned report UI
+(flat sections with subtotals, not the account tree); every line drills to the
+GL detail report; Net Income drills to the income statement.
+
+### 3. Drill-down chain + general ledger detail report
+
+The universal two-hop (research §5): statement amount → account transactions →
+journal entry.
+
+- **GL detail report** (`general-ledger.tsx`): journal lines joined to their
+ journal (posting date, journal `journalEntryId`, source type, document
+ reference, description, debit, credit via `toDisplayDebit`/`toDisplayCredit`)
+ filtered by account, company, date range, and source type; built on the
+ shared `Table` component (CSV export for free). When filtered to a single
+ account, shows an opening-balance row and a running balance column. Posted
+ and Reversed journals only by default (Draft visible via an explicit status
+ filter, excluded from running balance).
+- **Journal entry drawer** (`journals.$journalId.tsx`): header + lines via the
+ existing `getJournalEntry`, rendered as a Drawer overlay per the detail-view
+ convention. The GL detail rows and the journals list both link to it.
+- **Statements become drillable**: leaf rows in `FinancialStatementTree` and
+ trial balance rows link into the GL detail report pre-filtered to that
+ account + the report's window + company. Computed rows drill contextually
+ (Net Income / Retained Earnings → income statement — the Xero behavior).
+
+### 4. Four-column trial balance
+
+Extend the `trialBalance` RPC (CREATE OR REPLACE, forking the **newest**
+definition per `.ai/lessons.md`) to return, per leaf account: opening balance
+(debit/credit split of `balanceAtDate − netChange`), **period debits** and
+**period credits** (new leaf-movement sums: a line is a debit when
+`(class ∈ {Asset, Expense} AND amount > 0) OR (class ∈ {Liability, Equity,
+Revenue} AND amount < 0)`), and closing balance (existing debit/credit split).
+Existing return columns are kept — additive change. UI shows grouped columns
+Opening | Period activity | Closing with totals proving debits = credits;
+zero-balance suppression stays. This is the close tie-out artifact
+(period-closing readiness already runs a trial-balance sanity check).
+
+### 5. Comparative columns
+
+Per research §4: comparisons are live recomputations, never snapshots, so they
+stay correct after a reopen — and balance-sheet accounts are always cumulative
+while P&L accounts are periodic (the SAP rule, already how
+`balanceAtDate`/`netChange` behave).
+
+- A `compare` search param on the income statement and balance sheet:
+ `none | priorPeriod | priorYear`.
+- Income statement: comparison window = same-length window immediately before
+ `startDate` (priorPeriod) or the same window shifted one year (priorYear).
+ Balance sheet: comparison as-of = one month before `endDate` (priorPeriod) or
+ one year before (priorYear).
+- Loader runs the same balance call twice (or `getConsolidatedBalances` twice
+ in consolidated mode) and zips by account id; UI adds Comparison, $ Variance,
+ and % Variance columns to the tree.
+- Date-math presets in v1; once period-closing's `fiscalYear`/`periodNumber`
+ land, the period picker (§9) drives the same date params. The budgeting spec's
+ Phase 3 "Compare to budget" picker plugs into this same column mechanism with
+ the budget RPC as the alternate source — built here, consumed there.
+
+### 6. CSV export
+
+- GL detail: automatic via the shared `Table` component
+ (`.ai/rules/table-csv-export.md`).
+- Statement trees + trial balance + cash flow: an Export CSV button per report
+ serializing the loaded rows (account number, name, and the visible amount
+ columns) via `json2csv` — the existing standalone pattern
+ (`ExchangeRateForm.tsx`). Filename `{report}-{endDate}.csv`.
+- PDF statements package: §8.
+
+### 7. Consolidated cash flow
+
+Extends §2 to multi-company (the "All companies" selector the other statements
+already have). Standard IAS 21 / ASC 830 presentation, mirroring the rate
+model already in `translateTrialBalance`
+(`20260315000002_exchange-rate-history.sql`: `translated = local × rate`,
+average = AVG of daily rates over the window, closing = latest rate on/before
+a date, fallbacks average → closing → 1):
+
+- Compute each company's cash flow statement in its base currency (§2), then
+ translate: **flow lines and Net Income at the window's average rate**,
+ **beginning cash at the closing rate as of the window start**, **ending cash
+ at the closing rate as of the window end**.
+- Merge lines across companies by account id (the chart is shared per
+ `companyGroupId`), summing translated amounts.
+- **Effect of exchange rate changes on cash** = translated ending cash −
+ translated beginning cash − translated net flows — the standard plug line,
+ rendered between Financing and the cash reconciliation footer. With a single
+ currency it is exactly zero.
+- Intercompany eliminations are *not* applied to the SCF: elimination journals
+ are non-cash balanced adjustments; IC receivable/payable deltas net out
+ across the group inside Operating. (The elimination entity's own journals are
+ included when it is part of the selection, same as the other statements.)
+
+### 8. PDF financial statements package
+
+The close deliverable: one PDF containing Balance Sheet, Income Statement, and
+Cash Flow for the selected window and company (or consolidated) selection —
+the "three-way reporting" package (research §8).
+
+- **Hand-built react-pdf tree** (`FinancialStatementsPDF` in
+ `packages/documents/src/pdf/`) wrapped in the shared `Template.tsx` page
+ shell — the non-customizable authoring style per
+ `.ai/rules/pdf-generation-patterns.md`. No document-template/block-registry
+ integration in v1 (statements are not customer-customizable documents).
+- Served from a `file+` PDF route (canonical `renderToStream` → Buffer →
+ `application/pdf` response, copying the sales-invoice PDF route), driven by
+ query params (`companies`, `startDate`, `endDate`) and reusing the exact
+ service calls the screens use — the PDF always matches what the user sees.
+- A "Download PDF" button on the three statement screens links to the route
+ with the current filter params.
+
+### 9. Period picker (report by fiscal period)
+
+NetSuite's "Report by Period" semantics as pure UI over the existing
+date-range contract: `ReportFilters` gains a Dates | Period mode toggle; Period
+mode shows fiscal year + period selects populated from `accountingPeriod`
+(`fiscalYear` / `periodNumber` columns from the period-closing migration) and
+**writes the selected period's `startDate`/`endDate` into the URL** — loaders,
+comparison math, exports, and the PDF route are untouched. Comparison presets
+keep their date math (periods are calendar months via
+`createFiscalYearPeriods`, so −1 month / −1 year already lands on period
+boundaries); the comparison column header shows the period name when period
+mode is active. The picker reads `accountingPeriod` directly (columns via
+cast), so it depends only on the period-closing **migration** being applied,
+not its service layer; when the columns are absent or no periods exist, the
+toggle hides and reports behave exactly as today.
+
+### 10. Saved report views
+
+Named, per-user saved filter sets for the five report screens. The existing
+table saved-views system is table-bound (`SavedView.table`, filter/sort URL
+params) and doesn't fit statement screens, so reports get their own minimal
+table — `reportView` — mirroring the `userModulePreference` personal-preference
+pattern (`20260512174538_menu-customization.sql`: simple PK, `userId`-scoped
+RLS on all four policies, `(userId, companyId, X, name)` uniqueness):
+
+- Row = `{ name, report, params }` where `report` names the screen
+ (`balance-sheet` | `income-statement` | `cash-flow` | `trial-balance` |
+ `general-ledger`) and `params` is the URL search-param set (companies, dates,
+ compare, translated, account, statuses).
+- `ReportFilters` gains a views dropdown (apply = navigate with the saved
+ params) plus Save / Delete actions backed by one resource route. Views are
+ personal (no sharing in v1).
+
+### 11. Posted-only balances (readiness audit fold-in)
+
+Added per the public-company readiness audit (`.ai/specs/2026-07-03-public-company-readiness.md`, SD-1) — done here because this spec already redefines the `trialBalance` RPC and touches every report loader, so the retrofit cost is near zero now and real later. Today `accountTreeBalancesByCompany` and the `journalLines` view **include Draft journals in reported balances** (documented as intentional in `20260702122210_journal-lines-view.sql`); this spec already chose Posted+Reversed for the GL detail report. Extend that decision to the statements:
+
+- `accountTreeBalancesByCompany` and `trialBalance` gain a `p_include_drafts BOOLEAN DEFAULT FALSE` parameter (added while `trialBalance` is being redefined for four columns anyway; `accountTreeBalancesByCompany` redefined in the same migration). Default **excludes Draft** journals — statements, trial balance, cash flow, and comparatives all report posted reality by default.
+- Report filter bars gain an "Include drafts" toggle (preview workflow preserved; off by default) that passes the param through; the account-ledger drill-down drawer follows its parent's toggle so the tie-out contract (drawer == tree row) holds in both modes, with the existing Draft badge marking draft lines when included.
+- The period-closing readiness check ("draft journals in period" = close blocker) is unchanged — drafts must still be resolved before close; they just no longer move the statements silently in the meantime.
+
+### Out of scope (all phases)
+
+Cash-basis reporting toggle (accrual only), dimension/cost-center-filtered
+statements (future spec; budget columns belong to the budgeting spec's
+Phase 3), block-template customization of the PDF package, shared/company-wide
+saved views.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Statement structure | Account tree + `accountType`/`incomeBalance` classification; **no layout designer** | QBO proves type-driven placement suffices at SMB scale; SAP FSV/NetSuite layouts are enterprise add-ons. Carbon's tree already encodes placement. Unclassified accounts surface in a section, never dropped (SAP "Not assigned"). |
+| RE / Net Income | Computed at report time; RE row = posted balance + prior-years' income; Net Income = fiscal-YTD | NetSuite/QBO/Xero consensus; the period-closing spec's virtual year-end requires exactly this; self-healing on prior-year reopen. No closing entries, ever. |
+| Fiscal year boundary | Derived from `fiscalYearSettings.startMonth` (fallback: calendar year when missing) | Works before period-closing's generated periods exist; period-closing backfills `fiscalYear` from the same source, so the two stay consistent. |
+| Cash flow method | Indirect only | SAP/NetSuite/QBO standard, US GAAP-required reconciliation, computable entirely from existing GL data. Xero's direct method is the documented cautionary tale (top feature request is the indirect view). |
+| Cash flow classification | Default by `accountType` + nullable per-account `cashFlowActivity` override | QBO's fixed-by-type without override causes real misclassification pain; QuickBooks Desktop "Classify Cash" is the fix. One nullable column, no mapping table. |
+| Accumulated depreciation bucket | Operating (default) | Its delta is the D&A addback; distinct `accountType` lets Carbon be correct-by-default where QBO structurally can't. |
+| SCF scope | Single company AND consolidated (flows at average rate, cash at closing rates, explicit FX-effect plug line) | Standard IAS 21/ASC 830 presentation; mirrors the exact rate model of `translateTrialBalance` (`local × rate`, avg → closing → 1 fallbacks). Eliminations skipped on SCF (non-cash by construction). |
+| PDF package | Hand-built react-pdf tree (`FinancialStatementsPDF`) in `Template.tsx` shell + `file+` PDF route reusing the screens' service calls | The non-customizable authoring style per `.ai/rules/pdf-generation-patterns.md`; block-registry is for customer-customizable docs, which statements are not. PDF = what the screen shows, by construction. |
+| Period picker | UI-only mode in `ReportFilters` that writes the period's start/end dates to the URL; reads `accountingPeriod.fiscalYear`/`periodNumber` directly via cast | Loaders/compare/export/PDF stay date-driven (zero contract change); depends only on the period-closing migration, not its services; hides gracefully when columns/periods are absent. |
+| Saved report views | New `reportView` table (`userId`-scoped RLS, `(userId, companyId, report, name)` unique, `params` JSONB) mirroring `userModulePreference` | Existing saved-views system is Table-component-bound; personal-preference precedent is the exact fit. One resource route serves all five reports. |
+| Trial balance upgrade | Extend `trialBalance` RPC additively (opening + period debits/credits + closing) | Four-column is the accountant handoff form (SAP F0996); additive return columns avoid breaking the existing screen during transition. |
+| Comparatives | Two live balance calls zipped in the loader; `compare` URL param; variance computed in TS | Never snapshot (stays correct after reopen); simplest thing that also serves budgeting Phase 3's column mechanism. |
+| Draft journals in balances | Excluded by default (`p_include_drafts DEFAULT FALSE` on both balance RPCs) + explicit "Include drafts" toggle; drill-down drawer follows its parent | Readiness audit SD-1: statements handed to reviewers/auditors are IPE and must reflect posted reality; matches this spec's own GL-detail default; cheapest while the RPCs are already being redefined. |
+| Drill target | New GL detail report route + `journals.$journalId` Drawer | The two-hop is universal (research §5); Drawer per detail-view convention. |
+| Multi-tenancy (heuristic 1) | One new table: `reportView` with `companyId` + `userId` (personal preference rows; simple PK per the `userModulePreference` precedent). `cashFlowActivity` lands on `account` (group-scoped by `companyGroupId`, its existing pattern); all journal queries scope `companyId` | `account` deliberately has no `companyId` (shared chart); `reportView` follows the established personal-preference shape rather than the composite-PK business-entity template. GL detail service filters `journalLine.companyId` explicitly. |
+| Service shape (heuristic 2) | `getCashFlowStatement`, `getConsolidatedCashFlowStatement`, `getCurrencyRatesForWindow`, `getGeneralLedgerLines`, `getReportViews`/`upsertReportView`/`deleteReportView`, extended `getFinancialStatementBalances`/`getTrialBalance` — all in `accounting.service.ts`, `(client, ...)` → `{data, error}` | One module service file; no new files beyond routes/UI and the PDF component. |
+| RLS (heuristic 3) | `reportView`: four policies gated on `"userId" = auth.uid()::text` (personal rows — `userModulePreference` precedent). Everything else inherits: `account` UPDATE policy covers the new column; GL detail reads ride `journal`/`journalLine` SELECT policies | Personal-preference tables use owner-scoped RLS, not module-permission RLS — established precedent; verified policies exist on all read tables. |
+| Permissions (heuristic 4) | All report loaders + the PDF route `view: "accounting"` + `role: "employee"` (matches existing report routes); `cashFlowActivity` edits ride the account form's `update: "accounting"` action; report-view saves need only the report's own `view` permission (personal data) | Exact precedent: `balance-sheet.tsx:31`. |
+| Forms (heuristic 5) | Cash Flow Activity select added to the existing account form (`ValidatedForm` + extended `accountValidator`); save-view uses a small named form via the resource route (`ValidatedForm` + `reportViewValidator`) | Both follow the standard form pattern. |
+| Module layout (heuristic 6) | Everything in `apps/erp/app/modules/accounting/` + `routes/x+/accounting+/` | No new module; report UI under `modules/accounting/ui/Reports/`. |
+| Backward compatibility (heuristic 7) | RPC extended additively; `getFinancialStatementBalances` gains optional args; the Net Income line's *meaning* changes (fiscal-YTD instead of inception-to-date) | The meaning change is the point of the feature and only affects display (no posted data). Called out in acceptance criteria; no frozen surface touched. |
+
+## Data Model Changes
+
+One idempotent migration (`pnpm db:migrate:new financial-reporting`, randomized
+HHMMSS — never `000000`), then `pnpm run generate:types`:
+
+```sql
+-- Cash flow activity override (QuickBooks Desktop "Classify Cash" pattern).
+-- NULL = derive from accountType at read time.
+DO $$ BEGIN
+ CREATE TYPE "cashFlowActivity" AS ENUM ('Operating', 'Investing', 'Financing');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+ALTER TABLE "account"
+ ADD COLUMN IF NOT EXISTS "cashFlowActivity" "cashFlowActivity";
+
+-- Redefine the accounts view so the new column is exposed (DROP + recreate
+-- with SELECT * per view-redefinition convention).
+DROP VIEW IF EXISTS "accounts";
+CREATE VIEW "accounts" WITH(SECURITY_INVOKER=true) AS
+SELECT * FROM "account";
+
+-- Saved report views — personal-preference table mirroring
+-- userModulePreference (20260512174538_menu-customization.sql):
+-- simple PK, owner-scoped RLS, (userId, companyId, report, name) unique.
+CREATE TABLE IF NOT EXISTS "reportView" (
+ "id" TEXT NOT NULL DEFAULT id('rpv'),
+ "userId" TEXT NOT NULL REFERENCES "user"("id") ON DELETE CASCADE,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+ "report" TEXT NOT NULL CHECK ("report" IN
+ ('balance-sheet', 'income-statement', 'cash-flow', 'trial-balance', 'general-ledger')),
+ "name" TEXT NOT NULL,
+ "params" JSONB NOT NULL DEFAULT '{}',
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "reportView_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "reportView_userId_companyId_report_name_key"
+ UNIQUE ("userId", "companyId", "report", "name")
+);
+CREATE INDEX IF NOT EXISTS "reportView_userId_companyId_idx"
+ ON "reportView" ("userId", "companyId");
+ALTER TABLE "reportView" ENABLE ROW LEVEL SECURITY;
+-- Owner-scoped policies (personal rows), per userModulePreference precedent:
+-- SELECT / INSERT / UPDATE / DELETE all gate on "userId" = auth.uid()::text
+
+-- Four-column trial balance: fork the NEWEST definition
+-- (20260315000001_per-company-balance-rpc.sql) and extend additively.
+-- New return columns: openingDebit, openingCredit, periodDebits,
+-- periodCredits (closing = existing debitBalance/creditBalance).
+DROP FUNCTION IF EXISTS "trialBalance"(TEXT, TEXT, DATE, DATE);
+CREATE OR REPLACE FUNCTION "trialBalance" (
+ p_company_group_id TEXT,
+ p_company_id TEXT DEFAULT NULL,
+ from_date DATE DEFAULT (now() - INTERVAL '100 year'),
+ to_date DATE DEFAULT now()
+)
+RETURNS TABLE (
+ "accountId" TEXT,
+ "accountNumber" TEXT,
+ "accountName" TEXT,
+ "accountClass" "glAccountClass",
+ "incomeBalance" "glIncomeBalance",
+ "openingDebit" NUMERIC(19, 4),
+ "openingCredit" NUMERIC(19, 4),
+ "periodDebits" NUMERIC(19, 4),
+ "periodCredits" NUMERIC(19, 4),
+ "debitBalance" NUMERIC(19, 4), -- closing, kept for compatibility
+ "creditBalance" NUMERIC(19, 4), -- closing, kept for compatibility
+ "netChange" NUMERIC(19, 4)
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+-- Body: existing leaf/balance logic + a movements CTE:
+-- periodDebits = Σ ABS(amount) of in-range lines where the line is a debit:
+-- (class IN ('Asset','Expense') AND amount > 0) OR
+-- (class IN ('Liability','Equity','Revenue') AND amount < 0)
+-- periodCredits = the mirror case
+-- opening = balanceAtDate − netChange, split debit/credit by class sign
+-- (same CASE style as the existing closing-balance split)
+$$;
+```
+
+Notes:
+- One new table (`reportView`, personal-preference shape with owner-scoped RLS
+ and audit-by-ownership — no `createdBy`, matching `userModulePreference`);
+ everything else inherits (`account` is group-scoped by design;
+ `journal`/`journalLine` policies unchanged).
+- The `accounts` view is a plain `SELECT *` today
+ (`20260229000003_chart-of-accounts-tree.sql`); recreating it after the column
+ add follows the view-redefinition convention.
+- `DROP FUNCTION` before `CREATE` because the return table changes (Postgres
+ cannot `CREATE OR REPLACE` with a different OUT row type); both statements
+ are idempotent so the migration re-runs safely.
+
+## API / Service Changes
+
+All in `apps/erp/app/modules/accounting/accounting.service.ts` (+ zod in
+`accounting.models.ts`, types in `types.ts`, barrel exports unchanged):
+
+```ts
+// Extended: fiscal-year-aware RE/CYE split (extra RPC call over the FY window)
+getFinancialStatementBalances(client, companyGroupId, companyId, {
+ startDate, endDate,
+ includeCurrentYearEarnings?: boolean // now splits RE (prior years) from Net Income (fiscal YTD)
+})
+
+// New: indirect-method cash flow (single company, local currency)
+getCashFlowStatement(client, companyGroupId, companyId, { startDate, endDate })
+// → { data: { operating: Line[], investing: Line[], financing: Line[],
+// unclassified: Line[], netIncome, netChangeInCash,
+// beginningCash, endingCash }, error }
+
+// New: consolidated cash flow — per-company SCF translated to parent currency
+// (flows × average rate, cash × closing rates) + FX-effect plug line
+getConsolidatedCashFlowStatement(client, companyGroupId, companyIds, parentCurrency, { startDate, endDate })
+// → same shape + { effectOfExchangeRates: number }
+
+// New: scalar rates for a currency over a window (mirrors translateTrialBalance
+// fallbacks: average → closing → 1); parent currency returns 1s
+getCurrencyRatesForWindow(client, companyGroupId, currencyCode, { startDate, endDate })
+// → { data: { average, closingAtStart, closingAtEnd }, error }
+
+// New: saved report views (personal; owner-scoped RLS does the heavy lifting)
+getReportViews(client, companyId, userId, report)
+upsertReportView(client, { id?, userId, companyId, report, name, params })
+deleteReportView(client, id, userId)
+
+// New: GL detail (journal lines + journal header, paginated)
+getGeneralLedgerLines(client, companyId, args: GenericQueryFilters & {
+ accountId?: string; startDate?: string; endDate?: string;
+ sourceType?: string; status?: string[]; // default Posted + Reversed
+})
+// plus getGeneralLedgerOpeningBalance(client, companyGroupId, companyId, accountId, beforeDate)
+// for the running-balance row (reuses accountTreeBalancesByCompany)
+
+// Unchanged signature; returns the four-column RPC shape
+getTrialBalance(client, companyGroupId, companyId, { startDate, endDate })
+
+// New pure helper (models or utils): default bucket from accountType
+getCashFlowActivityForAccountType(accountType | null): CashFlowActivity | "Excluded" | null
+```
+
+Models: `accountValidator` gains optional `cashFlowActivity`;
+`cashFlowActivities` enum array exported for the select.
+
+Routes (all under `apps/erp/app/routes/x+/accounting+/` unless noted, loaders
+`view: "accounting"` + `role: "employee"`):
+- `cash-flow.tsx` — new statement route (company selector incl. consolidated,
+ date range, FX-effect line in consolidated mode, export).
+- `general-ledger.tsx` — new GL detail report (shared `Table`, filters, running
+ balance when single-account).
+- `journals.$journalId.tsx` — new Drawer child of `journals.tsx` showing the
+ entry via `getJournalEntry`.
+- `income-statement.tsx` / `balance-sheet.tsx` — `compare` param, second
+ balance call, variance columns.
+- `trial-balance.tsx` — four-column data, drill links.
+- `report-views.tsx` — resource route (actions only) with `intent`:
+ `save` | `delete`, shared by all five report screens.
+- `apps/erp/app/routes/file+/accounting+/financial-statements[.]pdf.tsx` — PDF
+ package route (query params `companies`, `startDate`, `endDate`); canonical
+ `renderToStream` shape copied from the sales-invoice PDF route.
+
+`path.to` additions: `cashFlowStatement`, `generalLedger`, `journalEntry(id)`,
+`reportViews`, `financialStatementsPdf`.
+
+PDF component: `FinancialStatementsPDF` in `packages/documents/src/pdf/`
+(hand-built tree in the `Template.tsx` shell; barrel-exported from
+`pdf/index.ts`; styled via `useTw()` semantic grays).
+
+## UI Changes
+
+All under `apps/erp/app/modules/accounting/ui/` (copying the nearest existing
+screen per UI precedent rule):
+
+- **`Reports/CashFlowStatement.tsx`** — sectioned statement (Operating /
+ Investing / Financing / Unclassified + cash reconciliation footer); rows link
+ to GL detail; header warning when the Unclassified section is non-empty
+ ("N accounts need a cash flow activity — set account type or override").
+- **`Reports/FinancialStatementTree.tsx`** — leaf amounts become links to GL
+ detail (account + window prefilled); comparison/variance columns when
+ `compare` is active; Retained Earnings row shows the augmented balance with a
+ "computed" affordance (tooltip: posted + prior years' income); Net Income row
+ drills to the income statement.
+- **`Reports/TrialBalanceTable.tsx`** — Opening | Period | Closing column
+ groups with debit=credit footer totals; rows link to GL detail.
+- **`Reports/ReportFilters.tsx`** — gains the Compare select (income statement
+ / balance sheet) — everything else (date pickers, company selector,
+ translation toggle) reused as-is.
+- **`GeneralLedger/GeneralLedgerTable.tsx`** — shared `Table` over
+ `getGeneralLedgerLines` (CSV export automatic); opening-balance + running
+ balance in single-account mode; each row links to the journal drawer.
+- **`JournalEntries/JournalEntryDrawer.tsx`** — read-only entry header + lines
+ (Drawer overlay convention).
+- **Account form** (`ChartOfAccounts/`) — Cash Flow Activity select (options
+ Operating/Investing/Financing + "Default (from account type)" for NULL),
+ visible for Balance Sheet accounts only.
+- **Export CSV button** on the three statement routes + trial balance
+ (`json2csv` standalone pattern); **Download PDF button** on the three
+ statement routes linking to the financial-statements PDF route with current
+ params.
+- **`Reports/ReportFilters.tsx`** additions: Dates | Period mode toggle
+ (Period mode = fiscal year + period selects reading `accountingPeriod`;
+ writes the period's dates to the URL; hidden when period columns/rows are
+ absent) and a saved-views dropdown (apply/save/delete via the `report-views`
+ resource route).
+- **Cash flow consolidated mode**: "All companies" option renders translated
+ sections in the parent currency plus an "Effect of exchange rate changes on
+ cash" line between Financing and the cash reconciliation footer.
+- Sidebar: Cash Flow and General Ledger added to the accounting nav beside the
+ existing reports.
+
+## Acceptance Criteria
+
+- [ ] **RE/CYE split**: with FY = calendar year and posted revenue of 100 in Dec 2025 and 40 in Mar 2026, the balance sheet as of 2026-03-31 shows Retained Earnings = RE-account posted balance + 100 and Net Income = 40; the equity section totals match today's single-line total; balance sheet still balances (Assets − Liabilities − Equity ≈ 0 at the root).
+- [ ] With no `Retained Earnings`-typed account in the chart, the balance sheet renders the legacy single Net Income line plus a header warning — no crash, still balanced.
+- [ ] **Cash flow**: for a period containing a cash sale of 100, an on-credit sale of 50, and a depreciation entry of 20, the statement shows Net Income 170 − AR change 50 + depreciation addback 20 in Operating, net change in cash 120, and Beginning + Net change = Ending equal to the Bank/Cash accounts' GL movement for the period.
+- [ ] The cash flow tie-out holds on the demo dataset: Net Income + Σ section effects = Net change in cash, with zero Unreconciled difference while all BS accounts have a bucket; deliberately nulling an account's `accountType` moves it to the Unclassified section (with header warning) without breaking the tie-out.
+- [ ] Setting `cashFlowActivity = 'Financing'` on an Other Current Liability account (via the account form) moves its delta from Operating to Financing on the next render.
+- [ ] **Drill-down**: clicking a leaf amount on the balance sheet opens the GL detail report filtered to that account + the report window + company; the sum of the listed (Posted/Reversed) lines equals the statement amount; clicking a line opens the journal entry drawer showing balanced lines.
+- [ ] GL detail in single-account mode shows an opening-balance row and a running balance whose final value equals the account's closing balance on the trial balance for the same window.
+- [ ] **Trial balance**: four column groups render with footer totals where total debits = total credits for opening, period, and closing; for any account, opening + period debits − period credits (class-signed) = closing; zero-balance suppression unchanged.
+- [ ] **Comparatives**: income statement with `compare=priorYear` renders Comparison, $ Variance, % Variance columns; the comparison column for a given account equals the plain report run over the shifted window; works in consolidated (multi-company) mode.
+- [ ] **Export**: every report (income statement, balance sheet, cash flow, trial balance, GL detail) downloads a CSV whose rows match the visible data.
+- [ ] Consolidated balance sheet / income statement behavior (translation, CTA, eliminations) is unchanged from before this feature (regression: same numbers on the demo group).
+- [ ] **Consolidated cash flow**: with two companies sharing the parent currency, "All companies" shows summed sections and an FX-effect line of exactly 0; with a foreign-currency subsidiary and differing average vs closing rates, Beginning + Σ flows + FX effect = Ending in the parent currency.
+- [ ] **PDF package**: Download PDF on the balance sheet returns an `application/pdf` response containing all three statements whose totals match the on-screen reports for the same params; works in consolidated mode.
+- [ ] **Period picker**: with the period-closing migration applied and FY2026 periods generated, selecting "FY2026 · P6" sets the June date range and the report matches the same report run with those dates typed manually; without period rows, the toggle is absent and reports behave as before.
+- [ ] **Saved views**: saving "Board pack" on the income statement (consolidated + prior-year compare) and reopening it from the dropdown restores the exact URL params; the view is invisible to another user; deleting removes it.
+- [ ] **Posted-only default**: with a Draft journal of 75 on a revenue account, the income statement/trial balance exclude it by default; enabling "Include drafts" reproduces the pre-change numbers and the drill-down drawer's tie-out strip matches the tree row in both modes; the period-close readiness blocker for draft journals still fires.
+- [ ] `pnpm run generate:types` then scoped typecheck (`pnpm exec turbo run typecheck --filter=@carbon/erp`) and `pnpm run lint` pass; migration applies idempotently twice.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Fiscal-year derivation wrong for companies whose `startMonth` changed historically | Med | Derive FY start from `fiscalYearSettings` at report time (same source period-closing backfills from); document that historical startMonth changes shift the RE/NI split; the period picker (§9) sidesteps it by using stored period boundaries |
+| Existing charts have NULL `accountType` on many leaves → noisy Unclassified section | Med | Unclassified section + header warning makes the gap visible and actionable (set type or override); tie-out identity is preserved regardless |
+| `trialBalance` RPC return-shape change breaks the existing screen during migration | Low | Additive columns; existing `debitBalance`/`creditBalance`/`netChange` keep their meaning; screen updated in the same phase; types regenerated before typecheck |
+| Two balance calls per comparative/consolidated render → slow reports on big charts | Low | The RPC is a single recursive query already used per render; two calls stay interactive; period-closing's closed periods make caching possible later if needed |
+| CTA account matched by hardcoded number `"3200"` in existing consolidation code | Low | Out of scope to fix here, but new code must not copy the pattern; noted for a follow-up (use account designation, not number) |
+| Net Income line meaning change surprises existing users | Low | It becomes *correct* (fiscal-YTD); release note + tooltip on the computed rows; prior behavior only ever existed pre-first-year-end |
+| Running balance pagination (GL detail) — page N needs cumulative sum of pages 1..N−1 | Low | Opening balance computed server-side for the filter window start; running balance rendered only when a single account is selected and sort is posting-date ascending |
+| Sparse `exchangeRateHistory` (few daily rates) makes the average rate unrepresentative → inflated FX-effect plug | Med | Same fallback chain as `translateTrialBalance` (average → closing → 1) keeps it consistent with the BS/IS translation; the FX line makes the distortion visible instead of hiding it in section totals |
+| Period picker reads period-closing's columns before that feature ships | Low | Reads columns via cast directly from `accountingPeriod`; toggle hides when columns/rows are absent — zero coupling to period-closing's service layer or UI |
+| PDF render cost for large charts (three statements in one document) | Low | Fonts are bundled/registered in-process (no network); data calls are the same three the screens make; statements render summary rows, not journal lines |
+
+## Open Questions
+
+> All questions resolved 2026-07-02 (recommendations accepted; user requested
+> spec + plan together, delegating open-question resolution to best judgment —
+> same pattern as the period-closing and plaid-bank-feeds specs).
+
+- [x] **Consolidated cash flow in v1?** — **Answer (revised 2026-07-02):** In scope — user brought Phase 2 into v1. Flows and Net Income translate at the window's average rate, cash balances at closing rates for their respective dates, with an explicit "Effect of exchange rate changes on cash" plug line (§7); rate model mirrors `translateTrialBalance` exactly. *(Original resolution deferred this to Phase 2.)*
+- [x] **PDF financial-statements package in v1?** — **Answer (revised 2026-07-02):** In scope — user brought Phase 2 into v1. Hand-built `FinancialStatementsPDF` in the `Template.tsx` shell served from a `file+` PDF route reusing the screens' service calls (§8). CSV export still ships alongside. *(Original resolution deferred this to Phase 2.)*
+- [x] **Computed-row naming** — **Answer:** Keep "Net Income" (NetSuite/QBO naming; existing Carbon label). The augmented Retained Earnings row keeps the account's own name with a computed-value tooltip.
+- [x] **GL detail default status filter** — **Answer:** Posted + Reversed by default. Draft journals are visible only behind an explicit status filter and are always excluded from the running balance (they aren't real GL yet).
+- [x] **Comparative presets before period-closing ships** — **Answer (revised 2026-07-02):** Date-math presets stay (correct for calendar-month periods), AND the period picker ships in v1 as UI over the date params (§9) — it reads `accountingPeriod.fiscalYear`/`periodNumber` directly and hides gracefully when the period-closing migration hasn't been applied. *(Original resolution deferred the picker to Phase 2.)*
+- [x] **Dimension/cost-center-filtered statements** — **Answer:** Out of scope for this spec — a future spec of its own. Budget comparison columns remain owned by the budgeting spec (Phase 3), which plugs into this spec's comparison-column mechanism.
+
+## Changelog
+
+- 2026-07-02: Created — grounded in codebase exploration (existing trial balance / balance sheet / income statement routes, `accountTreeBalancesByCompany` semantics, class-normal sign convention in `packages/utils/src/accounting.ts`, consolidation path) and competitor research (SAP FSV/F0996/F3076, NetSuite layouts + computed RE + Classify-Cash-style overrides, QBO/Xero computed equity rows and drill-down); see `.ai/research/financial-reporting.md`. Coordinated with the period-closing spec (virtual year-end → report-time RE) and budgeting spec (Phase 3 reuses the comparison-column mechanism).
+- 2026-07-02: All open questions resolved (recommendations accepted; user delegated by requesting spec + plan together); status → in-progress. Key calls: SCF single-company in v1, PDF package deferred (CSV ships), "Net Income" label kept, GL detail defaults to Posted+Reversed, date-math comparison presets, dimension-filtered statements out of scope.
+- 2026-07-03: **Posted-only balances folded in** per the public-company readiness audit (`2026-07-03-public-company-readiness.md` SD-1, roadmap `.ai/plans/2026-07-03-public-company-readiness-roadmap.md`): `p_include_drafts DEFAULT FALSE` on `accountTreeBalancesByCompany` + `trialBalance`, "Include drafts" toggle on report filters, drawer follows parent. Update `.ai/plans/2026-07-02-financial-reporting.md` tasks accordingly before implementation.
+- 2026-07-02: Phase 2 folded into v1 scope at user request — consolidated cash flow (§7, `translateTrialBalance` rate model + FX-effect plug), PDF financial statements package (§8, hand-built react-pdf per `.ai/rules/pdf-generation-patterns.md`), period picker (§9, UI-only over date params, reads period-closing's columns via cast), saved report views (§10, new `reportView` table mirroring `userModulePreference`). Three open-question answers revised accordingly. Still out: cash-basis toggle, dimension-filtered statements, PDF customization, shared views.
diff --git a/.ai/specs/2026-07-02-period-closing.md b/.ai/specs/2026-07-02-period-closing.md
new file mode 100644
index 0000000000..782f10afe1
--- /dev/null
+++ b/.ai/specs/2026-07-02-period-closing.md
@@ -0,0 +1,324 @@
+# Accounting Period Closing
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-02
+> Research notes: `.ai/research/period-closing.md`
+
+## TLDR
+
+Carbon already has an `accountingPeriod` table with `closedAt`/`closedBy` columns and a single close gate buried in `getOrCreateAccountingPeriod`, but no way to close a period from the UI, no soft-close stage, and several posting paths (notably manual journal entries) that never check the period at all. This spec introduces a first-class period close lifecycle — **Open → Locked → Closed** — modeled on NetSuite's period statuses and SAP's authorization-group posting intervals: *Locked* is a soft close where only accounting users can post adjustments (operational postings from receipts, shipments, and invoices are blocked), and *Closed* is a hard close enforced by a database trigger that no posting path can bypass. Periods gain explicit `fiscalYear`/`periodNumber` identity generated from `fiscalYearSettings`, closes are sequential (like NetSuite), a **NetSuite-style persisted close checklist** per period (ordered tasks with owners and sign-off evidence; system tasks auto-evaluated from computed checks — draft journals, unposted documents, negative inventory, unmatched intercompany, TB balance; skip-with-reason for warnings; Close as the terminal task) gates closing, and year-end stays implicit — Carbon's virtual Net Income / retained-earnings computation means no closing entries are ever posted, which is self-healing by construction (the same property SAP achieves with re-runnable balance carryforward).
+
+## Problem Statement
+
+There is no way to close an accounting period in Carbon. Concretely:
+
+- A controller finishes the June close, runs the June income statement for the board — and a week later a warehouse user posts a backdated receipt into June. The statements silently change. Nothing in the product prevents this.
+- The `accountingPeriod` table has `closedAt`/`closedBy` columns ([20230705033432_ledgers.sql:32-50](packages/database/supabase/migrations/20230705033432_ledgers.sql)) and `getOrCreateAccountingPeriod` refuses to post into a period where `closedAt` is set ([accounting.service.ts:517-523](apps/erp/app/modules/accounting/accounting.service.ts)) — but **nothing ever sets `closedAt`**. The gate is dead code.
+- `postJournalEntry` ([accounting.service.ts:1896-1959](apps/erp/app/modules/accounting/accounting.service.ts)) validates balance but never checks the period, so manual journal entries bypass even the dead gate.
+- Periods are created lazily one month at a time with no fiscal-year identity (`fiscalYear`, `periodNumber`), so there is no way to render "FY2026 · Period 6" or enforce sequential close.
+- The `status` enum (`Inactive`/`Active`) tracks "which period is current," which is a different axis from open/closed and is derivable from the date anyway.
+
+Every serious ERP treats period close as a core control: SAP gates postings per account type and user group via posting period variants (OB52), NetSuite walks a dependency-ordered close checklist ending in a hard close, D365 locks per-module per-period. Carbon needs the same control, sized for a mid-market manufacturer.
+
+## Proposed Solution
+
+### Lifecycle: Open → Locked → Closed
+
+A new `periodCloseStatus` enum and `closeStatus` column on `accountingPeriod`:
+
+| Status | Operational postings (receipts, shipments, invoices, adjustments, backflush) | Accounting postings (manual JE, depreciation, eliminations, FX) | Who can transition |
+|--------|------|------|------|
+| **Open** | ✅ allowed | ✅ allowed | — |
+| **Locked** | ❌ blocked | ✅ allowed (requires `update: accounting`) | Lock/unlock: `update: accounting` |
+| **Closed** | ❌ blocked | ❌ blocked (DB trigger backstop) | Close: `update: accounting`; Reopen: see Open Questions |
+
+This two-stage close is the elegant core of the design. It captures the essence of NetSuite's "Lock A/R → Lock A/P → Lock All → Close" progression and SAP's interval-1 authorization group ("only the close team may post during close") with **one column and one rule**, instead of a per-subledger flag matrix. Per-subledger locks (AR/AP/Inventory independently) can be layered on later without schema churn if real customers need them.
+
+The mapping of "operational vs accounting" posting is by journal `sourceType`: manual journal entries, `Asset Depreciation`, `Asset Disposal`, intercompany eliminations, and FX revaluation are *accounting* sources; everything driven by documents (receipt, shipment, invoice, payment, inventory adjustment, backflush) is *operational*.
+
+### Sequential close, ordered reopen
+
+- A period can only be **Closed** if every earlier period in the company is Closed (NetSuite rule). This guarantees an unbroken audit boundary.
+- A period can only be **reopened** if every later period is Open — i.e., you unwind the boundary from the most recent close backwards, never punching a hole in the middle.
+- **Locking** is not sequential — a controller may lock June for close prep while May is still being tidied.
+
+### Fiscal-year identity and period generation
+
+Add `fiscalYear INT` and `periodNumber INT` to `accountingPeriod`, and a `createFiscalYearPeriods` service that generates the 12 monthly periods for a fiscal year from `fiscalYearSettings.startMonth`. The existing lazy auto-create in `getOrCreateAccountingPeriod` remains as a fallback but now stamps `fiscalYear`/`periodNumber` so lazily-created and generated periods are indistinguishable.
+
+The `Active`/`Inactive` status column is left in place but deprecated: "current period" is derivable from `startDate <= today <= endDate`, and the toggle logic in `getOrCreateAccountingPeriod` is removed once nothing reads it (verified below in Open Questions).
+
+### Enforcement: one choke point + a database backstop
+
+1. **Service layer (the choke point).** `getOrCreateAccountingPeriod` gains a posting-context parameter: `getOrCreateAccountingPeriod(client, companyId, date, source: "operational" | "accounting")`. It enforces the matrix above and returns the existing `{data, error}` shape. Every posting path already calls it (post-receipt, post-shipment, post-purchase-invoice, payments, backflush) or must be made to (`postJournalEntry` — the known gap; also `postDepreciationRun`, `postDisposal` in `accounting.server.ts`).
+2. **Database trigger (the backstop).** A `BEFORE INSERT OR UPDATE` trigger on `journal` raises an exception when the row's `accountingPeriodId` (or the period containing `postingDate`) has `closeStatus = 'Closed'`. Edge functions, Inngest jobs with the service-role key, and any future code path all hit this regardless of whether they remembered to call the service gate. Locked-period nuance (who is posting) stays at the service layer where user identity is known; the trigger only enforces the hard invariant *nothing posts into a Closed period*.
+3. **Reversal symmetry.** `reverseJournalEntry` must date the reversing entry in the *current open period*, never back into the closed source period (standard SAP/NetSuite behavior for reversals across a close boundary).
+4. **Posted-record immutability (same trigger wave).** Added per the public-company readiness audit (`.ai/specs/2026-07-03-public-company-readiness.md`, MW-1) — cheaper to build with this migration than to retrofit: a second `BEFORE UPDATE` backstop makes **posted journals immutable in every period state, not just Closed**. On `journal`, the only permitted UPDATE once `status = 'Posted'` is the status transition `Posted → Reversed` (setting `reversedById`); on `journalLine`, all UPDATE/DELETE is rejected once the parent journal is Posted. SECURITY DEFINER like the period trigger, so it binds edge functions and service-role jobs. This closes the existing RLS hole (`20260402000000:84-92` allows posted-header updates with `WITH CHECK (true)`) at the same layer, in the same review, with the same writer inventory this spec already requires. Corrections remain reversal-only. `journalLine` also gains `createdBy` in this migration so every line carries preparer identity from day one of enforced close.
+
+### NetSuite-style close checklist (persisted tasks + computed auto-checks)
+
+*(Scope revised 2026-07-04 at user direction — the original v1 deliberately deferred the persisted task engine; it is now in scope so that later close tasks — FX revaluation, revenue recognition, bank reconciliation, depreciation scheduling — register into an existing substrate instead of retrofitting one.)*
+
+Each accounting period gets a **persisted, ordered checklist** of close tasks (the NetSuite Period Close Checklist model): tasks have owners, statuses, sort order, and completion evidence; system tasks auto-evaluate from computed checks; manual tasks are human sign-offs; the terminal task is Close itself.
+
+Two tables:
+
+- **`periodCloseTaskDefinition`** — the company-level template: name, `taskType`, sort order, `required`, `active`, optional default assignee, optional `autoCheckKey` binding the task to a computed evaluator. Companies can add manual tasks, reorder, and toggle optional ones; seeded system definitions cannot be deleted (deactivate instead).
+- **`periodCloseTask`** — per-period instances, created idempotently from active definitions when the period's close drawer first opens (or on Lock). Status `Open | Done | Skipped`; `completedBy/At`; `skippedReason` (required on skip); optional evidence link (journal id / note).
+
+**Auto-evaluated tasks** bind to the computed readiness checks (which remain, as the evaluator layer):
+
+| Seeded task (default order) | Type | Auto-check | Severity |
+|---|---|---|---|
+| 1. Post pending operational documents (receipts/shipments/invoices dated in period; posting queue drained) | Auto | pending-postings | Blocker |
+| 2. Post or re-date draft journal entries in the period | Auto | draft-journals | Blocker |
+| 3. Lock the period (operational postings blocked) | Action | — | Required |
+| 4. Post depreciation runs covering the period | Auto | draft-depreciation | Warning |
+| 5. Match & eliminate intercompany transactions (group companies only) | Auto | unmatched-ic | Warning |
+| 6. Review negative on-hand inventory | Auto | negative-inventory | Warning |
+| 7. Trial balance in balance for the period | Auto | tb-balanced | Blocker |
+| 8. Review financial statements | Manual | — | Required |
+| 9. Close the period | Action | — | Terminal |
+
+Semantics:
+
+- An **Auto** task's live pass/fail is computed on every checklist render; when its check passes it reads Done (system), and its final state is persisted at Close for the audit record.
+- **Blocker** auto-tasks can never be skipped; **Warning** auto-tasks and optional manual tasks can be skipped with a required reason (permission `update: accounting`), recorded on the row.
+- **Close** is enabled only when every `required` task is Done/Skipped and no Blocker fails — the same gate the computed-only design enforced, now with owners, sign-off evidence, and a durable per-period record (the close binder auditors ask for).
+- Later features register their own definitions when they ship (FX revaluation, revenue recognition, bank-rec-complete-per-account, consolidated-rates) — the readiness roadmap's Phase-1 items name this checklist as their execution surface.
+- `getPeriodCloseReadiness` remains as the evaluator service backing the auto-checks; the drawer renders the checklist, not the raw check list.
+
+### Year-end: implicit, no closing entries
+
+Carbon already computes Net Income virtually (`NET_INCOME_ACCOUNT_ID`, never posted) — the NetSuite model, and the one this spec keeps. Closing period 12 of a fiscal year **is** the year-end close; retained earnings roll-forward happens at report time and is self-healing if a prior year is ever reopened and adjusted (the property SAP needs re-runnable FAGLGVTR carryforward to achieve). No "Close Income Statement" batch job (Business Central) and no closing journals. If materialized carryforward is ever needed for report performance, it can be added later without changing this model.
+
+### Audit trail
+
+Every transition (Lock, Unlock, Close, Reopen) is recorded via the existing audit log system (`.ai/rules/audit-log-system.md`) with user, timestamp, and prior status. `closedAt`/`closedBy` (existing columns) hold the latest close; `lockedAt`/`lockedBy` are added for symmetry. Reopen clears `closedAt`/`closedBy` (history lives in the audit log).
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Status model | New `closeStatus` column (`periodCloseStatus` enum: `Open`/`Locked`/`Closed`), NOT new values on `accountingPeriodStatus` | Open/closed is a different axis from the existing Active/Inactive "current period" toggle; Postgres enums can't remove values, so overloading is irreversible. Enum uses capitalized display-friendly values per convention. |
+| Soft close granularity | Single `Locked` status gating by posting source (operational vs accounting), not per-subledger AR/AP/Inventory flags | One column captures SAP's interval-1 authorization group and most of NetSuite's staged locks; per-subledger flags can be layered on later. Simplicity first. |
+| Hard-close enforcement | DB trigger on `journal` + service-layer gate | Posting happens from edge functions, Inngest service-role jobs, and app services — only a trigger catches all of them. Locked semantics stay in the service layer where the user is known. |
+| Posted-record immutability | Second SECURITY DEFINER trigger in the same migration: Posted journals allow only `Posted → Reversed`; journalLines frozen once parent is Posted; `journalLine.createdBy` added | Readiness audit MW-1 (SOX AS 2401 / GoBD Unveränderbarkeit); same writer inventory, same trigger surface, same review — retrofit later would touch every posting path twice |
+| Year-end | Implicit (virtual retained earnings, no closing entries) | Carbon already computes Net Income virtually; matches NetSuite; self-healing on prior-year reopen. |
+| Close ordering | Sequential close, reverse-sequential reopen, non-sequential lock | NetSuite rule; guarantees a contiguous closed boundary with no holes. |
+| Checklist | **Persisted NetSuite-style task list** (`periodCloseTaskDefinition` template + per-period `periodCloseTask`), with the computed readiness checks retained as the auto-evaluator layer | Revised 2026-07-04 at user direction: later close tasks (FX reval, rev rec, bank rec, depreciation) need a registration surface — building it now avoids retrofitting; auto-checks keep the zero-config control value; persisted rows give owners, sign-offs, and the per-period close binder auditors request. |
+| Multi-tenancy | Existing `accountingPeriod` keeps its legacy single-column PK (`xid()`); no new tables in v1 | Altering the PK of a referenced table is high-risk churn for zero behavior gain; all new columns are on the existing table. No new tables ⇒ heuristic satisfied by inheritance. |
+| Service shape | `lockAccountingPeriod` / `closeAccountingPeriod` / `reopenAccountingPeriod` / `getPeriodCloseReadiness` in `accounting.service.ts`, `(client, companyId, ...)` → `{data, error}`, never throw | `.ai/rules/conventions-services.md`; one module service file, no new files. |
+| RLS | `accountingPeriod` UPDATE policy requires `accounting_update`; status transitions additionally validated in service (sequential rules can't be expressed in RLS cleanly) | Matches existing permission-based policy pattern. |
+| Permission for close/lock | `update: "accounting"` via `requirePermissions` | Matches fiscal-year-settings and journal-posting precedent; a dedicated close permission is an Open Question. |
+| Form pattern | `ValidatedForm` + zod validator + route actions with `intent` field | Matches `settings+/accounting.tsx` precedent. |
+| Reversals across close boundary | Reversing entry posts to current open period | SAP/NetSuite standard; preserves closed-period immutability. |
+| Backward compatibility | `getOrCreateAccountingPeriod` keeps its signature with a new optional `source` param defaulting to `"operational"` | All existing callers become safely gated by default; accounting paths opt in to the looser rule explicitly. |
+
+## Data Model Changes
+
+One idempotent migration (`pnpm db:migrate:new period-close-lifecycle`, randomized HHMMSS), then `pnpm run generate:types`:
+
+```sql
+-- New enum for the close lifecycle (separate axis from Active/Inactive)
+DO $$ BEGIN
+ CREATE TYPE "periodCloseStatus" AS ENUM ('Open', 'Locked', 'Closed');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+ALTER TABLE "accountingPeriod"
+ ADD COLUMN IF NOT EXISTS "closeStatus" "periodCloseStatus" NOT NULL DEFAULT 'Open',
+ ADD COLUMN IF NOT EXISTS "fiscalYear" INTEGER,
+ ADD COLUMN IF NOT EXISTS "periodNumber" INTEGER,
+ ADD COLUMN IF NOT EXISTS "lockedAt" TIMESTAMP WITH TIME ZONE,
+ ADD COLUMN IF NOT EXISTS "lockedBy" TEXT REFERENCES "user"("id") ON DELETE RESTRICT;
+
+-- Backfill closeStatus from the (never-populated, but be safe) closedAt column
+UPDATE "accountingPeriod" SET "closeStatus" = 'Closed'
+WHERE "closedAt" IS NOT NULL AND "closeStatus" = 'Open';
+
+-- Backfill fiscalYear/periodNumber from fiscalYearSettings.startMonth
+-- (calendar math in migration; COALESCE to calendar year/month when settings missing)
+
+CREATE UNIQUE INDEX IF NOT EXISTS "accountingPeriod_company_fy_period_idx"
+ ON "accountingPeriod" ("companyId", "fiscalYear", "periodNumber");
+
+-- Hard backstop: nothing posts into a Closed period
+CREATE OR REPLACE FUNCTION check_accounting_period_open() RETURNS TRIGGER AS $$
+DECLARE period_status "periodCloseStatus";
+BEGIN
+ SELECT "closeStatus" INTO period_status
+ FROM "accountingPeriod"
+ WHERE ("id" = NEW."accountingPeriodId")
+ OR (NEW."accountingPeriodId" IS NULL
+ AND "companyId" = NEW."companyId"
+ AND NEW."postingDate" BETWEEN "startDate" AND "endDate");
+ IF period_status = 'Closed' THEN
+ RAISE EXCEPTION 'Accounting period is closed for posting date %', NEW."postingDate";
+ END IF;
+ RETURN NEW;
+END; $$ LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS "journal_check_period_open" ON "journal";
+CREATE TRIGGER "journal_check_period_open"
+ BEFORE INSERT OR UPDATE OF "postingDate", "accountingPeriodId" ON "journal"
+ FOR EACH ROW EXECUTE FUNCTION check_accounting_period_open();
+```
+
+Checklist tables (same migration wave; standard audit columns + four RLS policies gated on `accounting_*` per conventions):
+
+```sql
+CREATE TABLE IF NOT EXISTS "periodCloseTaskDefinition" (
+ "id" TEXT NOT NULL DEFAULT id('pctd'),
+ "companyId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "taskType" TEXT NOT NULL DEFAULT 'Manual', -- 'Auto' | 'Action' | 'Manual'
+ "autoCheckKey" TEXT, -- binds Auto tasks to a readiness evaluator
+ "sortOrder" INTEGER NOT NULL DEFAULT 1,
+ "required" BOOLEAN NOT NULL DEFAULT true,
+ "severity" TEXT, -- 'Blocker' | 'Warning' (Auto tasks)
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "isSystem" BOOLEAN NOT NULL DEFAULT false, -- seeded rows: deactivate, never delete
+ "defaultAssigneeId" TEXT REFERENCES "user"("id"),
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "periodCloseTaskDefinition_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "periodCloseTaskDefinition_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE TABLE IF NOT EXISTS "periodCloseTask" (
+ "id" TEXT NOT NULL DEFAULT id('pct'),
+ "companyId" TEXT NOT NULL,
+ "accountingPeriodId" TEXT NOT NULL, -- FK accountingPeriod (legacy single-col PK)
+ "definitionId" TEXT, -- NULL = ad-hoc task added for this period
+ "name" TEXT NOT NULL, -- snapshot from definition
+ "taskType" TEXT NOT NULL,
+ "autoCheckKey" TEXT,
+ "sortOrder" INTEGER NOT NULL,
+ "required" BOOLEAN NOT NULL,
+ "severity" TEXT,
+ "status" TEXT NOT NULL DEFAULT 'Open', -- 'Open' | 'Done' | 'Skipped'
+ "assigneeId" TEXT REFERENCES "user"("id"),
+ "completedBy" TEXT REFERENCES "user"("id"), -- NULL for system-auto completions
+ "completedAt" TIMESTAMP WITH TIME ZONE,
+ "skippedReason" TEXT, -- required when status = 'Skipped'
+ "evidenceJournalId" TEXT,
+ "notes" TEXT,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "periodCloseTask_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "periodCloseTask_period_definition_key" UNIQUE ("companyId", "accountingPeriodId", "definitionId")
+);
+-- Seed: the 9 default system definitions (table above) per existing company +
+-- in seed-company for new companies.
+```
+
+Notes:
+- No views select from `accountingPeriod` today (verify during implementation; if any do, DROP/recreate with `SELECT *`).
+- `closedAt`/`closedBy` columns are reused as-is; the existing `closedAt` check in `getOrCreateAccountingPeriod` is replaced by `closeStatus` checks.
+- The trigger intentionally does **not** distinguish Locked — that requires knowing the actor, which lives in the service layer.
+
+## API / Service Changes
+
+All in `apps/erp/app/modules/accounting/accounting.service.ts` (+ zod in `accounting.models.ts`):
+
+```ts
+// Extended gate — all existing callers default to "operational" and become stricter
+getOrCreateAccountingPeriod(client, companyId, date, source: "operational" | "accounting" = "operational")
+// → { data: periodId, error } ; error when closeStatus === 'Closed',
+// or closeStatus === 'Locked' && source === 'operational'
+
+// Lifecycle transitions (validate sequential rules, stamp lockedAt/By, closedAt/By, write audit log)
+lockAccountingPeriod(client, { periodId, companyId, userId })
+unlockAccountingPeriod(client, { periodId, companyId, userId })
+closeAccountingPeriod(client, { periodId, companyId, userId }) // requires earlier periods Closed + no blockers
+reopenAccountingPeriod(client, { periodId, companyId, userId }) // requires later periods Open
+
+// Generation + queries
+createFiscalYearPeriods(client, { companyId, fiscalYear, userId }) // 12 periods from fiscalYearSettings
+getAccountingPeriods(client, companyId, { fiscalYear? })
+getPeriodCloseReadiness(client, companyId, periodId) // → { blockers: Check[], warnings: Check[] } — the auto-check evaluator layer
+
+// Close checklist (NetSuite-style)
+getPeriodCloseChecklist(client, companyId, periodId)
+// instantiates tasks from active definitions if missing (idempotent via the
+// (companyId, accountingPeriodId, definitionId) unique key), overlays live
+// auto-check results onto Auto tasks, returns ordered tasks
+completeCloseTask(client, { taskId, companyId, userId, evidenceJournalId?, notes? }) // Manual/Action tasks
+skipCloseTask(client, { taskId, companyId, userId, reason }) // rejected for Blocker auto-tasks; reason required
+addCloseTask(client, { companyId, accountingPeriodId, name, assigneeId?, userId }) // ad-hoc per-period task
+get/upsert/deactivatePeriodCloseTaskDefinition(...) // template CRUD (settings surface)
+// closeAccountingPeriod additionally: requires every required task Done/Skipped and
+// no failing Blocker auto-check; persists final auto-task states on the rows at close.
+```
+
+Callers to update:
+- `postJournalEntry` — add the period gate (`source: "accounting"`) before setting status to Posted. **This closes the biggest existing hole.**
+- `postDepreciationRun`, `postDisposal` (`accounting.server.ts`) — gate with `source: "accounting"`.
+- `generateEliminations` — gate with `source: "accounting"`.
+- Edge functions `post-receipt`, `post-shipment`, `post-purchase-invoice`, payment posting — already call `getOrCreateAccountingPeriod`; the default `"operational"` source makes them respect Locked with no signature change at call sites.
+- `reverseJournalEntry` — if the source entry's period is Locked/Closed, date the reversal in the current open period.
+
+Routes (new, under `apps/erp/app/routes/x+/accounting+/`):
+- `periods.tsx` — loader (`view: "accounting"`) lists periods grouped by fiscal year; action (`update: "accounting"`) with `intent`: `lock` | `unlock` | `close` | `reopen` | `generate`.
+- `periods.$periodId.close.tsx` — Drawer child route (per Drawer-overlay convention) showing `getPeriodCloseReadiness` results with confirm.
+
+## UI Changes
+
+- **Periods page** (`/x/accounting/periods`): table grouped by fiscal year — period number, name ("FY2026 · P6 (Jun)"), date range, status badge (Open gray / Locked amber / Closed green, plain counts, no parenthesized numbers), closed-by/at. Row actions: Lock, Unlock, Close…, Reopen (visibility driven by status + sequential rules). "Generate FY{next}" button when the next fiscal year has no periods. Added to the accounting sidebar next to Fiscal Year settings.
+- **Close drawer = the checklist** (NetSuite Period Close Checklist shape): ordered task rows with status icon, assignee avatar, and per-type affordances — Auto tasks show live pass/fail with a drill link to the offending records (draft JEs list, unposted documents, IC matching page); Action tasks deep-link (Lock button, Close button); Manual tasks have Complete (with optional evidence/notes) and Skip-with-reason. Blockers render red and disable Close; skipped warnings show amber with the reason. Progress indicator ("6 of 9 done") also renders on the periods table row. Follows the Drawer-overlay detail-view convention.
+- **Checklist template settings**: a section on the periods page (or accounting settings) listing `periodCloseTaskDefinition` rows — add manual tasks, reorder, set default assignees, deactivate optional tasks; system rows lock their type/autoCheck fields.
+- **Journal entry form**: v1 relies on the server-side gate — posting into a Locked/Closed period fails with a clear flash error from `postJournalEntry`. An inline pre-submit warning on the posting-date field is deferred (see plan's non-goals).
+- **Flash messages** on all transitions per `.ai/rules/flash-system.md`.
+
+## Acceptance Criteria
+
+- [ ] Controller with `accounting_update` can generate FY periods, and lock, close, and reopen periods from `/x/accounting/periods`; each transition flashes success and appears in the audit log with user + timestamp.
+- [ ] Closing period N fails with a clear error while period N−1 is not Closed; reopening period N fails while period N+1 is Closed.
+- [ ] With June **Locked**: posting a receipt dated June 15 via the normal receipt flow fails with "period is locked"; posting a manual journal entry dated June 15 as an accounting user succeeds.
+- [ ] With June **Closed**: `postJournalEntry`, post-receipt, post-shipment, post-purchase-invoice, depreciation run, and disposal all fail with a period-closed error; a direct SQL `INSERT` into `journal` with a June posting date (service-role) is rejected by the trigger.
+- [ ] Close drawer shows a blocker when a draft journal entry dated in the period exists, and Close is disabled until it is posted or re-dated; warnings (negative inventory, unmatched IC) allow close after explicit skip-with-reason.
+- [ ] Opening the close drawer for a fresh period instantiates the 9 seeded checklist tasks exactly once (re-opening does not duplicate); Auto tasks flip to Done as their checks pass; a Manual task records completedBy/At; a Warning task skips only with a reason and never a Blocker; Close is enabled only when every required task is Done/Skipped, and closing persists the final task states.
+- [ ] A custom manual task added to the template appears in the next period's checklist with its default assignee; deactivating it removes it from future periods without touching past ones.
+- [ ] Reversing a journal entry whose period is Closed creates the reversing entry dated in the current open period, and both entries reference each other.
+- [ ] Trial balance / balance sheet / income statement for a closed period return identical numbers before and after unrelated postings in later periods.
+- [ ] A **Posted** journal in an **Open** period rejects direct header UPDATEs (description, postingDate) and any journalLine UPDATE/DELETE via PostgREST — with user credentials and with the service role; the `Posted → Reversed` status transition still succeeds; new journal lines carry `createdBy`.
+- [ ] Existing lazy period auto-creation still works for a date with no period, and the created period carries correct `fiscalYear`/`periodNumber`.
+- [ ] `pnpm run generate:types` then `pnpm run typecheck` and `pnpm run lint` pass; migration applies idempotently twice in a row.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| In-flight `post-transaction` Inngest jobs reference a period that closes mid-flight → job fails against trigger | Med | Jobs already retry (3x); error message is explicit; readiness blocker "pending posting-queue items" prevents closing on top of a hot queue |
+| Xero sync writes inbound transactions dated in a Locked/Closed period → sync errors or silent divergence | High | Open Question 4; minimum: sync handler catches the period error and surfaces it in the integration error queue rather than looping |
+| Trigger fires on every journal insert → hot-path overhead | Low | Single indexed PK/date-range lookup per posted journal; journals are not high-frequency inserts |
+| Backfilled `fiscalYear`/`periodNumber` wrong for companies that changed `startMonth` after old periods were created | Med | Backfill from period `startDate` month arithmetic, not from current settings alone; flag mismatches in migration NOTICE |
+| Users locked out of legitimate late adjustments (auditors, tax) | Med | Reopen is supported, permission-gated, and fully audited; virtual year-end means prior-year reopen self-heals retained earnings |
+| Deprecating `Active`/`Inactive` breaks an unnoticed reader of `status = 'Active'` | Med | Phase the removal: keep the toggle in v1, grep + remove in a follow-up once verified unused |
+
+## Open Questions
+
+> All questions resolved 2026-07-02 (user delegated to best judgment).
+
+- [x] **Locked semantics** — **Answer:** Source-based locking in v1 (operational blocked, accounting allowed with `update: accounting`). Per-subledger AR/AP/Inventory locks deferred; the single `closeStatus` column layers them on later without schema churn. Simplicity first.
+- [x] **Reopen permission** — **Answer:** Reopen requires `delete: "accounting"` — the de-facto module-admin tier. Adding a dedicated permission would touch the RBAC system (explicitly ask-first territory) for marginal v1 gain. Lock/unlock/close stay at `update: "accounting"`. Every reopen is audit-logged.
+- [x] **Adjustment period** — **Answer:** Deferred to v2. `periodNumber` schema and the unique index already accommodate a period 13; nothing in v1 hard-codes 12.
+- [x] **Xero sync vs closed periods** — **Answer:** Reject (option a). Inbound sync writes into Locked/Closed periods fail with the period error and surface through the existing sync error handling — no silent re-dating, no special bypass. Matches the "reject and surface" posture of the trigger backstop.
+- [x] **Group/consolidation ordering** — **Answer:** Warning, not a block. `getPeriodCloseReadiness` warns when the company belongs to a group and unmatched intercompany transactions exist for the period. Close remains strictly per-company in v1.
+- [x] **`Active`/`Inactive` deprecation** — **Answer:** Keep the toggle untouched in v1 (minimal impact); removal is a follow-up after a grep audit confirms nothing reads `status = 'Active'`.
+- [x] **Queue behavior on closed-period failure** — **Answer:** Fail loudly through the existing Inngest retry/error path — no new dead-letter UI in v1. The readiness blocker for pending posting-queue items prevents most occurrences by construction.
+
+## Changelog
+
+- 2026-07-02: Created — grounded in codebase exploration (existing `accountingPeriod`/`closedAt` gate, posting entry-point inventory) and ERP research (SAP OB52/AFC, NetSuite period close checklist, D365/BC/Odoo lock models); see `.ai/research/period-closing.md`.
+- 2026-07-02: All open questions resolved (user delegated to best judgment); status → in-progress. Key calls: source-based Locked in v1, reopen gated by `delete: accounting`, adjustment period deferred, sync writes rejected into non-open periods, group ordering as warning, Active/Inactive removal deferred, no dead-letter UI.
+- 2026-07-02: Implementation plan written at `.ai/plans/2026-07-02-period-closing.md`; migration drafted at `packages/database/supabase/migrations/20260702044133_period-close-lifecycle.sql` (not yet applied). Recon finding folded in: edge functions use a separate period helper (`packages/database/supabase/functions/shared/get-accounting-period.ts`) with no close check — added as a mandatory gate point; depreciation/disposal are gated at their routes; eliminations post via DB RPC and are covered by the trigger backstop. Inline journal-form warning deferred to v2.
+- 2026-07-04: **NetSuite-style persisted close checklist added at user direction**, superseding the v1 "computed, not persisted" decision (and its earlier open-question resolution): `periodCloseTaskDefinition` template + per-period `periodCloseTask` with Auto (readiness-check-backed) / Action / Manual tasks, skip-with-reason (never for Blockers), sign-off evidence, 9 seeded system tasks, and template customization. The computed readiness checks remain as the auto-evaluator layer. Later close tasks (FX revaluation, rev rec, bank rec, consolidated rates — readiness roadmap Phase 1+) register definitions here instead of retrofitting a task engine. Plan updated with addendum tasks 17–20.
+- 2026-07-03: **Posted-record immutability folded in** per the public-company readiness audit (`2026-07-03-public-company-readiness.md` MW-1, roadmap `.ai/plans/2026-07-03-public-company-readiness-roadmap.md`): second SECURITY DEFINER trigger (posted journals = status-transition-only in all period states; journalLines frozen once posted), `journalLine.createdBy` column. Extend the drafted migration + plan tasks accordingly before implementation. Rationale: same trigger surface, same writer inventory — right the first time.
diff --git a/.ai/specs/2026-07-02-plaid-bank-feeds.md b/.ai/specs/2026-07-02-plaid-bank-feeds.md
new file mode 100644
index 0000000000..1973224e60
--- /dev/null
+++ b/.ai/specs/2026-07-02-plaid-bank-feeds.md
@@ -0,0 +1,214 @@
+# Plaid Bank Feeds & Cash Position (Bank Reconciliation Phase 2)
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-02
+> Research notes: `.ai/research/plaid-bank-feeds.md` (Plaid mechanics verified against plaid.com/docs 2026-07-02)
+> Parent spec: `.ai/specs/2026-07-02-bank-reconciliation.md` (Phase 2 of its phasing table)
+
+## TLDR
+
+Phase 1 gives Carbon bank reconciliation with manually uploaded statements; Phase 2 removes the manual step and adds daily cash visibility. A **Plaid integration** (following the Xero integration architecture exactly: `packages/ee` registry entry, `companyIntegration` row, webhook route, Inngest jobs) lets a controller connect their banks through Plaid Link, map each Plaid account to a Carbon `bankAccount`, and from then on statement lines flow in automatically: a webhook-driven **`bank-feed-sync`** job runs the `/transactions/sync` cursor loop (restart-on-mutation semantics, cursor committed only after a complete loop), inverts Plaid's outflow-positive sign, swaps pending lines for posted ones via `pending_transaction_id`, flags feed-removed-but-matched lines for review, snapshots balances into `bankAccountBalance`, and finishes by running the Phase 1 auto-matcher. Item health is managed end-to-end: ES256-JWT-verified webhooks, `ITEM_LOGIN_REQUIRED`/`PENDING_EXPIRATION` → a Requires Reauth banner → Link **update mode** (same access token, no re-exchange), plus a daily scheduled catch-up sync as webhook-loss insurance. Access tokens are stored Vault-backed per the parent spec's resolved decision — with an explicit environment probe and an app-layer AES-GCM fallback if Vault turns out to be absent from the self-hosted stack (it is currently unverified there). On top of the feed, a **Cash Position** page becomes the Banking landing: per account, the latest bank balance vs GL balance with the drift decomposed into unmatched statement lines, outstanding GL items, and an unexplained residual — the "your books are wrong" signal, daily instead of at month-end. **Cross-account transfer detection** proposes matches for opposite-signed equal-amount lines between own accounts and books the transfer JE on accept.
+
+## Problem Statement
+
+With Phase 1 alone, a controller must log into each bank portal, download OFX/CSV files, and upload them — weekly at best, so unrecorded fees, duplicate ACHs, and failed deposits hide for days or weeks, and the reconcile workspace is only as fresh as the last upload. Concretely: a $12,400 customer wire lands Monday; nobody uploads a statement until Friday; the part shipment waiting on "payment received" sits five days. Meanwhile "how much cash do we have right now, and do the books agree?" still requires opening three bank portals and a trial balance side by side. Transfers between own accounts (operating → payroll) appear as two unmatched lines in two workspaces with no linkage, and each must be hand-coded as a JE.
+
+NetSuite ships bank feeds through aggregators (Salt Edge named for Europe; US partner unnamed) on top of the same two-stage flow Carbon built in Phase 1; Xero/QBO treat feeds as the default and file upload as the fallback. Plaid is the natural aggregator for Carbon's mid-market US customer base, and the parent spec already resolved the decisions (Plaid SDK server-side, script-tag Link, Vault-backed tokens, 90-day default backfill).
+
+## Proposed Solution
+
+### Integration registration (Xero pattern, verbatim)
+
+- `packages/ee/src/plaid/config.tsx`: registry entry (id `plaid`, category Banking, logo, description); hidden unless `PLAID_CLIENT_ID` + `PLAID_SECRET` env vars are set. Added to the `integrations` array in `packages/ee/src/index.ts`.
+- `packages/ee/src/plaid/hooks.server.ts` registered in `packages/ee/src/hooks.server.ts`: `onInstall` (no event-system subscriptions needed — the feed is inbound-only), `onUninstall` (remove webhooks is a no-op — Plaid webhook URL is per-Item; mark Items disconnected, clear connection status on mapped bank accounts, delete stored tokens), `onHealthcheck` (per Item: `/accounts/get`; any `ITEM_LOGIN_REQUIRED` → unhealthy).
+- `packages/ee/src/plaid/client.ts`: thin wrapper over the `plaid` Node SDK (new production dependency in `@carbon/ee`, resolved in the parent spec), constructed from `PLAID_CLIENT_ID`/`PLAID_SECRET`/`PLAID_ENV` (`sandbox` | `production`).
+- If the `integration` registry table requires a seeded row (verify how Xero's row exists), a one-line idempotent migration seeds `plaid`.
+
+### Connect flow
+
+1. **Start** (settings → integrations → Plaid, or "Connect bank" on the bank accounts page): action route `api+/integrations.plaid.link-token.ts` calls `/link/token/create` with `products: ["transactions"]`, `webhook: <app URL>/api/webhook/plaid`, `transactions.days_requested` from the user's backfill choice (**90 default / 180 / 365 / 730** — immutable per Item after link, so it is chosen here), `user.client_user_id = userId`.
+2. **Link** (client): Plaid Link loaded via script tag (no npm client dep); on success posts `public_token` + institution metadata to `api+/integrations.plaid.exchange.ts`.
+3. **Exchange** (server): `/item/public_token/exchange` → `access_token` + `item_id`. Token goes to secret storage (below); `companyIntegration('plaid', companyId).metadata.items[]` gains `{ itemId, tokenRef, institutionId, institutionName, daysRequested, cursor: null, status: "Connected", connectedBy, connectedAt }`. The row is upserted `active: true` on first connect.
+4. **Map accounts**: the exchange response lists the Item's accounts (`/accounts/get`); a mapping step shows each Plaid account (name, mask, type, currency) with three choices per account: create a new `bankAccount` (prefilled name/mask/type/currency — GL account picked by the user), link to an existing unmapped `bankAccount` (currency must match), or skip (not synced). Mapped accounts get `plaidItemId`/`plaidAccountId`/`source = 'Plaid'`/`connectionStatus = 'Connected'`.
+5. **Prime**: fire `bank-feed-sync` for the Item immediately — `SYNC_UPDATES_AVAILABLE` only starts firing after the first `/transactions/sync` call on an Item (verified), so priming is mandatory, and it also delivers the initial backfill without waiting for a webhook.
+
+### Token storage (Vault, with a probed fallback)
+
+Parent-spec decision: Supabase Vault. **Unverified in this stack** (no `vault`/`pgsodium` anywhere in migrations or `config.toml`) — so:
+
+- Implementation Task 1 probes `SELECT 1 FROM vault.secrets LIMIT 0` on the local stack and the Docker/cloud deploy targets.
+- **If present**: `tokenRef = { kind: "vault", secretId }` via `vault.create_secret(access_token)`; reads happen server-side only (service role) through `vault.decrypted_secrets`.
+- **If absent anywhere we deploy**: fallback is app-layer **AES-256-GCM** with a required `PLAID_TOKEN_ENCRYPTION_KEY` env secret (32 bytes, base64); `tokenRef = { kind: "aes", ciphertext, iv, tag }` stored in the metadata JSON. Same interface (`getItemAccessToken(companyId, itemId)` in `packages/ee/src/plaid/tokens.server.ts`), so the storage backend is swappable and the Xero-token migration can follow either way.
+- Never the Xero plaintext pattern for bank credentials (fallback pre-approved; see resolved Open Question 1).
+
+### Sync job — `bank-feed-sync`
+
+Inngest function (`carbon/bank-feed-sync`, registered in `packages/lib/src/trigger.ts` + `events.ts`), payload `{ companyId, itemId, trigger: "webhook" | "manual" | "scheduled" | "connect" }`, concurrency-keyed on `companyId:itemId` so one Item never syncs twice concurrently:
+
+1. Load Item (metadata + token), resolve mapped `bankAccount`s by `plaidAccountId`.
+2. **Cursor loop**: `/transactions/sync` from the stored cursor until `has_more = false`, buffering pages. On `TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION`, restart the whole loop from the stored cursor (verified requirement). Only after a complete loop: apply changes + persist `next_cursor` to metadata.
+3. **Apply** per mapped account (unmapped accounts' transactions are skipped):
+ - `added`: insert `bankTransaction` (`source: 'Plaid'`, `externalId = transaction_id`, **amount = −plaid.amount**, `status = pending ? 'Pending' : 'Unmatched'`, `pendingExternalId = pending_transaction_id`, `counterparty` from `merchant_name ?? name`, `raw` = trimmed payload) with `ON CONFLICT (bankAccountId, externalId) DO NOTHING`.
+ - `modified`: update the same columns by `externalId` **only when the row is still Pending/Unmatched**; a modified-but-Matched line gets `needsReview = true` instead of silent mutation.
+ - `removed`: delete Pending/Unmatched rows; a removed-but-Matched/Reconciled row gets `needsReview = true` (never deleted).
+ - Pending→posted swap: when an `added` posted row carries `pendingTransactionId`, delete the matching Pending row (by `externalId = pending_transaction_id`) in the same transaction.
+4. **Balances**: `/accounts/balance/get` → upsert `bankAccountBalance` (`date = today`, `source = 'Plaid'`, `balance = current`, sign flipped for credit accounts so the stored balance is in Carbon's convention) — one snapshot per account per day (existing unique index).
+5. **Match**: `run_bank_matching(bankAccountId, companyId, userId)` per affected account (userId = the job's acting user: the Item's `connectedBy`).
+6. Stamp `bankAccount.lastSyncedAt`; clear `connectionStatus` to `Connected` on success.
+
+**Scheduled catch-up**: a daily Inngest cron iterates all active plaid `companyIntegration` rows and fires `bank-feed-sync` per Item (webhook-loss insurance + keeps dev environments fresh where webhooks can't reach). "Sync now" button fires the same event with `trigger: "manual"`.
+
+### Webhook route — `api+/webhook.plaid.ts`
+
+Pure verify-and-dispatch (Xero webhook precedent):
+
+1. Verify the `Plaid-Verification` header JWT: `alg` must be ES256; fetch the public key from `/webhook_verification_key/get` by the JWT's `kid` (cache keys by `kid` in module scope); reject `iat` older than 5 minutes; compare the `request_body_sha256` claim to the SHA-256 of the **raw** body with a constant-time comparison. Any failure → 401, no processing.
+2. Route by `webhook_type`/`webhook_code`:
+ - `TRANSACTIONS` / `SYNC_UPDATES_AVAILABLE` → `trigger("bank-feed-sync", { companyId, itemId, trigger: "webhook" })` (company resolved by scanning `companyIntegration` metadata for the `item_id` — add a small `getCompanyByPlaidItemId(serviceRole, itemId)` helper).
+ - `ITEM` / `ERROR` with `ITEM_LOGIN_REQUIRED`, `PENDING_EXPIRATION`, `PENDING_DISCONNECT` → set the Item's metadata `status: "Requires Reauth"` and `connectionStatus = 'Requires Reauth'` on its mapped bank accounts.
+ - `ITEM` / `USER_PERMISSION_REVOKED` → Item `status: "Error"`, accounts `connectionStatus = 'Error'` (bank account rows and history are always kept — resolved: keep-and-relink).
+ - Everything else (legacy `INITIAL_UPDATE`/`HISTORICAL_UPDATE`/`DEFAULT_UPDATE`/`TRANSACTIONS_REMOVED`) → 200, ignored (sync handles state).
+3. Always 200 fast; never do sync work inline.
+
+### Re-auth (Link update mode)
+
+- Requires-Reauth banner on the bank accounts page and Cash Position (existing Phase 1 banner slot) with a "Reconnect" button → `api+/integrations.plaid.link-token.ts` with the Item's `access_token` (update mode — no products); on Link success, no re-exchange is needed (verified: the access token is unchanged) — just reset Item + account statuses to Connected and fire a sync.
+
+### Cash Position page (Banking landing)
+
+Route `x+/accounting+/banking.tsx`, sidebar "Cash Position" atop the Banking group. Per active bank account:
+
+- **Bank balance**: latest `bankAccountBalance` (badge shows source + as-of date).
+- **GL balance**: sum of posted journal lines on `glAccountId` (reuses the trial-balance query path).
+- **Drift decomposition** (all as of the balance date, sign convention positive = inflow):
+ `residual = bankBalance − glBalance + Σ(unmatched GL lines) − Σ(unmatched/pending bank lines)`
+ Displayed as: bank balance, GL balance, "explained by *n* statement lines awaiting match (Σx) and *m* outstanding GL items (Σy)", and **Residual** — green at 0, red otherwise (the misstatement signal).
+- Unmatched count (links to the reconcile workspace), days since last completed reconciliation, connection badge, last synced, 30-day balance sparkline from `bankAccountBalance` (simple inline SVG — no charting dep).
+- Company-total header (base-currency accounts summed; foreign-currency accounts listed separately, unconverted, in v1).
+
+### Transfer detection
+
+- `detectBankTransfers(client, companyId)`: pairs of **Unmatched** lines across two *different* active bank accounts with equal absolute amount, opposite signs, same currency, dates within ±3 days; excludes pairs where either line already has a pending proposal; returns proposals ranked by date proximity.
+- Surfaced as banners in the reconcile workspace (both sides) and a card on Cash Position. Accept → new server fn `createBankTransferFromTransactions` (accounting.server.ts, Kysely tx): one posted `journal` (sourceType `Manual`, description "Transfer {from} → {to}") with two lines (debit receiving GL, credit sending GL, base currency — both accounts must be base-currency in v1, matching quick-create's FX restriction), plus **two match groups**, each pairing one bank line with its own journal line. Dismiss → records nothing (recomputed proposals naturally drop pairs whose lines got matched elsewhere).
+
+### Sandbox & testing strategy
+
+- `PLAID_ENV=sandbox` for local/dev; credentials `user_good`/`pass_good`.
+- Automated tests bypass the Link UI entirely with `/sandbox/public_token/create` → exchange → prime sync (no browser needed); `/sandbox/item/reset_login` drives the re-auth path; `/sandbox/item/fire_webhook` exercises the webhook route **against a deployed environment** — local `*.dev` is unreachable from Plaid, so the local dev loop is "Sync now" + the scheduled catch-up, by design.
+- Sandbox Items auto-enter `ITEM_LOGIN_REQUIRED` after 30 days — dev banners appearing after a month are expected behavior, not a bug.
+
+### Non-goals (Phase 2)
+
+Money movement of any kind (Plaid Auth/Transfer), investments/liabilities products, non-Plaid aggregators (Salt Edge etc.), cash-flow forecasting, converting foreign-currency balances in the Cash Position totals, and auto-accepting transfer proposals.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| New tables | **None** — Phase 1 schema carries everything (`bankAccount` linkage columns, `bankTransaction.pendingExternalId`/`needsReview`, `bankAccountBalance`); possible one-row `integration` registry seed | Feed state (tokens, cursors, Item status) is integration state → `companyIntegration.metadata`, per Xero precedent |
+| Multi-tenancy / RLS / service shape / forms | Inherited — no new tables, services follow `(client, ...) → {data, error}`, connect-flow routes under `api+` use the Xero permission pattern, Cash Position under `view: "accounting"` | Heuristics 1–6 satisfied by Phase 1 surfaces + Xero-precedent routes |
+| Permission scoping | Connect/disconnect: `update: "settings"` (integration management, Xero precedent); sync-now / transfer-accept / re-auth: `update: "accounting"`; Cash Position: `view: "accounting"` | Connecting a bank is company-integration admin; day-to-day feed actions are accounting work |
+| Token storage | Vault-backed `tokenRef` with probed AES-256-GCM env-key fallback behind one `getItemAccessToken` interface | Parent-spec decision, adapted to the fact Vault is unverified in this stack; interface makes the backend swappable |
+| Cursor persistence | Buffer full loop, persist cursor only on loop completion; restart from stored cursor on `TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION` | Verified Plaid requirement; partial-loop cursors lose data permanently |
+| Sign & balance convention | Amount = −plaid.amount at ingest; credit-account balances flipped at snapshot | One inversion point per direction; everything downstream stays in Carbon's positive-=-inflow convention |
+| Modified/removed on matched lines | `needsReview = true`, never mutate or delete | Phase 1 lifecycle rule; evidential integrity of matched/reconciled lines |
+| Webhook handling | Verify-and-dispatch route (ES256 JWT, body hash, 5-min replay window, key cache); all work in Inngest | Xero precedent; keeps the route fast and idempotent |
+| Backfill window | Connect-time choice 90/180/365/730 days, stored per Item | `days_requested` is immutable per Item (verified) — must be chosen up front |
+| Priming | Immediate sync on connect | `SYNC_UPDATES_AVAILABLE` never fires before the first sync call (verified) |
+| Sync concurrency | Inngest concurrency key `companyId:itemId`, limit 1 | Cursor loops must not interleave per Item |
+| Job identity | `run_bank_matching` + row stamps use the Item's `connectedBy` user | Deterministic attribution without a synthetic system user |
+| Transfer accept | One JE + two match groups in one Kysely tx; base-currency accounts only | Reuses Phase 1 primitives; FX transfers deferred with quick-create's restriction |
+| Sparkline | Inline SVG from `bankAccountBalance` | No charting dependency for 30 points |
+
+## Data Model Changes
+
+None, except (verify at implementation) a seed row if the `integration` registry table is migration-seeded:
+
+```sql
+-- Only if integration rows are seeded by migration (mirror however 'xero' exists):
+INSERT INTO "integration" ("id", "name", "active")
+VALUES ('plaid', 'Plaid', TRUE)
+ON CONFLICT ("id") DO NOTHING;
+```
+
+`companyIntegration('plaid').metadata` documented shape (JSON, not schema):
+
+```jsonc
+{
+ "items": [{
+ "itemId": "item-abc",
+ "tokenRef": { "kind": "vault", "secretId": "..." }, // or { "kind": "aes", "ciphertext", "iv", "tag" }
+ "institutionId": "ins_109508",
+ "institutionName": "First Platypus Bank",
+ "daysRequested": 90,
+ "cursor": "AAAA...", // null until first completed loop
+ "status": "Connected", // Connected | Requires Reauth | Error
+ "connectedBy": "user_x",
+ "connectedAt": "2026-07-02T..."
+ }]
+}
+```
+
+## API / Service Changes
+
+- **`packages/ee/src/plaid/`**: `config.tsx`, `hooks.server.ts`, `client.ts` (SDK wrapper), `tokens.server.ts` (`storeItemAccessToken`, `getItemAccessToken`), `sync.server.ts` (the cursor-loop + apply logic, shared by job and connect-prime), `index.ts`.
+- **Env** (`packages/env/src/index.ts`): `PLAID_CLIENT_ID` (public), `PLAID_SECRET` (secret), `PLAID_ENV` (default `sandbox`), `PLAID_TOKEN_ENCRYPTION_KEY` (secret; required only in AES fallback mode). `.env.example` updated.
+- **Routes** (`apps/erp/app/routes/`):
+ - `api+/integrations.plaid.link-token.ts` — action; `update: "settings"` for connect, or `update: "accounting"` when `itemId` present (update mode); returns `{ linkToken }`.
+ - `api+/integrations.plaid.exchange.ts` — action; exchanges token, stores secret, upserts metadata item, returns the Item's accounts for the mapping step.
+ - `api+/integrations.plaid.map-accounts.ts` — action; applies the account mapping (create/link/skip per Plaid account), then fires the priming sync.
+ - `api+/webhook.plaid.ts` — the verify-and-dispatch webhook (public, JWT-gated).
+ - `x+/accounting+/banking.tsx` — Cash Position loader (`view: "accounting"`) + actions (`intent: "sync" | "accept-transfer" | "dismiss-transfer"`).
+- **Services** (`accounting.service.ts`): `getCashPosition(client, companyId)` (balances + GL sums + drift terms per account), `detectBankTransfers(client, companyId)`; (`accounting.server.ts`): `createBankTransferFromTransactions(db, args)`.
+- **Jobs** (`packages/jobs/src/inngest/functions/integrations/`): `bank-feed-sync.ts` (event `carbon/bank-feed-sync`) + `bank-feed-scheduled.ts` (daily cron fan-out). Registered in `packages/lib/src/trigger.ts` / `events.ts` / the jobs index.
+
+## UI Changes
+
+- **Integrations page**: Plaid card (logo, description, Connected-items summary, Connect/Disconnect) — Xero card precedent.
+- **Connect modal**: backfill-window select (90/180/365/730 days with "cannot be changed later" helper text) → Link (script-tag) → account-mapping step (per Plaid account: create new / link existing / skip, with currency-mismatch rows disabled) → done state showing the priming sync kicked off.
+- **Bank accounts page** (Phase 1): "Connect bank" button goes live; Plaid rows show connection badge + "Sync now" + relink action when Requires Reauth; reauth banner wired to update-mode Link.
+- **Cash Position** (`/x/accounting/banking`, new sidebar entry "Cash Position"): per-account rows/cards with bank balance (as-of), GL balance, drift decomposition with green/red residual, unmatched-count link into the workspace, sparkline; transfer-proposal card with Accept/Dismiss; company-total header. ERP `size="md"`, plain numbers, Lingui throughout.
+- **Reconcile workspace** (Phase 1): transfer-proposal banner on lines that are one side of a detected pair.
+
+## Acceptance Criteria
+
+- [ ] With `PLAID_*` env unset, the Plaid card is absent and all Plaid routes 404/no-op; with sandbox env set, connect → Link (`user_good`/`pass_good`) → mapping step creates/links bank accounts with `plaidItemId`/`plaidAccountId` and fires a priming sync that lands the backfilled lines (sign inverted: a Plaid-positive debit stores negative).
+- [ ] `SYNC_UPDATES_AVAILABLE` delivered to `api+/webhook.plaid.ts` with a valid ES256 JWT triggers an incremental sync; an invalid signature, wrong `alg`, body-hash mismatch, or `iat` >5 min old each return 401 and trigger nothing.
+- [ ] A sync interrupted by `TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION` restarts from the stored cursor and applies the update exactly once (no duplicate `bankTransaction` rows — unique `(bankAccountId, externalId)` holds).
+- [ ] A pending line shows status Pending and is unmatchable; when its posted version arrives with `pending_transaction_id`, the Pending row is gone and the posted row is Unmatched; a feed `removed` on a Matched line sets `needsReview` and the workspace surfaces it.
+- [ ] `/sandbox/item/reset_login` flips the Item and its accounts to Requires Reauth with a banner; completing update-mode Link restores Connected without re-mapping accounts, and the same access token keeps syncing.
+- [ ] Daily scheduled catch-up syncs every active Item without webhooks; "Sync now" does the same on demand; two concurrent triggers for one Item never interleave (concurrency key).
+- [ ] After each sync, balances land in `bankAccountBalance` (one row per account/day) and `run_bank_matching` has run — a payment posted before the sync auto-matches its feed line with no user action.
+- [ ] Cash Position shows, per account, bank balance vs GL balance with residual = bankBalance − glBalance + Σ(unmatched GL) − Σ(unmatched+pending bank lines); residual is 0 (green) on a fully explained account and red otherwise; sparkline renders 30 days of snapshots.
+- [ ] Two opposite $5,000 Unmatched lines in two base-currency accounts within 3 days produce a transfer proposal; Accept books one JE and both lines flip to Matched (each in its own group); Dismiss leaves both Unmatched and the pair is not re-proposed while unchanged.
+- [ ] Token storage: access tokens are never present in `companyIntegration.metadata` plaintext (only `tokenRef`); with Vault available, secrets live in `vault.secrets`; in fallback mode, ciphertext decrypts only server-side with `PLAID_TOKEN_ENCRYPTION_KEY`.
+- [ ] `pnpm exec turbo run typecheck --filter=erp --filter=@carbon/ee --filter=@carbon/jobs` and `pnpm run lint` pass.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Vault absent in self-hosted/Docker deploys → token-storage decision blocked | Med | Probe first; AES-GCM env-key fallback pre-approved behind the same interface — the probe cannot block |
+| Webhook endpoint is public and attacker-reachable | Med | Full verification chain (ES256 + `kid` key fetch + body hash constant-time + 5-min replay window); route does nothing but dispatch |
+| Cursor loss/corruption in metadata JSON → re-ingest storm | Low | Unique `(bankAccountId, externalId)` makes re-ingest idempotent (duplicates skipped); worst case is wasted API calls |
+| Item webhook → company resolution scans metadata JSON | Low | Items per company are few; add a `metadata->items` GIN index only if it ever shows up in traces |
+| Plaid production approval/pricing not in place when Phase 2 lands | Med | Resolved: account created now, approval runs in parallel; sandbox works end-to-end without approval, so build/test isn't blocked |
+| Local dev can't receive webhooks → devs think feeds are broken | Low | Scheduled catch-up + "Sync now" keep dev fresh; documented in the integration card copy and the research notes |
+| `modified` rewrites of Unmatched lines fight a user mid-match | Low | Updates only touch Pending/Unmatched rows; Matched+ rows go to `needsReview` |
+| Balance snapshot sign errors on credit accounts | Med | One flip point at snapshot write + acceptance criterion; class-aware convention already established in Phase 1 |
+
+## Open Questions
+
+> ✅ All resolved 2026-07-02 — recommendations accepted verbatim by Brad ("let's go with the recommendations"). Implementation may proceed.
+
+- [x] **Vault probe outcome & fallback approval** — the parent spec chose Supabase Vault, but `vault`/`pgsodium` appear nowhere in this stack's migrations/config. If the probe finds Vault missing in any deploy target, is the AES-256-GCM + `PLAID_TOKEN_ENCRYPTION_KEY` fallback approved as the v1 storage (same interface, swappable later)? Matters because it gates the token-storage implementation and the Xero-migration follow-up. **Answer: approved — if the probe finds Vault missing in any deploy target, ship the AES-256-GCM + `PLAID_TOKEN_ENCRYPTION_KEY` fallback behind the same `getItemAccessToken` interface.**
+- [x] **Webhook URL / environment reachability** — webhooks need a public HTTPS URL per Item. Production uses the app URL; what should *deployed dev/staging* Items use, and do we accept "no webhooks locally, scheduled+manual sync only" as the permanent local-dev story? Matters for how the webhook path gets exercised before production. **Answer: accepted — local dev is scheduled + manual sync only; the webhook path is verified on the deployed dev environment via `/sandbox/item/fire_webhook`.**
+- [x] **Plaid account ownership & production approval** — who owns the Plaid dashboard account, and when do we start production access approval (it gates real banks + pricing)? Matters for launch sequencing, not build. **Answer: Brad creates the Plaid dashboard account now and starts production approval in parallel; implementation proceeds entirely on sandbox.**
+- [x] **Retention on revocation** — when `USER_PERMISSION_REVOKED` arrives (user cut access at the bank), keep the `bankAccount` + all transactions and allow relinking a future Item to the same account (history preserved), never auto-delete? Matters because deletion would destroy reconciliation history. **Answer: keep-and-relink, always — bank accounts and transaction history are never auto-deleted on revocation.**
+- [x] **Scheduled catch-up cadence** — daily (06:00 UTC) per Item, or twice daily? Plaid bills per connected account, not per API call, so frequency is about freshness vs job noise. Matters little; setting it once avoids churn. **Answer: daily; webhooks are the real-time channel.**
+
+## Changelog
+
+- 2026-07-02: Created — Phase 2 of `.ai/specs/2026-07-02-bank-reconciliation.md`. Plaid mechanics verified directly against plaid.com/docs (sync cursor/mutation-restart, webhook JWT verification chain, update mode, `days_requested` immutability, sandbox endpoints) after the Phase-1 research pass's verification outage; Vault availability flagged unverified in this stack. See `.ai/research/plaid-bank-feeds.md`.
+- 2026-07-02: All open questions resolved — recommendations accepted verbatim ("let's go with the recommendations"): AES-GCM fallback pre-approved pending the Vault probe; local-dev webhook story accepted; Plaid account + production approval started in parallel; keep-and-relink on revocation; daily catch-up cadence. Status → in-progress; ready for `/plan`.
diff --git a/.ai/specs/2026-07-03-multi-jurisdiction-tax.md b/.ai/specs/2026-07-03-multi-jurisdiction-tax.md
new file mode 100644
index 0000000000..5af6ab3457
--- /dev/null
+++ b/.ai/specs/2026-07-03-multi-jurisdiction-tax.md
@@ -0,0 +1,412 @@
+# Multi-Jurisdiction Tax Compliance
+
+> Status: draft (open questions resolved — ready for /plan)
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-03
+> Research notes: `.ai/research/multi-jurisdiction-tax.md`
+
+## TLDR
+
+Carbon's tax support today is a single flat `taxPercent` per line, defaulted from the customer record — and at posting time that tax is **credited into revenue** on the sales side and **capitalized into cost** on the purchase side; the `salesTaxPayableAccount` / `purchaseTaxPayableAccount` / `reverseChargeSalesTaxPayableAccount` fields that have existed in `accountDefault` since 2023 are dead config that no posting path reads. This spec introduces a unified multi-jurisdiction tax system built from the industry-consensus parts (research: SAP, NetSuite, Dynamics 365 BC, Odoo, Xero, Avalara), sized to Carbon's post-posting-group philosophy of **flat, direct configuration over classification matrices**: a **tax code** composed of **components** (one per jurisdiction/authority, each with its own rate and GL accounts — covering single-rate VAT and stacked US state+county+city alike); **direct assignment** of codes to customers, ship-to locations, and suppliers (the Xero model — two-hop resolution, no matrix), with address-based *suggestions* at assignment time and a single `taxable` boolean on items; an immutable **`taxLedger`** subledger written when documents post (the BC "VAT Entry" / SAP BSET pattern) that all tax reporting reads; **corrected GL posting** (revenue net of tax + per-component output-tax liability; recoverable input tax as an asset, with a non-recoverable flag preserving today's capitalize-into-cost behavior for US purchase tax); **reverse charge and US use-tax accrual** as compositions of the same paired-entry machinery; **memo tax** so credit/debit memos correctly unwind liability; company **tax registrations** that print on documents; **tax returns with settlement posting** (period-locked ledger rows, a settlement journal entry, and optional remittance through AP to the authority's supplier record); and an **Avalara AvaTax connector** (estimate on orders, committed transactions at posting, address validation, outage fallback) that swaps in behind the single `resolveLineTaxes` seam per company. Delivery is phased: Phase 1 determination + posting + ledger + reporting, Phase 2 returns/settlement + use tax, Phase 3 external engine + Xero tax mapping.
+
+## Problem Statement
+
+A manufacturer selling into several US states — or exporting from a VAT country — cannot use Carbon for tax compliance today:
+
+- **One flat rate per customer.** `customer.taxPercent` (NUMERIC, 0..1) is copied onto quote/order/invoice lines ([sales.service.ts:1937](apps/erp/app/modules/sales/sales.service.ts), [20241105002325_quote-taxes-and-shipping.sql](packages/database/supabase/migrations/20241105002325_quote-taxes-and-shipping.sql)). There is no notion of *where* the goods ship (destination-based US sourcing), *what* is being sold (item taxability), or *which authority* the tax belongs to. A Texas customer with plants in Austin (8.25%) and a no-nexus state gets one rate for both.
+- **Collected tax is booked as revenue.** `post-sales-invoice` computes the line total as `(qty × unitPrice + shipping + addOn) × (1 + taxPercent)` ([post-sales-invoice/index.ts:302-306](packages/database/supabase/functions/post-sales-invoice/index.ts)) and credits the **sales account** with that gross amount ([post-sales-invoice/index.ts:381-398](packages/database/supabase/functions/post-sales-invoice/index.ts)). Revenue is overstated by every dollar of tax collected, and no liability is recorded — there is nothing to remit against.
+- **Recoverable input tax is buried in cost.** `post-purchase-invoice` folds `taxAmount` into line cost ([post-purchase-invoice/index.ts:449-458](packages/database/supabase/functions/post-purchase-invoice/index.ts)) and only ever posts to `payablesAccount`. For US purchase tax that is correct (tax is part of cost); for VAT jurisdictions it is wrong — input VAT is a receivable, and burying it in inventory misstates both.
+- **The account plumbing exists but is dead.** `accountDefault.salesTaxPayableAccount`, `purchaseTaxPayableAccount`, and `reverseChargeSalesTaxPayableAccount` are referenced by **zero** posting paths (verified by grep across `packages/database/supabase/functions/`). The old per-type posting-group overrides are gone entirely — [20260229000000_drop-posting-groups.sql](packages/database/supabase/migrations/20260229000000_drop-posting-groups.sql) dropped the posting-group matrix in favor of flat `accountDefault` resolution (`functions/shared/get-posting-group.ts` → `getDefaultPostingGroup` now reads `accountDefault` directly).
+- **Exemption metadata is inert.** The recent `customerTax` / `supplierTax` tables ([20260430000001_tax-status.sql](packages/database/supabase/migrations/20260430000001_tax-status.sql)) capture `taxExempt`, exemption reason, and certificate number/file — but nothing reads `taxExempt` during calculation (verified: it appears only in forms and a header badge). An exempt customer with a resale certificate is still charged their `taxPercent`.
+- **Memos can't carry tax.** The `memo` table ([20260630093809_ar-ap-payments.sql:310](packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql)) is a header-only document (single `amount`, `direction` Credit/Debit, reason account) — a credit memo against a taxed invoice cannot reduce the tax liability.
+- **No reporting, no returns.** There is no record of taxable vs exempt bases by jurisdiction, so even the simplest filing question — "what do I owe Texas for Q2?" — is unanswerable, and there is no way to mark a period's tax as filed or post the settlement.
+
+Every surveyed ERP (SAP, NetSuite, BC, Odoo, Xero — see research) solves this with the same architecture: tax codes with per-jurisdiction components → posting to dedicated tax accounts → an immutable tax subledger → registrations gating scope → returns built from the subledger. None of it exists in Carbon.
+
+## Proposed Solution
+
+### One model for VAT, GST, and US sales tax
+
+Follow the unified pattern (Odoo/Xero/Avalara — research consensus #2 answer) rather than BC's parallel VAT-vs-sales-tax subsystems:
+
+- **`taxCode`** — a named treatment ("TX – Austin", "UK Standard 20%", "EU Reverse Charge", "Export Zero-Rated") with a `calculationType` (`Normal` | `Reverse Charge`), a `reportingCategory` (`Standard` | `Reduced` | `Zero-Rated` | `Exempt` | `Reverse Charge` | `Export` | `Out of Scope` — the attribute return layouts build on), an optional `invoiceMessage` (BC's VAT clause: "Reverse charge — VAT to be accounted for by the recipient"), and optional **address-match fields** (`countryId`, `state`) used to *suggest* the right code when assigning parties (never to silently resolve at document time).
+- **`taxCodeComponent`** — 1..n rows per code: component name ("TX State", "City of Austin"), `taxAuthorityId`, `rate`, `sequence`, `isCompound` (tax-on-tax, applied in sequence order), `isRecoverable` (purchase side: `true` = input tax posts to an asset account, `false` = capitalize into cost — unifies VAT and US purchase-tax behavior with one flag), optional per-component GL accounts (`salesTaxAccountId`, `purchaseTaxAccountId`, falling back to `accountDefault`), and `effectiveDate`/`expirationDate` for rate changes (BC Tax Detail pattern: to change a rate, expire the old component row and add a new one; determination picks rows effective at the document date).
+- **`taxAuthority`** — who you remit to (Texas Comptroller, HMRC), with an optional `supplierId` link so remittance becomes an ordinary payable (NetSuite's agency-as-vendor pattern — this is what Phase 2 settlement-to-AP builds on).
+
+UK VAT = one code, one component. Texas = one code, two to four components. Canada GST+PST = two components, PST optionally compound. The effective line rate is the compound-aware sum of effective components, and it lands in the existing `taxPercent` column — so every downstream consumer (invoice-total views from [20260604120000_invoice-totals-computed-in-views.sql](packages/database/supabase/migrations/20260604120000_invoice-totals-computed-in-views.sql), PDF math in `packages/documents/src/utils/sales-invoice.ts`, Xero sync) keeps working unchanged.
+
+### Determination: direct assignment, no matrix
+
+Carbon already tried the classification-matrix approach for GL accounts — customerType × itemPostingGroup posting groups — and **deliberately removed it** ([20260229000000_drop-posting-groups.sql](packages/database/supabase/migrations/20260229000000_drop-posting-groups.sql)) because the indirection was confusing; flat `accountDefault` resolution won. Tax determination follows the same philosophy, which is exactly Xero's model (per-contact default tax type + line override — research):
+
+- **Customers** get a `taxCodeId` (their default treatment). **Ship-to locations** (`customerLocation.taxCodeId`) override it for destination-based accuracy — the customer with an Austin plant and a California plant has a code on each location. **Suppliers** get a `taxCodeId` that defaults purchase lines (the supplier's invoice remains authoritative for amounts).
+- **Items** get a single **`taxable` boolean** (default `true`). Non-taxable items zero the line's tax and write an exempt-base ledger row. Rarer item-level distinctions (reduced-rate goods, state-specific service taxability) are a **line-level override** — pick a different code on the line; the long tail is the Avalara engine (Phase 3).
+- **Suggestion, not magic**: when a customer/location/supplier is created or its address edited, Carbon suggests active codes whose `countryId`/`state` match the address ("This address is in Texas — apply *TX – Austin*?"). The user confirms; documents then resolve deterministically from what was assigned. No document-time address inference, so a posted invoice's tax is always explainable by two fields.
+
+Resolution for a sales line (`resolveLineTaxes`):
+
+1. **Exempt customer?** `customerTax.taxExempt` → zero tax, no code; exemption reason and certificate number snapshot into the tax ledger at posting (exempt sales are *recorded*, not skipped — research consensus #6).
+2. **Non-taxable item?** `item.taxable = false` → zero tax; ledger row carries the base as exempt.
+3. **Code**: ship-to `customerLocation.taxCodeId` → `customer.taxCodeId` → none.
+4. Resolved code stamps `taxCodeId` + computed `taxPercent` on the line (override allowed, audit-logged per OQ 3).
+5. **No code** → fall back to today's behavior (`customer.taxPercent`, manual edit allowed). Companies that configure nothing see zero behavior change in determination.
+
+**Document-level shipping** is taxed at the document's resolved code when `companySettings.shippingIsTaxable` is on (OQ 5 resolution); off (default) keeps shipping untaxed, today's behavior.
+
+**Nexus semantics**: assignment *is* the nexus switch — a customer/location with no code (in a state where you aren't registered) gets no tax, mirroring Avalara's "no declared nexus → zero tax" (research consensus #5). The registrations page cross-warns: codes whose match fields point at a country/state with no active `taxRegistration`, and registrations with no matching code.
+
+### The tax subledger: `taxLedger`
+
+The BC VAT Entry / SAP BSET pattern (research consensus #3). When `post-sales-invoice` / `post-purchase-invoice` / memo posting post, they write one immutable `taxLedger` row per line per component: source (Sales/Purchase), document + line, journal id, code + component snapshots (name, authority, rate — self-contained even if config is later edited), taxable base, tax amount, exempt base, exemption reason, party, posting date, currency + exchange rate (amounts stored in base currency, journal parity). Exempt, non-taxable-item, and zero-rated lines write rows with `exemptAmount` — returns need exempt bases. VOID re-posting (the existing pattern in `post-sales-invoice`) writes reversing rows. Drafts never hit the ledger; they compute live from current components, so unposted documents float with rate changes and posted documents are frozen. Rows carry a nullable `taxReturnId` — stamped when a return is finalized (Phase 2), making filed rows immutable-by-inclusion (BC's open/closed VAT entries).
+
+### Corrected GL posting
+
+The behavior fix (research consensus #4), inside the existing edge functions:
+
+| Path | Today | After |
+|------|-------|-------|
+| Sales invoice | Dr AR gross / Cr Revenue **gross** | Dr AR gross / Cr Revenue **net** / Cr output tax per component (`component.salesTaxAccountId` → `accountDefault.salesTaxPayableAccount`) |
+| Purchase invoice (non-recoverable or no code) | Dr cost gross / Cr AP gross | unchanged — tax capitalizes into cost (correct for US purchase tax) |
+| Purchase invoice (recoverable components) | — | Dr cost **net** / Dr input tax per component (`component.purchaseTaxAccountId` → `accountDefault.purchaseTaxPayableAccount`) / Cr AP gross |
+| Purchase invoice (Reverse Charge code, recoverable) | — | Dr input tax / Cr `accountDefault.reverseChargeSalesTaxPayableAccount` — paired entries netting zero, both sides in the ledger (research consensus #7); AP stays net (supplier charged no tax) |
+| Purchase invoice (Reverse Charge code, non-recoverable) = **US use tax** | — | Dr cost **gross of accrued tax** (capitalize) / Cr use-tax liability (`reverseChargeSalesTaxPayableAccount` or component account); AP stays net — self-assessment when the supplier didn't charge tax (BC Use Tax / Provincial Tax pattern) |
+| Credit memo (customer, taxed) | Dr reason gross / Cr AR gross | Dr reason **net** / Dr output tax (unwinding liability) / Cr AR gross — negative `taxLedger` rows |
+
+**Use tax falls out of the existing flags** (elegant composition, no new machinery): `calculationType = 'Reverse Charge'` produces the self-assessed paired entry; `isRecoverable = false` routes the debit side into cost instead of an input-tax asset. A purchase line whose supplier charged no tax gets an "Accrue use tax" affordance (Phase 2) where the user picks the applicable Reverse Charge code — the accrual posts with no AP impact.
+
+Legacy lines (manual `taxPercent`, no `taxCodeId`) get the same sales-side fix, posting to `accountDefault.salesTaxPayableAccount` — one consistent rule instead of a config-dependent bug (OQ 1 resolution). Rounding is **per line, half-up, at currency precision** — matching how tax is computed and displayed today and Avalara's default for new companies; document-level rounding is explicitly out of scope.
+
+### Memo tax (OQ 2 resolution)
+
+`memo` gains `taxCodeId` + `taxAmount`. Semantics preserve the AR/AP tie-out contract: `memo.amount` remains **the gross figure that hits AR/AP** (unchanged for existing rows, views, and the net-model tie-out); `taxAmount` is the tax portion *within* it (auto-computed as `amount × r/(1+r)` from the resolved code — defaulted from the party's assigned code — and editable before posting). Posting splits: AR/AP gross (unchanged), reason account net, tax account per component with direction-aware sign; `taxLedger` rows are negative for Credit memos against sales (liability unwound) and mirrored for the other three direction/party combinations. Memos with no tax code post exactly as today.
+
+### Registrations and documents
+
+- **`taxRegistration`**: country (+ optional state/region), registration number, effective/end dates. Frames the liability report and prints on sales documents (the registration matching the company's country — EU invoices legally require the seller's VAT number; `company.taxId` remains as the fallback display value).
+- Sales invoice PDFs gain a tax summary block grouped by component/authority (jurisdiction breakdown), the resolved codes' `invoiceMessage` clauses, and the customer's VAT number (already captured in `customerTax.vatNumber`) when the code is Reverse Charge/Export — the B2B compliance trifecta.
+
+### Reporting: liability, returns, settlement
+
+- **Tax liability report** (Phase 1): group `taxLedger` over a date range by authority → component: **taxable base, exempt base, tax collected (sales), input tax (purchases), net due**. Answers the US filing question and the VAT question (output − recoverable input) from the same rows. CSV export via the existing table-export path.
+- **Tax returns** (Phase 2): a `taxReturn` document (period start/end, optional authority scope, status `Draft → Finalized`, totals snapshot). Finalizing a return stamps `taxReturnId` on the included `taxLedger` rows (they can never be claimed by another return) and **posts the settlement journal entry**: Dr each output-tax account, Cr each input-tax account, net to `accountDefault.taxSettlementAccount` (BC "Calc. and Post VAT Settlement" pattern). When the return's authority has a linked `supplierId`, Carbon offers to **create a draft purchase invoice to that supplier for the net due** — remittance flows through normal AP and payments (the NetSuite pay-tax-liabilities pattern). Late-arriving documents dated inside a finalized period simply land in the next return (their rows are unstamped), matching Odoo's tax-lock semantics without blocking postings — the period-closing spec's `Locked`/`Closed` statuses provide the hard boundary when both features are active.
+- **Return layouts** (Phase 2): `taxReturnLayout` + `taxReturnLayoutLine` map ledger aggregates to official return boxes (BC VAT Statement / Xero ReportTaxType pattern): each line has a box label/number, a source (`Sales` | `Purchase`), an aggregate (`Tax` | `Taxable Base` | `Exempt Base`), and filters (reporting categories and/or specific tax codes), plus row-totaling. A built-in generic layout (liability by authority + VAT summary by reporting category) works with zero configuration; a UK-MTD-shaped 9-box layout ships as a seeded example.
+
+### External engine: Avalara AvaTax connector (Phase 3)
+
+All determination flows through `resolveLineTaxes` (app service) and a shared edge-function helper (`functions/shared/resolve-taxes.ts`, following the existing `functions/shared/` helper precedent — `get-accounting-period.ts`, `get-next-sequence.ts`). Phase 3 implements the Avalara engine behind that seam, following the research-verified API contract:
+
+- **Company integration** (`companyIntegration`, the Xero precedent in `packages/ee`): account id, license key, company code, environment; per-company toggle "use AvaTax for determination" — when enabled, the resolver delegates to Avalara.
+- **Estimates**: quotes/orders call `CreateTransaction` with type `SalesOrder` (temporary, never persisted by Avalara); results fill `taxPercent` + a component preview.
+- **Committed documents**: `post-sales-invoice` calls type `SalesInvoice` with `commit: true`, `code` = Carbon invoice id (idempotent — re-posting overwrites uncommitted docs; committed conflicts surface as errors); the response's per-jurisdiction `details[]` map 1:1 into `taxLedger` rows (the component-row shape was designed to be isomorphic to Avalara's response). VOID calls `VoidTransaction`.
+- **Address validation**: `ResolveAddress` action on customer/location forms (US/CA), the Avalara ERP-guide placement.
+- **Exemptions**: `entityUseCode` derived from the existing `taxExemptionReason` enum; certificate numbers pass through.
+- **Outage fallback** (Avalara ERP guide): on API failure, fall back to the internal codes, flag the document (`taxLedger.needsEngineReconciliation`), and provide a reconcile action that re-runs committed transactions once the service recovers — never silently commit guessed tax.
+- **Nexus mirror**: registrations page compares Carbon `taxRegistration` rows against declared Avalara nexuses and warns on drift.
+
+### Xero tax mapping (Phase 3)
+
+The Xero syncer currently emits `TaxType: "OUTPUT" | "NONE"` from `taxPercent` ([packages/ee/src/accounting/providers/xero/entities/invoice.ts](packages/ee/src/accounting/providers/xero/entities/invoice.ts)). Phase 3 maps `taxCode` → Xero `TaxType` through the existing `externalIntegrationMapping` table (entityType `taxCode`), with per-code assignment in the tax-codes UI when a Xero integration is active; unmapped codes keep today's OUTPUT/NONE behavior.
+
+### Delivery phases
+
+| Phase | Scope | Depends on |
+|-------|-------|-----------|
+| **1 — Determine, post, report** | Schema; tax codes/components/authorities/registrations CRUD + UI; direct assignment on customers/locations/suppliers with address suggestions; `item.taxable`; `resolveLineTaxes` on quotes/orders/invoices/memos; corrected posting (sales split, recoverable input tax, reverse charge); memo tax; shipping taxability setting; exemption wiring; `taxLedger`; PDF tax blocks; liability report; `customer.taxPercent` sunset UX | — |
+| **2 — Returns & self-assessment** | `taxReturn` finalize + settlement JE + AP remittance; return layouts (+ seeded generic & UK layouts); use-tax accrual affordance on purchase lines | Phase 1 |
+| **3 — Engines & sync** | Avalara connector (estimates, committed docs, address validation, fallback, nexus mirror); Xero tax-code mapping | Phase 1 (2 for returns interplay) |
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Unified vs dual tax systems | One model: `taxCode` + components covers VAT, GST, and stacked US jurisdictions | Research consensus — BC's VAT/sales-tax split is NAV legacy; Odoo/Xero/Avalara prove components subsume both; Carbon gets one determination path, one ledger, one report |
+| Determination shape | **Direct assignment** (`customerLocation.taxCodeId` → `customer.taxCodeId`), item `taxable` boolean, line override — **no classification matrix** | Carbon dropped the posting-group matrix for exactly this confusion ([20260229000000_drop-posting-groups.sql](packages/database/supabase/migrations/20260229000000_drop-posting-groups.sql)); Xero's per-contact default + line override is the proven SMB model; two-hop resolution is explainable at a glance |
+| Address handling | Match fields on `taxCode` drive *suggestions* at assignment time; documents never infer from addresses | Deterministic, auditable document tax; no silent behavior change when an address is edited; rooftop accuracy is the Avalara engine's job (Phase 3) |
+| Item-side granularity | `item.taxable` boolean; finer distinctions via line override or Avalara | Reduced-rate/item-class-per-region matrices are the confusing 20%; manufacturing B2B is overwhelmingly standard-rated; boolean covers the common non-taxable-service case |
+| Rate storage on lines | Keep `taxPercent`, auto-filled from the resolved code; add nullable `taxCodeId` | Views, PDF math, and Xero sync consume `taxPercent` today — zero churn there; null `taxCodeId` = legacy manual behavior |
+| Historical immutability | `taxLedger` snapshot rows at posting; drafts compute live; finalized returns stamp rows | BC VAT Entry / SAP BSET pattern; config edits must never change posted documents; returns need bases, which GL doesn't hold |
+| Tax accounts | Per-component accounts with `accountDefault` fallback | Accounts-on-the-code is the consensus (BC jurisdictions, SAP account keys, Xero rates, Odoo repartition); matches the flat `accountDefault` philosophy — no per-type overrides |
+| Purchase-side recoverability | `isRecoverable` flag per component; non-recoverable capitalizes (today's behavior), recoverable posts to input-tax asset | Unifies US purchase tax and VAT with one flag (BC Expense/Capitalize, Xero IsNonRecoverable, SAP NVV); default `false` preserves current behavior until configured |
+| Reverse charge & use tax | `calculationType = 'Reverse Charge'` → paired self-assessed entries; `isRecoverable` picks EU reverse charge (recoverable) vs US use tax (capitalize + accrue) | One mechanism, two regimes (SAP/BC pattern); activates the existing `reverseChargeSalesTaxPayableAccount`; use-tax code picked explicitly on the line (Phase 2) |
+| Memo tax semantics | `memo.amount` stays gross (the AR/AP figure); `taxAmount` = tax within it, back-computed `amount × r/(1+r)`, editable | Preserves the AR/AP net-model tie-out contract and all existing memo rows/views; posting splits reason-account net vs tax with direction-aware signs |
+| Exemptions | `customerTax.taxExempt` short-circuits determination; reason + certificate snapshot to ledger; non-taxable items write exempt bases | Wires existing inert metadata; exempt sales write ledger rows because returns report exempt bases (research consensus #6) |
+| Rate changes | `effectiveDate`/`expirationDate` on components; resolver filters by document date | BC Tax Detail / SuiteTax validity pattern; jurisdictions change rates on fixed dates and backdated documents are routine |
+| Rounding | Per line, half-up, currency precision; document-level out of scope | Matches existing per-line computation and Avalara's default; keeps invoice-total views untouched |
+| Returns model | `taxReturn` stamps ledger rows on finalize + posts settlement JE; late documents roll to the next return | BC settlement + Odoo tax-lock semantics without blocking postings; hard period boundaries come from the period-closing spec when both ship |
+| Settlement remittance | Net due → `accountDefault.taxSettlementAccount`; optional draft AP invoice to the authority's linked supplier | NetSuite agency-as-vendor pattern; remittance rides existing AP + payments rails |
+| Return layouts | `taxReturnLayout(Line)` filtered by reporting category / tax code with box labels; generic + UK layouts seeded | BC VAT Statement / Xero ReportTaxType pattern; box mapping is config, the code stays jurisdiction-neutral |
+| External engine | Avalara connector behind the `resolveLineTaxes` seam; SalesOrder estimates, committed SalesInvoice at posting keyed by invoice id; internal fallback with reconcile flag | NetSuite SuiteTax plug-in pattern + Avalara ERP integration guide; ledger rows isomorphic to Avalara `details[]` by design |
+| Registrations vs nexus | `taxRegistration` records registrations; code assignment drives collection; UI cross-warns; Phase 3 mirrors against Avalara nexuses | Avalara/Stripe registration-gating semantics without blocking legitimate edge cases |
+| Multi-tenancy (heuristic 1) | Every new table: `companyId`, composite PK `("id","companyId")`, `id()` default, audit columns, `customFields` on config tables | House convention; child FKs reference `("id","companyId")` composites |
+| Service shape (heuristic 2) | All new functions in `accounting.service.ts` / `accounting.models.ts`, `(client, companyId, ...)` → `{data, error}`, never throw | One module service file per house rule; tax is accounting-owned like currencies and payment terms |
+| RLS (heuristic 3) | Four standard policies per table; SELECT via `get_companies_with_employee_role()`, writes via `get_companies_with_employee_permission('accounting_*')` | Config is accounting-gated; `taxLedger` writes happen via service-role posting functions, INSERT policy still defined for completeness |
+| Permission scoping (heuristic 4) | Tax config + returns routes: `view/update: "accounting"`; determination runs inside existing sales/purchasing document permissions; line overrides keep document permissions + audit log (OQ 3) | Matches currencies/payment-terms precedent; audit posture without shop-floor friction |
+| Form pattern (heuristic 5) | `ValidatedForm` + zod validators (`taxCodeValidator`, `taxRegistrationValidator`, …) + route actions; Drawer overlays for detail views | House convention + drawer-detail feedback rule |
+| Module layout (heuristic 6) | No new module; accounting module + `ui/Tax/` component folder; routes under `x+/accounting+/tax-*`; Avalara code in `packages/ee` | Tax config is accounting settings; integrations live in ee (Xero precedent) |
+| Backward compatibility (heuristic 7) | All new columns nullable (or defaulted to current behavior); no backfill; views recreated via DROP + `SELECT *`; `customer.taxPercent` hidden once codes are assigned, with a migration banner (OQ 4); sales-side posting fix applies to all lines (OQ 1, approved) | Unconfigured companies behave identically except the approved posting correction |
+
+## Data Model Changes
+
+One idempotent migration for Phase 1 (`pnpm db:migrate:new multi-jurisdiction-tax`, randomized HHMMSS) + a Phase 2 migration for returns; `pnpm run generate:types` after each. Sketch (audit columns, indexes on `companyId` + every FK, and the four standard RLS policies apply to every table; abbreviated here):
+
+```sql
+-- Enums (capitalized display values; additive-only later)
+CREATE TYPE "taxCalculationType" AS ENUM ('Normal', 'Reverse Charge');
+CREATE TYPE "taxReportingCategory" AS ENUM
+ ('Standard', 'Reduced', 'Zero-Rated', 'Exempt', 'Reverse Charge', 'Export', 'Out of Scope');
+CREATE TYPE "taxLedgerSource" AS ENUM ('Sales', 'Purchase');
+CREATE TYPE "taxReturnStatus" AS ENUM ('Draft', 'Finalized'); -- Phase 2
+
+CREATE TABLE "taxAuthority" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "supplierId" TEXT, -- optional: remit via AP to this supplier
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("supplierId", "companyId") REFERENCES "supplier"("id", "companyId")
+);
+-- + UNIQUE ("companyId", "name")
+
+CREATE TABLE "taxCode" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "name" TEXT NOT NULL, -- "TX – Austin", "UK Standard 20%"
+ "description" TEXT,
+ "calculationType" "taxCalculationType" NOT NULL DEFAULT 'Normal',
+ "reportingCategory" "taxReportingCategory" NOT NULL DEFAULT 'Standard',
+ "invoiceMessage" TEXT, -- VAT clause printed on documents
+ "countryId" INTEGER REFERENCES "country"("id"), -- address-match SUGGESTION keys
+ "state" TEXT,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ -- audit columns, customFields …
+ PRIMARY KEY ("id", "companyId")
+);
+-- + UNIQUE ("companyId", "name")
+
+CREATE TABLE "taxCodeComponent" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "taxCodeId" TEXT NOT NULL,
+ "name" TEXT NOT NULL, -- "TX State", "City of Austin"
+ "taxAuthorityId" TEXT,
+ "rate" NUMERIC NOT NULL, -- 0..1
+ "sequence" INTEGER NOT NULL DEFAULT 1,
+ "isCompound" BOOLEAN NOT NULL DEFAULT FALSE, -- tax-on-tax, applied in sequence
+ "isRecoverable" BOOLEAN NOT NULL DEFAULT FALSE, -- purchase side: FALSE = capitalize (today's behavior)
+ "salesTaxAccountId" TEXT, -- fallback: accountDefault.salesTaxPayableAccount
+ "purchaseTaxAccountId" TEXT, -- fallback: accountDefault.purchaseTaxPayableAccount
+ "effectiveDate" DATE, -- NULL = always; rate change = expire + new row
+ "expirationDate" DATE,
+ -- audit columns …
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("taxCodeId", "companyId") REFERENCES "taxCode"("id", "companyId") ON DELETE CASCADE,
+ FOREIGN KEY ("taxAuthorityId", "companyId") REFERENCES "taxAuthority"("id", "companyId")
+);
+
+CREATE TABLE "taxRegistration" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "countryId" INTEGER NOT NULL REFERENCES "country"("id"),
+ "state" TEXT,
+ "registrationNumber" TEXT NOT NULL,
+ "effectiveDate" DATE,
+ "endDate" DATE,
+ -- audit columns, customFields …
+ PRIMARY KEY ("id", "companyId")
+);
+
+CREATE TABLE "taxLedger" (
+ "id" TEXT NOT NULL DEFAULT id('txl'),
+ "companyId" TEXT NOT NULL,
+ "source" "taxLedgerSource" NOT NULL,
+ "documentType" TEXT NOT NULL, -- 'Sales Invoice' | 'Purchase Invoice' | 'Memo'
+ "documentId" TEXT NOT NULL,
+ "documentLineId" TEXT,
+ "journalId" TEXT, -- GL traceability
+ "postingDate" DATE NOT NULL,
+ "taxCodeId" TEXT, -- NULL for legacy/exempt lines
+ "taxCodeComponentId" TEXT,
+ "componentName" TEXT, -- snapshots: self-contained if config edited
+ "taxAuthorityId" TEXT,
+ "customerId" TEXT,
+ "supplierId" TEXT,
+ "rate" NUMERIC NOT NULL DEFAULT 0,
+ "taxableAmount" NUMERIC NOT NULL DEFAULT 0, -- base currency
+ "taxAmount" NUMERIC NOT NULL DEFAULT 0, -- base currency; negative on VOID/credit-memo reversal
+ "exemptAmount" NUMERIC NOT NULL DEFAULT 0, -- exempt customer, non-taxable item, zero-rated
+ "taxExemptionReason" "taxExemptionReason", -- existing enum, snapshotted (NULL for non-taxable items)
+ "exemptionCertificateNumber" TEXT,
+ "currencyCode" TEXT,
+ "exchangeRate" NUMERIC,
+ "taxReturnId" TEXT, -- Phase 2: stamped on return finalize
+ "needsEngineReconciliation" BOOLEAN NOT NULL DEFAULT FALSE, -- Phase 3: engine-outage flag
+ "postedToInputAccount" BOOLEAN NOT NULL DEFAULT FALSE, -- recoverable input-tax leg (liability report reads this)
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"), -- required by audit-injection; stays NULL
+ PRIMARY KEY ("id", "companyId")
+);
+-- indexes: ("companyId","postingDate"), ("companyId","documentId"),
+-- ("companyId","taxAuthorityId"), ("companyId","taxReturnId")
+
+-- Phase 2
+CREATE TABLE "taxReturn" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "taxReturnId" TEXT NOT NULL, -- readable id via get_next_sequence
+ "taxAuthorityId" TEXT, -- NULL = all authorities
+ "taxReturnLayoutId" TEXT, -- NULL = built-in generic layout
+ "periodStart" DATE NOT NULL,
+ "periodEnd" DATE NOT NULL,
+ "status" "taxReturnStatus" NOT NULL DEFAULT 'Draft',
+ "totals" JSONB, -- snapshot at finalize (per box/component)
+ "journalId" TEXT, -- settlement entry
+ "remittanceInvoiceId" TEXT, -- optional draft AP invoice
+ "finalizedAt" TIMESTAMP WITH TIME ZONE,
+ "finalizedBy" TEXT REFERENCES "user"("id"),
+ -- audit columns, customFields …
+ PRIMARY KEY ("id", "companyId")
+);
+
+CREATE TABLE "taxReturnLayout" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "name" TEXT NOT NULL, -- "UK VAT Return (9 boxes)"
+ -- audit columns …
+ PRIMARY KEY ("id", "companyId")
+);
+
+CREATE TABLE "taxReturnLayoutLine" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "taxReturnLayoutId" TEXT NOT NULL,
+ "boxNumber" TEXT NOT NULL, -- "1", "6", …
+ "label" TEXT NOT NULL, -- "VAT due on sales"
+ "sequence" INTEGER NOT NULL DEFAULT 1,
+ "source" "taxLedgerSource", -- NULL for row-totaling lines
+ "aggregate" TEXT, -- 'Tax' | 'Taxable Base' | 'Exempt Base'
+ "reportingCategories" "taxReportingCategory"[],
+ "taxCodeIds" TEXT[], -- optional narrower filter
+ "rowTotaling" TEXT, -- "1+2-3" style, BC pattern
+ -- audit columns …
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("taxReturnLayoutId", "companyId")
+ REFERENCES "taxReturnLayout"("id", "companyId") ON DELETE CASCADE
+);
+```
+
+Column additions (all nullable or defaulted to current behavior, no backfill):
+
+```sql
+-- Phase 1
+ALTER TABLE "item" ADD COLUMN "taxable" BOOLEAN NOT NULL DEFAULT TRUE;
+ALTER TABLE "customer" ADD COLUMN "taxCodeId" TEXT; -- FK taxCode
+ALTER TABLE "customerLocation" ADD COLUMN "taxCodeId" TEXT; -- ship-to override
+ALTER TABLE "supplier" ADD COLUMN "taxCodeId" TEXT;
+ALTER TABLE "companySettings" ADD COLUMN "shippingIsTaxable" BOOLEAN NOT NULL DEFAULT FALSE; -- OQ 5
+ALTER TABLE "quoteLine" ADD COLUMN "taxCodeId" TEXT;
+ALTER TABLE "salesOrderLine" ADD COLUMN "taxCodeId" TEXT;
+ALTER TABLE "salesInvoiceLine" ADD COLUMN "taxCodeId" TEXT;
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "taxCodeId" TEXT;
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "taxCodeId" TEXT;
+ALTER TABLE "memo" ADD COLUMN "taxCodeId" TEXT; -- OQ 2
+ALTER TABLE "memo" ADD COLUMN "taxAmount" NUMERIC NOT NULL DEFAULT 0;
+ALTER TABLE "accountDefault" ADD COLUMN "taxSettlementAccount" TEXT; -- Phase 2 posting target
+```
+
+Affected views (`customers`, `suppliers`, `quoteLines`/order/invoice line views, memo views) are dropped and recreated with `SELECT *` per the view-redefinition rule, each forked from its **newest** migration definition. Every DDL statement is idempotency-guarded (`IF NOT EXISTS` / `DO $$ … duplicate_object`) per the migration-idempotency rule.
+
+## API / Service Changes
+
+All in `apps/erp/app/modules/accounting/` (models + service; no new files):
+
+- **CRUD**: `get/upsert/deleteTaxCode` (+ components batch upsert), `…TaxAuthority`, `…TaxRegistration`, `…TaxReturnLayout` — standard `(client, companyId, …) → {data, error}` shape, list variants with `GenericQueryFilters`.
+- **`resolveLineTaxes(client, companyId, args)`** — the determination seam: `{ source: "sales" | "purchase", customerId?/supplierId?, customerLocationId?, itemId?, date }` → `{ taxCodeId, taxPercent, components[], exempt, exemptionReason }`. Pure lookup (exempt check → item taxable check → location code → party code), no writes; internally dispatches to the internal codes or (Phase 3) the Avalara engine per company setting. Called by the quote/order/invoice/memo line create-and-update paths in `sales.service.ts`, `purchasing.service.ts`, and `invoicing.service.ts` where `customer.taxPercent` is copied today (e.g. [sales.service.ts:1937](apps/erp/app/modules/sales/sales.service.ts)); also exposed as a route action for the "recalculate taxes" affordance when ship-to changes.
+- **`suggestTaxCode(client, companyId, { countryId?, state? })`** — returns active codes whose match fields fit the address; used by customer/location/supplier forms to offer the assignment suggestion.
+- **`getEffectiveTaxComponents(client, companyId, taxCodeId, date)`** — effective-dated component resolution + compound-aware rate math (shared by resolver, UI preview, posting, and tests).
+- **`getTaxLiability(client, companyId, { startDate, endDate, taxAuthorityId? })`** — groups `taxLedger` by authority → component: taxable base, exempt base, tax collected, input tax, net.
+- **Phase 2**: `createTaxReturn` / `getTaxReturnPreview` (runs the layout against unstamped ledger rows) / `finalizeTaxReturn` (Kysely transaction: stamp rows, snapshot totals, post settlement JE via the journal service, optionally create the draft AP remittance invoice) / `reopenTaxReturn` (only the newest finalized return; reverses the settlement JE and unstamps).
+- **Edge functions**: `post-sales-invoice` and `post-purchase-invoice` gain the posting changes from the table above + `taxLedger` writes inside the existing Kysely transactions (VOID paths write reversing rows); memo posting gains the net/tax split. A shared `functions/shared/resolve-taxes.ts` mirrors component resolution for posting-time recomputation, following the `functions/shared/` helper precedent (`get-accounting-period.ts`, `get-next-sequence.ts`).
+- **Zod validators** in `accounting.models.ts`: `taxCodeValidator` (with match fields), `taxCodeComponentValidator` (rate 0..1, refine expiration > effective), `taxAuthorityValidator`, `taxRegistrationValidator`, `taxReturnValidator`, `taxReturnLayoutLineValidator`.
+- **Phase 3 (packages/ee)**: `AvalaraTaxEngine` implementing the resolver contract (`CreateTransaction` SalesOrder/SalesInvoice+commit, `VoidTransaction`, `ResolveAddress`), company-integration config UI, reconcile job for `needsEngineReconciliation` rows (Inngest, the existing jobs precedent); Xero syncer reads the `taxCode → TaxType` mapping from `externalIntegrationMapping`.
+
+## UI Changes
+
+- **Accounting nav — new "Tax" group** (`x+/accounting+/…`, list + Drawer detail per house pattern, `view/update: "accounting"`):
+ - `tax-codes` — table + drawer form with an inline components editor (name, authority, rate, dates, compound/recoverable flags, accounts), address-match fields, and a computed effective-rate preview; per-code Xero TaxType select when a Xero integration is active (Phase 3).
+ - `tax-authorities`, `tax-registrations` — simple list + drawer CRUD; registrations page cross-warns codes-without-registration and registrations-without-codes (Phase 3: + Avalara nexus drift).
+ - `tax-liability` — the report: date range + authority filter, grouped by authority/component, CSV export.
+ - `tax-returns` (Phase 2) — list + detail: period picker, layout select, live preview of boxes, Finalize action (posts settlement, offers AP remittance invoice), Reopen on the newest finalized return.
+- **Customer**: `CustomerTaxForm` gains a Tax Code select with address-based suggestion; `customerLocation` drawer gains the override select; customers table gains a bulk "Assign tax code" action for the `taxPercent` migration path (OQ 4). **Supplier**: same. **Item**: "Taxable" switch in the item properties panel (default on).
+- **Documents**: quote/order/invoice line drawers show the resolved tax code + amount with an override select (document permission; old→new logged to the audit system per OQ 3); a "recalculate taxes" action on header ship-to change; purchase invoice lines gain an "Accrue use tax" affordance (pick a Reverse Charge code) when the supplier charged no tax (Phase 2). Memo form gains the tax code + computed tax display (OQ 2).
+- **Settings**: accounting settings gain the `shippingIsTaxable` toggle; once any tax code is assigned to a party, customer/supplier `taxPercent` fields hide behind a "migrate to tax codes" banner listing parties still on flat percents (OQ 4).
+- **PDFs** (`packages/documents`): sales invoice gains a tax summary block by component/authority, code `invoiceMessage` clauses, seller registration number, and customer VAT number for Reverse Charge/Export codes.
+
+## Acceptance Criteria
+
+Phase 1:
+
+- [ ] Create a "TX – Austin" code (State 6.25% + City 2.0% components, match fields TX/US): the customer form suggests it for a Texas address; after assignment, a sales order line for that customer defaults `taxPercent = 0.0825`; posting the invoice credits revenue **net**, credits the two component accounts 6.25/2.00 split, debits AR gross; two `taxLedger` rows carry the correct bases and authorities.
+- [ ] A customer with a default code and a differently-coded ship-to location: lines resolve the location's code when that location is the ship-to, the customer's code otherwise.
+- [ ] Marking the customer `taxExempt` with a certificate: the same line resolves to zero tax; posting writes a `taxLedger` row with `exemptAmount` = base, snapshotted reason + certificate number; the invoice PDF shows no tax. An `item.taxable = false` line behaves the same with no exemption reason.
+- [ ] A purchase invoice line with a recoverable 20% VAT code: cost posts net, input tax debits the component's account, AP credits gross; with `isRecoverable = false` the posting matches today's capitalized behavior exactly.
+- [ ] A purchase invoice with a Reverse Charge (recoverable) code: paired GL lines (input tax debit + reverse-charge credit) net to zero, AP is net of tax, and the ledger shows both directions.
+- [ ] A Credit memo with a tax code against a taxed customer: AR credited gross (`amount` unchanged), reason account debited net, output tax debited; negative `taxLedger` rows; a no-code memo posts byte-identically to today.
+- [ ] With `shippingIsTaxable` on, document-level shipping on a taxable order is taxed at the document's resolved code; off, shipping stays untaxed.
+- [ ] A component with `expirationDate = 2026-06-30` and a successor row at 8.5% effective `2026-07-01`: invoices dated June 30 vs July 1 compute 8.25% vs 8.5% respectively.
+- [ ] Voiding a posted sales invoice writes reversing `taxLedger` rows; the liability report for the period nets to zero for that document.
+- [ ] The tax liability report for a quarter ties to the GL balance movement of the tax payable accounts for the same range (cross-check documented in the test).
+- [ ] Legacy lines (manual `taxPercent`, no code) post revenue net with tax to `accountDefault.salesTaxPayableAccount` (OQ 1); a company with no tax config and `taxPercent = 0` everywhere behaves byte-identically to today; all existing invoice-total views and PDFs render unchanged (typecheck + `pnpm run test` green, invoice-total snapshots unchanged for `taxPercent`-only fixtures).
+
+Phase 2:
+
+- [ ] A US purchase invoice line where the supplier charged no tax: "Accrue use tax" with a picked Reverse Charge (non-recoverable) code posts Dr cost gross-of-accrual / Cr use-tax liability, AP net; ledger rows carry the authority.
+- [ ] Finalizing a Q2 return stamps exactly the unstamped ledger rows in range, snapshots totals, posts the settlement JE (output accounts debited, input accounts credited, net to `taxSettlementAccount`), and — when the authority has a linked supplier — creates a draft AP invoice for the net due; rows stamped by the return are excluded from the next return's preview; a document posted into Q2 *after* finalize lands in Q3's preview.
+- [ ] Reopening the newest finalized return reverses the settlement JE and unstamps its rows; older returns cannot be reopened while a newer one is finalized.
+- [ ] The seeded UK layout renders the 9 boxes from reporting categories (Box 1 output tax, Box 4 input tax, Box 6/7 bases) against a mixed fixture of standard/zero-rated/reverse-charge documents.
+
+Phase 3:
+
+- [ ] With Avalara enabled and mocked API: a quote line calls `CreateTransaction(SalesOrder)`; posting the invoice calls `CreateTransaction(SalesInvoice, commit: true, code = invoice id)` and maps `details[]` to `taxLedger` rows per jurisdiction; voiding calls `VoidTransaction`; re-posting an uncommitted document with the same code overwrites idempotently.
+- [ ] With the Avalara API failing, posting falls back to the internal codes, flags rows `needsEngineReconciliation`, and the reconcile action clears them once the mock recovers — committed totals never silently diverge.
+- [ ] A `taxCode` mapped to a Xero `TaxType` syncs invoice lines with that TaxType; unmapped codes keep OUTPUT/NONE.
+- [ ] `pnpm exec turbo run typecheck --filter=@carbon/erp` and scoped tests pass after `pnpm run generate:types` (every phase).
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Sales-posting behavior change (revenue now net of tax) breaks users' report expectations | High | Approved via OQ 1; release note; applies only to newly posted documents — no retroactive restatement |
+| Per-party assignment under-collects when a customer ships somewhere new without a coded location | Med | Address-match suggestion fires on location creation/edit; registrations cross-warnings; Avalara engine (Phase 3) for businesses with wide destination spread |
+| Misconfigured rates produce wrong tax at scale | Med | Effective-rate preview; liability report makes errors visible quickly; line override remains possible |
+| Memo `amount` reinterpretation bugs the AR/AP tie-out | Med | `amount` semantics deliberately unchanged (gross, hits AR/AP); tax is carved out *within* it; tie-out views untouched — verified against the net-model contract |
+| Settlement JE interplay with period closing (posting into a locked period) | Med | Settlement posts as an *accounting* source under the period-closing matrix; finalize validates the period is postable first |
+| Avalara outage / API drift | Med | Fallback-and-flag pattern per Avalara's own ERP guide; connector isolated in `packages/ee`; internal codes always functional |
+| `taxLedger` growth on high-volume companies | Low | Append-only, indexed by `(companyId, postingDate)`; report queries are range-scans; same profile as `itemLedger` |
+| View recreation churn (customers/suppliers/line/memo views) | Med | DROP + `SELECT *` recreation per house rule; fork each view body from its newest migration definition (lessons.md backdated-migration rule) |
+| Rounding drift between line-level tax and authority expectations | Low | Line-level half-up documented; authorities tolerate penny-level differences (research); document-level rounding is a contained future setting |
+| Partial migration on deploy retry | Med | All DDL idempotency-guarded per the migrations-must-be-idempotent rule |
+| Scope breadth (3 phases) stalls delivery | Med | Phases are independently shippable; Phase 1 alone fixes the misstatement and delivers determination + reporting; /plan sequences per phase |
+
+## Open Questions
+
+> 🛑 HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] **1. Apply the sales-posting fix to legacy lines too?** — **Answer: Yes** (user approved, 2026-07-03). One consistent rule: any line with tax (code-resolved or manual `taxPercent`) posts revenue net and credits tax payable; the alternative preserved a known revenue misstatement. Applies to newly posted documents only.
+- [x] **2. Are credit/debit memos in v1 scope?** — **Answer: Yes, Phase 1.** `memo.taxCodeId` + `taxAmount` (tax carved out of the unchanged gross `amount`), direction-aware posting splits and signed ledger rows. Preserves the AR/AP tie-out contract.
+- [x] **3. Line-level tax override permission.** — **Answer: document permission + audit log.** Anyone who can edit the line can override the resolved code/percent; old→new is recorded via the audit log system. Accounting-gated override deferred until a customer asks.
+- [x] **4. Sunset path for `customer.taxPercent`.** — **Answer: hide once codes are assigned.** When a company has assigned ≥1 tax code, customer/supplier `taxPercent` fields hide behind a "migrate to tax codes" banner; a bulk "Assign tax code" action on the customers/suppliers tables completes the migration. Data is retained (it remains the no-code fallback).
+- [x] **5. Document-level shipping taxability.** — **Answer: in scope, Phase 1.** `companySettings.shippingIsTaxable` taxes shipment-level shipping at the document's resolved code; off (default) keeps it untaxed, preserving current behavior.
+- [x] **6. Historical reclassification.** — **Answer: out of scope, deliberately.** Tax previously posted into revenue stays unless manually reclassified; Carbon ships guidance (docs) for a one-time reclass journal entry. Automated restatement rewrites audited history and stays out even under the ambitious scope — the correct instrument is an accountant-authored JE.
+
+## Changelog
+
+- 2026-07-03: Created — research at `.ai/research/multi-jurisdiction-tax.md`; verified current-state findings (flat `taxPercent`, tax-into-revenue posting, dead tax-account config, inert exemption metadata) against the codebase.
+- 2026-07-03: All six open questions resolved (user: "yes, let's be very ambitious"). Scope expanded from single-phase to three phases: memo tax + shipping taxability pulled into Phase 1; tax returns with settlement posting + AP remittance, return layouts (seeded generic + UK), and US use-tax accrual added as Phase 2; Avalara AvaTax connector (estimates, committed transactions, address validation, outage fallback, nexus mirror) and Xero tax-code mapping added as Phase 3. Tax-inclusive pricing, document-level rounding, foreign-currency registrations, and automated historical restatement remain explicitly out of scope.
+- 2026-07-03: **Determination redesigned — matrix removed** (user feedback: the posting-group matrix was confusing and was deliberately dropped in [20260229000000_drop-posting-groups.sql](packages/database/supabase/migrations/20260229000000_drop-posting-groups.sql); the tax design must not resurrect it). Replaced `taxArea` × `taxCategory` × `taxRule` (three tables + matrix editor) with **direct assignment** (Xero model): `taxCodeId` on customer/location/supplier, `item.taxable` boolean, address-match *suggestions* at assignment time, line-level override. Shipping taxability simplified to a `shippingIsTaxable` boolean; Phase 2 use-tax code is picked explicitly on the line. Also corrected stale posting-group references in the problem statement.
diff --git a/.ai/specs/2026-07-03-public-company-readiness.md b/.ai/specs/2026-07-03-public-company-readiness.md
new file mode 100644
index 0000000000..b6d74d77a5
--- /dev/null
+++ b/.ai/specs/2026-07-03-public-company-readiness.md
@@ -0,0 +1,287 @@
+# Public-Company Readiness: Compliance Gap Audit & Remediation Program
+
+> Status: in-progress (all open questions resolved 2026-07-03)
+> Author: Claude (Big-4-style readiness assessment), for [email protected]
+> Date: 2026-07-03
+> Research: `.ai/research/public-company-compliance.md`
+> Baseline: this branch's six in-flight specs (period closing, financial reporting, multi-jurisdiction tax, budgeting, bank reconciliation, Plaid feeds) plus all previously implemented specs — treated as done
+
+## TLDR
+
+This spec is a readiness audit of Carbon's accounting platform against the requirements of a US-listed (or dual-listed) manufacturer operating in multiple countries, plus the remediation program to close the remaining gaps. The audit assumes every existing and in-flight spec is implemented as written — including this branch's period-closing lifecycle (hard close with a DB trigger backstop), multi-jurisdiction tax (tax subledger, corrected posting, returns, Avalara), financial reporting (cash flow, computed RE/Net-Income split, comparatives, GL detail, exports), budgeting (BvA, commitments, budget control), and bank reconciliation with Plaid feeds. That baseline eliminates three of the five findings that would otherwise be material weaknesses. **Two remain at material-weakness level**: posted accounting records are mutable in open periods and excluded from the audit log (which is itself opt-in, 30-day, and tamperable), and there is no journal-entry approval or segregation of duties anywhere — self-approval is possible in the one approval engine that exists. Beyond those: significant deficiencies (draft journals in reported balances, no DB-level double-entry enforcement, non-gapless editable numbering, FX/consolidation completeness, ITGC), GAAP capability build-outs (revenue recognition, leases, inventory valuation completeness, multi-book ledgers, segments), multi-country statutory machinery (e-invoicing, SAF-T/FEC exports, withholding/Intrastat), the ecosystem integration surface (TB/JE APIs, controlled JE import), and a vendor-level assurance program (SOC 1 Type II). The remediation is phased so the two remaining control keystones — immutable journals and JE approval — land first: they are the cheapest differentiators, the first things a SOX readiness firm tests, and the foundation every later phase posts into.
+
+## Problem Statement
+
+Carbon's goal is to be the accounting system a CFO adopts at seed and never leaves — through Series C, IPO readiness, and life as a public multi-national. The market evidence (research §Ecosystem) says this is winnable: companies graduate from QuickBooks/Xero at ~$5–30M revenue triggered by multi-entity consolidation, rev-rec spreadsheets, and inventory complexity (Carbon's manufacturing customers hit the inventory trigger earliest), and companies that reach NetSuite-class systems essentially never leave below $500M revenue — they IPO on them. Carbon already has unusually strong bones: company groups with subsidiary hierarchies, intercompany matching/eliminations with elimination entities, IAS 21-style translation with per-account rate types, a dimension-driven GL (the modern Intacct-style architecture), AR/AP settlement with tie-out RPCs, fixed assets with book + MACRS tax depreciation — and, with this branch, a real period-close lifecycle, a tax subledger, the full statements package, budgeting with commitment control, and bank reconciliation.
+
+But the audit fieldwork (nine research workstreams, 2026-07-03; inventories cited per finding below) shows the record-integrity and approval layer that makes the ledger *auditable* is still missing, several GAAP-required subsystems do not exist, and multi-country statutory compliance beyond indirect tax is unstarted. A public-company client on the post-branch baseline would still fail SOX 404(b) on the two remaining control fronts in year one.
+
+**Baseline for this audit** — the following are treated as done and their fixes are NOT re-reported as findings:
+
+| Assumed implemented | What it resolves |
+|---|---|
+| `.ai/specs/2026-07-02-period-closing.md` (+ migration `20260702044133`) | Hard period close: Open → Locked → Closed with a SECURITY DEFINER trigger backstop binding all writers incl. service role; sequential close / reverse-sequential reopen; fiscal-year identity; computed close-readiness checklist (draft journals, unposted docs, negative inventory, unmatched IC, TB balance); reversal-dating across the boundary; audited transitions |
+| `.ai/specs/2026-07-03-multi-jurisdiction-tax.md` | The tax misstatement (revenue net of tax; per-component tax payable/receivable posting), tax codes/components/authorities/registrations, immutable `taxLedger`, exemption enforcement, reverse charge + US use tax, memo tax, liability report, returns with settlement + AP remittance, return layouts (UK 9-box seeded), Avalara connector, Xero tax mapping |
+| `.ai/specs/2026-07-02-financial-reporting.md` | Cash flow statement (single + consolidated with FX-effect plug), Retained Earnings / Net Income split (virtual year-end — the chosen model; no closing entries by design), comparative columns with variance, GL detail report + journal drill-down (Posted+Reversed by default), four-column trial balance, CSV export everywhere, PDF statements package, fiscal-period picker, saved report views |
+| `.ai/specs/2026-07-02-budgeting.md` | Budget headers/lines (account × period × cost center), matrix editor, CSV round-trip, Budget vs Actual with hierarchy rollup, PO commitments, Warn/Block budget control with audited override, Approved-budget immutability trigger, income-statement budget columns, consolidated BvA |
+| `.ai/specs/2026-07-02-bank-reconciliation.md` + `2026-07-02-plaid-bank-feeds.md` | Bank account master (1:1 GL link, FX + credit-card accounts), statement ingestion (CSV/OFX/BAI2/MT940/CAMT.053 + Plaid feed), matching engine + rules, tolerance adjustments, reconciliation close-out with difference-must-be-zero gate and optional **preparer→approver workflow**, PDF reconciliation report, daily cash position/drift; adds nullable `journalLine.sourceAmount`/`sourceCurrencyCode` populated where the poster knows its currency |
+| `.ai/specs/2026-07-02-exchange-rate-convention-normalization.md` | GL base amounts on divide-to-base convention; phantom PPV on FX invoices; realized FX gain/loss signs; remittance currency labels; tie-out RPC rates |
+| `.ai/specs/implemented/memo-refactor-plan.md`; invoice/payment audit Tiers 1–2 (`.ai/runs/2026-07-02-invoice-payment-audit.md`); `.ai/specs/2026-07-02-account-ledger-drilldown.md`; `.ai/specs/2026-07-02-work-order-stitching.md` | Memo model + journal shapes; AR stranding / invoice-tax / WIP fixes; report drill-down + period selector; production-side stitching |
+
+Findings below only cover what remains beyond that baseline. Where a finding builds on or is narrowed by one of these, it says so.
+
+---
+
+## Findings
+
+Severity scale (ICFR framing): **MW** = would likely be assessed a material weakness (reasonable possibility of material misstatement not prevented/detected); **SD** = significant deficiency; **GAP** = capability absent — becomes a deficiency the moment the client has the underlying transaction type; **CO** = company/vendor-level program, not product code.
+
+### A. Control environment (ICFR core)
+
+#### MW-1 — Posted accounting records are mutable in open periods and not audit-logged
+
+**Condition.** (a) `journal` UPDATE RLS allows updates while status is Draft **or Posted** with `WITH CHECK (true)` — any `accounting_update` user can rewrite a posted journal's header (description, and postingDate within the same open period) via PostgREST (`20260402000000:84-92`). The period-closing trigger protects **closed** periods only — posted journals in open and locked periods remain mutable, and `journalLine` rows are only protected while the parent is Draft (nothing blocks service-role line edits on Posted journals). (b) `payment` UPDATE policy has no status condition (Posted-payment immutability is app-layer only, per the migration's own comment); `purchaseInvoice` RLS DELETE checks permission but not status. (c) The audit-log system is **opt-in per company (default off)**, retains 30 days hot, has a fully permissive `USING (true)` policy on its own tables, writes asynchronously through a queue (loss on pipeline failure), and its 26-entity coverage **excludes** `journal`, `journalLine`, `account`, `accountingPeriod`, `payment`, `memo`, `sequence`, `userPermission`, `apiKey`, and the approval tables. (The period-closing and budgeting specs both route their transition audit through this same system — their audit trail inherits these weaknesses.) (d) `journalLine` has no `createdBy`; `journal` has no preparer/approver identity.
+**Criteria.** AS 2401 requires a complete, tamper-evident JE population with preparer/approver/timestamps; Germany GoBD requires Unveränderbarkeit; France FEC requires a sequentially complete extract on 15 days' notice; NetSuite System Notes / SAP change documents are the reference bar. One schema investment covers all four regimes (research §Pattern 1).
+**Risk.** No auditor can rely on the ledger as evidence; fraud-testing analytics (backdating, off-hours, admin postings) are impossible; GoBD/FEC non-compliance in DE/FR entities; the period close's own audit trail can be silently edited or lost.
+**Remediation (build).** *(Items 1–2 for `journal`/`journalLine` are folded into the period-closing spec §Enforcement item 4 as of 2026-07-03 — same trigger wave; the rest remains Phase 0.)* (1) DB triggers making posted `journal`/`journalLine`/`payment`/`memo`/`invoiceSettlement` rows immutable in **all** period states — the only permitted transitions are status-only (`Posted → Reversed/Voided` with linkage columns); SECURITY DEFINER, binding service role, following the period-close trigger precedent. (2) Add `journalLine.createdBy`; add `preparedBy`/`approvedBy` to `journal` (populated by MW-2's workflow). (3) Accounting audit coverage: extend `audit.config.ts` to the excluded tables above and make audit logging **always-on and non-disablable for accounting entities** (the company toggle keeps governing operational entities only); write accounting audit rows **synchronously in the posting transaction** (or transactional outbox) rather than via PGMQ. (4) Lock the audit tables down: append-only policies, revoke UPDATE/DELETE, configurable retention with a floor of 7 years for accounting entities (30-day default stays for operational noise). (5) Full-population **JE export** (flat CSV/JSON, no row caps: journal id, line, account, signed amount, debit/credit presentation, posting date, created/posted timestamps, preparer, approver, source type, document reference, reversal linkage, currency + source amount, book) — this single export is the SOX/FEC/SAF-T/GoBD workhorse and the substrate for GAP-D3.
+
+#### MW-2 — No journal-entry approval, no segregation of duties, self-approval permitted
+
+**Condition.** Manual journals go Draft → Posted with no approval step (`journalEntryStatus` has no pending state). The generic approval engine (`approvalRequest`/`approvalRule`) covers only `purchaseOrder`, `qualityDocument`, `supplier`; journals, payments, and invoices have none. `canApproveRequest` never excludes `requestedBy` — **self-approval of POs is possible today**, and the budgeting spec's Block-override and the bank-rec spec's preparer→approver reconciliation flow are the only SoD-shaped controls anywhere (the latter optional, reconciliation-only). The permission model (module × CRUD) cannot express preparer ≠ approver; no SoD conflict detection exists (repo-wide grep); `salesOrderStatus` contains a dead `'Needs Approval'` value nothing sets.
+**Criteria.** Auditors specifically test whether submitter and approver credentials match (AS 2401 fraud procedures); SAP parks journals until workflow approval with requester ≠ approver enforced; NetSuite JE approval routing is standard pre-IPO configuration; a documented SoD matrix over roles is an ITGC prerequisite.
+**Risk.** Management-override risk is uncontrolled; every manual JE is a fraud-testing exception; SOX readiness assessment fails at the first control tested.
+**Remediation (build).** (1) Extend `approvalDocumentType` to `journalEntry`, `payment`, `purchaseInvoice` (and wire the dead sales-order status or remove it); journal state machine becomes `Draft → Pending Approval → Posted` when a matching rule exists, with amount/account-class routing reusing `approvalRule` tiers. (2) System-enforced **no-self-approval** in `canApproveRequest` (server-side, all document types, config flag defaulted on). (3) `journal.preparedBy`/`approvedBy` stamped from the request. (4) SoD v1 = detective: a conflict-matrix report over `userPermission` (canonical conflicts: vendor-create + payment-post; JE-create + JE-approve; sequence-edit + posting; bank-rec preparer + JE-post) plus a point-in-time **user access report** (per-user permissions by company, with grant history from the audit log) for quarterly access reviews. Preventive SoD enforcement is a later phase.
+
+### B. Significant deficiencies
+
+#### SD-1 — Statement integrity: drafts in reported balances, no DB-level double-entry enforcement
+
+**Condition.** The balance RPCs behind the trial balance, balance sheet, and income statement **intentionally include Draft journals** (`20260702122210_journal-lines-view.sql:5-6`); the financial-reporting spec excludes drafts from the new GL detail report and the period-closing readiness check blocks *closing* on open drafts, but the statements a controller reviews mid-period still move with unapproved drafts — and become IPE the moment they're handed to an auditor. Separately, debits=credits is asserted only in app code (manual-JE service, payment builder); the invoice/receipt/shipment/production posters have **no balance assertion at all**, and nothing at the DB guarantees a journal balances.
+**Criteria.** A trial balance that includes unapproved drafts cannot serve as IPE; a balanced-journal constraint is table stakes in every reference system; auditors roll the JE population forward opening→closing TB and any unbalanced journal breaks the identity the financial-reporting spec's cash flow tie-out also depends on.
+**Remediation (build).** (1) Reports default to **Posted-only** with an explicit "include drafts" preview toggle — *folded into the financial-reporting spec §11 as of 2026-07-03* (`p_include_drafts DEFAULT FALSE` on both balance RPCs). (2) DB-level balance enforcement: deferred constraint trigger asserting Σ(signed amounts) = 0 per journal at COMMIT (0.01 tolerance), covering every poster including edge functions — remains Phase 0.
+
+#### SD-2 — Numbering and dating are not audit-grade
+
+**Condition.** `journalEntryId` comes from the app-level `sequence` table — not gapless (failed transactions leave holes), and the `sequence` table is **editable by any `settings_update` user** (next-number can be rewound → duplicate/reused numbers), with sequence changes not audit-logged. Invoice numbering likewise has no legal-series concept (gapless per series is law across most of the EU/LatAm; Portugal additionally requires ATCUD + hash chaining). Manual-JE backdating within open periods is unrestricted and unflagged.
+**Remediation.** Gapless posting-time numbering: assign the final `journalEntryId` (and legal invoice numbers) inside the posting transaction from a DB-serialized per-company (per-series) counter; make `sequence` rows for accounting documents immutable-after-first-use and audit-logged; add `legalSeries` on customer-facing documents (per entity + country + document type) as the substrate for GAP-D2 e-invoicing; flag backdated entries (postingDate ≪ createdAt) in the JE export.
+
+#### SD-3 — ITGC gaps: authentication, deprovisioning, environments
+
+**Condition.** No MFA and no SAML/OIDC SSO (magic link + Google/Azure OAuth + passkeys only); deactivation does not revoke live sessions (no `auth.admin.signOut` anywhere); no idle timeout; API keys impersonate their creator and are excluded from audit logging; `getCarbonServiceRole()` bypass is convention-gated; deploys go main → prod with no staging tier; `pnpm audit` non-blocking; no CODEOWNERS.
+**Remediation.** MFA enforcement policy per company (TOTP + passkey step-up), SAML/OIDC SSO (enterprise gate), session revocation on deactivate + admin session listing, API-key usage audit events, staging environment in the deploy pipeline, CODEOWNERS for `packages/database` + posting functions. (Vendor-side SOC 1 controls in CO-1 depend on these.)
+
+#### SD-4 — FX completeness (beyond the convention-normalization and bank-rec specs)
+
+**Condition.** With the FX spec implemented, realized FX and base-amount magnitudes are correct, and the bank-rec spec adds nullable `journalLine.sourceAmount`/`sourceCurrencyCode` populated "where the poster knows its currency." Remaining: population is best-effort, not universal (FEC/SAF-T and remeasurement need transaction currency on **every** line); there is **no unrealized FX revaluation** of open AR/AP/bank at period end (comment in `build-payment-journal.ts` confirms FX only realizes at settlement — and the period-closing spec's readiness checklist has no FX-revaluation task because the capability doesn't exist); historical-rate memory is a single value per currency (no per-transaction historical rates for equity/assets).
+**Criteria.** ASC 830/IAS 21 require period-end remeasurement of monetary items with gains/losses in income; SAP FAGL_FCV / NetSuite "Revalue Open Foreign Currency Balances" is a standard close task (research §Pattern 5).
+**Remediation.** (1) Make `sourceAmount`/`sourceCurrencyCode` mandatory outputs of every posting path (base `amount` stays authoritative) — *folded into the bank-reconciliation spec's FX section as of 2026-07-03*. (2) Unrealized-revaluation close task: revalue open FX invoices, unapplied payments/memos, and FX bank balances at the period-end rate, posting auto-reversing entries to new `unrealizedExchangeGain/LossAccount` defaults; posts as an *accounting* source under the period-closing matrix and joins the close-readiness checklist. (3) Historical-rate table keyed by account/transaction where `account.consolidatedRate = 'Historical'` demands it.
+
+#### SD-5 — Consolidation correctness and completeness
+
+**Condition.** `exchangeRateHistory` — the source of closing/average rates for `translateTrialBalance` and the financial-reporting spec's consolidated cash flow — has **no writer** (the daily job updates `currency.exchangeRate` only; the migration comment "auto-populated by sync job" describes a job that does not exist). Unless rows are inserted by hand, translation silently falls back to rate 1, so translated/consolidated statements for any multi-currency group are wrong today — the financial-reporting spec itself flags "sparse exchangeRateHistory" as a risk without fixing the source. CTA is a display-time plug applied to hardcoded account number "3200" (`balance-sheet.tsx:80,160`; the `currencyTranslationAccount` default exists but is unread — violating the repo's own control-account lesson, also flagged as a follow-up in the financial-reporting spec); CTA never posts or rolls forward. Translated income statements are life-to-date (the translate RPC lacks `netChange`). IC matching is exact-amount with no tolerance and no FX-difference handling; consolidation is 100%-summation (no ownership %/NCI); no group close lock.
+**Remediation.** (1) Extend the daily exchange-rate job to append `exchangeRateHistory` (closing) and derive period averages; surface rate-coverage warnings on consolidated reports instead of the silent rate-1 fallback. (2) Post CTA to the configured `currencyTranslationAccount` (resolved by id) as part of group close; CTA rolls forward as a real balance. (3) Teach `translateTrialBalance` `netChange`. (4) IC matching tolerance + FX-difference posting to a dedicated difference account; IC document mirroring (PO↔SO) and netting later. (5) Ownership %/NCI deferred until sub-100% subsidiaries are a real customer need (SAP-tier; NetSuite also does 100% summation).
+
+#### SD-6 — Master-data change controls
+
+**Condition.** `accountDefault` (the entire GL account resolution layer), payment terms, tax codes/components (post-tax-spec: the rates that drive every tax posting), and counterparty tax data are editable by anyone with module update permission, with most of it outside audit-log coverage. Supplier bank details still don't exist anywhere (the bank-rec spec adds *company* bank accounts only) — but when AP payment execution arrives, unaudited vendor bank-detail changes are the #1 fraud vector.
+**Remediation.** Audit-log coverage (MW-1) for `accountDefault`, `paymentTerm`, `taxCode`/`taxCodeComponent`, `customerTax`/`supplierTax`, `bankAccount`, sequences; approval-workflow option on supplier bank-detail changes (extends MW-2's engine) the moment vendor bank details exist; change-alert notifications to accounting owners.
+
+### C. GAAP capability build-outs
+
+#### GAP-1 — Revenue recognition (ASC 606 / IFRS 15)
+
+Revenue is recognized in full at sales-invoice posting (net of tax once the tax spec lands, but still point-in-time); the seeded Deferred Revenue account has no writer; no schedules, obligations, POC, milestone/progress billing, or customer deposits. For Carbon's manufacturing base, the v1 cut that matters is: **deferred revenue schedules** (invoice → schedule → monthly recognition journal, posting as an *accounting* source and joining the close-readiness checklist), **customer deposits/prepayments** (liability until shipment), and **over-time recognition for long-lead contracts** (cost-to-cost POC using the job-costing data Carbon already has — a genuine differentiation vs the AI-GL startups, which have no cost basis to recognize against). SSP allocation across bundled obligations is deferred until product mix demands it. Contract asset/liability rollforward report ships with v1 (auditors ask for it first).
+
+#### GAP-2 — Leases (ASC 842 / IFRS 16)
+
+Nothing exists (verified: zero code hits). Build a lease subledger inside fixed assets: lease master (payments, term, IBR), PV computation, ROU asset + liability with effective-interest schedules, operating vs finance treatment (and IFRS 16 single-model when multi-book lands — GAP-5), monthly JEs from the close calendar, maturity-analysis disclosure export. Point-tool import (FinQuery JE upload) is the interim path via GAP-E1's JE import.
+
+#### GAP-3 — Inventory valuation completeness (manufacturing credibility core)
+
+Standard costing is enum-only (`standardCost` has no write path — Standard items cost at $0); no LCNRV write-downs; the `Revaluation` costLedgerType and `inventoryAdjustmentVarianceAccount`/overhead/lot-size/subcontracting variance accounts are dead schema; quantity adjustments post no GL; overhead absorption stops at estimates; no landed cost. Remediate in order: (1) wire standard cost input + actual-vs-standard variance posting (the accounts already exist), (2) inventory revaluation document (posts `Revaluation` cost-ledger rows + GL), (3) LCNRV write-down run with reversal support **per book** (US GAAP: no reversal; IAS 2: reversal required — first concrete consumer of GAP-5 multi-book), (4) GL posting for quantity adjustments, (5) overhead absorption to GL with `overheadVarianceAccount`, (6) landed cost (duty/freight/brokerage allocation onto receipts).
+
+#### GAP-4 — Fixed assets completeness
+
+Depreciation runs are entirely manual (no scheduled poster — a close-calendar risk now that period close is real); no impairment; no CIP; disposal lacks proceeds-based gain/loss (docs admit it); no component depreciation (IAS 16 requires it). Remediate: scheduled monthly depreciation proposal (Inngest) feeding an approvable Draft run and a close-readiness check; disposal-with-proceeds flow (link to sales invoice, gain/loss = proceeds − NBV); impairment posting (write-down account exists); CIP asset class + capitalization flow from job/PO costs; components as child assets (IFRS books later).
+
+#### GAP-5 — Multi-GAAP parallel books
+
+Single implicit book today. Per research (§Pattern 2), a book/ledger dimension is the single hardest retrofit in this list and is required the day the first foreign subsidiary files statutory accounts. Remediate in two steps: **now** (cheap): add `journal.bookId` defaulting to a seeded `PRIMARY` book, indexes and RPC filters included, so every future poster and report is book-aware from day one; **later**: adjustment-only books (NetSuite pattern — deltas on top of primary; first consumers: IFRS 16 leases, IAS 2 NRV reversals, statutory depreciation), book-specific depreciation per asset, and book columns in reporting UI.
+
+#### GAP-6 — Accruals, deferrals, recurring journals
+
+Only GR/IR exists. Build: prepaid-expense schedules (AP invoice line → amortization schedule → monthly journal; `prepaymentAccount` exists unused), recurring journal templates, and auto-reversing accrual JEs (flag on manual JE: post, auto-reverse day 1 next period — posting as *accounting* sources under the period matrix). All join the close-readiness checklist.
+
+#### GAP-7 — Segment reporting (ASC 280) and dimension enforcement
+
+Dimensions exist and system posters populate them, but the `required` flag is client-side only and there is no segment concept. Remediate: server-side enforcement of required dimensions at posting; a reserved **Segment** dimension derived from item/cost-center master data (SAP pattern: users never key segments); segment columns in the financial reports; ASU 2023-07 significant-expense breakdown by segment. (The budgeting spec's cost-center rollup is the structural precedent.)
+
+### D. Multi-country statutory
+
+#### GAP-D1 — Statutory tax filings beyond the tax spec
+
+The multi-jurisdiction tax spec delivers determination, the tax ledger, liability reporting, returns with settlement, and UK/generic return layouts. Remaining for multi-country operation: **withholding tax** on cross-border AP (treaty rates, certificates, WHT returns), **EC Sales List and Intrastat** extracts (commodity codes/weights partially exist via the EORI work), **UK MTD digital-links-compliant API submission** (the tax spec produces the boxes; MTD requires unbroken digital submission), and e-filing adapters where authorities require electronic returns. US sales-tax content and filing stays with Avalara behind the tax spec's connector.
+
+#### GAP-D2 — E-invoicing and legal invoice formats
+
+Zero e-invoicing code exists; mandates are imminent for any EU footprint (France issue-mandate Sept 2026, Poland KSeF Feb/Apr 2026, Germany issue 2027–28, ViDA intra-EU 2030). Build the **adapter framework, not fifty adapters**: EN 16931 semantic invoice model generated from Carbon invoices (the tax spec's registrations, tax summary blocks, and VAT clauses are prerequisites — this builds directly on them); format renderers starting with Peppol BIS 3.0 / Factur-X / XRechnung; a clearance/submission state machine per document (Pending → Submitted → Accepted/Rejected → Corrected) with retry and rectification-document flows; inbound structured-invoice receipt into AP; country routing via a middleware partner (Avalara/Sovos/Pagero pattern) behind one internal interface; legal numbering series from SD-2. Clearance-model countries (Italy SDI, Mexico CFDI, Brazil NF-e, India IRP) come per customer demand via the same framework.
+
+#### GAP-D3 — Statutory audit files, statutory COA, retention
+
+Build on MW-1's JE export: **France FEC** (18-field prescribed layout — near-free once journal data is complete with preparer identity and gapless numbering), **SAF-T** country flavors (PT/PL/NO/RO) generated from GL/AR/AP/assets/inventory (the tax spec's `taxLedger` supplies the tax section), GoBD-compliant data access export. Statutory chart-of-accounts support via an **alternative account number mapping table** per country (SAP three-layer pattern — never fork the group COA); statutory reports render through the mapping. Record retention: accounting archives (audit-log + JE exports + invoice originals) in WORM-configured storage with per-country retention ≥10 years and legal hold.
+
+### E. Ecosystem integration surface
+
+#### GAP-E1 — The feeds every bolt-on needs
+
+Public-company customers will bring BlackLine/FloQast, Workiva, Carta, provision tools, payroll, and expense systems (research §Ecosystem: even NetSuite doesn't build these). Carbon must expose: (1) **TB API** — balances by entity/book/period/dimension, stable account identifiers; (2) **JE-population export API** (MW-1's export, programmatic); (3) **controlled JE import API** — validated, approval-workflow-aware, period-status-aware, idempotent, audit-stamped (this is how Carta SBC entries, payroll summaries, lease JEs, and provision adjustments land); (4) webhooks for posting/close events (the period-closing lifecycle gives these real semantics). Most of this can ride the existing MCP/API-key infrastructure once approval + immutability gates exist.
+
+### F. Vendor-level program (company, not code)
+
+#### CO-1 — Assurance and operations
+
+No SOC 1/SOC 2/ISO 27001 posture exists or is claimed; DR is explicitly "not disaster recovery" (docs); no staging tier. Public-company customers' auditors **rely on the vendor's SOC 1 Type II** — without it every customer takes a control gap (research §6). Program: SOC 2 Type II first (procurement gate, ~2 quarters of evidence), SOC 1 Type II covering posting-integrity control objectives (posting correctness, tax calc, depreciation calc, costing calc) + ITGCs (needs SD-3's environment work as prerequisites), ISO 27001 for EU procurement, PITR/DR with stated RPO/RTO, and eventually country invoicing-software certifications (Portugal AT, France PDP) gated on GAP-D2 market entry. Timeline reality: a customer IPO-ing in 2 years needs Carbon's SOC 1 period started ~now.
+
+---
+
+## Proposed Solution — Remediation Program
+
+Phased so the remaining control keystones land first; each phase is independently shippable and PR-sized specs get cut from it per module. Phase ∅ is this branch: the six in-flight specs land per their own plans and are prerequisites for everything below.
+
+| Phase | Contents (findings) | Theme |
+|---|---|---|
+| **∅ — This branch** | Period closing, multi-jurisdiction tax, financial reporting, budgeting, bank reconciliation + Plaid — now carrying three readiness fold-ins: posted-journal immutability + `journalLine.createdBy` (period-closing §Enforcement 4), Posted-only balance defaults (financial-reporting §11), universal source-currency population (bank-rec FX section) | Land the in-flight specs (already planned; not re-spec'd here) |
+| **0 — Ledger integrity** | MW-1 remainder (payment/memo/settlement immutability triggers, accounting audit coverage always-on + synchronous, audit-table lockdown, JE export v1), MW-2 (JE/payment/invoice approval + no-self-approval + access/SoD reports), SD-1 remainder (DB balance constraint), SD-2 (gapless numbering, sequence lockdown, legal series substrate), GAP-5 step 1 (`journal.bookId`) | Make the ledger trustworthy. Schema seeds for everything later. |
+| **1 — Close & FX completeness** | SD-4.2–.3 (unrealized FX revaluation as a close task, historical rates), SD-5 (rate-history feed, posted CTA, translated netChange), GAP-4.1 (scheduled depreciation + close check), GAP-6 (accruals/prepaids/recurring JEs) | A complete close calendar on top of the period-close lifecycle. |
+| **2 — Subledger completeness** | GAP-1 (deferred revenue, deposits, POC v1), GAP-3 (standard cost, revaluation, LCNRV, adjustment GL, overhead, landed cost), GAP-4 (impairment, CIP, disposal proceeds), SD-6 (master-data controls incl. vendor bank details when payment execution lands) | Every balance-sheet line has a subledger that ties. |
+| **3 — Multi-book & statutory** | GAP-5 (adjustment books), GAP-2 (leases), GAP-D3 (FEC/SAF-T/statutory COA/retention), GAP-D2 (e-invoicing framework), GAP-D1 (withholding, ECSL/Intrastat, MTD), GAP-7 (segments, dimension enforcement) | Multi-country statutory + dual-GAAP. |
+| **4 — Scale-out** | SD-5.4–.5 (IC tolerance/netting/mirroring, NCI), GAP-E1 (TB/JE APIs, controlled JE import), SD-3 remainder (SSO/MFA enterprise, session revocation) | Consolidation maturity + ecosystem surface. |
+| **∥ — Company program** | CO-1 (SOC 2 → SOC 1 → ISO 27001, staging, DR) | Runs parallel from Phase 0. |
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|---|---|---|
+| 1 | Posted-record immutability mechanism | Status-transition-only SECURITY DEFINER triggers on posted rows, all period states, binding service role | The period-close trigger (`20260702044133`) set the precedent and proved the pattern; RLS alone demonstrably failed (`WITH CHECK (true)` gaps) |
+| 2 | Journal approval | Extend existing `approvalRule`/`approvalRequest` engine with `journalEntry`/`payment`/`purchaseInvoice` document types | Engine already has tiers/amounts/groups; per-document ad-hoc approvals are the anti-pattern; SAP parked→posted is the model; bank-rec's preparer→approver flow is the in-house precedent |
+| 3 | Self-approval | Blocked server-side in `canApproveRequest`, all approval document types, default on | AS 2401 auditor test #1; one-line check; also fixes the existing PO self-approval hole |
+| 4 | Year-end close | **Virtual** (computed RE/Net-Income split) — adopt the period-closing + financial-reporting decision; no posted closing entries, ever | Already decided on this branch; NetSuite/QBO model; self-healing on prior-year reopen; this audit originally proposed posted closing entries — withdrawn in favor of the branch's model |
+| 5 | Multi-book placement | `journal.bookId` (header-level), seeded `PRIMARY` book, column lands Phase 0 | Header-level matches NetSuite books/SAP ledger-group posting; deferring the column is the expensive retrofit (research §Pattern 2) |
+| 6 | Per-line currency | Adopt and universalize the bank-rec spec's `journalLine.sourceAmount`/`sourceCurrencyCode` (+ `exchangeRate`); base `amount` stays authoritative | One convention, already landing; FEC/SAF-T and remeasurement need it on every line, not best-effort |
+| 7 | Draft journals in reports | Posted-only default + explicit include-drafts toggle on the balance RPCs | IPE integrity; financial-reporting spec already chose Posted+Reversed for GL detail; period-close readiness keeps blocking close on drafts |
+| 8 | Audit logging for accounting entities | Always-on, synchronous in-transaction, append-only tables, ≥7-year retention | Async-opt-in-30-day serves operational forensics, not ICFR; the branch specs route their audit trail here, so hardening it protects them too |
+| 9 | Gapless numbering | DB-serialized per-company counter assigned inside the posting transaction; `sequence` rows immutable-after-first-use | FEC validates sequential completeness; app-level pre-allocation demonstrably gaps |
+| 10 | CTA | Posted to `currencyTranslationAccount` resolved by id at group close | Display-plug doesn't roll forward; hardcoded "3200" violates the repo's control-account lesson (also flagged by the financial-reporting spec as a follow-up) |
+| 11 | Rev-rec v1 scope | Deferred revenue + deposits + cost-based POC; SSP allocation deferred | Manufacturing customer need; POC leverages job costing Carbon uniquely has; NetSuite ARM full model is a later tier |
+| 12 | Recs/SEC/equity/provision/payroll | Never build; expose GAP-E1 feeds | Even NetSuite doesn't build these (research §Ecosystem); bank-rec covers reconciliation of cash natively — the rest of the rec universe stays ecosystem |
+| 13 | Multi-tenancy heuristic | All new tables: `companyId` + composite PK + `id('prefix')` + audit columns; books group-scoped like `account`/`currency` (scoping question below) | Matches company-group master-data pattern (`20260228023426`) |
+| 14 | Service shape / RLS / permissions / forms / module layout | Per repo conventions; new work in `modules/accounting` (+ `modules/invoicing` where document-side); `requirePermissions` with `accounting_*` scopes; follows the branch specs' precedent of reusing `accounting_update`/`accounting_delete` tiers rather than new permission actions | Heuristics 2–6; the period-closing spec already established reopen = `delete: accounting` rather than a new action — follow it |
+| 15 | Backward compatibility | Additive schema only; immutability + Posted-only reports are behavior changes shipped behind a company-level activation event (see Open Questions on the accounting switch) | FROZEN surfaces unaffected; posting-function changes ship as coordinated PRs per the FX-spec precedent |
+
+## Data Model Changes (representative sketches, Phase 0)
+
+The period-close lifecycle, tax subledger, budget, and bank tables are already specified in their own specs on this branch — not repeated here. Phase 0 adds:
+
+```sql
+-- Journal control columns (MW-1/MW-2, GAP-5, SD-4)
+ALTER TABLE "journal"
+ ADD COLUMN IF NOT EXISTS "bookId" TEXT NOT NULL DEFAULT 'PRIMARY', -- FK "accountingBook", seeded per group
+ ADD COLUMN IF NOT EXISTS "preparedBy" TEXT REFERENCES "user"("id"),
+ ADD COLUMN IF NOT EXISTS "approvedBy" TEXT REFERENCES "user"("id"),
+ ADD COLUMN IF NOT EXISTS "approvalRequestId" TEXT;
+ALTER TABLE "journalLine"
+ ADD COLUMN IF NOT EXISTS "createdBy" TEXT REFERENCES "user"("id");
+-- sourceAmount / sourceCurrencyCode arrive via the bank-reconciliation spec's
+-- migration; Phase 0 makes every posting path populate them (+ exchangeRate).
+
+-- Immutability backstop (period-close trigger pattern: SECURITY DEFINER,
+-- binds service role). Posted journals: only status-transition updates
+-- (Posted -> Reversed with reversedById) allowed, in ALL period states;
+-- journalLine rows frozen once the parent is Posted; payment/memo/
+-- invoiceSettlement mirror with Posted -> Voided.
+
+CREATE TABLE IF NOT EXISTS "accountingBook" (
+ "id" TEXT NOT NULL DEFAULT id('bk'),
+ "companyGroupId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "type" TEXT NOT NULL DEFAULT 'Primary', -- Primary | Adjustment
+ "accountingPrinciple" TEXT, -- US-GAAP | IFRS | Local | Tax
+ "baseBookId" TEXT, -- for Adjustment books
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "accountingBook_pkey" PRIMARY KEY ("id", "companyGroupId")
+);
+
+-- Deferred constraint trigger: per-journal Σ(signed line amounts) = 0 at COMMIT
+-- (0.01 tolerance) — covers every poster including edge functions.
+
+-- Audit hardening: audit.config.ts gains journal/journalLine/account/
+-- accountingPeriod/payment/memo/sequence/userPermission/apiKey/approval*/
+-- accountDefault/taxCode/taxCodeComponent/bankAccount; accounting entities
+-- write synchronously in-transaction; auditLog_* tables become append-only
+-- (REVOKE UPDATE/DELETE + restrictive policies); per-class retention config.
+```
+
+RLS per conventions; all new tables audit-logged from day one. Full DDL per phase lands in that phase's implementation spec.
+
+## API / Service Changes
+
+Phase 0 (representative): posting edge functions populate `journalLine.createdBy` + source-currency columns and `journal.preparedBy`; `postJournalEntry` gains approval-state checks (`Draft → Pending Approval → Posted` when a rule matches); `canApproveRequest` self-approval block; JE-population export route + service (`/x/accounting/exports/journal-entries`, streaming, no row caps); user-access-report and SoD-conflict-report services under settings; balance RPCs gain a `p_include_drafts` parameter defaulting false. Phases 1–4 per their own specs when cut.
+
+## UI Changes
+
+Phase 0: journal-entry approval states in `JournalEntryForm` + approval inbox reuse; "include drafts" toggle on the report filter bars; JE export page; access-review + SoD-conflict reports under settings/users; audit-log settings lose the disable toggle for accounting entities (with explanatory copy). Later phases per their specs.
+
+## Acceptance Criteria
+
+Phase 0 (the ICFR keystones — each maps to an auditor test; the period-close criteria live in the period-closing spec):
+
+- [ ] A posted journal's header and lines cannot be modified via PostgREST with any role, including a direct service-role UPDATE, in an **open** period — only `Posted → Reversed` transitions succeed; same for posted payments/memos (`Posted → Voided`).
+- [ ] With an approval rule active, a manual journal cannot reach `Posted` without a second user's approval; the preparer attempting to approve their own entry is rejected server-side; `preparedBy`/`approvedBy` appear on the journal and in the JE export; the same self-approval block now also applies to purchase orders.
+- [ ] The JE export for a fiscal year contains every journal line (manual + all system source types), reconciles opening TB + export = closing TB per account, and includes preparer, approver, createdAt, postedAt, source type, book, source currency/amount, and reversal linkage on every row.
+- [ ] An unbalanced journal insert (Σ signed amounts ≠ 0) is rejected at COMMIT regardless of which code path wrote it.
+- [ ] Trial balance/BS/IS show Posted-only by default; the drafts toggle reproduces today's numbers; period-close readiness still flags open drafts.
+- [ ] Journal numbering shows no gaps across a simulated posting-failure test; editing a used sequence is rejected and logged.
+- [ ] Changes to `journal`, `account`, `accountingPeriod`, `payment`, `sequence`, `taxCode`, and `userPermission` appear in the audit log with actor + before/after, synchronously with the transaction, with audit logging on regardless of the company toggle; UPDATE/DELETE on the audit tables themselves is impossible for every role.
+- [ ] The user access report lists every user's effective permissions per company as of a chosen date; the SoD report flags a seeded test user holding JE-create + JE-approve.
+
+Phase 1 spot checks: unrealized FX revaluation posts and auto-reverses from the close checklist; a consolidated report of a two-currency group with no manual rate entry uses real rates (and warns when history is missing) with CTA posted to the configured account; depreciation proposal appears on schedule and blocks close-readiness until posted or skipped. Later phases define theirs in their specs.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| Immutability triggers break existing flows that mutate posted journals (void/reverse paths, Xero sync writebacks) | High | Inventory every writer first (posters are enumerable); allow status-transition writes; extend the post-payment golden-master tests; ship behind the activation event |
+| Gapless posting-time numbering serializes posting throughput per company | Med | Per-company (not global) advisory-lock counter; measure; documents keep draft IDs until post |
+| Synchronous audit writes slow posting hot paths | Med | Same-transaction insert is one row per change; benchmark; transactional outbox as fallback — never fire-and-forget for accounting entities |
+| Posted-only reports change numbers customers currently see | Med | Release note + drafts toggle; tie-outs unaffected (they already reconcile to control accounts); close-readiness unaffected |
+| Interplay with the six in-flight specs (this program's Phase 0 touches the same posting functions their plans touch) | Med | Sequence: land Phase ∅ first; Phase 0 rebases on their merged state; the immutability trigger must permit the tax spec's VOID re-posting and bank-rec's tolerance JEs (status-transition + new-document patterns only) |
+| Behavior changes vs the "accounting is a switch" positioning confuse existing users | Med | All Phase-0 controls activate at a company-level cutover event (see Open Questions) |
+| Scope: this program is quarters of work competing with product roadmap | High | Phases are independently valuable; Phase 0 alone is a marketable "SOX-ready controls" release; later phases gate on customer geography/stage |
+
+## Open Questions
+
+> 🛑 HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] **Does "accounting is a switch" survive?** — **Answer (Brad, 2026-07-03): No.** `accountingEnabled` is a temporary **internal feature flag** while the accounting suite is completed — not a product concept. At GA, accounting is always-on: new companies get it from creation; existing companies go through a one-way, dated **cutover event** (opening-balance journal, config lock, controls on from day one), after which the flag is removed from the codebase. Cutover runbook and flag-retirement criteria: `.ai/plans/2026-07-03-public-company-readiness-roadmap.md` §Cutover.
+- [x] **Sanctioned repair path under immutability** — **Answer (Brad, 2026-07-03): reversal-only, plus a controlled repair channel.** No in-place edits ever, for anyone including the service role. Data fixes post correcting entries through an immutable, audit-logged `'Repair'` journal source type (permissioned, reason required). The invoice/payment audit's deferred historical-repair work uses this channel.
+- [x] **Approval scope at launch** — **Answer (Brad, 2026-07-03): journals + payments + purchase invoices, ASAP**, reusing the existing PO approval engine (`approvalRule`/`approvalRequest`). Pulled forward in the roadmap: this workstream has no dependency on Phase ∅ and starts immediately.
+- [x] **Gapless numbering domain** — **Answer (2026-07-03):** the `JE-yyyy-mm` format is not a compliance violation and **existing journals are never renumbered** (retroactive renumbering is itself an audit red flag). The defects are gaps (number taken before the transaction commits) and a rewindable `sequence` table. Fix forward-only in Phase 0 Spec C: number assigned inside the posting transaction, used sequences immutable + audit-logged, historical-gap cutover date documented. Legal invoice series (statutory gapless numbering of customer-facing invoices in EU/LatAm — not journals) get their table in Phase 0, wired to documents with e-invoicing in Phase 3.
+- [x] **Draft journals in balance RPCs** — **Answer (2026-07-03):** Posted-only by default, with an explicit "Include drafts" toggle preserving the preview workflow. Folded into the financial-reporting spec §11 (`p_include_drafts DEFAULT FALSE`) since that spec redefines the RPCs anyway; drill-down drawer follows its parent so the tie-out contract holds in both modes.
+- [x] **Rev-rec v1 cut** — **Answer (Brad, 2026-07-03): accepted with a TODO.** Deferred revenue + customer deposits + cost-based POC; SSP/multi-element allocation deferred. **TODO before cutting the Phase-2 spec: validate the cut against real customer contracts** (do any current/pipeline customers bundle obligations that need SSP allocation?).
+- [x] **Unrealized FX method** — **Answer (Brad, 2026-07-03): SAP-style auto-reverse** — revaluation posts at period end and auto-reverses on day 1 of the next period; self-healing by construction.
+- [x] **E-invoicing partner** — **Answer (Brad, 2026-07-03): Avalara, as a first-class integration** — same posture as the tax spec's AvaTax connector (Avalara E-Invoicing/ELR APIs behind Carbon's adapter interface and clearance state machine), not a thin passthrough.
+- [x] **SoD preventive vs detective for v1** — **Answer (Brad, 2026-07-03): detective.** Conflict-matrix reporting + documented mitigating controls; preventive grant-blocking deferred to customer demand.
+- [x] **SOC 1 timing and scope** — **Answer (Brad, 2026-07-03): recommendation accepted.** SOC 2 Type II evidence period starts now; SOC 1 Type II scoped to posting integrity + depreciation + costing after Phase 0 lands; tax calculation joins the scope once the tax spec stabilizes in production.
+- [x] **Book scoping** — **Answer (Brad, 2026-07-03): recommendation accepted.** Group-scoped `accountingBook` definitions with per-company enablement — matches the shared chart-of-accounts pattern; a statutory book (e.g. HGB) is defined once at group level and enabled only for the entities it applies to. Unblocks the Phase-0 `bookId` seed.
+
+## Changelog
+
+- 2026-07-03: Created from the public-company readiness assessment (9 research workstreams: accounting core, multi-entity/FX, controls/ITGC, domain subledgers, repo baseline, NetSuite, SAP, regulatory inventory, ecosystem). Research: `.ai/research/public-company-compliance.md`.
+- 2026-07-04: MW-2 remediation spec'd: `.ai/specs/2026-07-04-document-approvals.md` (scope expanded to include memos as a fourth gated document type; reversals/voids not gated in v1; opt-in rules; escalation reminder; access + SoD reports). The dead sales-order `'Needs Approval'` enum value stays untouched (Postgres enums can't drop values; SO approvals out of scope).
+- 2026-07-03: All remaining open questions resolved by Brad (repair channel; approvals for JEs+payments+purchase invoices ASAP on the existing engine; forward-only gapless numbering, no renumbering of history; rev-rec cut accepted with a contract-validation TODO; auto-reverse FX; Avalara first-class for e-invoicing; detective SoD; SOC timing accepted; group-scoped books with per-company enablement). Gate cleared — Phase-0 specs may be cut; approvals workstream pulled forward to start immediately. Status → in-progress.
+- 2026-07-03: Open question 1 resolved (accounting switch = temporary internal FF; always-on at GA with a cutover event). Program plan created at `.ai/plans/2026-07-03-public-company-readiness-roadmap.md`. Three right-the-first-time fold-ins pushed into the unbuilt specs: posted-record immutability + `journalLine.createdBy` → period-closing spec (shrinks MW-1 remediation to audit-coverage + export + payment/memo immutability); Posted-only balance defaults → financial-reporting spec (resolves SD-1's draft half); universal `sourceAmount`/`sourceCurrencyCode` population → bank-reconciliation spec (resolves SD-4.1).
+- 2026-07-03: Rebased onto the `period-closing-spec` branch baseline. The branch's six in-flight specs (period closing, multi-jurisdiction tax, financial reporting, budgeting, bank reconciliation, Plaid feeds) are now assumed implemented: former findings MW-1 (period close), MW-4 (tax misstatement), most of MW-5 (year-end/cash flow/comparatives — via the branch's virtual year-end model, which this audit now adopts), GAP-8 (budgets/flux), and GAP-9 (bank) are removed or re-scoped to their remainders. Two material-weakness-level findings remain (record immutability/audit trail; JE approval/SoD); phases renumbered around a Phase ∅ = land this branch.
diff --git a/.ai/specs/2026-07-04-accounting-cutover-activation.md b/.ai/specs/2026-07-04-accounting-cutover-activation.md
new file mode 100644
index 0000000000..02a0919fd1
--- /dev/null
+++ b/.ai/specs/2026-07-04-accounting-cutover-activation.md
@@ -0,0 +1,274 @@
+# Accounting Cutover & Activation
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1057
+> Implements: `.ai/plans/2026-07-03-public-company-readiness-roadmap.md` §Cutover (runbook followed verbatim)
+> Depends on: `.ai/specs/2026-07-02-period-closing.md` (close lifecycle + `journal_check_period_open` trigger) — activation cannot ship before it lands
+> Related: `.ai/specs/2026-07-03-public-company-readiness.md` (resolved: "accounting is a switch" does NOT survive)
+
+## TLDR
+
+`companySettings.accountingEnabled` is a temporary internal feature flag, resolved on 2026-07-03 to never become a product concept. This spec builds the machinery that retires it: a **one-way, per-company activation event** (config-completeness check → opening-balance wizard → permissioned confirmation) that posts an opening trial balance as a new `'Opening Balance'` journal dated cutover − 1 day, stamps `company.accountingActivatedAt/By`, locks `baseCurrencyCode` and `fiscalYearSettings`, generates the fiscal year's periods, and **closes every pre-cutover period** so the period-close trigger guarantees empty pre-history — the opening journal is the only bridge from the past. New companies at GA activate from creation via `seed-company` with a zero ledger. Once every active company carries `accountingActivatedAt`, one PR removes the enumerated `accountingEnabled` reads and a follow-up migration drops the column.
+
+## Problem Statement
+
+- Nine posting edge functions, three job-costing DB functions, and fourteen ERP app files branch on `accountingEnabled`. When the flag is off, operational documents post inventory/item ledgers but **no GL** — flipping the flag later would leave a company with stock and invoices that have no accounting history, and nothing stops a backdated document from then generating GL into periods that predate real books.
+- There is no way for an existing company to *start* accounting correctly: no opening balances, no assertion that subledgers tie to the GL on day one, no lock on the currency/fiscal settings the ledger is denominated in.
+- `seed-company` creates companies with `accountingEnabled = false` (column default); at GA new companies must get accounting always-on from creation.
+- The GA gate (roadmap §Cutover) requires cutover tooling "shipped and exercised on at least two internal companies" before the flag can be removed. That tooling does not exist.
+
+## Proposed Solution
+
+### 1. One-way activation event
+
+A per-company, permissioned, irreversible event, exposed as a wizard at `/x/accounting/activation`. Requires `accounting_update` (`requirePermissions({ update: "accounting" })`) plus an explicit typed confirmation (the company name), because it is one-way: there is no deactivation path, by design.
+
+**Config-completeness check** (`getActivationReadiness`) — all must pass before the wizard advances past step 1:
+
+| Check | Passes when |
+|---|---|
+| Chart of accounts | ≥ 1 posting account exists for the company |
+| Account defaults | The company's `accountDefault` row exists and **every referenced default account column is set** and resolves to an active account |
+| Fixed-asset classes | Every active `fixedAssetClass` has its asset + accumulated-depreciation accounts set (only when assets exist) |
+| Fiscal settings | `fiscalYearSettings` row exists; user confirms `startMonth` in the wizard (it locks at activation) |
+| Base currency | `company.baseCurrencyCode` set (locks at activation) |
+| Tax codes | Every active customer/supplier has a tax code assigned — enforced only when the multi-jurisdiction tax spec is live for the company; otherwise informational |
+| Bank accounts | Every active `bankAccount` is GL-linked (has its GL account set) |
+| Cutover date | First day of a fiscal period (derived from `startMonth`) — see §3 |
+
+**What activation does**, in one orchestrated server transaction (order matters — the opening journal must post *before* its period closes):
+
+1. Re-run readiness + opening-balance validations server-side (never trust the wizard's client state).
+2. Generate the cutover fiscal year's periods via the period-closing spec's `createFiscalYearPeriods`, plus the single prior period containing cutover − 1 day if not already present.
+3. Post the opening-balance Draft journal (§2) through `postJournalEntry` (source `"accounting"`), dated cutover − 1.
+4. **Close all periods with `endDate` < cutover date** — a dedicated `closePreCutoverPeriods` bulk path (see Design Decisions: it bypasses the close checklist because these periods are empty except the opening journal). The `journal_check_period_open` trigger then guarantees pre-history stays empty: no retroactive GL from old operational documents, ever.
+5. Stamp `company.accountingActivatedAt = now()`, `accountingActivatedBy = userId`, `accountingCutoverDate = cutoverDate`.
+6. Set `companySettings.accountingEnabled = true` — the mechanical bridge until flag retirement (§5); all posting paths turn on.
+7. Write the audit log entry for the activation event (§6).
+
+From `accountingActivatedAt` forward, a `SECURITY DEFINER` trigger rejects updates to `company.baseCurrencyCode` and to `fiscalYearSettings.startMonth` (the ledger's denomination and calendar are frozen facts once books exist).
+
+### 2. Opening-balance wizard
+
+The wizard builds a **Draft journal** — new `journalEntrySourceType` value `'Opening Balance'`, `postingDate` = cutover − 1 day — as the proposed opening trial balance. The Draft journal *is* the wizard state: editable via the existing journal-entry line editor, no parallel staging tables.
+
+**Proposed lines** (each section regenerable independently; proposals are suggestions the user can edit):
+
+| Section | Source | Lines proposed |
+|---|---|---|
+| Inventory | `costLedger`/`itemCost` valuation as of cutover (existing `get_inventory_value_by_location` totals, grouped by posting-group inventory account) | Dr each inventory account for its valuation total |
+| AR | Open sales-invoice balances via `get_ar_open_by_customer` as of cutover − 1 | Dr AR control account(s). Post-tax-spec: net + tax split (revenue-side detail stays in the prior system; the split populates the tax ledger's opening liability); pre-tax-spec: gross to control |
+| AP | Open purchase-invoice balances via `get_ap_open_by_supplier` as of cutover − 1 | Cr AP control account(s), same net + tax split rule |
+| Fixed assets | The `fixedAsset` register: Σ `acquisitionCost` and Σ `accumulatedDepreciation` per `fixedAssetClass` | Dr class asset account; Cr class accumulated-depreciation account |
+| Everything else | Manual entry (cash, loans, equity, accruals) | User-entered rows + a live **remaining-to-balance** line the wizard maintains and the user must consciously assign to a real account (typically opening equity) before validation |
+
+**Validations** — all must pass before the Activate button enables, and are re-run inside the activation transaction:
+
+1. **Journal balances**: Σ signed line amounts = 0 (± 0.01).
+2. **AR/AP tie-outs**: because pre-cutover GL is empty by construction, the draft journal's control-account lines *are* the GL side. The validation compares Σ draft lines on the AR (resp. AP) control accounts against the subledger totals from `get_ar_open_by_customer`/`get_ap_open_by_supplier` as of cutover − 1 — the same subledger arithmetic `get_ar_tie_out`/`get_ap_tie_out` use, so the first real tie-out run after activation passes by construction. Variance > 0.01 blocks.
+3. **Inventory valuation vs GL**: Σ draft lines on inventory accounts must equal the `costLedger`/`itemCost` valuation total per account. Variance > 0.01 blocks.
+4. **Fixed-asset register vs GL**: draft asset/accumulated-depreciation lines must equal register sums per class. Variance > 0.01 blocks (skipped when no assets exist).
+
+**Alternative path — prior-system closing TB (CSV import)**: instead of section-by-section proposals, import the old GL's closing trial balance as CSV (`accountNumber, description, debit, credit`), mapped to Carbon accounts by account number with an inline mapping step for misses. This *replaces the proposal step only* — the same four validations run unchanged, which means open AR/AP invoices and inventory quantities/costs **must already be migrated into Carbon** (via the existing CSV import system) before activation, so the subledger side of each tie-out exists. The TB is the assertion; Carbon's subledgers are the evidence. A TB that doesn't tie is a data-migration bug surfaced *before* activation, not after.
+
+### 3. Cutover date: fiscal-period start only
+
+**RESOLVED (Brad, 2026-07-04): cutover happens only at a fiscal-period start.** The wizard's date picker offers only first-of-period dates.
+
+Mid-year cutovers (any period start that isn't period 1) are supported, but a **YTD P&L reload is out of scope for v1**: the opening journal is balance-sheet-shaped, and the prior system's YTD net income arrives collapsed inside the manual equity section (current-year-earnings line), not as per-account P&L history. Consequence, documented in the wizard: Carbon's income statement shows post-cutover activity only for the stub year; YTD comparatives for that year live in the prior system. **v2 workaround (deferred)**: one opening journal per elapsed period of the cutover year, restoring monthly P&L granularity — the `'Opening Balance'` source type and validation machinery already accommodate it.
+
+### 4. New-company path at GA
+
+`seed-company` activates accounting at creation: after seeding COA, `accountDefault`, `fiscalYearSettings`, and the `PRIMARY` book (Phase 0 schema seed), it stamps `accountingActivatedAt = now()`/`accountingActivatedBy = userId`, sets `accountingCutoverDate` = first day of the creation period, sets `accountingEnabled = true`, generates the current fiscal year's periods, and closes periods that end before the creation period (same empty-pre-history invariant). **No opening balances** — the ledger starts at zero on day one; no wizard, no tie-outs. Until the GA gate is met this behavior sits behind a `SEED_ACCOUNTING_ACTIVE` env toggle so internal companies exercise it first.
+
+### 5. Flag retirement
+
+**Complete reader inventory of `accountingEnabled`** (verified by grep, 2026-07-04 — the removal PR checklist):
+
+- **Edge functions** (`packages/database/supabase/functions/`): `post-receipt`, `post-shipment`, `post-purchase-invoice`, `post-sales-invoice`, `post-payment`, `post-memo`, `issue`, `close-job`, `post-production-event`.
+- **DB functions** (latest definitions): `backflush_job_materials` + `complete_job_to_inventory` (`20260630092517_job-costing-item-dimension.sql`), `sync_finish_job_operation` (`20260511120000_backflush-job-materials.sql`).
+- **ERP app**: `modules/settings/settings.service.ts`; `modules/accounting/ui/useAccountingSubmodules.tsx`; `modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx`; `modules/invoicing/ui/Dashboard/InvoicingDashboard.tsx`; `modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx`; `modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx`; routes `x+/invoicing+/_index.tsx`, `receivables.tsx`, `receivables.adjust.tsx`, `payables.tsx`, `payables.adjust.tsx`, `x+/sales-invoice+/$invoiceId.status.tsx`, `x+/purchase-invoice+/$invoiceId.status.tsx`, `x+/settings+/accounting.tsx`.
+- **Generated** (fall out of `pnpm run generate:types` after the drop migration): `packages/database/src/types.ts`, `packages/database/src/swagger-docs-schema.ts`, `packages/database/supabase/functions/lib/types.ts`.
+- **Schema**: `20260508000000_accounting-enabled.sql` (adds the column); docs language in `docs/content/docs/reference/accounting.mdx` (rewritten at GA — accounting is not optional).
+
+**Retirement sequence** (roadmap §Cutover step 5 + GA gate):
+
+1. GA gate met: Phase ∅ fully landed; Phase 0 fully landed; cutover tooling exercised end-to-end on **at least two internal companies**.
+2. Every active company has `accountingActivatedAt` set (verified by query; stragglers are cut over or archived).
+3. **Removal PR**: delete every `accountingEnabled` read above — edge functions and DB functions treat accounting as unconditionally on; ERP surfaces gate on `accountingActivatedAt IS NOT NULL` where a gate is still meaningful (activation wizard entry) or drop the branch entirely. `settings+/accounting.tsx` loses the flag; the wizard is the only "turn on accounting" surface.
+4. **Follow-up migration** drops `companySettings.accountingEnabled` + re-runs `generate:types`.
+
+### 6. Audit posture
+
+The activation event, the opening journal, the config-lock trigger installs/rejections, and every pre-cutover period close are **audit-logged** (audit log system, `.ai/rules/audit-log-system.md`; Phase 0 Spec A makes the accounting trail synchronous, append-only, immutable). `accountingCutoverDate` is the start of auditable history in Carbon — anything earlier lives in the prior system's records under its retention policy, and the roadmap's "first close" step (parallel-run TB comparison at month 1) is the migration's audit evidence. The opening journal is itself immutable once posted (period-closing fold-in) and repairable only by reversal into an open period.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Multi-tenancy | **No new tables.** New columns on existing `company` (single-col PK, legacy); wizard state = the Draft `'Opening Balance'` journal + `journalLine` rows | Heuristic satisfied by inheritance; a staging table would duplicate the journal editor and need its own RLS/audit for zero gain |
+| 2 | Service shape | `getActivationReadiness` / `buildOpeningBalanceProposal` / `validateOpeningBalance` / `activateAccounting` / `closePreCutoverPeriods` in `accounting.service.ts`, `(client, ...)` → `{data, error}`, never throw | `.ai/rules/conventions-services.md`; one module service file |
+| 3 | RLS coverage | No new tables ⇒ no new policies; `company` activation columns writable only via the service path (existing company UPDATE policy + lock trigger backstop) | Trigger is `SECURITY DEFINER` so service-role writers are equally bound |
+| 4 | Permission scoping | Wizard route `requirePermissions({ update: "accounting" })`; activation additionally demands typed company-name confirmation | Matches fiscal-year-settings and journal-posting precedent (period-closing spec); one-way events need friction, not a new RBAC tier (ask-first) |
+| 5 | Form pattern | `ValidatedForm` + zod validators (`accounting.models.ts`) + route actions with `intent` (`propose` \| `import-tb` \| `validate` \| `activate`) | `settings+/accounting.tsx` precedent |
+| 6 | Module layout | Everything in `apps/erp/app/modules/accounting/` (models/service/ui) + routes under `x+/accounting+/` | No scattering; activation is an accounting concern |
+| 7 | Backward compatibility | Additive migration (enum value + nullable columns + triggers). Flag semantics unchanged until the removal PR; `seed-company` change env-gated until GA. Posting edge functions untouched by this spec | FROZEN surfaces unaffected; retirement is its own reviewed PR with the §5 checklist |
+| 8 | One-way | No deactivation, no un-activation, ever | A ledger that can be switched off is the exact posture resolved against on 2026-07-03; reversal would orphan posted GL |
+| 9 | Opening journal placement | Dated cutover − 1, **posted before** pre-cutover periods close (activation step ordering) | The close trigger would reject it afterward; closing behind it makes it the unique bridge — invariant by construction, not convention |
+| 10 | Pre-cutover closes bypass the checklist | Dedicated `closePreCutoverPeriods` bulk path: stamps `closeStatus='Closed'`, `closedAt/By`, audit-logs each period; skips `periodCloseTask` instantiation | The 9-task checklist is meaningless for periods that structurally contain at most one journal; sequential-close invariant preserved (closes run oldest-first) |
+| 11 | Tie-out mechanics | Validate draft lines against subledger RPC totals (`get_ar_open_by_customer`/`get_ap_open_by_supplier`, inventory valuation, asset register) rather than teaching `get_ar_tie_out`/`get_ap_tie_out` to see Draft journals | RPCs stay Posted-only (financial-reporting fold-in); post-activation tie-outs pass by construction |
+| 12 | Grandfathering internal companies | Companies already running with `accountingEnabled = true` are backfilled by the migration: `accountingActivatedAt = now()`, `accountingActivatedBy` = system, `accountingCutoverDate` = start of earliest period containing a posted journal; no wizard, no tie-outs (their history is already in Carbon) | They never had a cutover; forcing a synthetic one would fabricate an opening journal on top of real history. Locks apply from backfill forward |
+| 13 | CSV TB prerequisite | Open AR/AP invoices + inventory must be migrated before TB import; validations enforce it | The TB alone is unverifiable; tie-outs need the subledger side to exist |
+
+## Data Model Changes
+
+One idempotent migration (`pnpm db:migrate:new accounting-activation`), then `pnpm run generate:types`:
+
+```sql
+-- New journal source type (enum ADD VALUE pattern per database-migration-patterns)
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Opening Balance';
+
+-- Activation stamp on company (legacy single-column PK table; additive columns only)
+ALTER TABLE "company"
+ ADD COLUMN IF NOT EXISTS "accountingActivatedAt" TIMESTAMP WITH TIME ZONE,
+ ADD COLUMN IF NOT EXISTS "accountingActivatedBy" TEXT REFERENCES "user"("id") ON DELETE RESTRICT,
+ ADD COLUMN IF NOT EXISTS "accountingCutoverDate" DATE;
+
+-- Config locks: baseCurrencyCode + fiscal settings freeze once activated
+CREATE OR REPLACE FUNCTION check_accounting_config_locked() RETURNS TRIGGER
+SECURITY DEFINER SET search_path = public AS $$
+BEGIN
+ IF TG_TABLE_NAME = 'company' THEN
+ IF OLD."accountingActivatedAt" IS NOT NULL
+ AND NEW."baseCurrencyCode" IS DISTINCT FROM OLD."baseCurrencyCode" THEN
+ RAISE EXCEPTION 'baseCurrencyCode is locked: accounting was activated %', OLD."accountingActivatedAt";
+ END IF;
+ IF OLD."accountingActivatedAt" IS NOT NULL
+ AND (NEW."accountingActivatedAt" IS DISTINCT FROM OLD."accountingActivatedAt"
+ OR NEW."accountingActivatedBy" IS DISTINCT FROM OLD."accountingActivatedBy"
+ OR NEW."accountingCutoverDate" IS DISTINCT FROM OLD."accountingCutoverDate") THEN
+ RAISE EXCEPTION 'accounting activation is one-way and immutable';
+ END IF;
+ ELSIF TG_TABLE_NAME = 'fiscalYearSettings' THEN
+ IF EXISTS (SELECT 1 FROM "company" c WHERE c."id" = NEW."companyId"
+ AND c."accountingActivatedAt" IS NOT NULL)
+ AND NEW."startMonth" IS DISTINCT FROM OLD."startMonth" THEN
+ RAISE EXCEPTION 'fiscal year settings are locked: accounting is activated';
+ END IF;
+ END IF;
+ RETURN NEW;
+END; $$ LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS "company_accounting_config_locked" ON "company";
+CREATE TRIGGER "company_accounting_config_locked"
+ BEFORE UPDATE ON "company" FOR EACH ROW EXECUTE FUNCTION check_accounting_config_locked();
+DROP TRIGGER IF EXISTS "fiscalYearSettings_accounting_config_locked" ON "fiscalYearSettings";
+CREATE TRIGGER "fiscalYearSettings_accounting_config_locked"
+ BEFORE UPDATE ON "fiscalYearSettings" FOR EACH ROW EXECUTE FUNCTION check_accounting_config_locked();
+
+-- Grandfather backfill (Design Decision 12): companies already live on the flag
+UPDATE "company" c SET
+ "accountingActivatedAt" = NOW(),
+ "accountingActivatedBy" = 'system',
+ "accountingCutoverDate" = sub."cutover"
+FROM (
+ SELECT j."companyId", MIN(ap."startDate") AS "cutover"
+ FROM "journal" j JOIN "accountingPeriod" ap ON ap."id" = j."accountingPeriodId"
+ WHERE j."status" = 'Posted' GROUP BY j."companyId"
+) sub
+WHERE sub."companyId" = c."id" AND c."accountingActivatedAt" IS NULL
+ AND EXISTS (SELECT 1 FROM "companySettings" s
+ WHERE s."id" = c."id" AND s."accountingEnabled" = true);
+```
+
+Flag-retirement follow-up migration (separate, after the §5 removal PR ships):
+
+```sql
+ALTER TABLE "companySettings" DROP COLUMN IF EXISTS "accountingEnabled";
+```
+
+## API / Service Changes
+
+All in `apps/erp/app/modules/accounting/accounting.service.ts` (+ zod in `accounting.models.ts`):
+
+```ts
+getActivationReadiness(client, companyId)
+// → { data: { checks: ReadinessCheck[]; cutoverDateOptions: string[] }, error }
+
+buildOpeningBalanceProposal(client, { companyId, cutoverDate, section, userId })
+// section: 'inventory' | 'ar' | 'ap' | 'fixedAssets' — (re)generates that section's
+// lines on the company's Draft 'Opening Balance' journal (creates it if missing,
+// dated cutoverDate − 1); idempotent per section (delete + reinsert its lines)
+
+importOpeningTrialBalance(client, { companyId, cutoverDate, rows, userId })
+// CSV path: replaces ALL proposal lines with mapped TB rows; unmapped accounts error
+
+validateOpeningBalance(client, { companyId, journalId })
+// → { data: { balanced, arTieOut, apTieOut, inventoryTieOut, fixedAssetTieOut }, error }
+// each: { draftAmount, subledgerAmount, variance, pass }
+
+activateAccounting(client, { companyId, userId, confirmation })
+// orchestration of §1 steps 1–7 in one transaction; rejects unless every readiness
+// check and every validation passes and confirmation === company.name
+
+closePreCutoverPeriods(client, { companyId, cutoverDate, userId })
+// internal to activateAccounting; oldest-first, audit-logged per period
+```
+
+**Routes** (new, `apps/erp/app/routes/x+/accounting+/`):
+- `activation.tsx` — loader (`view: "accounting"`) returns readiness + draft journal + validations; action (`update: "accounting"`) with `intent`: `propose` | `import-tb` | `validate` | `activate`.
+- `activation.import.tsx` — CSV upload + account-mapping step (existing CSV import system patterns).
+
+**Edge function**: `seed-company` gains the §4 activation block (env-gated until GA). No changes to posting edge functions in this spec.
+
+## UI Changes
+
+- **Activation wizard** (`/x/accounting/activation`, linked from `settings+/accounting.tsx` and `useAccountingSubmodules` when `accountingActivatedAt IS NULL`): four steps — (1) readiness checklist with red/green rows and deep links to fix each miss + cutover-date picker (period starts only, with the §3 mid-year P&L note); (2) opening balances — per-section Propose buttons or the CSV TB import, editing via the existing journal-entry line editor, live remaining-to-balance indicator; (3) validation — the four tie-out cards with draft vs subledger amounts and variances; (4) activate — consequences summary (one-way; locks; pre-cutover closes; audit start date), typed company-name confirmation, Activate button.
+- **Post-activation**: wizard route redirects to `/x/accounting/periods`; settings page shows a read-only "Accounting activated {date} by {user}" banner; `baseCurrencyCode` and fiscal-year fields render disabled with a lock tooltip.
+- Flash messages on every action per `.ai/rules/flash-system.md`.
+
+## Acceptance Criteria
+
+Two-company end-to-end per the roadmap GA gate — company A (wizard-proposal path), company B (prior-system CSV TB path), both taken from flag-off to activated:
+
+- [ ] Company A with a missing `accountDefault` account cannot pass step 1; fixing it flips the readiness row without restarting the wizard; the cutover date picker offers only fiscal-period-start dates.
+- [ ] Company A's proposals tie: inventory lines equal `get_inventory_value_by_location` totals; AR/AP lines equal `get_ar_open_by_customer`/`get_ap_open_by_supplier` totals as of cutover − 1; fixed-asset lines equal register Σ cost / Σ accumulated depreciation per class; the remaining-to-balance line updates live and blocks activation until assigned.
+- [ ] Company B: importing a closing TB with an unmapped account number errors with the row identified; after mapping, the same four validations run; a TB whose AR control differs from Carbon's open-invoice total by > 0.01 blocks activation with the variance shown.
+- [ ] Activating either company (with `accounting_update` + typed company name): posts the `'Opening Balance'` journal dated cutover − 1 as Posted; stamps `accountingActivatedAt/By` + `accountingCutoverDate`; generates the fiscal year's periods; closes every period ending before cutover (visible on `/x/accounting/periods`); a user without `accounting_update` gets a 403 on the action.
+- [ ] Post-activation, `get_ar_tie_out` and `get_ap_tie_out` as of the cutover date return variance ≤ 0.01 for both companies; the trial balance as of cutover − 1 equals exactly the opening journal.
+- [ ] Post-activation, posting a backdated receipt or manual JE dated before cutover fails with the period-closed error (service gate and direct service-role `INSERT` against the trigger); reversing the opening journal creates the reversal in the current open period.
+- [ ] Post-activation, updating `company.baseCurrencyCode` or `fiscalYearSettings.startMonth` fails (via PostgREST with user credentials AND with the service role); clearing `accountingActivatedAt` fails.
+- [ ] Activation event, opening journal, config-lock rejections, and each pre-cutover period close appear in the audit log with user + timestamp.
+- [ ] With `SEED_ACCOUNTING_ACTIVE` on, a freshly seeded company has `accountingActivatedAt` set, `accountingEnabled = true`, current-FY periods generated, pre-creation periods closed, and zero journals other than none (empty ledger); without the env flag, seeding behaves as today.
+- [ ] Migration backfills grandfathered companies (flag on + posted journals) with activation stamps and a cutover date equal to their earliest posted-journal period start; flag-off companies remain unstamped; migration applies idempotently twice.
+- [ ] The §5 reader inventory is verified empty of stragglers by `grep -rn accountingEnabled` limited to non-generated files at removal-PR time (criterion for the retirement PR, not this spec's PRs).
+- [ ] `pnpm run generate:types`, scoped `typecheck`, and `pnpm run lint` pass.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Subledger data changes between validation and activation (e.g., a receipt posts mid-wizard) | Med | Validations re-run inside the activation transaction; any variance aborts with a "re-validate" flash |
+| Enum `ADD VALUE` cannot run inside the same transaction as its first use | Low | Enum value added in its own migration statement wave (established `ADD VALUE IF NOT EXISTS` pattern); service usage ships after migration applies |
+| Grandfather backfill locks fiscal settings for an internal company that still wanted to change them | Low | Internal companies only; a one-off SQL unlock (clear stamp, change, re-stamp) is available to us pre-GA and is itself audit-visible |
+| `closePreCutoverPeriods` on a company with years of empty lazy-created periods is slow / partially fails | Low | Bulk single-statement close oldest-first inside the transaction; all-or-nothing |
+| Mid-year cutover users expect YTD P&L in Carbon and are surprised | Med | Wizard step 1 shows the §3 note at date selection; docs updated; v2 monthly-opening-journal path documented |
+| Activation transaction spans period generation + posting + closes and exceeds statement timeout on large datasets | Med | Proposal/validation (the heavy reads) happen pre-transaction; the transaction itself writes bounded rows (1 journal + N periods) |
+
+## Open Questions
+
+> All blocking questions resolved before writing (per spec-writing Step 5); resolutions baked in above.
+
+- [x] **Does "accounting is a switch" survive?** — **Answer (Brad, 2026-07-03): No.** Temporary internal flag; always-on at GA; one-way cutover event for existing companies; flag removed from the codebase. (Readiness spec, resolved inline.)
+- [x] **Mid-year cutover / YTD P&L reload?** — **Answer (Brad, 2026-07-04):** Cutover only at a fiscal-period start; mid-year YTD P&L reload deferred to v2 (workaround: monthly opening journals). v1 opening journal is balance-sheet-shaped with YTD earnings collapsed into equity. (§3.)
+- [x] **Wizard state storage** — **Answer:** The Draft `'Opening Balance'` journal is the state; no staging tables. (Design Decision 1.)
+- [x] **Do pre-cutover closes run the close checklist?** — **Answer:** No — dedicated bulk path, audit-logged per period, sequential-close invariant preserved. (Design Decision 10.)
+- [x] **Grandfathered internal companies** — **Answer:** Migration backfills activation stamps from earliest posted-journal period; no synthetic wizard run. (Design Decision 12.)
+- [x] **Retirement-PR timing vs archived companies**: the "every active company has `accountingActivatedAt`" query needs a definition of *active* (billing status? recent login?) — companies that are dormant-but-not-deleted could block flag removal indefinitely. Recommend: active = non-archived with activity in the last 90 days; dormant companies get force-activated with zero opening balances or archived. Needs Brad's call at retirement time — blocks the removal PR (§5 step 2), **not** this spec's implementation. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Active = non-archived with any activity in the trailing 90 days. At retirement time, dormant non-archived companies are force-activated at zero balances or archived — they never block the flag-removal PR indefinitely.
+
+## Changelog
+
+- 2026-07-04: Created. Implements roadmap §Cutover verbatim (activation event, opening-balance wizard + CSV TB path, seed-company GA path, flag-retirement inventory + GA gate, audit posture). Cutover-at-period-start resolved by Brad same day; mid-year YTD reload deferred with documented workaround. Reader inventory of `accountingEnabled` verified by grep across edge functions, DB functions, ERP app, and generated types.
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/2026-07-04-accounting-implementation-meta.md b/.ai/specs/2026-07-04-accounting-implementation-meta.md
new file mode 100644
index 0000000000..aeedc80c1b
--- /dev/null
+++ b/.ai/specs/2026-07-04-accounting-implementation-meta.md
@@ -0,0 +1,94 @@
+# Accounting Implementation Meta Spec — the DAG to Public-Company Readiness
+
+> Status: active (program definition — stays open until the exit criteria pass)
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: [crbnos/carbon#1060](https://github.com/crbnos/carbon/issues/1060)
+> Companions: audit `.ai/specs/2026-07-03-public-company-readiness.md` · roadmap `.ai/plans/2026-07-03-public-company-readiness-roadmap.md` · research `.ai/research/public-company-compliance.md`
+
+## Purpose
+
+This is the **program contract for autonomous execution**: implement every existing accounting spec and everything else required for Carbon to pass a compliance audit as the accounting system of a public company operating in multiple countries. The unit of work is a **GitHub issue** (#1030–#1059); this spec defines the DAG between them, the execution protocol an agent follows for each, and the exit criteria for the whole program. Issues reference the detailed specs; where a workstream has no spec yet, its issue says so and the agent writes one first (creating more specs as needed is expected and encouraged — new spec ⇒ new changelog entry here).
+
+Binding rules:
+- **The issues are the binding.** An issue's body + its referenced specs define the work. If this spec and an issue disagree, fix the disagreement before building (comment on the issue).
+- **The DAG is authoritative here.** An issue is *ready* when all its hard dependencies are closed. Do not start a non-ready issue.
+- **Humans stay in the loop at spec gates only.** Open questions are resolved by @barbinbrad in issue comments before a spec is written (per `.ai/skills/spec-writing/SKILL.md` — interview first, document second). Everything else is autonomous.
+
+## Exit criteria — "we would pass the audit"
+
+The program is complete when all of the following hold (expanded form in the roadmap's Definition of full readiness):
+
+1. **ICFR controls**: period close enforced at the DB for every writer; posted records immutable everywhere with reversal/void-only correction and the audited Repair channel; document approvals live on JEs/payments/purchase invoices/memos with system-enforced no-self-approval; always-on, synchronous, append-only audit trail (≥7-year accounting retention) covering all accounting + permission tables; gapless numbering from the cutover epoch; access-review and SoD reports produce auditor-ready CSVs; the JE population export reconciles opening→closing trial balance for any fiscal year.
+2. **Financial statements**: BS/IS/TB/SCF/GL-detail, Posted-only, comparatives, consolidated across mixed currencies with real (warned) rates and posted, rolled-forward CTA; budget-vs-actual; drill-down to journal lines everywhere; CSV/PDF exports.
+3. **GAAP subsystems**: deferred revenue + deposits + POC with rollforwards; lease subledger; standard cost + revaluation + LCNRV + landed cost; impairment/CIP/component assets; prepaid/recurring/auto-reversing engines; at least one adjustment book proving multi-GAAP; segment-tagged statements with server-enforced dimensions.
+4. **Multi-country statutory**: tax determination/posting/returns per registration; e-invoicing live via Avalara for at least one clearance market with the state machine proven; FEC + one SAF-T flavor validating; statutory COA mapping; WORM retention + legal hold.
+5. **Ecosystem**: TB API, JE export/import APIs (import approval- and period-aware), close webhooks — documented.
+6. **Cutover**: accounting always-on; `accountingEnabled` flag deleted; ≥2 companies migrated through the activation runbook with tying opening balances.
+7. *(Company program, outside agent scope but gating the audit itself)*: SOC 1 Type II underway per roadmap §∥.
+
+## The DAG
+
+Waves are a scheduling convenience; the truth is the edge list. `⚠ spec-first` = the issue requires writing a spec (with the Brad interview) before building.
+
+| Issue | Workstream | Spec status | Hard deps | Soft deps / coordination |
+|---|---|---|---|---|
+| [#1030](https://github.com/crbnos/carbon/issues/1030) | FX convention normalization | spec exists — **3 open questions to resolve in-issue first** | — | ship as one coordinated PR |
+| [#1031](https://github.com/crbnos/carbon/issues/1031) | Period close + posted-record immutability + **NetSuite-style close checklist** | spec + plan exist (two delta banners; plan Addendum Tasks 17–20) | — | land before #1036 (shared `post-*` surface); seeds the checklist registration surface downstream close tasks use |
+| [#1032](https://github.com/crbnos/carbon/issues/1032) | Document approvals + SoD reporting | spec exists — `/plan` next | — | **highest priority** |
+| [#1033](https://github.com/crbnos/carbon/issues/1033) | ITGC hardening | **CLOSED — deferred** (Brad, 2026-07-04) | — | reopen when the SOC program starts |
+| [#1034](https://github.com/crbnos/carbon/issues/1034) | Bank reconciliation Phase 1 | spec + plan exist (delta banner) | #1030 | |
+| [#1035](https://github.com/crbnos/carbon/issues/1035) | Financial reporting package | spec + plan exist (delta banner) | #1031 | |
+| [#1036](https://github.com/crbnos/carbon/issues/1036) | Tax Phase 1 | spec exists — `/plan` next | #1030 | after #1031 (posting triggers) |
+| [#1037](https://github.com/crbnos/carbon/issues/1037) | Budgeting Phase 1 | spec + plan exist | #1031 | |
+| [#1038](https://github.com/crbnos/carbon/issues/1038) | Gapless numbering + legal series | spec exists (`2026-07-04-gapless-numbering-legal-series.md`) — `/plan` next | #1031 | coordinate with #1047 |
+| [#1039](https://github.com/crbnos/carbon/issues/1039) | Close automation (depreciation, accruals, recurring) | spec exists (`2026-07-04-close-automation.md`) — `/plan` next | #1031 | |
+| [#1040](https://github.com/crbnos/carbon/issues/1040) | Inventory valuation completeness | spec exists (`2026-07-04-inventory-valuation-completeness.md`) — `/plan` next | #1031 | IAS 2 reversal waits for #1052 |
+| [#1041](https://github.com/crbnos/carbon/issues/1041) | Fixed assets completeness | spec exists (`2026-07-04-fixed-assets-completeness.md`) — `/plan` next | #1031 | |
+| [#1042](https://github.com/crbnos/carbon/issues/1042) | Plaid bank feeds + cash position | spec exists — `/plan` next | #1034 | |
+| [#1043](https://github.com/crbnos/carbon/issues/1043) | Tax Phase 2 (returns, settlement) | spec exists | #1036, #1031 | |
+| [#1044](https://github.com/crbnos/carbon/issues/1044) | Tax Phase 3 (Avalara, Xero mapping) | spec exists | #1036 | foundation for #1054 |
+| [#1045](https://github.com/crbnos/carbon/issues/1045) | Budgeting Phases 2–3 | spec + plan exist | #1037, #1035 | |
+| [#1046](https://github.com/crbnos/carbon/issues/1046) | Bank rec Phases 3–4 | spec exists | #1034 | |
+| [#1047](https://github.com/crbnos/carbon/issues/1047) | Record integrity, audit hardening, JE export, book seed | spec exists (`2026-07-04-record-integrity-audit-hardening.md`) — `/plan` next | #1031, #1032, #1034 | the spec is the `audit.config.ts` ask |
+| [#1048](https://github.com/crbnos/carbon/issues/1048) | Revenue recognition (full ASC 606 + SSP + POC) | spec exists (`2026-07-04-revenue-recognition.md`) — `/plan` next; 2 open questions in-issue | #1031, #1036 | |
+| [#1049](https://github.com/crbnos/carbon/issues/1049) | Segments + dimension enforcement | spec exists (`2026-07-04-segment-reporting.md`) — `/plan` next | #1035 | |
+| [#1050](https://github.com/crbnos/carbon/issues/1050) | FX + consolidation completeness | spec exists (`2026-07-04-fx-consolidation-completeness.md`) — `/plan` next; 2 open questions in-issue | #1031, #1034, #1035 | |
+| [#1051](https://github.com/crbnos/carbon/issues/1051) | Master-data controls + vendor bank details | spec exists (`2026-07-04-master-data-controls.md`) — `/plan` next | #1032, #1047 | prereq for any payment execution |
+| [#1052](https://github.com/crbnos/carbon/issues/1052) | Multi-book adjustment books | spec exists (`2026-07-04-multi-book.md`) — `/plan` next | #1047 | owns the shared book DDL contract with #1047 |
+| [#1053](https://github.com/crbnos/carbon/issues/1053) | Statutory exports (FEC, SAF-T, GoBD, statutory COA, retention) | **CLOSED — deferred** (Brad, 2026-07-04; reopen before any French/statutory-filing entity goes live) | — | |
+| [#1054](https://github.com/crbnos/carbon/issues/1054) | E-invoicing framework (Avalara first-class) | spec exists (`2026-07-04-e-invoicing.md`) — `/plan` next; 3 open questions in-issue | #1036, #1038, #1044, #1061 | **France mandate Sept 2026; Poland KSeF already in force** |
+| [#1055](https://github.com/crbnos/carbon/issues/1055) | Withholding, ECSL/Intrastat, MTD | spec exists (`2026-07-04-withholding-ecsl-intrastat-mtd.md`) — `/plan` next; 2 open questions in-issue | #1043 | |
+| [#1056](https://github.com/crbnos/carbon/issues/1056) | Lease subledger (lessee + lessor, 842/IFRS 16) | spec exists (`2026-07-04-lease-accounting.md`) — `/plan` next; 2 open questions in-issue | #1052 | |
+| [#1057](https://github.com/crbnos/carbon/issues/1057) | Cutover tooling + flag retirement | spec exists (`2026-07-04-accounting-cutover-activation.md`) — `/plan` next | #1031, #1036, #1047, #1038 | gates GA / always-on |
+| [#1058](https://github.com/crbnos/carbon/issues/1058) | Intercompany maturity | spec exists (`2026-07-04-intercompany-maturity.md`) — `/plan` next; 2 open questions in-issue | #1050 | |
+| [#1059](https://github.com/crbnos/carbon/issues/1059) | Integration surface (TB/JE APIs, JE import, webhooks) | spec exists (`2026-07-04-integration-surface.md`) — `/plan` next | #1032, #1047 | |
+| [#1061](https://github.com/crbnos/carbon/issues/1061) | Avalara integration foundation (registry, credentials, shared client) | **spec + plan exist** (`2026-07-04-avalara-integration-foundation.md`, plan same slug) — execute next; 1 open question in-issue | — | consumed by #1044 and #1054 |
+
+Rendered graph: see [#1060](https://github.com/crbnos/carbon/issues/1060) (mermaid).
+
+**Critical path to "controls pass" (the two MW findings):** #1031 → #1047, with #1032 in parallel. **Critical path to always-on accounting:** #1031/#1030 → #1036 → (#1038, #1047) → #1057. **First external deadline:** #1054 (France, Sept 2026) via #1036 → #1044.
+
+## Execution protocol (per issue — the agent contract)
+
+1. **Pick** the highest-priority *ready* issue (all hard deps closed). Priority order when several are ready: #1032 first (standing instruction), then critical-path issues, then wave order.
+2. **Spec gate**: if the issue is ⚠ spec-first, run `/spec-writing` — fieldwork, then post the open questions as an issue comment tagging @barbinbrad, **wait for answers**, then write the spec with resolutions baked in and commit it. If the issue references a spec with unresolved questions (#1030), resolve them the same way before building.
+3. **Plan**: run `/plan` from the finalized spec → `.ai/plans/{date}-{slug}.md`.
+4. **Build** on a feature branch (`feature/{slug}`), following the plan; migrations idempotent, randomized HHMMSS timestamps, never backdated (`.ai/lessons.md`); `pnpm run generate:types` after schema changes before typechecking; scoped typecheck (`pnpm exec turbo run typecheck --filter=<pkg>`), lint, tests.
+5. **Verify**: every acceptance criterion in the spec and every definition-of-done box in the issue, with evidence (command output, screenshots for UI) posted to the issue. Never claim done without running the verification.
+6. **PR**: one PR per issue, linking the issue (`Closes #NNNN`) and the spec (`Tracking spec:` line). Follow `.ai/skills/check-and-commit/SKILL.md` before committing.
+7. **Close-out**: on merge — check the issue off in #1060; tick the roadmap checkbox; update the spec's changelog (and move to `implemented/` when fully done); if the work changed any assumption in this meta spec or the DAG, update this file in the same PR.
+8. **New specs as needed**: any discovery that meets the spec-writing triggers (new module, 3+ files, data-model change) gets its own spec under the standard flow and, if it's a new unit of work, a new issue wired into the DAG here.
+
+Coordination rules: issues sharing the `post-*` edge-function surface (#1030, #1031, #1036, #1047) must rebase on each other's merged state — do not run two of them concurrently. The six Phase-∅ specs carry ⚠ delta banners on their plans; apply the deltas before executing. **Close-checklist registration**: #1031 ships the persisted checklist (`periodCloseTaskDefinition`/`periodCloseTask`, 9 seeded tasks); any later workstream that adds a period-end activity (#1039 depreciation/accruals, #1042/#1046 bank rec completeness, #1048 revenue recognition, #1050 FX revaluation + consolidated rates) delivers its close integration by **registering a task definition** (with an auto-check where the state is computable) — never by inventing a parallel checklist mechanism.
+
+## Out of scope for agents
+
+SOC 1/SOC 2/ISO 27001 evidence programs, auditor selection, PITR/DR contracts, and country software certifications (Portugal AT, France PDP) are company-program items (roadmap §∥) — agents support them (e.g., #1033's controls) but cannot complete them.
+
+## Changelog
+
+- 2026-07-04: **All 18 residual per-workstream open questions resolved** under the program ambition heuristic (Brad: ambitious and thorough now; back out at /plan stage if needed) — recorded inline in each spec's Open Questions section with the back-out valve named. No spec in the program carries an unchecked question; every issue is executable with no gates beyond /plan. The two commercial items (Avalara contract coverage FR/PL/IT + inbound; HMRC vendor registration) are recorded as company actions with build-side assumptions that don't block execution.
+- 2026-07-04: **All spec-first workstreams spec'd** (16 specs + the Avalara plan written in one batch with Brad's 15 resolutions baked in — full ASC 606 incl. SSP, ambitious segments/leases/multi-book, propose-only depreciation, gapless all-sequences, current-infra APIs). #1033 (ITGC) and #1053 (statutory archives) closed/deferred by Brad. #1061 (Avalara integration foundation) added — no deps; #1044 and #1054 now depend on it. Every remaining issue is executable: spec → `/plan` → build. Residual per-workstream open questions live in their issues (14 total across 8 issues) — resolve in-issue before the affected portion builds; none block schema-level starts except where noted.
+- 2026-07-04: Period-closing scope expanded at user direction to include the NetSuite-style persisted close checklist (#1031 row updated; issues #1031/#1039/#1048/#1050 bodies updated). New coordination rule: downstream period-end workstreams integrate by registering `periodCloseTaskDefinition` rows, never by building parallel checklist mechanisms. DAG unchanged (no new nodes or edges).
+- 2026-07-04: Created. 30 workstream issues (#1030–#1059) + tracking issue #1060 opened; DAG defined; execution protocol set. All program-level open questions were resolved 2026-07-03/04 (see the readiness spec); per-workstream questions resolve in-issue at each spec gate.
diff --git a/.ai/specs/2026-07-04-avalara-integration-foundation.md b/.ai/specs/2026-07-04-avalara-integration-foundation.md
new file mode 100644
index 0000000000..f06ddebd8c
--- /dev/null
+++ b/.ai/specs/2026-07-04-avalara-integration-foundation.md
@@ -0,0 +1,201 @@
+# Avalara Integration Foundation
+
+> Status: in-progress
+> Author: Claude Code (directed by Brad, [email protected])
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1061
+
+## TLDR
+
+Avalara is Carbon's first-class partner for **both** US sales-tax determination (crbnos/carbon#1044, `.ai/specs/2026-07-03-multi-jurisdiction-tax.md` Phase 3) and EU e-invoicing clearance (crbnos/carbon#1054, `.ai/specs/2026-07-04-e-invoicing.md`, written by a parallel agent). This spec ships the **shared substrate** both consumers plug into so neither builds its own: a `packages/ee/src/avalara/` integration following the Xero architecture exactly — registry entry (`defineIntegration`, id `avalara`), per-company config in `companyIntegration.metadata` (company code, sandbox|production, feature toggles for tax determination and e-invoicing), server lifecycle hooks (`onInstall`/`onUninstall`/`onHealthcheck` pinging `/utilities/ping` and verifying the company-code mapping), and a typed REST client covering the AvaTax surface (`CreateTransaction`, `CommitTransaction`, `VoidTransaction`, `ResolveAddress`, `ListNexus`) plus the e-invoicing document surface (submit/status/mandates) behind one retry/timeout/error taxonomy. Credentials are env-level (`AVALARA_ACCOUNT_ID` + `AVALARA_LICENSE_KEY`; integration hidden unless both are set) — **no plaintext secrets ever land in `companyIntegration.metadata`**, per the Plaid Vault-probe/AES-GCM precedent. The AvaTax determination connector itself and the e-invoicing flows are explicit non-scope: this is the socket, not the appliances.
+
+## Problem Statement
+
+Two approved workstreams both need Avalara:
+
+1. **Multi-jurisdiction tax Phase 3** (#1044): an `AvalaraTaxEngine` behind the `resolveLineTaxes` seam — `CreateTransaction(SalesOrder)` estimates on quotes/orders, `CreateTransaction(SalesInvoice, commit: true)` at posting with `details[]` mapped 1:1 to `taxLedger` rows, `VoidTransaction` on void, `ResolveAddress` on customer/location forms, nexus mirroring.
+2. **E-invoicing** (#1054): document submission to clearance/network mandates across the EU via Avalara's e-invoicing API (customers all over Europe + US — resolved: Avalara is the partner for both).
+
+Without a shared foundation, each workstream would independently invent: an integration registry entry, credential plumbing, a REST client with retries and error mapping, environment switching (sandbox vs production), a company-code mapping, and a healthcheck. That means duplicated code in `packages/ee`, two half-compatible config schemas fighting over the same `companyIntegration('avalara')` row, and no single install/uninstall lifecycle. Carbon already has the exact pattern to avoid this — the Xero integration (`packages/ee/src/xero/` config + hooks, `packages/ee/src/accounting/providers/xero/` client) — it just needs an Avalara instance of it.
+
+## Proposed Solution
+
+### Package layout (Xero precedent, adapted)
+
+```
+packages/ee/src/avalara/
+├── config.tsx # defineIntegration registry entry (client + server bundled — no server imports)
+├── hooks.server.ts # onInstall / onUninstall / onHealthcheck (registered in packages/ee/src/hooks.server.ts)
+├── service.server.ts # getAvalaraClient(companyId), getAvalaraConfig(companyId), isAvalaraFeatureEnabled(...)
+├── lib/
+│ ├── client.ts # AvalaraClient — shared HTTP core: auth, base URLs, retry, timeout, error taxonomy
+│ ├── avatax.ts # AvaTax surface: ping, companies, createTransaction, commit, void, resolveAddress, listNexus
+│ ├── einvoicing.ts # E-invoicing surface: submitDocument, getDocumentStatus, listDocuments, listMandates
+│ └── types.ts # namespace Avalara — request/response models for both surfaces
+└── index.ts # barrel (exported as @carbon/ee/avalara + @carbon/ee/avalara/hooks.server)
+```
+
+### Registry entry (`config.tsx`)
+
+`defineIntegration({ id: "avalara", name: "Avalara", category: "Tax & Compliance", active: !!AVALARA_ACCOUNT_ID && !!AVALARA_LICENSE_KEY, ... })`. No `oauth` block — AvaTax authenticates with account-level Basic credentials, so `active` is computed from env presence exactly like the Plaid spec's "hidden unless env set" rule (Xero achieves the same via its OAuth `clientId` check). Added to the `integrations` array in `packages/ee/src/index.ts`; a one-row idempotent migration seeds the `integration` registry table (`INSERT ... ('avalara', ...) ON CONFLICT DO NOTHING`, per the Jira/Linear precedent — the `integrations` view CROSS JOINs `integration` × `company`).
+
+Per-company settings (zod `AvalaraSettingsSchema`, stored in `companyIntegration.metadata`):
+
+| Setting | Type | Default | Notes |
+|---|---|---|---|
+| `companyCode` | options (dynamic) | — required | Avalara company code this Carbon company maps to; options populated live from `GET /api/v2/companies` (Xero dynamic account-list precedent) |
+| `avalaraCompanyId` | derived, not a form field | — | Numeric Avalara company id resolved from `companyCode` at save/install (needed by `ListNexus`) |
+| `environment` | options: `sandbox` \| `production` | `sandbox` | Selects base URLs for both API surfaces |
+| `taxDetermination` | switch | `false` | Feature toggle consumed by the tax connector (#1044); the `resolveLineTaxes` dispatcher checks this |
+| `eInvoicing` | switch | `false` | Feature toggle consumed by the e-invoicing flows (#1054) |
+
+### Credential handling (Plaid precedent applied)
+
+- **Env-level (server-only)**: `AVALARA_ACCOUNT_ID` (non-secret) + `AVALARA_LICENSE_KEY` (secret) added to `packages/env/src/index.ts` via `getEnv(..., { isRequired: false, isSecret: true })`, following `XERO_CLIENT_ID`/`XERO_CLIENT_SECRET`, and surfaced through the same `@carbon/auth` re-export path the Xero config uses. One Avalara account serves the whole install; tenancy separation is the per-company `companyCode`.
+- **Per-company**: only non-secret config in `companyIntegration.metadata` (table above). **No plaintext secrets in metadata, ever.** v1 needs no per-company secret at all; if one ever appears (e.g. per-company Avalara sub-account keys), it MUST use the Plaid-resolved storage: Vault probe → `{ kind: "vault", secretId }`, else AES-256-GCM env-key fallback → `{ kind: "aes", ciphertext, iv, tag }`, behind a `tokens.server.ts`-style accessor (`.ai/specs/2026-07-02-plaid-bank-feeds.md` §Token storage — fallback pre-approved there).
+- The `AvalaraClient` is constructed **only** in server code (`service.server.ts`, hooks, API routes); `config.tsx` never imports it (configs are bundled for the browser — `packages/ee/AGENTS.md` "Never").
+
+### Typed client (`lib/`)
+
+One HTTP core (its own small class modeled on `accounting/core/utils.ts` `HTTPClient`, extended — that class has no retry/timeout and lives inside the accounting sync package) shared by both surfaces:
+
+- **Base URLs**: AvaTax `https://rest.avatax.com` / `https://sandbox-rest.avatax.com` (paths `/api/v2/...`); e-invoicing `https://api.avalara.com/einvoicing` / `https://api.sbx.avalara.com/einvoicing` (header `avalara-version`). Chosen by `environment`.
+- **Auth**: AvaTax — HTTP Basic `base64(accountId:licenseKey)`. E-invoicing — pluggable `AuthStrategy` (see open question: Avalara Identity OAuth2 client-credentials vs license key). Required `X-Avalara-Client: Carbon; {version}; REST; v2; {host}` header on AvaTax calls.
+- **Timeout**: `AbortSignal.timeout(ms)` — 10s default, 30s for `createTransaction` (Avalara's own guidance for large carts).
+- **Retry**: max 2 retries, exponential backoff + jitter, **only** on 429 (honoring `Retry-After`), 502/503/504, and network errors; never on 4xx validation errors; never retry a `commit: true` call after an ambiguous timeout without an idempotent `code` (the tax spec keys committed docs by Carbon invoice id, making retry safe — document this contract on the method).
+- **Error taxonomy** (`AvalaraError extends Error` with `kind`, `status`, `avalaraCode`, `retryable`, `details`):
+
+| kind | From | Retryable |
+|---|---|---|
+| `auth` | 401/403 | no |
+| `validation` | 400 + AvaTax error body (`error.details[]` parsed) | no |
+| `not_found` | 404 (unknown companyCode/transaction) | no |
+| `conflict` | 409 / "document already committed" class errors | no — surface to caller (tax-spec idempotency contract) |
+| `rate_limit` | 429 | yes (Retry-After) |
+| `transient` | 5xx, network, timeout | yes |
+
+Methods (all return `{ data, error }`, never throw past the taxonomy — service-shape heuristic applied to a client):
+
+- **AvaTax** (`avatax.ts`): `ping()` → `GET /api/v2/utilities/ping` (asserts `authenticated: true`); `listCompanies(filter?)` / `getCompanyByCode(code)`; `createTransaction(model)` (`type: SalesOrder | SalesInvoice | ReturnInvoice...`, `commit`, `code`); `commitTransaction(companyCode, transactionCode)`; `voidTransaction(companyCode, transactionCode, reason)`; `resolveAddress(address)`; `listNexus(avalaraCompanyId)`.
+- **E-invoicing** (`einvoicing.ts`): `submitDocument(payload, meta)`; `getDocumentStatus(documentId)`; `listDocuments(query)`; `listMandates()` (country/mandate discovery, needed by the e-invoicing spec's routing).
+
+### Lifecycle hooks (`hooks.server.ts`, registered in `packages/ee/src/hooks.server.ts`)
+
+- `onInstall(companyId)`: no event-system subscriptions (unlike Xero — both consumers call Avalara synchronously/from their own jobs; nothing is push-synced from DB triggers). Best-effort: resolve `companyCode` → `avalaraCompanyId` via `getCompanyByCode` and persist it into metadata.
+- `onUninstall(companyId)`: clear the Redis health-cache key; no subscriptions to remove. Consumers own their teardown (non-scope).
+- `onHealthcheck(companyId, metadata)`: parse metadata with `AvalaraSettingsSchema`; `ping()` must return `authenticated: true`; `getCompanyByCode(companyCode)` must resolve to an active Avalara company. Healthy only if both pass (this is what the existing `getIntegrationHealth` in `settings.server.ts` calls and caches for 5 min).
+
+### Consumer contract (`service.server.ts`) — the seam #1044 and #1054 import
+
+```ts
+getAvalaraConfig(client, companyId) // → { data: AvalaraSettings & { installed: boolean }, error }
+getAvalaraClient(client, companyId) // → { data: AvalaraClient, error } — error if not installed/env unset
+isAvalaraFeatureEnabled(client, companyId, feature: "taxDetermination" | "eInvoicing") // → boolean
+```
+
+The tax spec's `resolveLineTaxes` dispatcher and the e-invoicing submission path call `isAvalaraFeatureEnabled` first, then `getAvalaraClient`. Neither reads `companyIntegration` directly.
+
+### Settings UI + connect flow
+
+The generic integration page (`x+/settings+/integrations.$id.tsx`) renders everything from `config.tsx` settings — no bespoke page. Additions on top:
+
+- **Dynamic company-code options**: `settings.server.ts` populates `companyCode` `listOptions` from `listCompanies()` when env creds are present (mirrors the Xero `defaultSalesAccountCode` dynamic-options wiring backed by `api+/integrations.xero.accounts.ts`).
+- **Test connection**: an `actions` entry (`{ id: "test-connection", label: "Test Connection", endpoint: "/api/integrations/avalara/test" }`, the Xero `sync-data` action precedent). The route runs the same checks as `onHealthcheck` uncached and flashes success ("Connected to Avalara — company `ACME` (sandbox)") or the taxonomy-mapped failure reason.
+- Card is invisible in the integrations list when env creds are absent (`active: false` — same behavior as Xero without `XERO_CLIENT_ID`).
+
+### Design Decisions
+
+Heuristics note (honest N/A): this is `packages/ee` client/registry code — **no new tables**, so heuristics 1 (multi-tenancy PKs) and 3 (RLS) are N/A beyond the one seed row into the existing `integration` registry table, which is global by design (per-company state lives in `companyIntegration`, which already has RLS).
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Multi-tenancy (heuristic 1) | N/A — no new tables; per-company state in `companyIntegration.metadata` keyed by `companyId` | Xero/Plaid precedent: integration state is metadata, not schema |
+| Service shape (heuristic 2) | `service.server.ts` functions take `client` first, return `{ data, error }`, never throw; client methods mirror the shape | House rule applied to the seam consumers import |
+| RLS (heuristic 3) | N/A — no new tables; seed row in global `integration` table (no `companyId` column, existing pattern) | Registry rows are product catalog, not tenant data |
+| Permission scoping (heuristic 4) | New API routes (`test`, `companies`) require `update: "settings"` — same scope as the integrations settings page | Only settings admins configure integrations |
+| Form pattern (heuristic 5) | No custom form — generic integrations renderer + zod `AvalaraSettingsSchema` via `defineIntegration` | Zero bespoke UI; Xero precedent |
+| Module layout (heuristic 6) | All code in `packages/ee/src/avalara/`; no ERP module touched; exports `@carbon/ee/avalara`(+`/hooks.server`) | Integrations live in ee (tax-spec heuristic-6 row already says so) |
+| Backward compatibility (heuristic 7) | Purely additive: new env vars optional, new seed row, new package exports; nothing existing changes behavior | Env unset ⇒ integration invisible ⇒ zero behavior delta |
+| One integration, two consumers | Single `avalara` registry entry with two feature switches, not `avalara-tax` + `avalara-einvoicing` | One credential set, one company mapping, one health status; toggles gate consumers independently |
+| Credential level | Env-level account id + license key; per-company only `companyCode` | Avalara bills per account; Carbon Cloud runs one account with per-company codes; self-hosted sets its own env. Avoids secret-in-metadata entirely (Plaid rule) |
+| Secret storage (future) | If per-company secrets ever needed: Vault probe → AES-256-GCM fallback, Plaid interface | Pre-approved precedent; do not invent a third scheme |
+| Client home | `packages/ee/src/avalara/lib/`, NOT `accounting/providers/` | Avalara is not a `BaseProvider` accounting-sync engine (no entity syncers, no `externalIntegrationMapping` flows); forcing it into `SyncFactory` shape would be false symmetry |
+| Retry policy | Retries only on 429/5xx/network; commit-call retry safety documented as caller's idempotent-`code` contract | Tax spec already keys committed docs by invoice id (idempotent overwrite of uncommitted docs) |
+| Sandbox default | New installs default `environment: sandbox` | Safe-by-default; production is an explicit switch |
+| onInstall subscriptions | None | Both consumers are call-time/outbound; Xero's event-system subscriptions exist for DB-driven push sync, which Avalara doesn't do |
+
+## Data Model Changes
+
+No new tables, no columns. One idempotent seed migration (registry pattern, cf. `20260215000000_add_jira_integration.sql`):
+
+```sql
+INSERT INTO "integration" ("id", "jsonschema")
+VALUES ('avalara', '{"type": "object", "properties": {}}'::json)
+ON CONFLICT ("id") DO NOTHING;
+```
+
+`companyIntegration.metadata` shape for `avalara` (documented, not enforced by schema):
+
+```jsonc
+{
+ "companyCode": "ACME",
+ "avalaraCompanyId": 123456, // resolved at install/save
+ "environment": "sandbox", // "sandbox" | "production"
+ "taxDetermination": false,
+ "eInvoicing": false
+}
+```
+
+## API / Service Changes
+
+- `packages/env/src/index.ts`: `AVALARA_ACCOUNT_ID`, `AVALARA_LICENSE_KEY` (optional; key is secret), exported through the existing `@carbon/auth` path.
+- `packages/ee`: new files per layout above; `avalara` added to `integrations` array + `serverHooks` registry; `package.json` exports `./avalara`, `./avalara/hooks.server`.
+- `apps/erp/app/routes/api+/integrations.avalara.test.ts` — action, `update: "settings"`: uncached health probe, flash result.
+- `apps/erp/app/routes/api+/integrations.avalara.companies.ts` — loader, `update: "settings"`: `listCompanies()` for dynamic options.
+- `apps/erp/app/modules/settings/settings.server.ts`: dynamic-options wiring for `avalara.companyCode` (beside the Xero accounts wiring).
+
+## UI Changes
+
+None bespoke. The existing integrations list/detail pages render the Avalara card (logo, settings groups Connection / Features, Test Connection action) entirely from the registry entry. Card hidden when env creds absent; health badge driven by `onHealthcheck`.
+
+## Explicit Non-Scope
+
+- **AvaTax determination connector** (#1044 / tax spec Phase 3): `AvalaraTaxEngine`, `resolveLineTaxes` dispatch, `taxLedger` mapping, outage fallback, reconcile job, nexus-drift UI.
+- **E-invoicing flows** (#1054 / `.ai/specs/2026-07-04-e-invoicing.md`): document building (UBL/CII), submission orchestration, status polling jobs, mandate UX.
+- Per-company secret storage implementation (nothing secret per company in v1; precedent reserved above).
+- Any accounting-sync (`BaseEntitySyncer`) integration — Avalara syncs no entities.
+
+## Acceptance Criteria
+
+- [ ] With `AVALARA_ACCOUNT_ID`/`AVALARA_LICENSE_KEY` unset, the Avalara card does not appear in `/x/settings/integrations` and `getAvalaraClient` returns a "not configured" error.
+- [ ] With env set, the card appears under Tax & Compliance; installing with a `companyCode` chosen from live Avalara options persists metadata matching `AvalaraSettingsSchema` (and `avalaraCompanyId` after install) with **no secret material in the row**.
+- [ ] `onHealthcheck` returns healthy only when `ping().authenticated === true` AND the company code resolves; a wrong license key or bogus code shows the unhealthy badge.
+- [ ] Test Connection flashes the environment + resolved company name on success and the taxonomy-mapped reason (`auth` vs `not_found` vs `transient`) on failure.
+- [ ] Unit tests (mocked fetch) prove: Basic-auth header + `X-Avalara-Client` sent; 429 honored via `Retry-After` then succeeds; 400 maps to `validation` with parsed `details[]` and does NOT retry; 503 retries then maps to `transient`; timeout aborts at the configured budget.
+- [ ] Sandbox smoke (mocked in CI; live run env-gated): `createTransaction({ type: "SalesOrder", ... })` against sandbox returns computed `totalTax` + `details[]`; `resolveAddress` returns a validated address; `voidTransaction` on a committed test doc returns status `Cancelled`.
+- [ ] Feature toggles round-trip: `isAvalaraFeatureEnabled(companyId, "taxDetermination")` reflects the switch; both toggles independent.
+- [ ] `pnpm --filter @carbon/ee typecheck`, `--filter @carbon/erp typecheck`, `pnpm --filter @carbon/ee test`, `pnpm run lint` all pass.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| E-invoicing API auth differs from AvaTax (Avalara Identity OAuth2) | Med | Pluggable `AuthStrategy` in the client core; open question below gates only `einvoicing.ts` internals, not its method contract |
+| Consumers bypass the seam and read `companyIntegration` directly | Low | Contract functions exported + documented in both consumer specs; rule file added for `packages/ee/src/avalara/**` |
+| Commit-call retry double-commits | Med | No auto-retry on ambiguous commit timeouts; idempotency delegated to caller-supplied `code` (tax-spec contract) documented on the method |
+| Avalara rate limits under batch posting | Low | 429 taxonomy + Retry-After honored; consumers own batch pacing |
+| Sandbox/production config mistake taxes real documents | Med | `sandbox` default; environment shown in Test Connection result and card description |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] Is Avalara the partner for both tax determination and e-invoicing, or tax-only? — **Answer: both (resolved by Brad): first-class partner for US sales tax (#1044) AND EU e-invoicing clearance (#1054); this foundation is the shared substrate.**
+- [x] Where do credentials live? — **Answer: env-level account id + license key (integration hidden unless set), per-company non-secret config in `companyIntegration.metadata`; any future per-company secret uses the Plaid Vault-probe/AES-GCM precedent (pre-approved in the Plaid spec).**
+- [x] One integration or two? — **Answer: one `avalara` registry entry with independent `taxDetermination`/`eInvoicing` feature toggles.**
+- [x] **E-invoicing API credentials**: Avalara's e-invoicing (ELR) API appears to require Bearer tokens from Avalara Identity (OAuth2 client-credentials — i.e. separate `AVALARA_CLIENT_ID`/`AVALARA_CLIENT_SECRET`) rather than the AvaTax license key. Verify against current Avalara docs during Task 2; if confirmed, approve adding the two env vars. Blocks only the `einvoicing.ts` auth internals — AvaTax surface, config, hooks, and UI are unaffected. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Assume the separate Avalara Identity OAuth2 client-credentials model — add `AVALARA_CLIENT_ID`/`AVALARA_CLIENT_SECRET` env pair and a token manager in the client core alongside the AvaTax license-key auth. Verify in sandbox during plan/execute; if docs confirm license-key auth suffices, back the token manager out.
+
+## Changelog
+
+- 2026-07-04: Created — foundation substrate for #1044 (tax Phase 3) and #1054 (e-invoicing), tracking crbnos/carbon#1061. Xero architecture followed exactly; Plaid credential precedent applied; consumer contract (`getAvalaraClient`/`isAvalaraFeatureEnabled`) defined for both downstream specs.
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/2026-07-04-close-automation.md b/.ai/specs/2026-07-04-close-automation.md
new file mode 100644
index 0000000000..e1bbd2c379
--- /dev/null
+++ b/.ai/specs/2026-07-04-close-automation.md
@@ -0,0 +1,308 @@
+# Close Automation: Scheduled Depreciation, Prepaid Amortization, Recurring Journals, Auto-Reversing Accruals
+
+> Status: in-progress (all open questions resolved pre-writing, per the updated spec-writing flow)
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: [crbnos/carbon#1039](https://github.com/crbnos/carbon/issues/1039)
+> Parent: `.ai/specs/2026-07-03-public-company-readiness.md` (findings GAP-4.1, GAP-6) · `.ai/specs/2026-07-04-accounting-implementation-meta.md` (Phase 1)
+> Depends on: `.ai/specs/2026-07-02-period-closing.md` (#1031 — close lifecycle + persisted checklist) · `.ai/specs/2026-07-04-document-approvals.md` (#1032 — JE approval gating)
+
+## TLDR
+
+One Inngest scheduled function — the **close-calendar job** — automates the four recurring period-end mechanics Carbon lacks: (1) **scheduled depreciation proposals** — Draft `depreciationRun`s created monthly for every company with due Active assets; posting stays human (**propose-only**, resolved by Brad 2026-07-04), (2) **prepaid-expense amortization** — AP invoice lines flagged prepaid post to the (currently dead) `accountDefault.prepaymentAccount` and spawn a straight-line `prepaidSchedule` whose monthly amortization journals the job drafts, (3) **recurring journal templates** — fixed-amount template header/lines with monthly/quarterly/annual frequency; the job drafts the journal and advances `nextRunDate`, and (4) **auto-reversing accruals** — an `autoReverseOn` date on manual JEs; on arrival the job posts the mirror reversal into the next period automatically via the existing `reversalOfId`/`reversedById` machinery. All generated journals carry new *accounting* source types (`Prepaid Amortization`, `Recurring Journal` — additive enum values) so they obey the period-close Locked/Closed matrix, and every close-checklist integration lands by **registering `periodCloseTaskDefinition` rows** (per the meta-spec coordination rule — never a parallel mechanism): seeded task 4's `draft-depreciation` auto-check tightens to "proposal generated **and** posted," and two new definitions register — "Prepaid amortization posted" and "Recurring journals generated." Accrual reversals need no task (justified below: the next period's existing draft-journals Blocker catches any failed auto-post).
+
+## Problem Statement
+
+Period close is now a real control (#1031), but the work that fills a close calendar is entirely manual:
+
+- **Depreciation never proposes itself** (GAP-4.1). A controller must remember to open `/x/accounting/depreciation-runs`, click New, and post — every month, per company. `.ai/rules/fixed-asset-lifecycle.md` states it plainly: "no scheduled/cron job exists." Miss a month and seeded checklist task 4 only warns about *draft* runs — a run that was never created passes silently.
+- **No prepaid-expense machinery** (GAP-6). `accountDefault.prepaymentAccount` has existed since `20230820020844_posting-groups.sql:52` and is selected into every posting-group view — but no posting path ever debits or amortizes it. An annual insurance invoice hits expense in full in month 1; the controller maintains the amortization spreadsheet NetSuite retired a decade ago.
+- **No recurring journals** (GAP-6). Rent, insurance allocations, and standing management fees are re-keyed by hand monthly — the highest-volume source of JE typos an auditor samples.
+- **No auto-reversing accruals** (GAP-6). A month-end accrual requires the controller to remember the manual reversal next month; forget it and the expense doubles. The `reversalOfId`/`reversedById` columns (`20260402000000_journal-entries.sql:44-45`) already model the linkage — nothing schedules it.
+
+Only GR/IR accrual automation exists today. Verified: zero code hits for recurring/prepaid/accrual journal machinery in `apps/erp/app/modules/accounting/`.
+
+## Proposed Solution
+
+### The close-calendar job (one Inngest function, four steps)
+
+A single scheduled function `period-close-automation` in `packages/jobs/src/inngest/functions/scheduled/period-close-automation.ts`, following the `update-exchange-rates` pattern (service-role client, per-company loop, `step.run` per concern, `retries: 2`). **Daily cron** (`0 2 * * *`), not monthly: each step is an idempotent "is anything due?" check, so a missed fire self-heals next day, quarterly/annual recurrences need no second schedule, and accrual reversals land on day 1 rather than waiting for a month-end tick. Rows created by the job stamp `createdBy = 'system'` (the seeded system user, `20230123004317_companies-rls.sql:76`).
+
+| Step | Due condition | Action |
+|---|---|---|
+| 1. Depreciation proposal | Month M has ended and no `depreciationRun` with `periodEnd` = last day of M exists for a company with Active assets | Insert Draft run + lines via the same shared service the manual route uses |
+| 2. Prepaid amortization | An Active `prepaidSchedule` has an entry with `amortizationDate <= today` and no `journalId` | Draft one amortization journal per due entry |
+| 3. Recurring journals | An active `recurringJournalTemplate` has `nextRunDate <= today` | Draft the journal from template lines; advance `nextRunDate` by frequency |
+| 4. Accrual reversal | A Posted journal has `autoReverseOn <= today` and `reversedById IS NULL` | **Post** the mirror reversal dated `autoReverseOn`, link both ways |
+
+**Propose-only posture (Resolution 1, Brad 2026-07-04).** Steps 1–3 create **Draft** documents only; a human posts. Prepaid and recurring journals post through `postJournalEntry`, so #1032's journal-entry approval rules gate them automatically where configured. Depreciation-run posting keeps its existing route action in v1; extending `approvalDocumentType` with `'depreciationRun'` so run-posting parks behind an approval rule is a small additive follow-on to #1032 (see Open Questions). Step 4 is the deliberate exception: the reversal is a deterministic mirror of an already-approved entry — SAP (FBS1/F.81) and NetSuite both post the reversal automatically — so it posts without a human touch, respecting the period matrix below.
+
+### 1. Scheduled depreciation proposals (GAP-4.1)
+
+Extract the body of `routes/x+/accounting+/depreciation-runs.new.tsx` into a shared service `createDepreciationRunProposal(client, { companyId, userId })` in `accounting.service.ts` (reusing `getNextPeriodEnd`, `buildDepreciationLines`, the tax-depreciation toggle, and the existing "run already exists for this period" guard). The route and the job call the same function — one code path, per the meta-spec's never-parallel rule. The job proposes runs up to the most recently *ended* month only (never a future period), catching up one period per day if several are missing.
+
+**Checklist task 4 tightens.** The `draft-depreciation` auto-check evaluator in `getPeriodCloseReadiness` currently only flags Draft runs. It becomes: *fail when no run whose `periodEnd` falls inside the period exists (proposal missing) OR such a run exists with `status = 'Draft'` (proposed, unposted)*. This is a semantics change to an existing evaluator, not a new task — the seeded definition row is untouched; its meaning is "proposal generated + posted."
+
+Toggle: `companySettings.depreciationProposalsEnabled BOOLean DEFAULT true`. Default on — a Draft run is a deletable proposal with zero GL effect, and defaulting off would recreate the exact close-calendar risk GAP-4.1 names.
+
+### 2. Prepaid-expense amortization (GAP-6)
+
+**Flag at AP invoice entry.** A `G/L Account` purchase invoice line gains a prepaid toggle plus schedule parameters (amortization start date, number of months; method fixed to Straight Line in v1). On `post-purchase-invoice`, a flagged line debits the **prepaid account** — `accountDefault.prepaymentAccount`, activated at last — instead of the line's expense account, and creates a `prepaidSchedule` capturing the line's expense account as the amortization target. Amounts are the line's **base-currency** posted amount (`journalLine.amount` is already base), so schedules never carry FX exposure.
+
+**Schedule → entries → journals.** Schedule creation precomputes one `prepaidScheduleEntry` per month: straight-line `totalAmount / months` rounded to 2dp, remainder folded into the final entry so the schedule always sums exactly. Each due entry gets a Draft journal (Debit expense / Credit prepaid, `sourceType: 'Prepaid Amortization'`, dimensions copied from the source invoice line); posting stamps `journalId` on the entry and completes the schedule when the last entry posts.
+
+**Register report.** A prepaid schedule register page lists schedules with original amount, amortized-to-date, and remaining balance, with a header tie-out row: Σ remaining balances vs. the GL balance of the prepaid account as of the selected period end. Any difference (manual postings to the account) renders as a highlighted reconciling amount — the tie-out auditors ask for.
+
+**New checklist definition:** "Prepaid amortization posted" — Auto, `autoCheckKey: 'prepaid-amortization'`, Warning. Fails when any entry with `amortizationDate` on/before the period end lacks a posted journal.
+
+### 3. Recurring journal templates (GAP-6)
+
+`recurringJournalTemplate` (name, description, frequency `Monthly | Quarterly | Annually`, `nextRunDate`, optional `endDate`, `active`) + `recurringJournalTemplateLine` (account, description, fixed debit/credit amount, dimensions v2). Balance is validated at template save (Σ debits = Σ credits) — the same rule `postJournalEntry` enforces. The job drafts a journal dated `nextRunDate` with `sourceType: 'Recurring Journal'`, then advances `nextRunDate` by the frequency (`endDate` passed ⇒ template deactivates). Generated drafts are ordinary journal entries: edited, posted (through JE approvals where a rule matches), or deleted via the existing JE surface.
+
+Management UI: a "Recurring Journals" section in accounting — templates table + `ValidatedForm` header with a line editor reusing the journal-entry line components, plus a "Generate now" row action calling the same generation service as the job.
+
+**New checklist definition:** "Recurring journals generated" — Auto, `autoCheckKey: 'recurring-journals'`, Warning. Fails when any active template's `nextRunDate` is on/before the period end (generation overdue). *Posting* the generated drafts is deliberately not re-checked here — the existing seeded **draft-journals Blocker** (task 2) already fails on any Draft journal dated in the period; the layering keeps each evaluator single-purpose.
+
+### 4. Auto-reversing accruals (GAP-6)
+
+One nullable column: `journal.autoReverseOn DATE`. The JE form exposes an "Auto-reverse" toggle that defaults the date to day 1 of the month following the posting date (editable, must be > postingDate — CHECK constraint). Set while Draft, so posted-record immutability is never touched.
+
+When `autoReverseOn` arrives, the job posts the reversal through the existing `reverseJournalEntry` machinery: mirror lines, `reversalOfId` on the new entry, original transitions `Posted → Reversed` with `reversedById` — exactly the transition the immutability trigger permits. Period rules, in order:
+
+- Reversal period **Open**: post dated `autoReverseOn`.
+- Reversal period **Locked**: still post — the reversal is an *accounting* source (`getOrCreateAccountingPeriod(…, source: "accounting")`), which the Locked matrix allows.
+- Reversal period **Closed** (pathological — closing N+1 with a pending reversal implies N closed with it too): do **not** post; skip and retry daily, surfacing in the job log. The close boundary is never punched.
+- Reversal period doesn't exist yet: lazy-created by `getOrCreateAccountingPeriod`, as today.
+
+**No checklist task — justified.** The pending reversal belongs to period N+1, not the period being closed; on day 1 it auto-posts, so by the time N+1's close begins there is nothing pending by construction. The one failure mode — the job drafts nothing, but a `reverseJournalEntry` failure could leave the original un-reversed — is caught because the *original* entry still shows `autoReverseOn` past-due with `reversedById IS NULL`, and any manually-intervened Draft reversal in N+1 trips that period's draft-journals Blocker. Adding a task would duplicate an existing control.
+
+### Source types and the period matrix (scope item 6)
+
+Two additive enum values (the established pattern — `20260504000000:22-25`, `20260524143826:2-3`, `20260630093809:182-184`):
+
+```sql
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Prepaid Amortization';
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Recurring Journal';
+```
+
+Depreciation proposals keep `'Asset Depreciation'`; accrual reversals inherit the source entry's type (`'Manual'`) per existing `reverseJournalEntry` behavior. All four flows are **accounting** sources under #1031's matrix: post into Open or Locked periods (Locked human posts still require `update: accounting`), never into Closed — service gate plus the DB trigger backstop, which binds the service-role job too.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Automation posture | Propose-only: job drafts, humans post (accrual reversal is the sole auto-post) | **Resolved (Brad 2026-07-04).** Keeps a human control point on every new GL posting; drafted journals flow through #1032 approvals where a rule matches; reversals are deterministic mirrors of approved entries (SAP F.81 / NetSuite behavior) |
+| Job shape | One Inngest function, daily cron, one `step.run` per concern | `update-exchange-rates` precedent; daily + idempotent due-checks self-heal missed fires and cover quarterly/annual frequencies without extra schedules |
+| Depreciation code path | Extract `createDepreciationRunProposal` shared by route + job | Meta-spec rule: register into existing mechanisms, never build parallel ones |
+| Task-4 auto-check | Extend `draft-depreciation` evaluator to "run exists AND posted" | A never-created run must fail the check; same definition row, no new task |
+| Prepaid GL flow | Debit `prepaymentAccount` directly at invoice posting (no post-then-reclass) | One journal, no expense flicker in reports; NetSuite amortization-schedule behavior; finally activates the dead default |
+| Prepaid schedule grain | Precomputed `prepaidScheduleEntry` rows, remainder in final entry | Register report + GL tie-out need per-month persisted amounts; rounding is settled once at creation |
+| Prepaid currency | Schedules amortize the base-currency posted amount | `journalLine.amount` is already base; avoids FX churn inside schedules |
+| Recurring v1 scope | Fixed amounts, no dimensions/allocation formulas | GAP-6 names fixed-amount templates as v1; drafts are editable before posting anyway |
+| Accrual reversal storage | `journal.autoReverseOn` column; no pending-reversals table | The (autoReverseOn, reversedById) pair fully encodes "pending"; reuses `reverseJournalEntry` + Posted→Reversed transition unchanged |
+| Reversal into Locked period | Allowed (accounting source, service-role) | Matches #1031's matrix — Locked blocks operational sources only; a day-1 reversal is exactly the adjustment Locked exists for |
+| Checklist integration | Register 2 new `periodCloseTaskDefinition` system rows + tighten 1 evaluator; no task for reversals | Meta-spec coordination rule (#1039 registers, never re-invents); reversal failure is covered by N+1's draft-journals Blocker |
+| H1 Multi-tenancy | All 3 new tables: `companyId`, composite PK `("id","companyId")`, `id('prefix')` defaults (`ppd`/`ppde`/`rjt`/`rjtl`) | Convention; `depreciationRun` keeps its legacy `xid()` PK — no churn |
+| H2 Service shape | All new functions in `accounting.service.ts`, `(client, …) → {data, error}`, never throw | `.ai/rules/conventions-services.md`; no new service files |
+| H3 RLS | Four policies per new table gated on `accounting_view/create/update/delete` employee permissions | `depreciationRun` policy precedent (`20260524143827:280-289`) |
+| H4 Permissions | Routes: `view/create/update/delete: "accounting"`; job uses service role | Matches depreciation-run and JE routes |
+| H5 Forms | `ValidatedForm` + zod validators in `accounting.models.ts` + route actions with `intent` | Repo convention |
+| H6 Module layout | Models/services extend the existing accounting module files; UI under `accounting/ui/` | One service/models file per module |
+| H7 Backward compat | Enum values additive; `purchaseInvoiceLine` + `journal` + `companySettings` columns nullable/defaulted; no signature breaks (`createDepreciationRunProposal` is an extraction) | Existing callers unaffected; `post-purchase-invoice` change is behavior-gated on the new flag |
+
+## Data Model Changes
+
+One migration (`pnpm db:migrate:new close-automation`), then `pnpm run generate:types`:
+
+```sql
+-- Additive source types
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Prepaid Amortization';
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Recurring Journal';
+
+-- Auto-reversing accruals
+ALTER TABLE "journal" ADD COLUMN IF NOT EXISTS "autoReverseOn" DATE;
+ALTER TABLE "journal" ADD CONSTRAINT "journal_autoReverseOn_check"
+ CHECK ("autoReverseOn" IS NULL OR "autoReverseOn" > "postingDate");
+
+-- Depreciation proposal toggle
+ALTER TABLE "companySettings" ADD COLUMN IF NOT EXISTS
+ "depreciationProposalsEnabled" BOOLEAN NOT NULL DEFAULT true;
+
+-- Prepaid flag + schedule params on AP invoice lines (G/L Account lines only)
+ALTER TABLE "purchaseInvoiceLine"
+ ADD COLUMN IF NOT EXISTS "isPrepaid" BOOLEAN NOT NULL DEFAULT false,
+ ADD COLUMN IF NOT EXISTS "prepaidStartDate" DATE,
+ ADD COLUMN IF NOT EXISTS "prepaidMonths" INTEGER,
+ ADD CONSTRAINT "purchaseInvoiceLine_prepaid_check" CHECK (
+ "isPrepaid" = false OR
+ ("invoiceLineType" = 'G/L Account' AND "prepaidStartDate" IS NOT NULL
+ AND "prepaidMonths" IS NOT NULL AND "prepaidMonths" > 0)
+ );
+
+CREATE TABLE IF NOT EXISTS "prepaidSchedule" (
+ "id" TEXT NOT NULL DEFAULT id('ppd'),
+ "companyId" TEXT NOT NULL,
+ "purchaseInvoiceId" TEXT, -- source document
+ "purchaseInvoiceLineId" TEXT,
+ "description" TEXT NOT NULL,
+ "prepaidAccountId" TEXT NOT NULL, -- resolved prepaymentAccount (by id, per control-account lesson)
+ "expenseAccountId" TEXT NOT NULL, -- amortization target from the invoice line
+ "totalAmount" NUMERIC NOT NULL, -- base currency
+ "startDate" DATE NOT NULL,
+ "months" INTEGER NOT NULL CHECK ("months" > 0),
+ "method" TEXT NOT NULL DEFAULT 'Straight Line',
+ "status" TEXT NOT NULL DEFAULT 'Active', -- 'Active' | 'Complete' | 'Cancelled'
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "prepaidSchedule_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "prepaidSchedule_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE TABLE IF NOT EXISTS "prepaidScheduleEntry" (
+ "id" TEXT NOT NULL DEFAULT id('ppde'),
+ "companyId" TEXT NOT NULL,
+ "scheduleId" TEXT NOT NULL,
+ "amortizationDate" DATE NOT NULL, -- last day of each month
+ "amount" NUMERIC NOT NULL,
+ "journalId" TEXT REFERENCES "journal"("id"), -- set when the drafted journal posts
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ CONSTRAINT "prepaidScheduleEntry_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "prepaidScheduleEntry_schedule_date_key" UNIQUE ("companyId", "scheduleId", "amortizationDate")
+);
+
+CREATE TABLE IF NOT EXISTS "recurringJournalTemplate" (
+ "id" TEXT NOT NULL DEFAULT id('rjt'),
+ "companyId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "frequency" TEXT NOT NULL DEFAULT 'Monthly', -- 'Monthly' | 'Quarterly' | 'Annually'
+ "nextRunDate" DATE NOT NULL,
+ "endDate" DATE,
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "recurringJournalTemplate_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "recurringJournalTemplate_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE TABLE IF NOT EXISTS "recurringJournalTemplateLine" (
+ "id" TEXT NOT NULL DEFAULT id('rjtl'),
+ "companyId" TEXT NOT NULL,
+ "templateId" TEXT NOT NULL,
+ "accountId" TEXT NOT NULL,
+ "description" TEXT,
+ "debit" NUMERIC NOT NULL DEFAULT 0,
+ "credit" NUMERIC NOT NULL DEFAULT 0,
+ "sortOrder" INTEGER NOT NULL DEFAULT 1,
+ CONSTRAINT "recurringJournalTemplateLine_pkey" PRIMARY KEY ("id", "companyId")
+);
+
+-- RLS: ENABLE + four policies per table gated on accounting_* employee
+-- permissions, following the depreciationRun precedent (SELECT shown; INSERT/
+-- UPDATE/DELETE analogous with create/update/delete permissions):
+ALTER TABLE "prepaidSchedule" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "prepaidSchedule" FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_view'))::text[])
+);
+-- (same pattern for prepaidScheduleEntry, recurringJournalTemplate, recurringJournalTemplateLine)
+
+-- Checklist registration (#1031 substrate — INSERT ... ON CONFLICT DO NOTHING per company,
+-- plus seed-company for new companies): two new system definitions,
+-- ordered after seeded task 4:
+-- ('Prepaid amortization posted','Auto','prepaid-amortization','Warning', isSystem)
+-- ('Recurring journals generated','Auto','recurring-journals','Warning', isSystem)
+```
+
+## API / Service Changes
+
+`apps/erp/app/modules/accounting/accounting.service.ts` (+ zod in `accounting.models.ts`, barrel exports):
+
+```ts
+// Depreciation (extraction — route + job share it)
+createDepreciationRunProposal(client, { companyId, userId }) // Draft run + lines; no-op if run exists
+
+// Prepaids
+createPrepaidSchedule(client, { companyId, invoiceLineId, ... }) // called from post-purchase-invoice
+getPrepaidSchedules(client, companyId, { status? }) // register, with remaining-balance rollup
+generatePrepaidAmortizationJournals(client, { companyId }) // Draft JE per due entry (job step 2)
+cancelPrepaidSchedule(client, { scheduleId, companyId, userId }) // only while no entry posted
+
+// Recurring journals
+get/insert/update/deactivateRecurringJournalTemplate(...) // template + lines CRUD
+generateRecurringJournals(client, { companyId }) // Draft JEs due, advance nextRunDate (job step 3)
+
+// Accrual reversals
+postDueJournalReversals(client, { companyId }) // wraps reverseJournalEntry per due journal (job step 4)
+
+// Evaluators (extend getPeriodCloseReadiness)
+// draft-depreciation → fails when no run covers the period OR covering run is Draft
+// prepaid-amortization → fails on due entries without a posted journal
+// recurring-journals → fails when an active template's nextRunDate <= period end
+```
+
+Callers to update:
+
+- `post-purchase-invoice` edge function — flagged lines debit `prepaymentAccount` (resolved to an account id via the posting-group views) instead of the expense account; call `createPrepaidSchedule`. **Coordination:** this touches the shared `post-*` surface (meta-spec rule for #1030/#1031/#1036/#1047) — rebase on their merged state, never run concurrently.
+- `journalEntryValidator` / JE form action — accept `autoReverseOn`.
+- New Inngest function registered in `packages/jobs/src/inngest/functions/scheduled/index.ts` + functions index.
+
+Routes (under `routes/x+/accounting+/`): `recurring-journals*` (list/new/edit/generate), `prepaid-schedules*` (register list + detail drawer with entries and tie-out, cancel action).
+
+## UI Changes
+
+- **Purchase invoice line form**: "Prepaid" toggle on G/L Account lines revealing start date + months; badge on flagged lines.
+- **Prepaid schedule register** (`/x/accounting/prepaid-schedules`): table (source invoice, accounts, total, amortized, remaining, status), Σ-remaining vs GL prepaid-account balance tie-out header, drawer with monthly entries + posted-journal links.
+- **Recurring journals** (`/x/accounting/recurring-journals`): templates table (frequency, next run, active), form with line editor (balance-validated), "Generate now" action.
+- **Journal entry form**: "Auto-reverse" toggle + date (defaults to day 1 of next month); Reversed originals already render via existing status badges.
+- **Depreciation runs table**: job-created Draft rows appear with a "Proposed" indicator (`createdBy = 'system'`).
+- **Close drawer**: the two new Auto tasks render via #1031's existing checklist UI with drill links (due prepaid entries, overdue templates). No new mechanism.
+- Flash messages on all actions per `.ai/rules/flash-system.md`.
+
+## Acceptance Criteria
+
+- [ ] With Active assets and no run for the just-ended month, the daily job creates exactly one Draft `depreciationRun` (correct `periodEnd`, lines matching `buildDepreciationLines`, `createdBy = 'system'`); a second firing creates nothing; `companySettings.depreciationProposalsEnabled = false` suppresses it; posting stays manual via the existing route.
+- [ ] Checklist task 4 fails when no run covers the period, fails while the covering run is Draft, and passes once it posts.
+- [ ] Posting an AP invoice with a line flagged prepaid (12 months) debits the configured `prepaymentAccount` — not the expense account — and creates a `prepaidSchedule` with 12 entries summing exactly to the line's base amount (rounding remainder in month 12).
+- [ ] The job drafts an amortization journal (`sourceType 'Prepaid Amortization'`, Debit expense / Credit prepaid) for each due entry; posting it stamps `journalId` and the register's remaining balance ties to the GL prepaid account; the "Prepaid amortization posted" task fails until due entries post.
+- [ ] A monthly template with `nextRunDate` today yields one Draft journal (`sourceType 'Recurring Journal'`, lines matching the template) and `nextRunDate` advances one month (quarterly: +3, annually: +12); a template past `endDate` deactivates; the "Recurring journals generated" task fails while a due template hasn't generated.
+- [ ] A posted JE with `autoReverseOn = day 1 next period` is automatically reversed on that date: mirror entry posted with `reversalOfId`, original `Posted → Reversed` with `reversedById`; posting succeeds when the reversal period is Locked, is skipped-and-retried when Closed, and lazy-creates a missing period.
+- [ ] Generated prepaid/recurring drafts posted through `postJournalEntry` park behind a configured #1032 journal-entry approval rule like any manual JE.
+- [ ] Direct SQL insert of a `'Prepaid Amortization'` journal into a Closed period is rejected by the #1031 trigger (accounting sources respect the matrix).
+- [ ] RLS: a user without `accounting_view` reads zero rows from all four new tables.
+- [ ] Migration applies idempotently twice; `pnpm run generate:types`, scoped `typecheck`, and `pnpm run lint` pass; `pnpm --filter @carbon/jobs test` passes.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| `post-purchase-invoice` edit collides with in-flight #1030/#1031/#1036/#1047 work on the shared `post-*` surface | Med | Meta-spec coordination rule: rebase on merged state; prepaid branch is additive and gated on `isPrepaid` |
+| Draft-run proposals surprise companies mid-close ("who created this?") | Low | "Proposed"/system attribution in the UI; settings toggle; drafts have zero GL effect |
+| Auto-posted reversal fails repeatedly (e.g. account deactivated) and silently retries forever | Med | Job logs per-journal errors; past-due `autoReverseOn` with `reversedById IS NULL` is queryable — surface as a badge on the JE list in v1.1 if it occurs in practice |
+| Rounding drift between schedule entries and GL | Low | Remainder-in-final-entry at creation; entries are immutable once journaled |
+| Duplicate generation if the job fires twice (Inngest retry) | Med | Idempotency by construction: unique (schedule, date) entry key, `nextRunDate` advance in the same transaction as the draft insert, run-exists guard, `reversedById` check |
+| Prepaid flag misuse on inventory-linked lines | Low | CHECK constraint restricts to `G/L Account` lines |
+
+## Open Questions
+
+> Resolutions below were settled with Brad before writing (grill 2026-07-04); one scope question remains open.
+
+- [x] **Auto-post depreciation or propose-only?** — **Resolved (Brad, 2026-07-04): propose-only.** The scheduler creates Draft runs; posting stays human and flows through document approvals (#1032) where a rule matches. Task 4's auto-check reflects "proposal generated + posted."
+- [x] **Prepaid v1 method scope** — Straight-line only, flagged at AP invoice line entry, debiting `prepaymentAccount` directly at posting; custom curves/usage-based deferred.
+- [x] **Recurring template v1 scope** — Fixed amounts, monthly/quarterly/annual, Draft output; formulas/allocations/dimensions deferred (drafts are editable pre-post).
+- [x] **Accrual reversal mechanism** — Flag on the manual JE (`autoReverseOn`), auto-posted day 1 of the next period via existing `reversalOfId` machinery; posts under Locked (accounting source), never under Closed.
+- [x] **Checklist integration** — Register definitions on the #1031 substrate only: tighten `draft-depreciation`, add `prepaid-amortization` + `recurring-journals`; no task for accrual reversals (next period's draft-journals Blocker covers the failure mode).
+- [x] **Source types** — Additive `journalEntrySourceType` values `'Prepaid Amortization'` and `'Recurring Journal'`; both classified accounting sources under the period matrix.
+- [x] **Depreciation-run posting behind approvals?** — Resolution 1 says run posting "flows through #1032 where a rule matches," but #1032's v1 document types are JE/payment/invoice/memo — depreciation runs post via their own route, not `postJournalEntry`. Extend `approvalDocumentType` with `'depreciationRun'` in this spec (small additive PO-pattern wiring), or defer to a #1032 follow-up and rely on `update: accounting` permission in v1? Affects scope coordination with #1032's in-flight plan. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Extend `approvalDocumentType` with `'depreciationRun'` in THIS workstream — amount = run total, reusing the engine's tiers and no-self-approval. Back out to `update: accounting`-only at plan stage if the engine extension crowds v1.
+
+## Changelog
+
+- 2026-07-04: Created — readiness findings GAP-4.1 + GAP-6 (`2026-07-03-public-company-readiness.md`), Phase 1 of the remediation roadmap; propose-only posture resolved by Brad 2026-07-04. Builds on #1031's close checklist (registers definitions, per the meta-spec coordination rule) and #1032's approval engine; activates the dormant `accountDefault.prepaymentAccount`.
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/2026-07-04-document-approvals.md b/.ai/specs/2026-07-04-document-approvals.md
new file mode 100644
index 0000000000..f96ca688c8
--- /dev/null
+++ b/.ai/specs/2026-07-04-document-approvals.md
@@ -0,0 +1,195 @@
+# Document Approvals: Manual Journal Entries, Payments, Purchase Invoices, Memos
+
+> Status: in-progress (all open questions resolved pre-writing, per the updated spec-writing flow)
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Research: `.ai/research/public-company-compliance.md` (§Pattern 4: SAP parked→posted JE verification, NetSuite approval routing, AS 2401 self-approval testing)
+> Parent: `.ai/specs/2026-07-03-public-company-readiness.md` (finding MW-2) · `.ai/plans/2026-07-03-public-company-readiness-roadmap.md` (Phase 0 Spec B — pulled forward, starts now)
+
+## TLDR
+
+Extend the existing approval engine (`approvalRule`/`approvalRequest`, built for purchase orders) to four financial documents — **manual journal entries, payments, purchase invoices, and credit/debit memos** — with amount-tiered rules, a `Pending Approval` status on each document, and the PO wiring pattern replicated: post-intent creates the request and parks the document, approvers act from the document page (notified in-app/email/Slack), approve posts the document, reject returns it to Draft, the requester can withdraw. **Self-approval becomes impossible system-wide** (including the existing PO hole): `canApproveRequest` rejects the requester, gated by a `companySettings.enforceNoSelfApproval` flag that defaults on and is audit-logged + flagged as a standing exception when disabled. The dead `escalationDays` config comes alive as a daily reminder job. The spec also ships the two SoD surfaces the readiness audit requires: a **user access report** (per-user effective permissions per company, exportable, for quarterly access reviews) and a **SoD conflict report** (seeded conflict matrix over `userPermission` + rule membership, including "no JE rule configured" and "self-approval enforcement disabled" as reportable exceptions). Reversals and voids are deliberately not gated in v1 — they are audit-logged and fire notifications to the rule's approvers. This closes readiness finding MW-2 (the first control a SOX readiness firm tests) using machinery that already exists.
+
+## Problem Statement
+
+Manual journals go `Draft → Posted` with no approval step; payments and purchase invoices post on a single permission check; memos post unreviewed (the classic receivables write-off fraud vector). The one approval engine that exists covers only `purchaseOrder`/`qualityDocument`/`supplier` — and permits self-approval: `canApproveRequest` (`apps/erp/app/modules/shared/shared.service.ts:149-200`) checks rule/group membership only; `requestedBy` is not even in its input type. Auditors test exactly this first (AS 2401: submitter vs approver credentials, time-gap analytics). Specific holes found in fieldwork:
+
+- `postJournalEntry` (`accounting.service.ts:1896-1959`) posts any balanced Draft — reachable from two routes AND the MCP API (`accounting_postJournalEntry` in `api+/mcp+/lib/direct-executor.ts`), so a route-level gate would be bypassable; the gate must live in the service.
+- `post-purchase-invoice`'s post branch has **no status guard at all** (`post-purchase-invoice/index.ts:403` — fetch and post unconditionally); the Draft→Pending→Open dance is entirely route-managed.
+- `post-payment` is the only poster with in-transaction status re-assertion (`index.ts:425-437`) — the pattern the others need.
+- `salesOrderStatus` has carried a dead `'Needs Approval'` value since 2024 that nothing writes.
+- `escalationDays` (`20260119191608:58`) has no consumer — dead config with a commented-out form field.
+
+## Resolved Questions (answered before writing, 2026-07-04)
+
+- [x] **Reversals/voids gated?** — **No, not in v1.** Forward postings only. `reverseJournalEntry`, payment/memo void, and invoice void stay one-step but are audit-logged and fire an `ApprovalRequested`-family notification ("Posted document reversed/voided") to the matched rule's approvers. Gate can be added later if auditors push. (NetSuite default.)
+- [x] **Memos in scope?** — **Yes, fourth document type.** Same engine, same pattern as payments; closes the credit-memo write-off vector in the same release.
+- [x] **Seeded default rules?** — **No — opt-in per company** (today's PO behavior: no rule ⇒ no approval). The SoD report flags companies with no journal-entry rule; the accounting-activation cutover checklist (readiness roadmap §Cutover) requires rules to be configured.
+- [x] **Escalation?** — **Daily reminder in v1.** Inngest cron re-notifies approvers of requests pending longer than the rule's `escalationDays` and CCs `defaultApproverId`; the commented-out form field returns.
+- [x] *(inherited from the readiness spec)* Self-approval blocked server-side for **all** approval document types including existing POs; `companySettings.enforceNoSelfApproval` defaults on; disabling it is audit-logged and appears in the SoD report.
+
+## Proposed Solution
+
+### Document lifecycles (PO pattern replicated)
+
+| Document | Today | With a matching enabled rule | Amount evaluated (base currency) |
+|---|---|---|---|
+| Manual JE | Draft → Posted | Draft → **Pending Approval** → Posted (approve) / Draft (reject/withdraw) | `journalEntries.totalDebits` (balanced ⇒ == credits; `journalLine.amount` is already base) |
+| Payment | Draft → Posted → Voided | Draft → **Pending Approval** → Posted / Draft | payment total converted to base via the shared FX helper (never hardcode the operator — convention set by the FX-normalization spec) |
+| Purchase invoice | Draft → (route-transient Pending) → Open | Draft → **Pending Approval** → Pending → Open / Draft | `purchaseInvoices.totalAmount` view column (already base; includes tax + shipping) |
+| Memo | Draft → Posted → Voided | Draft → **Pending Approval** → Posted / Draft | memo amount converted to base via the same helper |
+
+Mechanics, per document:
+
+1. **Post intent** (existing post routes/actions; for JEs also the service entry point so the MCP path is covered): call `isApprovalRequired(type, companyId, baseAmount)`. If no enabled rule matches → post exactly as today (opt-in resolution). If one matches and the latest request for the document is not Approved → set status `Pending Approval`, `createApprovalRequest` (amount = base amount snapshot), notify approvers via the existing `ApprovalRequested` event, flash "submitted for approval". PO precedent: `$orderId.finalize.tsx:123-177`.
+2. **Approve** → `approveRequest` (existing Kysely transaction) gains cases for the four types. JE: re-validate balance + period gate inside the transaction, then `status='Posted'`, `postedAt/By`, `approvedBy` — guarded `WHERE status = 'Pending Approval'` (throw → rollback if changed, the PO guard pattern). Payment/memo: transition is **handled by the edge function** — the route invokes `post-payment`/`post-memo` after `approveRequest` marks the request Approved; the edge functions' status guards learn to accept `'Pending Approval'` **only when the latest request for the document is Approved** (checked inside the FOR-UPDATE transaction — no flip-to-Draft race). Purchase invoice: route runs today's posting dance from `Pending Approval` under the same approved-request check, and `post-purchase-invoice` finally gains a real status guard (accept only Draft, route-transient Pending, or approved Pending Approval).
+3. **Reject** → request Rejected with `decisionNotes`; document returns to `Draft` (guarded transition). Requester notified (`ApprovalRejected`).
+4. **Withdraw** → requester-only (`canCancelRequest`); request Cancelled; document returns to Draft.
+5. **Locked while pending**: documents in `Pending Approval` are not editable — JE: the existing `journal` UPDATE RLS policy allows only Draft/Posted, so the new status is edit-locked by construction (approve path runs service-role Kysely); payment/invoice/memo: extend the app-side Draft-only guards (`isPaymentLocked`, `isPurchaseInvoiceLocked`, memo equivalent) to treat `Pending Approval` as locked. Edits require withdraw-to-Draft first.
+6. **Approver identity on the record**: `journal.preparedBy` (stamped = the posting requester), `journal.approvedBy`, `journal.approvalRequestId` — the columns the readiness JE export needs. Payments/invoices/memos carry identity via `approvalRequest` (`requestedBy`/`decisionBy`), joined by the export.
+
+### No-self-approval (all document types, including POs)
+
+- `ApprovalRequestForApproveCheck` gains `requestedBy`; `canApproveRequest` and `canApproveRequestInWindow` return `false` when `userId === requestedBy` and `companySettings.enforceNoSelfApproval` is true. This closes the existing PO hole in the same change.
+- `enforceNoSelfApproval BOOLEAN NOT NULL DEFAULT true` on `companySettings`. Turning it off: settings permission required, audit-logged, and surfaced permanently in the SoD report as a standing exception. (Deadlock note for tiny teams: the requester sees "awaiting another approver" — the escape is a second approver on the rule or disabling the flag, both visible to auditors.)
+- `getPendingApprovalsForApprover` gains the same exclusion (it currently doesn't exclude own requests; `getApprovalsForUser` already does).
+
+### Escalation reminder
+
+Daily Inngest cron: for each Pending request whose rule has `escalationDays` and `requestedAt < now − escalationDays`, re-fire `ApprovalRequested` to the tier's approvers + `defaultApproverId`, at most once per day per request (stamp `lastRemindedAt` on the request). Un-comment the `escalationDays` field in `ApprovalRuleForm`.
+
+### Reversals & voids (not gated — resolved)
+
+`reverseJournalEntry`, payment/memo void, invoice void keep their current one-step flows, with two additions: the action is audit-logged (this rides Phase 0 Spec A's audit coverage; until then, the existing notification is the trail) and a notification is sent to the matched rule's approvers ("JE-2026-07-0042 was reversed by …"). Revisit gating post-v1 if audit feedback demands it.
+
+### Rules UI & engine hygiene
+
+- `approvalDocumentTypesWithAmounts` += the four new types; the settings page gains four cards (JE / Payment / Purchase Invoice / Memo), amount-tiered like the PO card.
+- Duplicate-floor validation: `upsertApprovalRule` rejects a second enabled rule with the same `(documentType, lowerBoundAmount)`; partial unique index backs it.
+- Notifications: `notify.ts` gains descriptions for the four types; `api+/link.ts` gains their deep links.
+- Pending-approvals visibility: the accounting dashboard and invoicing dashboard gain the same "assigned to me" widget the purchasing dashboard has (`getPendingApprovalsForApprover`), covering JEs and payments/invoices/memos respectively.
+
+### SoD & access-review reports (readiness Spec B scope)
+
+Two new settings-area reports, both CSV-exportable via the standard table export:
+
+1. **User access report** (`x+/settings+/access-report`): per user × company, effective permissions expanded from `userPermission` JSONB (module × action × company, `"0"` wildcard resolved), employee type, active status, last sign-in; grouped by user. This is the quarterly access-review artifact (the most common ITGC deficiency is stale access).
+2. **SoD conflict report** (`x+/settings+/sod-report`): evaluates a seeded conflict matrix and lists users/companies in violation, plus standing exceptions:
+ - JE create/update (`accounting_update`) + JE approver (rule membership) — flagged when self-approval enforcement is off; informational otherwise (the runtime block is the mitigating control).
+ - Supplier create (`purchasing_create`) + payment approver.
+ - Rule configuration (`settings_update`) + approver membership on any rule (can grant themselves approval authority).
+ - `settings_update` (sequence editing) + `accounting_update` (posting).
+ - Company has **no enabled journal-entry rule** (per the opt-in resolution — visibility instead of seeding).
+ - `enforceNoSelfApproval = false`.
+ The matrix lives in code (a typed constant), not a table — v1 is detective reporting per the readiness resolution; a configurable matrix comes with preventive enforcement later.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|---|---|---|
+| 1 | Engine | Extend `approvalRule`/`approvalRequest` — no new engine | Roadmap resolution; tiers/groups/notifications/decision audit already exist; per-document ad-hoc approvals are the anti-pattern |
+| 2 | Gate placement — JE | Inside `postJournalEntry` (service), not the route | MCP API calls the service directly (`direct-executor.ts`); a route gate is bypassable. Covers both routes + MCP with one check |
+| 3 | Gate placement — payment/memo | Route sets `Pending Approval`; edge function accepts that status only with an Approved request, verified inside the existing FOR UPDATE transaction | Avoids a flip-to-Draft TOCTOU; reuses `post-payment`'s proven re-assertion pattern (`index.ts:421-437`) |
+| 4 | Gate placement — purchase invoice | Route gate + a real status guard added to `post-purchase-invoice`'s post branch | The post branch currently has no status guard at all — fixing that is MW-1-adjacent hardening this spec gets for free |
+| 5 | New statuses | `ALTER TYPE ... ADD VALUE 'Pending Approval'` on `journalEntryStatus`, `paymentStatus`, `memoStatus`, `purchaseInvoiceStatus` | Additive, precedent `20260119191608:5` (PO) and `20260630093809:182-184`; `purchaseInvoices` view's status CASE gains the passthrough; `status-colors.ts` already maps a yellow "Needs Approval" — add "Pending Approval" alongside |
+| 6 | Naming | `'Pending Approval'` (not PO's `'Needs Approval'`) | PI enum already uses `'Pending'` for the route-transient posting state; "Pending Approval" avoids collision and reads correctly in the derived-status views. The dead `salesOrderStatus 'Needs Approval'` value is left untouched (Postgres enums can't drop values; SO approvals are out of scope) |
+| 7 | Amount basis | Base currency, snapshot on the request at creation (existing `amount` column) | Rules are company-wide; mixed-currency documents must tier consistently; FX helper shared with posting so the convention tracks the FX-normalization spec |
+| 8 | Self-approval | Blocked in `canApproveRequest` core, `enforceNoSelfApproval` default on, disable = audited standing exception | Readiness resolution; fixes POs too; AS 2401 test #1 |
+| 9 | Reversals/voids | Not gated; audit-logged + approver notification | Resolved 2026-07-04 (recommendation accepted) |
+| 10 | Memos | In scope, mirroring payments | Resolved 2026-07-04 |
+| 11 | Rule seeding | None — opt-in; SoD report + cutover checklist provide the visibility | Resolved 2026-07-04 |
+| 12 | Escalation | Daily reminder job + `lastRemindedAt`; no tier-jumping | Resolved 2026-07-04; makes dead config real without redesigning authority |
+| 13 | SoD matrix | Typed constant in code, detective-only v1 | Readiness resolution (detective); configurable matrix ships with preventive enforcement if/when demanded |
+| 14 | Multi-tenancy (H1) | No new business tables; new columns on existing composite-PK tables; `approvalRequest.lastRemindedAt` added | Engine tables already follow the convention |
+| 15 | Service shape (H2) | All engine changes in `shared.service.ts`; JE gate in `accounting.service.ts`; reports in `users`/`settings` service per module ownership; `(client, ...) → {data, error}` | House convention; no new service files |
+| 16 | RLS (H3) | `approvalRequest` keeps zero policies (service-role only, app-level auth) — unchanged, documented; new statuses covered by existing policies (JE edit-lock falls out of the Draft/Posted-only UPDATE policy) | Matches current engine posture; Phase 0 Spec A adds the audit coverage |
+| 17 | Permissions (H4) | Decision actions ride the documents' existing route permissions (`update: accounting` / `update: invoicing`) + `canApproveRequest`; reports require `view: users` (access) / `view: settings` (SoD); rules stay `settings_*` | Exact PO precedent |
+| 18 | Forms (H5) | `ValidatedForm` + zod: approval decision validators mirror `purchaseOrderApprovalValidator`; rule form reused | House convention |
+| 19 | Module layout (H6) | No new module; UI additions in existing `ui/` folders per module | House convention |
+| 20 | Backward compat (H7) | No rule configured ⇒ byte-identical behavior everywhere; new enum values additive; `enforceNoSelfApproval` default true changes PO behavior only for requester-approvers (the hole being closed is the point) | Release note for the PO self-approval change |
+
+## Data Model Changes
+
+One idempotent migration (`pnpm db:migrate:new document-approvals`, randomized HHMMSS — enum ADD VALUEs guarded and, per Postgres rules, positioned so new values aren't used in the same transaction; follow the `20260630093809:182-184` pattern), then `pnpm run generate:types`:
+
+```sql
+-- New approval document types
+ALTER TYPE "approvalDocumentType" ADD VALUE IF NOT EXISTS 'journalEntry';
+ALTER TYPE "approvalDocumentType" ADD VALUE IF NOT EXISTS 'payment';
+ALTER TYPE "approvalDocumentType" ADD VALUE IF NOT EXISTS 'purchaseInvoice';
+ALTER TYPE "approvalDocumentType" ADD VALUE IF NOT EXISTS 'memo';
+
+-- New document statuses
+ALTER TYPE "journalEntryStatus" ADD VALUE IF NOT EXISTS 'Pending Approval';
+ALTER TYPE "paymentStatus" ADD VALUE IF NOT EXISTS 'Pending Approval';
+ALTER TYPE "memoStatus" ADD VALUE IF NOT EXISTS 'Pending Approval';
+ALTER TYPE "purchaseInvoiceStatus" ADD VALUE IF NOT EXISTS 'Pending Approval';
+
+-- Approver identity for the JE export (readiness MW-1/MW-2)
+ALTER TABLE "journal"
+ ADD COLUMN IF NOT EXISTS "preparedBy" TEXT REFERENCES "user"("id"),
+ ADD COLUMN IF NOT EXISTS "approvedBy" TEXT REFERENCES "user"("id"),
+ ADD COLUMN IF NOT EXISTS "approvalRequestId" TEXT;
+
+-- Self-approval enforcement + escalation reminder bookkeeping
+ALTER TABLE "companySettings"
+ ADD COLUMN IF NOT EXISTS "enforceNoSelfApproval" BOOLEAN NOT NULL DEFAULT true;
+ALTER TABLE "approvalRequest"
+ ADD COLUMN IF NOT EXISTS "lastRemindedAt" TIMESTAMP WITH TIME ZONE;
+
+-- One enabled rule per (documentType, floor)
+CREATE UNIQUE INDEX IF NOT EXISTS "approvalRule_type_floor_enabled_idx"
+ ON "approvalRule" ("companyId", "documentType", "lowerBoundAmount")
+ WHERE "enabled" = true;
+
+-- purchaseInvoices view: add 'Pending Approval' to the status passthrough CASE
+-- (DROP + recreate, forked from the NEWEST definition per .ai/lessons.md)
+```
+
+## API / Service Changes
+
+- `shared.service.ts`: `canApproveRequest`/`canApproveRequestInWindow` gain `requestedBy` + the self-approval check; `approveRequest`/`rejectRequest` gain the four document cases with guarded status transitions; `getPendingApprovalsForApprover` excludes own requests; `createApprovalRequest` unchanged.
+- `accounting.service.ts`: `postJournalEntry` gains the approval gate (rule check → park + request + notify, or post) and stamps `preparedBy`/`approvedBy`; `reverseJournalEntry` fires the approver notification.
+- Edge functions: `post-payment` / `post-memo` status guards accept `'Pending Approval'` iff the latest request is Approved (checked in-transaction); `post-purchase-invoice` post branch gains a status guard (Draft / transient Pending / approved Pending Approval only).
+- Routes: post routes for the four documents gain the gate + submitted-for-approval flash; decision actions (approve/reject with notes) added to each document's detail route mirroring `$orderId.tsx:86-124`; withdraw actions mirror `canCancelRequest`; `api+/link.ts` + `notify.ts` learn the four types.
+- Jobs: `approval-escalation` daily cron in `packages/jobs`.
+- Reports: `getUserAccessReport` (users service), `getSodConflicts` (settings/users service) + two routes with CSV export.
+- MCP: `accounting_postJournalEntry` inherits the gate automatically (it calls the service).
+
+## UI Changes
+
+- Status badges (`Pending Approval` = yellow) across the four documents' tables/headers; Approve/Reject modal (notes field) on each document page for eligible approvers; withdraw button for requesters; edit surfaces disabled while pending.
+- Settings → Approval Rules: four new amount-tiered cards; `escalationDays` field restored.
+- Accounting + invoicing dashboards: pending-approvals widget (purchasing precedent).
+- Settings: Access Report + SoD Report pages with CSV export; `enforceNoSelfApproval` toggle with warning copy.
+
+## Acceptance Criteria
+
+- [ ] With a JE rule (floor $0) enabled: posting a balanced manual JE from the UI **and** from the MCP tool parks it in `Pending Approval` with a request (amount = totalDebits) and notifies approvers; with no rule, posting behaves byte-identically to today.
+- [ ] The requester — even when a rule approver — cannot approve their own JE/payment/invoice/memo/PO (server-rejected); a second approver can; with `enforceNoSelfApproval` off (audit-logged), the requester-approver can, and the SoD report shows the standing exception.
+- [ ] Approving a pending JE posts it (balance + period re-validated in-transaction) and stamps `preparedBy`/`approvedBy`; rejecting returns it to Draft with notes; the requester can withdraw; a parked JE cannot be edited via PostgREST or the UI without withdrawing first.
+- [ ] A payment above a $10k rule floor parks; direct invocation of `post-payment` on the parked payment fails until the request is Approved; after approval the normal post flow succeeds. Same for a memo and a purchase invoice; `post-purchase-invoice` now rejects posting any invoice that is not Draft / transient-Pending / approved-Pending-Approval.
+- [ ] Amount tiering: a $500 JE matches the $0 rule and a $50k JE the $25k rule; a $0-tier approver cannot approve the $50k entry; duplicate enabled floors are rejected at rule save.
+- [ ] Reversing a posted JE and voiding a posted payment still work one-step and fire a notification to the matched rule's approvers.
+- [ ] A request pending longer than `escalationDays` triggers exactly one reminder per day to approvers + default approver.
+- [ ] Access report lists a seeded user's effective permissions per company with the wildcard expanded; SoD report flags a user holding `accounting_update` + JE approver membership, a company with no enabled JE rule, and a company with enforcement off; both export CSV.
+- [ ] `pnpm run generate:types`, scoped typecheck, lint, and existing approval/PO tests pass; migration applies idempotently twice.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| Enum ADD VALUE + same-migration use (Postgres restriction) | Med | Follow the `20260630093809` guarded pattern; view recreation in the same migration only references, never inserts, the new values |
+| `approveRequest` grows four Kysely branches → drift vs edge-function logic | Med | JE posting logic shared via one validated SQL path; payment/memo/invoice transitions stay in their edge functions (single owner per document) |
+| Parked documents block month-end (approver on vacation) | Med | Escalation reminders + default approver; withdraw always available to the requester; close-readiness already blocks on drafts, pending items surface the same way |
+| PO behavior change (self-approval now blocked) surprises existing users | Med | Release note; `enforceNoSelfApproval` toggle exists but defaults on; SoD report explains the why |
+| MCP agents parking documents unexpectedly | Low | Gate returns a structured "submitted for approval" result, not an error; tool docs updated |
+| purchaseInvoices view recreation churn | Med | Fork from newest definition per `.ai/lessons.md`; `SELECT *` passthrough |
+
+## Open Questions
+
+> All resolved before writing (see Resolved Questions above) — none outstanding.
+
+## Changelog
+
+- 2026-07-04: Created under the updated spec-writing flow: engine + document-flow fieldwork first, four open questions resolved with Brad (recommendations accepted: reversals/voids not gated in v1; memos included; opt-in rules, no seeding; daily escalation reminder), spec written with resolutions baked in. Ready for `/plan`.
diff --git a/.ai/specs/2026-07-04-e-invoicing.md b/.ai/specs/2026-07-04-e-invoicing.md
new file mode 100644
index 0000000000..1013d4df1a
--- /dev/null
+++ b/.ai/specs/2026-07-04-e-invoicing.md
@@ -0,0 +1,301 @@
+# E-Invoicing — EN 16931 Semantic Model, Format Renderers, Clearance State Machine
+
+> Status: in-progress
+> Author: Claude (readiness finding GAP-D2)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1054
+> Related: `.ai/specs/2026-07-04-avalara-integration-foundation.md` (#1061 — credentials/client), `.ai/specs/2026-07-04-gapless-numbering-legal-series.md` (#1038 — legal series), `.ai/specs/2026-07-03-multi-jurisdiction-tax.md` (registrations, tax summary, `invoiceMessage`), `.ai/specs/2026-07-03-public-company-readiness.md` (GAP-D2, SD-2)
+
+## TLDR
+
+Carbon has zero e-invoicing code while mandates land on its actual customer base (EU + US footprint): **France's B2B issue mandate hits September 2026 (~2 months out)**, **Poland's KSeF is already mandatory in 2026**, **Germany has required inbound structured-invoice receipt since 2025** (issue mandate 2027–28), **Italy's SDI has been mandatory for years**, and ViDA makes structured intra-EU invoicing universal by 2030. This spec builds the **adapter framework, not fifty adapters** (SAP DRC pattern): a single **EN 16931 semantic invoice model** mapped from Carbon sales invoices and credit memos (using the tax spec's registrations, tax summary components, and VAT clauses) and validated against the BR-\* business rules before anything leaves the building; **pure-function format renderers** (Peppol BIS 3.0 UBL as the baseline, Factur-X for France, XRechnung for Germany, FatturaPA for Italy, FA(3) for Poland's KSeF); a per-document **clearance state machine** (`Pending → Submitted → Accepted/Rejected → Corrected`) with retries, surfaced rejection reasons, and rectification-document flows — an issued invoice is never edited; **transmission through Avalara's e-invoicing API** behind one internal `ClearanceAdapter` interface with country routing; **inbound** structured supplier invoices landing as draft purchase invoices with supplier/line matching; and **legal-series + issuance gating** so an invoice for a clearance-model country is not "issued" (numbered-final, deliverable) until the platform accepts it. Rollout is France first, then Poland/Italy, then Germany outbound.
+
+## Problem Statement
+
+1. **No structured output.** `packages/documents/src/pdf/SalesInvoicePDF.tsx` renders a human-readable PDF only. No UBL, no CII, no country XML. A German customer of a Carbon user can already lawfully refuse a paper/PDF-image invoice; from Sept 2026 a French Carbon user cannot legally *issue* one to a French B2B buyer at all.
+2. **No clearance concept.** In Poland (KSeF) and Italy (SDI) the government platform is in the legal path: the invoice does not exist as a legal document until the platform accepts it and (KSeF) assigns its number. Carbon's `salesInvoiceStatus` flow (`Draft → Pending → Submitted → Paid…`) has no notion of "posted in GL but not yet legally issued," no rejection handling, and no rectification chain.
+3. **No inbound.** Germany's receive mandate (since 2025) and Peppol generally mean suppliers will send XML, not PDFs. Carbon's only structured intake is AI PDF extraction (`documentExtraction`, migration `20260609001724`) — probabilistic, where XML is exact.
+4. **Prerequisites now exist on this branch.** The tax spec provides per-component tax breakdowns, `taxRegistration` (seller VAT IDs), `customerTax.vatNumber`, reporting categories (mapping to EN 16931 VAT category codes S/Z/E/AE/K/G/O), and `invoiceMessage` clauses. The gapless-numbering spec (#1038) provides `legalSeries` per entity + country + doc type. E-invoicing is the consumer both were built for.
+
+## Proposed Solution
+
+### 1. EN 16931 semantic invoice model (`packages/ee/src/e-invoicing/semantic/`)
+
+One TypeScript type, `SemanticInvoice`, structured after EN 16931's business terms (BT-1…BT-165, groups BG-1…BG-32): document header (BT-1 number, BT-2 issue date, BT-3 type code 380/381, BT-5 currency), seller (name, address, **BT-31 VAT identifier from `taxRegistration`** matched to the invoice country, electronic address/Peppol participant ID), buyer (from `customer` + `customerTax.vatNumber`), payment terms/means, allowances/charges, line group (BG-25: quantity, unit code UN/ECE Rec 20 mapped from `unitOfMeasure`, net price, item identifiers), and **VAT breakdown (BG-23) built directly from the tax spec's per-component summary** with category codes derived from `taxCode.reportingCategory` (`Standard→S`, `Zero-Rated→Z`, `Exempt→E`, `Reverse Charge→AE`, `Export→G/K`, `Out of Scope→O`) and exemption reason text from `invoiceMessage`.
+
+- **Builder**: `buildSemanticInvoice(client, companyId, { documentType, documentId })` in `eInvoicing.service.ts` — reads `salesInvoice(+Lines)`, `taxLedger` rows (posted; drafts compute live via `resolveLineTaxes`), registrations, payment terms. Credit memos map to type code 381 with the preceding-invoice reference (BG-3) — the rectification substrate.
+- **Validation**: `validateSemanticInvoice(model, countryCode)` runs (a) the core EN 16931 BR rules we implement as pure predicates (the arithmetic set BR-CO-\*, the mandatory-field set BR-1…BR-65, VAT-category rules BR-S/Z/E/AE/G/O-\*), then (b) a per-country CIUS delta (XRechnung's mandatory `BT-10 buyerReference`/Leitweg-ID, FatturaPA's codice destinatario, KSeF FA(3) structural constraints). Returns structured `{ rule, severity, message, path }[]` so the UI can point at the exact missing field **before** a round-trip to Avalara. Avalara re-validates; ours exists for actionable pre-flight errors.
+
+**Field mapping reference (core subset — the full table lives beside the builder as its test fixture):**
+
+| EN 16931 term | Carbon source |
+|---|---|
+| BT-1 Invoice number | `legalSeries` number (#1038); falls back to `salesInvoice.invoiceId` for non-mandate countries |
+| BT-2 / BT-9 Issue / due date | `salesInvoice.dateIssued` (stamped at issuance, §5) / `dateDue` from payment terms |
+| BT-3 Type code | 380 invoice; 381 credit memo; BG-3 preceding reference from the memo's originating invoice |
+| BT-5 Currency | `salesInvoice.currencyCode`; BT-6 (VAT accounting currency) = company base currency when they differ |
+| BG-4 Seller | `company` + active `taxRegistration` for the invoice country (BT-31); Peppol participant ID from `eInvoiceCountrySetting` |
+| BG-7 Buyer | `customer` + invoice-to address + `customerTax.vatNumber` (BT-48) |
+| BT-10 Buyer reference | `salesInvoice.customerReference` (Leitweg-ID for DE B2G) |
+| BG-13 Delivery | shipment ship-to address + ship date where linked |
+| BG-16 Payment instructions | payment terms + (bank-rec spec) company bank IBAN/BIC when configured |
+| BG-25 Lines | `salesInvoiceLine`: quantity, `unitOfMeasure` → UN/ECE Rec 20 code map, unit price net, item id/description |
+| BG-23 VAT breakdown | tax spec per-component summary; category from `taxCode.reportingCategory`, exemption text from `invoiceMessage` |
+| BT-106…115 Totals | invoice totals recomputed from lines and cross-checked (BR-CO-10…15) — a mismatch is a build error, never silently forwarded |
+
+### 2. Format renderers (`packages/ee/src/e-invoicing/formats/`)
+
+Pure functions `render(model: SemanticInvoice) → { xml: string, mimeType, filename }`:
+
+| Format | Country/use | Syntax | Notes |
+|---|---|---|---|
+| `peppol-bis-3` | Network baseline, NL/BE/Nordics, ViDA bet | UBL 2.1 | The house canonical serialization; every other renderer is a sibling, and archived alongside country formats |
+| `factur-x` | France | CII XML (+ hybrid PDF/A-3) | France's PDP syntaxes are UBL, CII, Factur-X. v1 transmits **CII XML**; hybrid PDF/A-3 assembly (embed XML into `SalesInvoicePDF` output via `pdf-lib`) is a fast-follow because react-pdf does not emit PDF/A (see Risks) |
+| `xrechnung` | Germany | UBL 2.1 + XRechnung CIUS | Leitweg-ID in BT-10 for B2G; plain EN 16931 core for B2B |
+| `fatturapa` | Italy | FatturaPA 1.2.x | Not EN 16931-syntax; rendered via a dedicated mapping from the same semantic model (richer party/regime fields from registrations) |
+| `ksef-fa3` | Poland | FA(3) XSD | KSeF's schema; KSeF number returned on acceptance is stored as `clearanceId` and printed on the PDF |
+
+Renderers are dependency-light string/XML builders with golden-file tests (sample semantic model → expected XML, validated against the official XSDs in CI). Carbon owns rendering (archival fidelity, partner independence); Avalara owns transmission.
+
+### 3. Clearance/submission state machine
+
+Every outbound legal document gets one `eInvoiceDocument` row snapshotting the semantic model at submission time (immutable after `Submitted` — status-transition-only trigger, per readiness DD-1):
+
+```
+Pending ──submit──▶ Submitted ──▶ Accepted
+ ▲ │
+ │ (retryable ├──▶ Rejected ──rectify──▶ Corrected (new document row,
+ │ transport error: │ supersedesId chain)
+ │ stays Pending, └──▶ Cancelled (voided before clearance)
+ │ attempts logged)
+```
+
+- **Submission** is an Inngest job (`e-invoice-submit`, event `carbon/e-invoice.submit`) fired on invoice posting for countries with an active `eInvoiceCountrySetting`: build → validate → render → `adapter.submit()` → record transmission attempt. Transport failures (5xx, timeout) retry with Inngest backoff, document stays `Pending`; **business rejections** (schema/BR/platform refusal) move to `Rejected` with `rejectionReasons` surfaced verbatim in the UI.
+- **Status updates** arrive via the Avalara webhook (route `api+/webhook.avalara-einvoicing.ts` → Inngest `e-invoice-status`) plus a reconciliation poll job for silent documents older than a threshold.
+- **Rectification, never edit**: a `Rejected` pre-clearance document may be fixed and resubmitted (new `eInvoiceDocument` row, `supersedesId` → old row → `Corrected`) because no legal document exists yet. Post-acceptance corrections go through **documents**: credit memo (type 381, references BT-25 preceding invoice) + optionally a new invoice — Poland's *faktura korygująca* and France's *avoir* map to exactly this. The sales invoice itself is never mutated after issuance (aligns with posted-record immutability, SD-1/MW-1).
+- **Adapter interface** (`packages/ee/src/e-invoicing/adapters/types.ts`):
+
+```ts
+interface ClearanceAdapter {
+ readonly id: "avalara" | "internal-archive"; // future: sovos, direct-ksef…
+ supports(countryCode: string, direction: "outbound" | "inbound"): boolean;
+ submit(doc: RenderedEInvoice): Promise<{ transportId: string } | ClearanceRejection>;
+ getStatus(transportId: string): Promise<ClearanceStatus>;
+ parseInbound(payload: unknown): Promise<SemanticInvoice>;
+}
+```
+
+`AvalaraEInvoicingAdapter` (Avalara E-Invoicing & Live Reporting API) is the first-class implementation — credentials, client, retry/rate-limit plumbing, and the `companyIntegration` row come from the Avalara foundation spec (#1061); this spec only consumes `getAvalaraClient(companyId)`. Country routing: `resolveAdapter(companyId, countryCode)` reads `eInvoiceCountrySetting.adapter` (default `avalara`). `internal-archive` is the no-mandate path (e.g. US customers): render + archive Peppol BIS, no transmission.
+
+**Per-country lifecycle nuances** (encoded as adapter/setting data, not code branches):
+
+| Country | Model | Issuance gate | Correction vehicle | Notes |
+|---|---|---|---|---|
+| France | Centralized exchange via PDP | No (post-audit lifecycle statuses) | Avoir (381) | Lifecycle statuses (deposited/rejected/refused by buyer) flow back through the PDP; buyer *refusal* maps to `Rejected` post-acceptance → corrective flow |
+| Poland | Clearance (KSeF) | **Yes** | Faktura korygująca (381 referencing KSeF number) | KSeF number is the legal identifier; printed on PDF; platform-offline mode deferred to Phase 2 detail |
+| Italy | Clearance (SDI) | **Yes** | Nota di credito (TD04) | SDI *scarto* (discard) within 5 days maps to `Rejected`; esito/acceptance maps to `Accepted` |
+| Germany | Post-audit | No | Storno/credit (381) | Receive mandate live since 2025 (inbound priority); outbound XRechnung/EN 16931 core |
+| Peppol network | Transport ack only | No | 381 | MLR/transport acks map to `Accepted` at network level |
+
+### 4. Inbound — structured supplier invoices → draft purchase invoices
+
+Avalara receives on Carbon's behalf (Peppol access point registration, KSeF inbound pull, SDI codice destinatario) and webhooks the payload. Inngest `e-invoice-inbound`:
+
+1. `adapter.parseInbound()` → `SemanticInvoice`; store the original XML in Supabase Storage (legal original, GoBD/retention — GAP-D3).
+2. Create `eInvoiceDocument` (direction `Inbound`, status `Accepted` — clearance already happened upstream).
+3. **Supplier match** by VAT number against `supplierTax.vatNumber`/supplier registrations; no match → document parks in the inbound inbox for manual assignment (never auto-create suppliers).
+4. Create a **draft `purchaseInvoice`** with header fields exact-from-XML and **line mapping**: match `supplierPart` numbers → item lines; unmatched lines land as G/L-only lines flagged for review. Totals from XML are authoritative; a mismatch between mapped lines and XML totals blocks release, not creation.
+5. Review happens in the existing purchase-invoice draft UI (same surface the `documentExtraction` flow feeds — XML intake is a second, exact-precision source into the same funnel).
+
+### 5. Legal series linkage and issuance gating
+
+- `eInvoiceDocument` records `legalSeriesId` + `legalNumber` assigned by the gapless-numbering spec's series (per entity + country + doc type, #1038). For **KSeF**, the platform's own number is additionally stored in `clearanceId` and printed on the human PDF.
+- **Issuance rule**: `eInvoiceCountrySetting.clearanceGatesIssuance` (true for PL/IT; false for FR post-audit-via-PDP and DE). When true, posting still writes GL + `taxLedger` (accounting recognition is Carbon's), but the invoice is held in a new `salesInvoice.issuedAt IS NULL` state: customer-facing delivery (email/PDF download by customer, portal) is blocked and the UI shows "Awaiting clearance." `Accepted` stamps `issuedAt` and releases delivery. When false, `issuedAt` stamps at posting and clearance runs in parallel.
+
+### 6. Rollout phasing
+
+| Phase | Market(s) | Why now | Ships |
+|---|---|---|---|
+| **1** | **France** (+ `internal-archive` everywhere) | Issue mandate **Sept 2026 — ~2 months**; largest EU exposure window | Semantic model + BR validation, Peppol BIS + Factur-X(CII) renderers, state machine, Avalara PDP submission, country settings, monitor UI, issuance non-gating |
+| **2** | **Poland, Italy** | KSeF **already mandatory in 2026** (any PL entity is non-compliant today); SDI long-mandatory (blocks any IT customer) | FA(3) + FatturaPA renderers, clearance-gated issuance, KSeF-number stamping, rectification flows |
+| **3** | **Germany + inbound everywhere** | DE receive mandate in force since 2025 (inbound is the urgent half); DE issue mandate 2027–28 | Inbound pipeline (§4), XRechnung outbound, Peppol network send for NL/BE/Nordics |
+| 4 | Per demand | ViDA 2030 runway; clearance-model non-EU (MX CFDI, BR NF-e, IN IRP) via the same adapter seam | New renderers/adapters only — no framework changes |
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|---|---|---|
+| 1 | Build vs. buy split | Carbon owns semantic model + rendering + state machine; **Avalara owns transmission/clearance connectivity** (PDP, KSeF, SDI, Peppol AP) | RESOLVED (Brad): Avalara is the first-class partner. Becoming a registered PDP/Peppol AP/SDI intermediary ourselves is a multi-year certification program (CO-1 notes PDP registration as a *later* company milestone); owning the model + renderers keeps partner independence and archival fidelity |
+| 2 | One semantic model, many renderers | EN 16931 business terms as the internal type; FatturaPA/FA(3) render from it too | SAP DRC / research consensus #8: adapter framework, not fifty adapters; ViDA converges on EN 16931 anyway |
+| 3 | Clearance vs. accounting | GL/`taxLedger` post at posting; **legal issuance** is a separate gate (`issuedAt`) controlled per country | Accounting recognition and legal document existence are different facts; blocking posting on a government API would couple close to platform uptime |
+| 4 | Corrections | Rectification documents only (credit memo 381 + reissue), `supersedesId` chain; pre-clearance rejections may resubmit | Legal requirement in every mandate country; matches posted-record immutability (SD-1) |
+| 5 | Multi-tenancy (heuristic 1) | All new tables: `companyId`, composite PK `("id","companyId")`, `id()` defaults, audit columns | House convention |
+| 6 | Service shape (heuristic 2) | `eInvoicing.service.ts` + `eInvoicing.models.ts` in `apps/erp/app/modules/invoicing/`; `(client, companyId, …) → {data, error}` | Invoicing-owned (sales + purchase invoices live there); one service file per module rule |
+| 7 | RLS (heuristic 3) | Four standard policies; SELECT via `get_companies_with_employee_role()`, writes via `get_companies_with_employee_permission('invoicing_*')`; state transitions via service role from Inngest jobs, guarded by transition trigger | Matches `taxLedger` posture: user-facing reads, job-driven writes |
+| 8 | Permission scoping (heuristic 4) | Country settings: `settings` + `invoicing_update`; monitor + resubmit: `invoicing_update`; inbound inbox: `invoicing_create` | Compliance config is settings-tier; day-to-day clearance ops are AR/AP clerks |
+| 9 | Form pattern (heuristic 5) | `ValidatedForm` + zod (`eInvoiceCountrySettingValidator`); monitor uses the standard table pattern; rejection detail in a Drawer | House convention |
+| 10 | Module layout (heuristic 6) | Framework code in `packages/ee/src/e-invoicing/` (`semantic/`, `formats/`, `adapters/`, `inbound/`); ERP glue in `modules/invoicing`; jobs in `@carbon/jobs` | ee is the integrations home (Xero precedent); no new package (ask-first rule) |
+| 11 | Backward compatibility (heuristic 7) | No `eInvoiceCountrySetting` rows → zero behavior change (no jobs fire, `issuedAt` backfilled = `postingDate` for existing invoices, delivery never blocked); all new columns nullable | US-only companies and existing invoices are untouched |
+| 12 | Pre-flight BR validation | Implement core BR-\* + country CIUS subset in-house even though Avalara validates | Rejection round-trips through a clearance platform are slow and opaque; field-level pre-flight errors at invoice edit time are the UX difference |
+| 13 | Inbound record creation | Draft purchase invoice immediately, park only on supplier-match failure | XML is exact — unlike `documentExtraction` there is no confidence threshold; the draft UI is the review gate |
+
+## Data Model Changes
+
+```sql
+CREATE TYPE "eInvoiceDirection" AS ENUM ('Outbound', 'Inbound');
+CREATE TYPE "eInvoiceFormat" AS ENUM ('Peppol-BIS-3', 'Factur-X', 'XRechnung', 'FatturaPA', 'KSeF-FA3');
+CREATE TYPE "eInvoiceStatus" AS ENUM ('Pending', 'Submitted', 'Accepted', 'Rejected', 'Corrected', 'Cancelled');
+CREATE TYPE "eInvoiceDocumentType" AS ENUM ('Sales Invoice', 'Credit Memo', 'Purchase Invoice');
+
+-- Per-company, per-country mandate configuration
+CREATE TABLE "eInvoiceCountrySetting" (
+ "id" TEXT NOT NULL DEFAULT id('eics'),
+ "companyId" TEXT NOT NULL,
+ "countryCode" TEXT NOT NULL, -- ISO 3166-1 alpha-2
+ "outboundEnabled" BOOLEAN NOT NULL DEFAULT false,
+ "inboundEnabled" BOOLEAN NOT NULL DEFAULT false,
+ "defaultFormat" "eInvoiceFormat" NOT NULL,
+ "adapter" TEXT NOT NULL DEFAULT 'avalara', -- 'avalara' | 'internal-archive'
+ "clearanceGatesIssuance" BOOLEAN NOT NULL DEFAULT false, -- true: PL, IT
+ "avalaraMandateId" TEXT, -- Avalara mandate identifier for routing
+ "legalSeriesId" TEXT, -- default series (gapless-numbering spec #1038)
+ "customFields" JSONB,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "eInvoiceCountrySetting_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "eInvoiceCountrySetting_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "eInvoiceCountrySetting_unique" UNIQUE ("companyId", "countryCode")
+);
+
+-- One row per legal document instance in the clearance lifecycle
+CREATE TABLE "eInvoiceDocument" (
+ "id" TEXT NOT NULL DEFAULT id('einv'),
+ "companyId" TEXT NOT NULL,
+ "direction" "eInvoiceDirection" NOT NULL,
+ "documentType" "eInvoiceDocumentType" NOT NULL,
+ "sourceDocumentId" TEXT, -- salesInvoice/memo id (outbound); purchaseInvoice id once created (inbound)
+ "countryCode" TEXT NOT NULL,
+ "format" "eInvoiceFormat" NOT NULL,
+ "status" "eInvoiceStatus" NOT NULL DEFAULT 'Pending',
+ "semanticModel" JSONB NOT NULL, -- EN 16931 snapshot; immutable after Submitted
+ "validationErrors" JSONB, -- pre-flight BR-*/CIUS failures
+ "renderedPath" TEXT, -- Supabase Storage path of XML (+ hybrid PDF)
+ "originalPath" TEXT, -- inbound: received XML original (retention)
+ "legalSeriesId" TEXT,
+ "legalNumber" TEXT, -- from gapless legal series (#1038)
+ "clearanceId" TEXT, -- KSeF number / SDI id / PDP lifecycle id / Peppol message id
+ "clearanceMetadata" JSONB,
+ "rejectionReasons" JSONB, -- [{ code, message, field? }] surfaced verbatim
+ "supersedesId" TEXT, -- correction chain (self-FK)
+ "submittedAt" TIMESTAMP WITH TIME ZONE,
+ "clearedAt" TIMESTAMP WITH TIME ZONE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "eInvoiceDocument_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "eInvoiceDocument_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "eInvoiceDocument_supersedes_fkey" FOREIGN KEY ("supersedesId", "companyId")
+ REFERENCES "eInvoiceDocument"("id", "companyId")
+);
+CREATE INDEX "eInvoiceDocument_source_idx" ON "eInvoiceDocument" ("companyId", "sourceDocumentId");
+CREATE INDEX "eInvoiceDocument_status_idx" ON "eInvoiceDocument" ("companyId", "status");
+
+-- Transport attempt log (retry forensics; append-only)
+CREATE TABLE "eInvoiceTransmission" (
+ "id" TEXT NOT NULL DEFAULT id('eitx'),
+ "companyId" TEXT NOT NULL,
+ "eInvoiceDocumentId" TEXT NOT NULL,
+ "attempt" INTEGER NOT NULL,
+ "adapter" TEXT NOT NULL,
+ "transportId" TEXT, -- Avalara submission id
+ "httpStatus" INTEGER,
+ "error" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ CONSTRAINT "eInvoiceTransmission_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "eInvoiceTransmission_doc_fkey" FOREIGN KEY ("eInvoiceDocumentId", "companyId")
+ REFERENCES "eInvoiceDocument"("id", "companyId") ON DELETE CASCADE
+);
+
+-- Issuance gate on the invoice itself. Distinct from the existing user-editable
+-- "dateIssued" DATE (the business document date, BT-2): "issuedAt" is the
+-- system-stamped legal-issuance instant, set by posting (non-gated countries)
+-- or by clearance acceptance (gated countries). Never user-editable.
+ALTER TABLE "salesInvoice" ADD COLUMN "issuedAt" TIMESTAMP WITH TIME ZONE;
+-- Backfill: existing posted invoices are considered issued at posting
+UPDATE "salesInvoice" SET "issuedAt" = "postingDate" WHERE "postingDate" IS NOT NULL;
+
+-- RLS (all three tables): standard four policies
+ALTER TABLE "eInvoiceDocument" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "eInvoiceDocument_SELECT" ON "eInvoiceDocument" FOR SELECT USING (
+ "companyId" = ANY (
+ SELECT unnest(get_companies_with_employee_role())
+ )
+);
+-- INSERT/UPDATE via get_companies_with_employee_permission('invoicing_update');
+-- status transitions additionally guarded by a SECURITY DEFINER trigger:
+-- semanticModel/renderedPath/legalNumber are frozen once status != 'Pending';
+-- only forward transitions allowed (Pending→Submitted→Accepted|Rejected→Corrected; Pending→Cancelled).
+```
+
+## API / Service Changes
+
+- **`packages/ee/src/e-invoicing/`** — `semantic/` (types + `mapSalesInvoice`, `mapCreditMemo`, `validate` with BR/CIUS rule tables), `formats/` (five renderers + XSD golden tests), `adapters/` (`types.ts`, `avalara.ts` consuming #1061's client, `internal-archive.ts`), `inbound/` (parser → `SemanticInvoice`, supplier/line matcher).
+- **`modules/invoicing/eInvoicing.service.ts`** — `getEInvoiceCountrySettings`, `upsertEInvoiceCountrySetting`, `getEInvoiceDocuments` (monitor list), `getEInvoiceDocument`, `buildSemanticInvoice`, `submitEInvoice` (creates row + fires event), `resubmitEInvoice` (rejected-only; creates superseding row), `createPurchaseInvoiceFromInbound`.
+- **Inngest** (`@carbon/jobs`): `e-invoice-submit` (build→validate→render→submit; Inngest retries on transport failure), `e-invoice-status` (webhook-driven transitions; stamps `issuedAt` on Accepted where gated; fires notification on Rejected), `e-invoice-reconcile` (hourly poll for stale `Submitted`), `e-invoice-inbound`. Rejections and inbound arrivals notify via `@carbon/notifications` to invoicing users (same channel pattern as existing document notifications).
+- **Routes**: `api+/webhook.avalara-einvoicing.ts` (signature-verified, per #1061); `x+/settings+/e-invoicing.tsx` (country settings); `x+/invoicing+/e-invoice-monitor*` (list + drawer); inbound inbox under `x+/invoicing+/`.
+- **Posting hook**: `post-sales-invoice` (edge function) gains a post-commit step — if an `eInvoiceCountrySetting` matches the invoice's tax country and `outboundEnabled`, fire `carbon/e-invoice.submit`; if `clearanceGatesIssuance`, leave `issuedAt` NULL, else stamp it. No setting → stamp `issuedAt`, done (today's behavior).
+- **Delivery gate**: invoice email/customer-PDF actions check `issuedAt IS NOT NULL` when a gating setting exists for the country.
+
+## UI Changes
+
+- **Country settings page** (settings → E-Invoicing): per-country cards with mandate model, format, adapter, series link, enable toggles; warns when a `taxRegistration` exists for a mandate country with no setting (mirrors the tax spec's cross-warning pattern).
+- **Sales invoice detail**: clearance status badge (Pending/Submitted/Accepted/Rejected + KSeF/SDI number), "Awaiting clearance" delivery lock state, rejection panel with field-level reasons and a "Fix & resubmit" action (pre-clearance) or "Create corrective credit memo" (post-clearance).
+- **E-invoice monitor** (SAP DRC monitor pattern): filterable table of `eInvoiceDocument` across statuses/countries, bulk retry for transport failures, correction-chain drilldown.
+- **Inbound inbox**: received documents pending supplier match; matched ones deep-link to their draft purchase invoice.
+- **Pre-flight validation**: posting a mandate-country invoice with BR/CIUS failures shows the structured error list (block or warn per `clearanceGatesIssuance`).
+
+## Acceptance Criteria
+
+All Avalara interactions run against a **mock Avalara e-invoicing endpoint** (test harness from #1061) supporting scripted accept/reject/timeout per submission.
+
+- [ ] Posting a sales invoice for a FR-registered customer with FR `eInvoiceCountrySetting` builds a `SemanticInvoice` whose BG-23 VAT breakdown matches the invoice's `taxLedger` component rows exactly (bases, rates, category codes) and whose BT-31 equals the company's FR `taxRegistration` number.
+- [ ] The Factur-X (CII) and Peppol BIS 3.0 renderers produce XML that validates against the official XSDs in CI (golden-file tests, `pnpm --filter @carbon/ee test`).
+- [ ] An invoice missing the buyer VAT number under a Reverse-Charge code fails pre-flight with rule id BR-AE-\* and a field path — no submission attempt is made, no `eInvoiceTransmission` row exists.
+- [ ] Mock accept: document goes `Pending → Submitted → Accepted`, `clearanceId` stored, `issuedAt` stamped (gated country) and delivery unblocks; mock 503 twice then accept: three `eInvoiceTransmission` rows, final status `Accepted`, document never entered `Rejected`.
+- [ ] Mock business rejection: status `Rejected`, reasons rendered in the invoice drawer; resubmit creates a new `eInvoiceDocument` with `supersedesId` set and the old row `Corrected`; the sales invoice row itself is byte-identical throughout (immutability trigger test).
+- [ ] For a PL-gated invoice, GL and `taxLedger` post at posting time while customer email/PDF delivery returns a blocked state until Accepted; a non-mandate US invoice posts and delivers exactly as before this spec (regression test with zero settings rows).
+- [ ] Attempting to UPDATE `semanticModel` or `legalNumber` on a `Submitted` document raises the trigger exception, including via service role.
+- [ ] Inbound: posting a sample Peppol BIS invoice to the mock webhook creates an `Inbound` `eInvoiceDocument` with the original XML archived, matches the supplier by VAT number, and produces a draft `purchaseInvoice` whose line for a known `supplierPart` maps to the right item and whose totals equal the XML totals; an unknown-supplier document parks in the inbox and creates nothing.
+- [ ] Credit memo for a cleared invoice renders type code 381 with the preceding invoice reference (BG-3) and follows the same clearance lifecycle.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| France deadline (~2 months) vs. build time | High | Phase 1 is deliberately thin: CII (no PDF/A-3 hybrid), Avalara does the PDP legwork; mandate applies to French *sellers* — confirm actual FR-entity customer count to calibrate (see OQ) |
+| react-pdf cannot emit PDF/A-3 → no native Factur-X hybrid | Med | Transmit pure CII/UBL (legally sufficient via PDP); hybrid via `pdf-lib` embedding + veraPDF conformance check as fast-follow |
+| Avalara mandate coverage gaps or contract scope (PDP, KSeF, SDI, Peppol AP) | High | Adapter seam keeps a direct-API or second-vendor escape hatch; verify per-mandate coverage before each market GA (OQ below) |
+| BR-\*/CIUS rule set drifts with annual releases (XRechnung 3.x, FA(3)→FA(4)) | Med | Rules as versioned data tables + golden tests; Avalara remains authoritative backstop validator |
+| Clearance outage blocks issuance in gated countries | Med | Posting/GL never blocks; monitor surfaces stuck documents; KSeF offline-mode handling per platform rules deferred to Phase 2 detail |
+| Inbound line-matching quality on messy supplier catalogs | Low | Totals-authoritative design; unmatched lines are reviewable G/L lines, never silent drops |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until unchecked items are answered.
+
+- [x] Middleware partner vs. direct government APIs? — **Resolved (Brad): Avalara is the first-class clearance partner**; direct APIs stay possible behind `ClearanceAdapter`. Credentials/client per `.ai/specs/2026-07-04-avalara-integration-foundation.md` (#1061).
+- [x] Customer footprint? — **Resolved (Brad): customers are all over Europe and the US** → France-first phasing by mandate date; `internal-archive` (render-only) for US companies from Phase 1.
+- [x] Where do legal numbering series come from? — **Resolved**: the gapless-numbering spec (#1038) owns `legalSeries`; this spec only links and prints.
+- [x] Commercial: does the Avalara contract (E-Invoicing & Live Reporting) cover FR PDP, PL KSeF, IT SDI transmission **and** inbound receipt (Peppol AP registration, SDI codice destinatario) for our customers' entities? Blocks GA per market, not the build. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Assume full coverage (FR PDP, PL KSeF, IT SDI transmission + inbound Peppol AP / SDI receipt) and build against Avalara's unified API. Verify the contract during planning; an uncovered market backs out that market's GA — the build is unaffected.
+- [x] Do any current customers have a **French or Polish legal entity issuing B2B invoices** (vs. selling into FR/PL from elsewhere — which the mandates do not cover)? Determines whether Phase 1 is a hard September deadline or a strong-default roadmap. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Assume yes — treat France Sept 2026 as a hard deadline. Confirm at plan stage; if no FR/PL issuing entity exists, France slips to demand-driven with zero design change.
+- [x] Italy: FatturaPA requires seller regime fiscale + full codice destinatario/PEC routing data we don't capture on `customer` today — confirm adding these as customer/registration fields (small schema add, Phase 2) rather than a generic `customFields` escape hatch. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Yes — real columns on customer/tax-registration in Phase 2, never customFields.
+
+## Changelog
+
+- 2026-07-04: Created. Scope per GAP-D2 with resolutions baked in (Avalara first-class, EU+US footprint, France-first phasing).
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/2026-07-04-fixed-assets-completeness.md b/.ai/specs/2026-07-04-fixed-assets-completeness.md
new file mode 100644
index 0000000000..77a23bf668
--- /dev/null
+++ b/.ai/specs/2026-07-04-fixed-assets-completeness.md
@@ -0,0 +1,351 @@
+# Fixed Assets Completeness — Disposal Proceeds, Impairment, CIP, Components
+
+> Status: in-progress
+> Author: Claude (readiness remediation, GAP-4 remainder)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1041
+> Readiness finding: `.ai/specs/2026-07-03-public-company-readiness.md` §GAP-4 (Phase 2 slice)
+> Related: `.ai/specs/2026-07-04-multi-book.md` (book-specific depreciation), close-automation spec (scheduled depreciation — GAP-4.1, **not** this spec), `.ai/specs/2026-07-02-period-closing.md` (posting matrix)
+
+## TLDR
+
+The fixed-asset subledger acquires, depreciates, and scraps — but cannot book a
+gain on sale (docs admit "no proceeds-based gain calculation"), impair
+(`writeDownAccountId` is a dead FK), accumulate construction costs (no CIP), or
+componentize (IAS 16 prerequisite for IFRS books). This spec adds to
+`modules/accounting`: (1) disposal with proceeds — full or partial — posting
+gain/loss = proceeds − NBV to the class's `disposalAccountId`, linked to a sales
+invoice or direct cash proceeds; (2) an impairment document (asset or class scope)
+posting Dr `writeDownAccountId` / Cr accumulated depreciation with an
+`accumulatedImpairment` tracking column, re-basing future depreciation; (3) CIP
+classes accumulating costs from Fixed Asset PO lines and job costs, capitalized
+into a depreciating class via a transfer document; (4) parent/child component
+assets with independent lives/methods, plus mid-life class transfers. All postings
+obey the period-close matrix and posted-journal immutability.
+
+## Problem Statement
+
+Verified against `20260524143827_fixed-assets.sql`, `accounting.server.ts`
+(`postDisposal` L37), `post-sales-invoice/index.ts` L578–800, and the docs
+(`docs/content/docs/reference/fixed-assets.mdx`):
+
+1. **Disposal ignores proceeds.** `postDisposal()` posts Dr accum dep / Dr
+ `writeOffAccountId` (NBV) / Cr asset at cost; the sales-invoice path books
+ proceeds as plain *revenue* and NBV to *write-off* — gross, never netted.
+ `fixedAssetDisposal.saleProceeds`/`gainLoss` exist but no gain is computed;
+ `disposalAccountId` (NOT NULL on every class) has **zero writers**. Cost 10,000,
+ accum dep 4,000, sold 7,500 shows 7,500 revenue + 6,000 expense instead of a
+ 1,500 gain. No partial disposal.
+2. **No impairment.** `writeDownAccountId` is required on every class and never
+ referenced by any posting path; ASC 360/IAS 36 write-downs become manual JEs
+ the subledger never learns about — NBV overstated, over-depreciation after.
+3. **No CIP.** Fixed Asset PO lines post straight to the class asset account and
+ depreciation can start before in-service; job costs (self-constructed
+ machinery — Carbon's customer base) can't reach an asset at all. No CIP aging.
+4. **No components.** No parent/child concept; IAS 16.43 componentization is a
+ prerequisite for IFRS books via the multi-book spec. No mid-life class
+ transfer either (wrong-class fixes mean dispose + re-create, losing history).
+
+## Proposed Solution
+
+### 1. Disposal with proceeds (full and partial)
+
+Extends the dispose flow (`$fixedAssetId.dispose` → `postDisposal()`).
+
+- **Proceeds source** — either a `salesInvoiceLine` of type `'Fixed Asset'` (link
+ exists via `salesInvoiceLine.assetId`), or direct proceeds with a user-selected
+ debit account (cash/clearing) for sales outside the invoicing flow.
+- **Journal** (`sourceType: 'Asset Disposal'`): Dr accumulated depreciation (incl.
+ impairment), Dr proceeds account (AR via invoice posting, or the cash account),
+ Cr asset at cost, balancing line to the class's **`disposalAccountId`** — gain
+ (credit) or loss (debit) = proceeds − NBV. The `post-sales-invoice` Fixed Asset
+ branch is rewritten to this pattern (proceeds stop hitting revenue; NBV stops
+ hitting write-off). `writeOffAccountId` stays the zero-proceeds (scrapping) target.
+- **Partial disposal**: entered as quantity (e.g. 2 of 5 units) or value fraction,
+ both resolving to `disposalFraction` (0 < f ≤ 1). Disposed cost and accumulated
+ balances = balance × f (pro-rata); asset stays `Active` with reduced balances;
+ `fixedAssetDisposal` records fraction + slices. `f = 1` is today's full disposal.
+
+### 2. Impairment — new `fixedAssetImpairment` document, Draft → Posted
+
+- **Scope**: single asset, or a class (one line per Active asset, each with its
+ own recoverable amount, prefilled with NBV). **Loss** = max(0, NBV −
+ recoverable), NBV = acquisitionCost − accumulatedDepreciation −
+ accumulatedImpairment.
+- **Posting** (new `journalEntrySourceType` `'Asset Impairment'`): Dr class
+ `writeDownAccountId` / Cr class `accumulatedDepreciationAccountId`. **Contra
+ treatment, not a new account column**: the credit lands in the existing
+ accumulated-depreciation account while `fixedAsset.accumulatedImpairment` tracks
+ the slice for the register, disposal clearing, and future IAS 36 reversals — a
+ seventh NOT NULL account FK would force a breaking backfill of every class.
+- **Re-basing**: future depreciation = (recoverable − residual) over remaining
+ life; `buildDepreciationLines()` subtracts `accumulatedImpairment` in its NBV
+ term. IAS 36 reversals: **out of scope** until multi-book adjustment books exist
+ — same staging as LCNRV reversals in GAP-3.
+
+### 3. CIP — construction in progress
+
+- **CIP class flag**: `fixedAssetClass.isConstructionInProgress BOOLEAN` — assets
+ in a CIP class never enter depreciation runs; status uses new enum value
+ `'Under Construction'`. Seed one CIP class per company group (all six account
+ FKs point at the CIP account — NOT NULL satisfied, depreciation ones never post).
+- **Cost accumulation** — append-only `fixedAssetCipCost` rows, two sources:
+ (1) **PO lines**: a Fixed Asset PO line pointing at a CIP asset posts Dr CIP
+ asset account (existing acquisition path, unchanged) and appends a row (source
+ `'Purchase Invoice'`, document line FK); (2) **job costs**: a job (or cost
+ slice) attached to a CIP asset posts Dr CIP asset account / Cr WIP
+ (`postingGroupInventory.workInProgressAccount`) and appends a row (source
+ `'Job'`) — WIP-credit timing is an open question below.
+- **Capitalization** = `fixedAssetTransfer` of type `'Capitalization'`: target
+ class + in-service date; posts Dr target asset account / Cr CIP asset account
+ at accumulated cost; sets `acquisitionCost`, `acquisitionDate`,
+ `depreciationStartDate` (= in-service date), status → `Active`.
+- **CIP aging report**: accumulated cost bucketed by age of first cost
+ (0–90/91–180/181–365/365+ days) — the auditor's stale-CIP question.
+
+### 4. Component assets and class transfers
+
+- **Components**: `fixedAsset.parentFixedAssetId` self-FK (one level; a component
+ cannot itself have children — trigger-enforced). Components are ordinary assets
+ with their own class, method, life, and cost — depreciation/disposal/impairment
+ work per component unchanged; the parent may carry residual cost (IAS 16.46
+ "remainder"); register UI rolls children up under the parent. Componentization
+ is the structural prerequisite for the multi-book spec
+ (`.ai/specs/2026-07-04-multi-book.md`), whose per-book depreciation parameters
+ attach to components.
+- **Class transfer** (type `'Reclassification'`, same `fixedAssetTransfer` table):
+ Dr new / Cr old asset account at cost, Dr old / Cr new accumulated-depreciation
+ account (skip lines where accounts match); new `journalEntrySourceType`
+ `'Asset Transfer'`. Method/life do **not** change on transfer (estimate change,
+ edited on the asset directly).
+
+### 5. Period close and immutability
+
+Every posting above goes through the existing journal insert path and inherits
+the period-close posting matrix (`20260702044133`) and posted-journal immutability
+— no special cases. Posting actions resolve `accountingPeriodId` from the document
+date and fail with the standard closed-period error; posted documents are
+immutable, corrections are reversing documents. Scheduled depreciation and the
+close-readiness depreciation check are the **close-automation spec's** scope —
+referenced only so `Under Construction` assets are excluded from that check.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Gain/loss account | Net single line to class `disposalAccountId` (gain credit / loss debit) | Column is NOT NULL + seeded + unwritten — it was built for exactly this; NetSuite/BC both post net gain-loss, not gross revenue+expense |
+| 2 | Sales-invoice disposal path | Rewrite `post-sales-invoice` Fixed Asset branch to gain/loss pattern; proceeds stop posting to revenue | Revenue overstatement is a GAAP error (ASC 610-20: derecognition gain, not revenue); coordinated-PR posting change per the readiness spec's decision 15 |
+| 3 | Partial disposal representation | Single `disposalFraction` + frozen disposed-cost/accum snapshot columns on `fixedAssetDisposal` | Quantity and value entry both collapse to a fraction; snapshots make the disposal row self-auditing after the asset's balances shrink |
+| 4 | Impairment credit side | Contra within existing accumulated-depreciation account + new `accumulatedImpairment` tracking column | A new NOT NULL account FK breaks every existing class (backfill + form churn); subledger column preserves the impairment split for register/disposal/IAS 36 reversals; BC's "Write-Down" posting type uses the same collapsed-contra pattern |
+| 5 | Impairment reversals | Out of scope until multi-book adjustment books | US GAAP forbids reversal; IAS 36 requires it — inherently book-specific, same staging as GAP-3 LCNRV |
+| 6 | CIP modeling | Class-level flag + `'Under Construction'` status + cost ledger, not a separate CIP module | Reuses acquisition paths already keyed to `fixedAssetClass` accounts; SAP AuC / BC "CIP class" precedent |
+| 7 | Capitalization & reclass | One `fixedAssetTransfer` table, `type IN ('Capitalization','Reclassification')` | Same shape (from/to class, journal, date); two tables would duplicate posting + RLS + UI |
+| 8 | Component depth | One level (parent → components), trigger-enforced | IAS 16 needs parts, not trees; deep hierarchies wreck register rollups and disposal math for no auditor benefit |
+| 9 | Multi-tenancy (H1) | New tables: `companyId`, composite PK `("id","companyId")`, `id('prefix')`, audit columns | Repo convention (`packages/database/AGENTS.md`); existing fixed-asset tables predate it (xid, single PK) — new tables follow current convention; FKs still target `fixedAsset("id")` |
+| 10 | Service shape (H2) | New functions in `accounting.service.ts` / posting transactions in `accounting.server.ts`, `(client, args)` → `{data,error}`, never throw | One service file per module; disposal/depreciation posting already lives there |
+| 11 | RLS + permissions (H3/H4) | Four policies per new table via `get_companies_with_employee_permission('accounting_*')`; routes use `requirePermissions` with `accounting_*`; posting = `create`, like dispose today | Matches every existing fixed-asset table; no new permission actions — readiness spec decision 14 |
+| 12 | Forms + module layout (H5/H6) | `ValidatedForm` + zod validators in `accounting.models.ts`, route actions under `x+/fixed-asset+` / `x+/impairment+`; everything in `modules/accounting` | Existing `FixedAssetDisposalForm`/route precedent; fixed assets already live there |
+| 13 | Backward compatibility (H7) | Additive schema only; behavior changes are the two posting rewrites (dispose, post-sales-invoice), shipped as coordinated PRs | No FROZEN surface touched; existing disposals/journals untouched (new columns nullable/defaulted) |
+
+## Data Model Changes
+
+```sql
+-- Enums (separate pre-migration file, per ADD VALUE transaction rule)
+ALTER TYPE "fixedAssetStatus" ADD VALUE IF NOT EXISTS 'Under Construction';
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Asset Impairment';
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Asset Transfer';
+
+-- fixedAsset: components + impairment tracking
+ALTER TABLE "fixedAsset"
+ ADD COLUMN "parentFixedAssetId" TEXT REFERENCES "fixedAsset"("id") ON DELETE SET NULL,
+ ADD COLUMN "accumulatedImpairment" NUMERIC NOT NULL DEFAULT 0;
+-- + index on parentFixedAssetId; trigger rejects a parent that itself has a parent
+
+-- fixedAssetClass: CIP flag
+ALTER TABLE "fixedAssetClass"
+ ADD COLUMN "isConstructionInProgress" BOOLEAN NOT NULL DEFAULT FALSE;
+
+-- fixedAssetDisposal: proceeds linkage + partial disposal (additive)
+ALTER TABLE "fixedAssetDisposal"
+ ADD COLUMN "salesInvoiceLineId" TEXT REFERENCES "salesInvoiceLine"("id") ON DELETE SET NULL,
+ ADD COLUMN "proceedsAccountId" TEXT REFERENCES "account"("id"),
+ ADD COLUMN "disposalFraction" NUMERIC NOT NULL DEFAULT 1,
+ -- posting-time snapshots: cost × fraction, accumulated dep/impairment × fraction
+ ADD COLUMN "disposedCost" NUMERIC,
+ ADD COLUMN "disposedAccumulatedDepreciation" NUMERIC,
+ ADD COLUMN "disposedAccumulatedImpairment" NUMERIC;
+
+-- Impairment document (header + lines). All new tables: audit columns (createdBy/
+-- createdAt/updatedBy/updatedAt REFERENCES "user"("id")), "customFields" JSONB on
+-- headers, companyId FK → company ON DELETE CASCADE.
+CREATE TABLE "fixedAssetImpairment" (
+ "id" TEXT NOT NULL DEFAULT id('faim'),
+ "companyId" TEXT NOT NULL,
+ "impairmentId" TEXT NOT NULL, -- readable, sequence-backed
+ "scope" TEXT NOT NULL CHECK ("scope" IN ('Asset', 'Class')),
+ "fixedAssetClassId" TEXT REFERENCES "fixedAssetClass"("id") ON DELETE RESTRICT,
+ "testDate" DATE NOT NULL,
+ -- Draft→Posted lifecycle: "status" CHECK IN ('Draft','Posted'), "postedAt", "postedBy"
+ CONSTRAINT "fixedAssetImpairment_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "fixedAssetImpairment_impairmentId_companyId_key" UNIQUE ("impairmentId", "companyId")
+);
+CREATE TABLE "fixedAssetImpairmentLine" (
+ "id" TEXT NOT NULL DEFAULT id('fail'),
+ "companyId" TEXT NOT NULL,
+ "impairmentId" TEXT NOT NULL, -- FK → fixedAssetImpairment(id)
+ "fixedAssetId" TEXT NOT NULL REFERENCES "fixedAsset"("id") ON DELETE RESTRICT,
+ "netBookValue" NUMERIC NOT NULL, -- snapshot at posting
+ "recoverableAmount" NUMERIC NOT NULL,
+ "impairmentLoss" NUMERIC NOT NULL, -- max(0, NBV − recoverable)
+ "journalId" TEXT REFERENCES "journal"("id") ON DELETE SET NULL,
+ CONSTRAINT "fixedAssetImpairmentLine_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "fixedAssetImpairmentLine_asset_key" UNIQUE ("impairmentId", "fixedAssetId")
+);
+
+-- CIP cost ledger (append-only)
+CREATE TABLE "fixedAssetCipCost" (
+ "id" TEXT NOT NULL DEFAULT id('facc'),
+ "companyId" TEXT NOT NULL,
+ "fixedAssetId" TEXT NOT NULL REFERENCES "fixedAsset"("id") ON DELETE RESTRICT,
+ "sourceType" TEXT NOT NULL CHECK ("sourceType" IN ('Purchase Invoice', 'Receipt', 'Job', 'Manual')),
+ "sourceDocumentId" TEXT,
+ "sourceDocumentLineId" TEXT,
+ "jobId" TEXT REFERENCES "job"("id") ON DELETE SET NULL,
+ "amount" NUMERIC NOT NULL,
+ "costDate" DATE NOT NULL,
+ "journalId" TEXT REFERENCES "journal"("id") ON DELETE SET NULL,
+ CONSTRAINT "fixedAssetCipCost_pkey" PRIMARY KEY ("id", "companyId")
+); -- + index on fixedAssetId
+
+-- Capitalization + reclassification (Draft→Posted lifecycle like fixedAssetImpairment)
+CREATE TABLE "fixedAssetTransfer" (
+ "id" TEXT NOT NULL DEFAULT id('fatr'),
+ "companyId" TEXT NOT NULL,
+ "transferId" TEXT NOT NULL, -- readable, sequence-backed
+ "type" TEXT NOT NULL CHECK ("type" IN ('Capitalization', 'Reclassification')),
+ "fixedAssetId" TEXT NOT NULL REFERENCES "fixedAsset"("id") ON DELETE RESTRICT,
+ "fromClassId" TEXT NOT NULL REFERENCES "fixedAssetClass"("id") ON DELETE RESTRICT,
+ "toClassId" TEXT NOT NULL REFERENCES "fixedAssetClass"("id") ON DELETE RESTRICT,
+ "transferDate" DATE NOT NULL,
+ "inServiceDate" DATE, -- Capitalization only
+ "transferredCost" NUMERIC NOT NULL,
+ "transferredAccumulatedDepreciation" NUMERIC NOT NULL DEFAULT 0,
+ "journalId" TEXT REFERENCES "journal"("id") ON DELETE SET NULL,
+ -- Draft→Posted lifecycle columns as fixedAssetImpairment
+ CONSTRAINT "fixedAssetTransfer_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "fixedAssetTransfer_transferId_companyId_key" UNIQUE ("transferId", "companyId")
+);
+
+-- RLS: all four tables get the standard four policies (accounting_view/create/
+-- update/delete via get_companies_with_employee_permission(...)::text[]).
+-- Seeds: "sequence" rows for fixedAssetImpairment + fixedAssetTransfer; one
+-- 'Construction in Progress' class per company group.
+```
+
+## API / Service Changes
+
+- `accounting.models.ts`: extend `fixedAssetDisposalValidator` (proceeds source,
+ `salesInvoiceLineId` | `proceedsAccountId` + amount, quantity/fraction); new
+ impairment + transfer validators; status arrays gain `'Under Construction'`.
+- `accounting.service.ts`: CRUD for impairments, transfers, CIP costs;
+ `getCipAging`; `getFixedAssetComponents` — all `(client, args)` → `{data,error}`.
+- `accounting.server.ts` (Kysely transactions): `postDisposal()` gains proceeds +
+ fraction handling; new `postImpairment()`, `postTransfer()`, `attachJobCostToCip()`.
+- `accounting.utils.ts`: `buildDepreciationLines()` subtracts `accumulatedImpairment`
+ in its basis term; excludes `'Under Construction'`.
+- Edge functions: `post-sales-invoice` Fixed Asset branch → gain/loss pattern;
+ `post-receipt`/`post-purchase-invoice` append `fixedAssetCipCost` rows when the
+ target asset's class is CIP (GL lines unchanged — CIP class's own asset account).
+- Routes: `x+/fixed-asset+/$fixedAssetId.{dispose,transfer,components}`;
+ `x+/impairment+/{new,$impairmentId,$impairmentId.post}`; `x+/accounting+/cip-aging`.
+
+## UI Changes
+
+- `FixedAssetDisposalForm`: proceeds section (invoice picker filtered to this
+ asset's Fixed Asset lines, or direct account + amount) and partial-disposal
+ quantity/fraction input with live gain/loss preview.
+- New `FixedAssetImpairmentForm` (scope toggle, per-line recoverable amounts,
+ computed loss) + table; new `FixedAssetTransferForm` (type, target class,
+ in-service date), reused as the "Capitalize" action on CIP assets.
+- `FixedAssetForm`: parent-asset combobox; register groups components under
+ parents; NBV column = cost − accum dep − accum impairment. CIP aging report
+ page (buckets by first-cost age, drill to cost ledger).
+
+## Acceptance Criteria
+
+- [ ] Cost 10,000, accum dep 4,000, sold via sales invoice for 7,500: journal
+ Dr AR 7,500, Dr Accum Dep 4,000, Cr Asset 10,000, Cr `disposalAccountId`
+ 1,500 (gain); `gainLoss` = 1,500; no revenue line; asset `Disposed`.
+- [ ] Same asset scrapped (proceeds 0): unchanged legacy journal — Dr Accum Dep
+ 4,000, Dr `writeOffAccountId` 6,000, Cr Asset 10,000.
+- [ ] Partial disposal, fraction 0.4, direct proceeds 3,000 to cash: Dr Cash
+ 3,000, Dr Accum Dep 1,600, Cr Asset 4,000, Cr gain 600; asset stays `Active`
+ at cost 6,000 / accum dep 2,400; disposal row stores 0.4 + snapshots 4,000/1,600.
+- [ ] Impairment: NBV 6,000 (10,000 − 4,000), recoverable 4,500 → Dr
+ `writeDownAccountId` 1,500 / Cr accum dep 1,500; `accumulatedImpairment` =
+ 1,500; next run (straight line, 36 months left, 0 residual) charges 125.00
+ (= 4,500/36), not 166.67.
+- [ ] Class-scope impairment creates one line per Active asset, prefilled with
+ each NBV; lines with recoverable ≥ NBV post nothing.
+- [ ] CIP asset receives a 6,000 Fixed Asset PO line (purchase-invoice posting) +
+ a 2,500 job-cost attachment: two `fixedAssetCipCost` rows; 8,500 Dr in the
+ CIP asset account (2,500 credited from WIP); `Under Construction`; shown in
+ CIP aging; excluded from depreciation runs.
+- [ ] Capitalizing it into Machinery & Equipment, in-service 2026-08-01: Dr
+ Machinery asset account 8,500 / Cr CIP asset account 8,500; `acquisitionCost`
+ 8,500, `depreciationStartDate` 2026-08-01, `Active`; August run depreciates it.
+- [ ] Component with `parentFixedAssetId`, own class and 60-month life,
+ depreciates independently; parenting under an asset that itself has a
+ parent is rejected. Reclassification posts cost + accumulated-depreciation
+ reclass lines, skipping lines where source and target accounts match.
+- [ ] Posting any of these into a Closed period fails with the standard
+ closed-period error; posted documents reject edits (immutability trigger
+ pattern) and the UI offers reversal instead.
+- [ ] All new tables have four RLS policies + `companyId` scoping; `pnpm exec
+ turbo run typecheck --filter=erp` passes after `pnpm run generate:types`.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Rewriting `post-sales-invoice` Fixed Asset branch regresses AR/tax lines | High | Coordinated PR with edge-function integration tests covering invoice-with-asset-line fixtures before/after |
+| Partial-disposal rounding drift (fraction × cost vs stored balances) | Med | Snapshot columns are authoritative for the journal; final partial (remaining fraction) disposes exact remaining balances |
+| Impairment inside accum-dep account complicates account-level reconciliation | Med | Register report splits dep vs impairment from subledger columns; note in docs; revisit split account when multi-book lands |
+| CIP WIP credit double-counts if job later ships/completes normally | High | Jobs attached to a CIP asset are blocked from normal completion costing (see open question 6) |
+| Enum ADD VALUE in same transaction as usage | Low | Separate enums migration file, as the existing `20260524143826` precedent |
+
+## Open Questions
+
+> HARD STOP: unchecked items must be resolved before implementation.
+
+- [x] Where does disposal gain/loss post? — **Resolved:** net to the class's
+ existing `disposalAccountId` (proceeds − NBV); `writeOffAccountId` stays the
+ scrapping target. (Resolution 1.)
+- [x] Partial disposals in scope? — **Resolved:** yes; quantity or value fraction,
+ pro-rata cost/accumulated split. (Resolution 1.)
+- [x] Impairment credit: new account column or contra? — **Resolved:** contra in
+ the existing accumulated-depreciation account + `accumulatedImpairment`
+ column; no new NOT NULL account FK. (Resolution 2 + Decision 4.)
+- [x] CIP cost sources? — **Resolved:** Fixed Asset PO lines + job costs both
+ accumulate onto a CIP asset; capitalization transfers to a depreciating
+ class, depreciation starting at in-service date. (Resolution 3.)
+- [x] Components for IFRS? — **Resolved:** one-level parent/child, independent
+ lives/methods; book-specific parameters are the multi-book spec's layer. (Resolution 4.)
+- [x] Depreciation scheduling / close checks here? — **Resolved:** no — the
+ close-automation spec owns them; this spec only excludes
+ `Under Construction` from runs. (Resolution 5.)
+- [x] **Job → CIP WIP credit timing:** credit WIP at attachment (cost leaves the
+ job immediately) vs at capitalization (WIP holds until in-service).
+ Recommended: at attachment — matches SAP AuC settlement, keeps WIP clean at
+ close — but it changes production job costing, and CIP-attached jobs must
+ be blocked from normal completion costing. Cross-module → needs sign-off. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** At attachment (SAP AuC pattern) — cost leaves WIP when attached to the CIP asset; CIP-attached jobs are blocked from normal completion costing. The cross-module production change is accepted.
+- [x] **Fate of the standalone "Sell" flow:** `$fixedAssetId.sell` creates a
+ sales order at book value; the invoice posts revenue. Keep Sell as the
+ invoice-generating front end with its posting rewritten to net to
+ `disposalAccountId` (recommended), or fold it into the dispose form?
+ Changes posted invoices' GL → needs confirmation. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Keep `$fixedAssetId.sell` as the invoice-generating front end with its posting rewritten to net proceeds to `disposalAccountId`.
+
+## Changelog
+
+- 2026-07-04: Created from readiness finding GAP-4 remainder (tracking crbnos/carbon#1041); scope resolutions 1–5 baked in; two new blocking questions surfaced (WIP credit timing, Sell-flow fate).
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/2026-07-04-fx-consolidation-completeness.md b/.ai/specs/2026-07-04-fx-consolidation-completeness.md
new file mode 100644
index 0000000000..4690d0b6cb
--- /dev/null
+++ b/.ai/specs/2026-07-04-fx-consolidation-completeness.md
@@ -0,0 +1,307 @@
+# FX & Consolidation Completeness — Unrealized Revaluation, Rate History, Posted CTA, Historical Rates
+
+> Status: in-progress
+> Author: Claude (readiness remediation Phase 1), for [email protected]
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1050
+> Readiness findings: SD-4 (FX completeness), SD-5 (consolidation correctness) — `.ai/specs/2026-07-03-public-company-readiness.md`
+
+## TLDR
+
+With the exchange-rate convention normalization spec implemented (divide-to-base everywhere, realized FX correct at settlement) and the bank-rec spec making `journalLine.sourceAmount`/`sourceCurrencyCode` mandatory on every posting path, four ASC 830/IAS 21 machines are still missing: (1) **period-end unrealized FX revaluation** of open monetary items as an auto-reversing close task (SAP FAGL_FCV / NetSuite "Revalue Open Foreign Currency Balances"); (2) a **writer for `exchangeRateHistory`** — today the table the entire translation layer reads from is never populated, so consolidated statements silently translate at rate 1; (3) **posted CTA** — currently a display-time plug applied to hardcoded account number `'3200'` (`balance-sheet.tsx:80,160`), violating the control-accounts-by-id lesson, never rolling forward; (4) **historical-rate memory** — a single `currency.historicalExchangeRate` per currency instead of per-transaction layers for equity. This spec delivers all four plus `netChange` on `translateTrialBalance` (translated income statements are currently life-to-date), and registers two new period-close checklist definitions: "Revalue open foreign currency balances" and "Verify consolidated exchange rates".
+
+## Problem Statement
+
+Facts (verified in code, 2026-07-04):
+
+1. **No unrealized revaluation exists.** FX gain/loss realizes only at settlement (`build-payment-journal`); an open EUR invoice at period end is carried at the booking-date rate, misstating AR/AP and income under ASC 830 ¶ remeasurement / IAS 21.28. The period-closing spec's checklist has no FX task because the capability doesn't exist (SD-4).
+2. **`exchangeRateHistory` has no writer.** The migration comment ("auto-populated by sync job", `20260315000002`) describes a job that does not exist — `update-exchange-rates.ts` updates `currency.exchangeRate` only. `translateTrialBalance` falls back `COALESCE(v_closing_rate, 1)` etc., so any multi-currency group's consolidated statements are silently wrong today (SD-5).
+3. **`exchangeRateHistory.rate` semantics are undefined.** The table has no base-currency column; `translateTrialBalance` multiplies `localBalance × rate` toward an arbitrary `p_target_currency` — inverted relative to the platform's normalized foreign-per-base ÷ convention and ambiguous about what the rate is quoted against.
+4. **CTA is a display plug on a hardcoded number.** `getConsolidatedBalances` computes `cta = assets − (liabilities+equity)` and `balance-sheet.tsx:80,160` attaches it to `accounts.find(a => a.number === "3200")`. `accountDefault.currencyTranslationAccount` (NOT NULL, FK, seeded → 3200) is **never read**. CTA never posts, never rolls forward, is invisible to drill-down and the JE population (`.ai/lessons.md` "Never resolve a control account by number/name").
+5. **Translated income statements are life-to-date.** `translateTrialBalance` returns only `balanceAtDate` even though `accountTreeBalancesByCompany` already computes `netChange` — flagged in the drill-down and financial-reporting specs.
+6. **Historical-rate memory is one number per currency.** `currency.historicalExchangeRate` cannot represent equity issued in tranches at different rates, or fixed-asset acquisition history, for `account.consolidatedRate = 'Historical'`.
+
+Builds on (treated as implemented): `.ai/specs/2026-07-02-exchange-rate-convention-normalization.md` (rate = foreign units per base unit; **divide** to base), `.ai/specs/2026-07-02-bank-reconciliation.md` FX section (universal `sourceAmount`/`sourceCurrencyCode`), `.ai/specs/2026-07-02-period-closing.md` (persisted close checklist; later features register `periodCloseTaskDefinition` rows).
+
+## Proposed Solution
+
+### 1. Unrealized FX revaluation as an auto-reversing close task
+
+A **currency revaluation run** per company per accounting period (SAP-style auto-reverse: post at period end, reverse on day 1 of the next period — realized-at-settlement logic stays untouched and self-heals):
+
+- **Exposure set**, all measured **as of the period end date**:
+ - Open FX AR/AP invoices: document-currency open balance at period end (invoice balance re-derived as-of-date from `invoiceSettlement` rows dated ≤ period end).
+ - Unapplied FX payments and memos: unapplied remainder at period end.
+ - FX-denominated bank/cash GL balances: Σ `journalLine.sourceAmount` per bank GL account where the linked `bankAccount.currencyCode` ≠ company base.
+- **Revalued base value** = source amount ÷ closing rate (divide convention). Closing rate for document currency D vs company base B derived from group history: `rate(D)/rate(B)` where `rate(X)` = X units per group presentation unit (see §2); when B is the presentation currency, `rate(B) = 1`.
+- **Posting**: one journal at the period end date (`sourceType 'Currency Revaluation'`, posted with `source: "accounting"` so it is legal in Locked periods) + one reversing journal dated day 1 of the next period, created and posted atomically, linked via `journal.reversedById`.
+ - AR exposure: Dr/Cr **AR Revaluation Adjustment** (new balance-sheet account) ↔ Cr/Dr `unrealizedExchangeGainAccount`/`unrealizedExchangeLossAccount`.
+ - AP exposure: mirror via **AP Revaluation Adjustment**.
+ - Bank/cash exposure: posted **direct on the bank GL account** ↔ unrealized gain/loss.
+ - Revaluation lines carry `sourceCurrencyCode` = exposure currency and `sourceAmount = 0` (a valuation posting moves base value only — satisfies the universal-population mandate honestly, SAP semantics).
+- One Posted run per (company, period); redo = Void (reverses both journals) then re-run.
+- **Checklist registration**: seeded `periodCloseTaskDefinition` "Revalue open foreign currency balances" (Auto, `autoCheckKey: 'fx-revaluation'`, severity Warning). Auto-check passes when the company has no open FX exposure at period end **or** a Posted revaluation run exists for the period.
+
+Exposure-computation detail:
+
+- As-of open balance for an invoice = posted invoice total (document currency) − Σ `invoiceSettlement` principal/discount/write-off dated ≤ period end — the same settlement-dated derivation the aging RPCs use, so a payment applied on Aug 3 does not shrink the Jul 31 exposure. Dust-forgiven invoices (`20260630151500`) with zero residual are excluded.
+- `bookedBaseAmount` for AR/AP = document open amount ÷ invoice exchange rate (the booking-date rate carried on the invoice, divide convention). For bank exposure, booked base = the GL balance of the bank account at period end; source balance = Σ `sourceAmount` on the same lines (mandatory population makes this exact go-forward; accounts with legacy NULL-source lines are reported as unrevaluable with a warning rather than revalued from partial data).
+- Out of scope for v1 (documented, not silently ignored): FX-denominated GR/IR, customer deposits (GAP-1 territory), and FX intercompany loans — the exposure preview lists these categories as "not covered" when the company has balances on them in foreign currency.
+
+### 2. Rate-history feed + coverage warnings
+
+- Extend `update-exchange-rates.ts`: after the per-company `currency` upsert loop, for each distinct `companyGroupId` processed, upsert one `exchangeRateHistory` row per enabled currency for today: `(companyGroupId, currencyCode, effectiveDate = today UTC, rate)` on the existing unique key, where **rate = currency units per one unit of the group presentation currency** (the base currency of the group's root company — the company with `parentCompanyId IS NULL`). A new `exchangeRateHistory.baseCurrencyCode` column makes the quote basis explicit.
+- **Period averages stay derived** (AVG over daily rows in the RPC) — no second storage of the same fact.
+- **Backfill is honestly NULL**: no fabricated history. Coverage begins at deploy; gaps surface as warnings, never as invented rates.
+- **Kill the rate-1 fallback**: `translateTrialBalance` keeps the fallback *chain* (average→closing, historical→layers→closing) but when no rate exists at all it falls back to the live `currency.exchangeRate` with a `rateSource = 'spot-fallback'` flag, and to NULL (`rateSource = 'missing'`, translated balance NULL) when even that is absent. `getConsolidatedBalances` aggregates these into per-currency warnings that the consolidated report banners; it never silently shows rate-1 numbers.
+- **Checklist registration**: seeded definition "Verify consolidated exchange rates" (Auto, `autoCheckKey: 'fx-rate-coverage'`, Warning; meaningful for group companies, auto-passes for single-company/single-currency setups). Check: for every currency in use across the group (company bases + open exposure currencies), a closing rate exists on or ≤ period end and no more than 7 days stale, and ≥ 1 in-period rate exists for the average.
+
+### 3. Posted CTA at group close
+
+- **Resolution by id**: consolidated reports and the CTA poster read `accountDefault.currencyTranslationAccount` (already NOT NULL + seeded). Both `number === "3200"` lookups in `balance-sheet.tsx` are deleted.
+- **Posting mechanics** (decided): a **two-line elimination-entity journal**. A balanced journal cannot absorb a translation plug — translation is a report-time transform, and any balanced entry nets to zero against the imbalance — so materializing CTA in the GL requires an offset. The alternatives were (a) a full consolidation ledger with per-account group-currency deltas (SAP Group Reporting / parallel currencies — correct, and out of scope until a stored consolidated ledger exists) or (b) offset-account materialization. We choose (b):
+ - New seeded equity account **"Currency Translation Offset"** + `accountDefault.currencyTranslationOffsetAccount`.
+ - Service `postCurrencyTranslationAdjustment` computes live cumulative CTA for the group as of period end, reads the posted balance of the CTA account on the elimination entity, and posts the **movement**: Dr/Cr CTA ↔ Cr/Dr Offset on the parent node's elimination entity (`sourceType 'Consolidation'`, elimination entity's own accounting period, `source: "accounting"`). Precedent: `generateEliminationEntries` already posts group-level entries on elimination entities.
+ - Consolidated reports: the CTA account row now comes from the GL (posted, drillable, rolls forward across periods as a real balance); the offset account is **excluded by id** from consolidated statements; a residual line "Unposted translation adjustment" = live plug − posted CTA renders only when non-zero (≈ 0 right after posting, live during open periods). The balance identity is unchanged (CTA + offset net to zero inside equity), so nothing else moves.
+- Runs as part of the parent/elimination company's close checklist (the CTA step is a Manual task the controller completes from the consolidation UI; evidence = the posted journal id). A formal group-close lock stays Phase 4 (SD-5.4–.5).
+
+Worked example: USD group, EUR subsidiary with net assets €1,000,000. July: closing 1.05, average 1.08, equity layers at 1.25. Translated assets − translated (liabilities + equity + income at average) leaves a cumulative plug of, say, $38,400 while the elimination entity's CTA account holds $30,000 from prior closes. `postCurrencyTranslationAdjustment` posts Dr Currency Translation Offset $8,400 / Cr CTA (3200) $8,400 on the elimination entity dated Jul 31; the consolidated balance sheet now shows CTA $38,400 from the GL, no offset row, and a zero residual line. August's movement computes against the new $38,400 posted balance — CTA rolls forward instead of being re-plugged from nothing.
+
+### 4. `translateTrialBalance`: netChange + convention alignment
+
+DROP/recreate (return-type change) forking from the **newest** definition per the lessons rule:
+
+- New output columns `netChange`, `translatedNetChange` (income-statement rows translated at the **average** rate over the window — period activity, not life-to-date), and `rateSource TEXT` (`'history' | 'spot-fallback' | 'missing' | 'historical-layers'`).
+- Rate math aligned to the platform convention: with `rate(X)` = X units per presentation unit, translation to `p_target_currency` T is `local × rate(T) / rate(source)` — divide-to-presentation, cross-rate to any target; degenerates to `÷ rate(source)` when T is the presentation currency.
+- Rate-1 fallback removed per §2.
+
+### 5. Historical-rate layers
+
+Replace the single `currency.historicalExchangeRate` with per-transaction layers for accounts where `account.consolidatedRate = 'Historical'` (equity; fixed-asset history when asset accounts are so tagged):
+
+- New table `historicalRateLayer`: one row per posted journal line hitting a Historical account — local (company-base) amount + the rate in force at posting.
+- **Capture by trigger** on journal status → Posted (the only surface every poster crosses: edge functions, Inngest, app services — same rationale as the period-close trigger). Rate resolved from `exchangeRateHistory` at posting date; NULL when uncovered (flagged by the coverage check, editable in UI).
+- `translateTrialBalance` for Historical accounts: Σ(`localAmount ÷ rate`) over layers ≤ period end, plus any residual (`balance − Σ localAmount`) at closing rate with `rateSource` flagging the residual.
+- `currency.historicalExchangeRate` is kept as a **deprecated fallback** for layer-less history (pre-deploy balances), last in the chain before closing; no fabricated backfill.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Revaluation model | **Auto-reversing** (post period end, reverse day 1 next period), not delta-carrying | SAP FAGL_FCV auto-reverse mode; settlement-time realized FX logic untouched; self-healing when invoices settle mid-period; resolution baked in per readiness roadmap |
+| 2 | Balance-sheet presentation | **Adjustment accounts** for AR/AP (`AR/AP Revaluation Adjustment`), **direct-on-account** for bank GL | AR/AP control accounts must keep tying to the subledger (tie-out RPCs compare control vs open invoices — a direct posting breaks them); SAP posts valuation to per-recon-account adjustment accounts for exactly this reason. Bank GL accounts have no subledger tie-out and their balance *is* the statement line; bank rec matches on `sourceAmount`, unaffected |
+| 3 | Checklist severity | Both new tasks seeded as **Warning** (skippable with reason), not Blocker | Matches the depreciation and IC seeded precedent; auto-pass when no FX exposure / single currency keeps zero-config companies unblocked; a controller can harden to Blocker via the template settings |
+| 4 | `exchangeRateHistory` semantics | rate = currency units **per group presentation unit**; explicit `baseCurrencyCode` column; cross-rate to any target | Matches the normalized foreign-per-base ÷ convention; the current table is quote-basis-ambiguous; one stored basis + cross-rates avoids N×N rows |
+| 5 | Backfill | None — honest NULL history, warnings instead of invented rates | Fabricated history would silently launder the exact silent-rate-1 defect this spec kills |
+| 6 | CTA mechanics | Two-line elimination-entity journal (CTA ↔ Offset), offset excluded from consolidated statements by id; residual line for unposted remainder | A balanced journal cannot absorb a one-sided plug; the full per-account consolidation ledger (SAP parallel currencies) is deferred; offset materialization gives posted/drillable/rolling CTA at a fraction of the cost, with the residual line keeping the report honest |
+| 7 | Historical rates | Per-line `historicalRateLayer` captured by Posted-status trigger; `currency.historicalExchangeRate` demoted to deprecated fallback | Trigger is the only surface all posting paths cross; equity tranches at different rates are the norm, not the exception (IAS 21.23(b)) |
+| 8 | Multi-tenancy (heuristic 1) | New tables carry `companyId`, composite PK `("id","companyId")`, `id('prefix')`, audit columns; `exchangeRateHistory` change is additive on the existing group-scoped table | House convention; rate history stays group-scoped like the chart |
+| 9 | Service shape (heuristic 2) | All new functions in `accounting.service.ts` / models in `accounting.models.ts`, `(client, ...) → {data, error}` | One module service file, never scatter |
+| 10 | RLS (heuristic 3) | Four policies per new table gated on `get_companies_with_employee_permission('accounting_*')`; `exchangeRateHistory` policies already exist | Standard pattern; no deprecated helpers |
+| 11 | Permissions (heuristic 4) | Revaluation run + CTA posting behind `update: "accounting"`; report reads `view: "accounting"` | Matches journal posting and period close/lock precedent |
+| 12 | Forms (heuristic 5) | Revaluation review + layer editor use `ValidatedForm` + zod validators; route actions with `intent` | Standard form pattern |
+| 13 | Module layout (heuristic 6) | Everything under `modules/accounting/` + `routes/x+/accounting+/`; job change in `packages/jobs` | No new module |
+| 14 | Backward compatibility (heuristic 7) | `translateTrialBalance` recreated (its callers are all in this repo and updated together); rate-1 fallback removal is the *point*; `currency.historicalExchangeRate` kept as fallback; revaluation entirely additive | Consolidated numbers change from "silently wrong" to "right or flagged" — called out in acceptance criteria |
+
+## Data Model Changes
+
+One migration wave (`pnpm db:migrate:new fx-consolidation-completeness`, randomized HHMMSS — never `000000`), then `pnpm run generate:types`. Sketches (bare `NUMERIC` per database conventions):
+
+```sql
+-- 1. Quote basis for rate history + honest coverage
+ALTER TABLE "exchangeRateHistory"
+ ADD COLUMN IF NOT EXISTS "baseCurrencyCode" TEXT REFERENCES "currencyCode"("code");
+-- Backfill: set to the group's root-company baseCurrencyCode for any existing rows.
+
+-- 2. New journal sources
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Currency Revaluation';
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Consolidation';
+
+-- 3. Account defaults (nullable → backfill → NOT NULL, idempotent, per 20260630093809 pattern)
+ALTER TABLE "accountDefault"
+ ADD COLUMN IF NOT EXISTS "unrealizedExchangeGainAccount" TEXT,
+ ADD COLUMN IF NOT EXISTS "unrealizedExchangeLossAccount" TEXT,
+ ADD COLUMN IF NOT EXISTS "arRevaluationAccount" TEXT,
+ ADD COLUMN IF NOT EXISTS "apRevaluationAccount" TEXT,
+ ADD COLUMN IF NOT EXISTS "currencyTranslationOffsetAccount" TEXT;
+-- Seed per company group (parents resolved by "isGroup" = TRUE AND name = '<Group Name>',
+-- NEVER by number — lessons rule; NULL parent = error):
+-- 'Unrealized Exchange Gains' (Other Income, next free number near 4120)
+-- 'Unrealized Exchange Losses' (Other Expenses, next free number near 7060)
+-- 'AR Revaluation Adjustment' (Asset, under the Receivables group header)
+-- 'AP Revaluation Adjustment' (Liability, under the Payables group header)
+-- 'Currency Translation Offset' (Equity, isSystem, sibling of 3200)
+-- Backfill accountDefault by resolved account *id*; then SET NOT NULL + FK + indexes.
+
+-- 4. Revaluation run
+CREATE TABLE "currencyRevaluationRun" (
+ "id" TEXT NOT NULL DEFAULT id('crr'),
+ "companyId" TEXT NOT NULL,
+ "accountingPeriodId" TEXT NOT NULL REFERENCES "accountingPeriod"("id"),
+ "rateDate" DATE NOT NULL, -- period end
+ "status" TEXT NOT NULL DEFAULT 'Draft', -- 'Draft' | 'Posted' | 'Voided'
+ "journalId" TEXT REFERENCES "journal"("id"), -- period-end valuation entry
+ "reversingJournalId" TEXT REFERENCES "journal"("id"), -- day-1 auto-reversal
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "currencyRevaluationRun_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "currencyRevaluationRun_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE UNIQUE INDEX "currencyRevaluationRun_one_posted_per_period_idx"
+ ON "currencyRevaluationRun" ("companyId", "accountingPeriodId")
+ WHERE "status" = 'Posted';
+
+CREATE TABLE "currencyRevaluationLine" (
+ "id" TEXT NOT NULL DEFAULT id('crl'),
+ "companyId" TEXT NOT NULL,
+ "runId" TEXT NOT NULL,
+ "exposureType" TEXT NOT NULL, -- 'AR Invoice' | 'AP Invoice' | 'Payment' | 'Memo' | 'Bank'
+ "documentId" TEXT, -- invoice/payment/memo id; NULL for bank GL exposure
+ "accountId" TEXT NOT NULL REFERENCES "account"("id"), -- adjustment or bank GL account
+ "currencyCode" TEXT NOT NULL REFERENCES "currencyCode"("code"),
+ "sourceOpenAmount" NUMERIC NOT NULL, -- document-currency exposure at period end
+ "bookedBaseAmount" NUMERIC NOT NULL,
+ "closingRate" NUMERIC NOT NULL, -- doc units per company-base unit
+ "revaluedBaseAmount" NUMERIC NOT NULL,
+ "gainLossAmount" NUMERIC NOT NULL, -- revalued − booked, signed
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ CONSTRAINT "currencyRevaluationLine_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "currencyRevaluationLine_run_fkey" FOREIGN KEY ("runId", "companyId")
+ REFERENCES "currencyRevaluationRun"("id", "companyId") ON DELETE CASCADE
+);
+-- RLS: four policies each, SELECT via get_companies_with_employee_role(),
+-- writes via get_companies_with_employee_permission('accounting_<action>'), ::text[] casts.
+
+-- 5. Historical-rate layers
+CREATE TABLE "historicalRateLayer" (
+ "id" TEXT NOT NULL DEFAULT id('hrl'),
+ "companyId" TEXT NOT NULL,
+ "accountId" TEXT NOT NULL REFERENCES "account"("id"),
+ "journalLineId" TEXT, -- NULL for manually entered opening layers
+ "effectiveDate" DATE NOT NULL,
+ "localAmount" NUMERIC NOT NULL, -- company-base amount of the movement
+ "rate" NUMERIC, -- company-base units per presentation unit; NULL = uncovered
+ "notes" TEXT,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "historicalRateLayer_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "historicalRateLayer_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+-- Trigger: AFTER UPDATE OF "status" ON "journal" WHEN NEW."status" = 'Posted'
+-- (and AFTER INSERT for journals born Posted) → insert one layer per journalLine
+-- whose account has "consolidatedRate" = 'Historical', rate from exchangeRateHistory
+-- at postingDate (NULL when uncovered).
+
+-- 6. translateTrialBalance: DROP + recreate (fork the NEWEST definition) with
+-- netChange/translatedNetChange/rateSource outputs, divide-to-presentation
+-- cross-rate math, historical-layer valuation, and NO rate-1 fallback.
+-- Rate resolution sketch (rates quoted as units per presentation unit):
+-- v_closing := latest history row ≤ p_period_end for the source currency;
+-- v_average := AVG(history) over [p_period_start, p_period_end];
+-- v_target := latest history row ≤ p_period_end for p_target_currency
+-- (1 when p_target_currency = history baseCurrencyCode);
+-- translated := local × v_target / v_rate_for_account;
+-- Historical accounts: Σ(layer.localAmount × v_target / layer.rate)
+-- + (balance − Σ layer.localAmount) × v_target / v_closing [flagged residual];
+-- fallback chain: average→closing; layers→currency.historicalExchangeRate→closing;
+-- closing→currency.exchangeRate ('spot-fallback')→NULL ('missing'). Never 1.
+
+-- 7. Seed the two periodCloseTaskDefinition system rows per company
+-- ('fx-revaluation', 'fx-rate-coverage'; Auto, Warning) + seed-company for new companies.
+```
+
+## API / Service Changes
+
+`apps/erp/app/modules/accounting/accounting.service.ts` (+ zod in `accounting.models.ts`):
+
+```ts
+// Revaluation
+buildCurrencyRevaluationRun(client, { companyId, periodId, userId }) // compute exposures → Draft run + lines
+postCurrencyRevaluationRun(client, { runId, companyId, userId }) // both journals atomically; enforce next period exists & not Closed
+voidCurrencyRevaluationRun(client, { runId, companyId, userId }) // reverse both journals; run → Voided
+getCurrencyRevaluationRuns(client, companyId, { periodId? })
+
+// Rate coverage + history
+getExchangeRateCoverage(client, companyGroupId, { periodStart, periodEnd })
+// → per-currency { hasClosing, closingStaleDays, hasAverage } — backs 'fx-rate-coverage'
+// getExchangeRateHistory: existing, unchanged
+
+// CTA
+postCurrencyTranslationAdjustment(client, { companyGroupId, eliminationCompanyId, periodEnd, userId })
+// movement = live cumulative CTA − posted CTA balance; 2-line journal on the elimination entity
+
+// Consolidation
+// getConsolidatedBalances: returns { data, cta: { postedBalance, unpostedResidual }, warnings: RateWarning[] }
+// translateCompanyBalances: passes through netChange/translatedNetChange/rateSource
+
+// Historical layers
+get/upsert/deleteHistoricalRateLayer(...) // manual opening layers + rate fixes for NULL-rate captures
+
+// getPeriodCloseReadiness: two new evaluators keyed 'fx-revaluation', 'fx-rate-coverage'
+```
+
+`packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts`: after the currency upsert loop, one `exchangeRateHistory` upsert per (group, currency, today) quoted against the group presentation currency; groups deduplicated across their member integrations; failures logged per group without aborting the loop.
+
+Edge functions: none touched — revaluation and CTA post through the app-side journal services (`source: "accounting"`).
+
+## UI Changes
+
+- **Currency Revaluation** page under `routes/x+/accounting+/` : period picker → exposure preview table (per line: document, currency, source open amount, booked vs revalued base, gain/loss) → Post / Void; linked from the close-checklist task's drill-down.
+- **Close checklist**: the two new Auto tasks render with drill links (revaluation page; rate-coverage detail listing missing currencies/days).
+- **Consolidated balance sheet**: `'3200'` lookups deleted; CTA row sourced from GL by `accountDefault.currencyTranslationAccount` id; offset account suppressed; "Unposted translation adjustment" residual row when non-zero; rate-coverage warning banner (currencies + `rateSource` fallbacks in play).
+- **Translated income statement / trial balance**: switch to `translatedNetChange` for the statement window.
+- **Account settings**: `AccountDefaultsForm` gains the five new selects; historical-layer editor on Historical-rate accounts (list layers, add opening layer, fill NULL rates).
+
+## Acceptance Criteria
+
+Numeric master case — company base USD, EUR invoice of €1,100 posted at rate 1.10 (EUR per USD ⇒ booked base $1,000.00), open at period end 2026-07-31, closing rate 1.05:
+
+- [ ] AR run: revalued base = 1,100 ÷ 1.05 = **$1,047.62**; period-end journal Dr `arRevaluationAccount` 47.62 / Cr `unrealizedExchangeGainAccount` 47.62 dated 2026-07-31; reversal Dr gain / Cr adjustment dated 2026-08-01; both `sourceType 'Currency Revaluation'`, linked via `reversedById`; AR **control account balance unchanged** and AR tie-out RPC still passes.
+- [ ] Same facts as AP: unrealized **loss** 47.62 — Dr `unrealizedExchangeLossAccount` / Cr `apRevaluationAccount`.
+- [ ] EUR bank account with source balance €10,000 booked at $9,090.91: revaluation posts Dr bank GL $432.90 / Cr unrealized gain (10,000 ÷ 1.05 = 9,523.81); bank rec on the account is unaffected (revaluation line has `sourceAmount = 0`).
+- [ ] Second Posted run for the same (company, period) is rejected; Void reverses both journals and permits a re-run; posting is blocked when the next period is Closed.
+- [ ] 'fx-revaluation' auto-check: fails for a period with open FX exposure and no Posted run; passes after posting; passes vacuously for a company with no FX exposure.
+- [ ] Daily job appends one `exchangeRateHistory` row per (group, enabled currency, day) with `baseCurrencyCode` = group presentation currency; re-run same day upserts, no duplicates.
+- [ ] With zero rate coverage, the consolidated balance sheet shows a warning banner naming the uncovered currencies and no figure is produced from an implicit rate 1 (`rateSource` ∈ {'spot-fallback','missing'} surfaces per currency); 'fx-rate-coverage' auto-check fails, and passes once closing + in-period rates exist.
+- [ ] `translateTrialBalance` returns `netChange`/`translatedNetChange`; a EUR subsidiary's translated income statement for July equals July activity ÷ July average rate — not life-to-date.
+- [ ] `postCurrencyTranslationAdjustment` posts the CTA movement on the elimination entity to the account resolved from `accountDefault.currencyTranslationAccount` (grep confirms no `"3200"` literal remains in app code); after posting, the consolidated residual line is ~0 and the CTA account balance rolls into the next period.
+- [ ] Posting equity of €500,000 on a `consolidatedRate = 'Historical'` account at rate 1.25 auto-captures a layer (localAmount = base amount, rate 1.25 basis); translation at a later closing rate 1.05 still values that tranche at its layer rate; a second tranche at a different rate translates independently; residual without a layer falls back to closing with a `rateSource` flag.
+- [ ] Regression: single-currency companies see byte-identical journals and reports (no exposure ⇒ no run; rate(base)=1 ⇒ translation unchanged).
+- [ ] `pnpm run generate:types` then `pnpm exec turbo run typecheck --filter=@carbon/erp --filter=@carbon/jobs` pass.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| As-of-date open-balance reconstruction (invoice balance at period end from settlements) diverges from live view balances | Med | Reuse the settlement-dated derivation the aging/tie-out RPCs use; acceptance test with a post-period-end settlement |
+| `ALTER TYPE ... ADD VALUE` cannot run inside the same transaction as usage | Low | Separate migration file for the enum values, ordered first (existing repo precedent) |
+| Layer-capture trigger adds write-path latency on every posting | Low | Fires only for Historical-rate accounts (rare); simple insert; index on `account.consolidatedRate` predicate |
+| Rate-source API rate limits when appending history per group | Low | One fetch per day already; history append reuses the fetched/cached rates, no extra API calls |
+| CTA offset account confuses users if surfaced | Low | `isSystem`, excluded from consolidated statements by id, named explicitly; docs note it mirrors CTA |
+| Groups whose elimination entity base ≠ presentation currency | Med | Guard in `postCurrencyTranslationAdjustment`: refuse with explicit error (see open question) |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until the unchecked items are answered.
+
+- [x] Auto-reversing vs delta revaluation? — **Auto-reversing** (SAP-style), per readiness roadmap resolution.
+- [x] Direct-on-account vs adjustment-account presentation? — **Adjustment accounts for AR/AP, direct for bank GL** (Design Decision 2).
+- [x] Fabricate rate-history backfill? — **No**; honest NULL + coverage warnings.
+- [x] Keep the rate-1 fallback? — **No**; spot-fallback with flag, then NULL + warning.
+- [x] CTA posting mechanics? — **Two-line elimination-entity journal with excluded offset account**; full consolidation ledger deferred (Design Decision 6).
+- [x] Historical rates per currency or per transaction? — **Per-transaction layers**, trigger-captured; `currency.historicalExchangeRate` demoted to deprecated fallback.
+- [x] Checklist severity for the two new tasks? — **Warning**, hardenable per company via the template.
+- [x] Do all existing company groups have an elimination entity whose base currency equals the group presentation currency (root-company base)? If not, is refusing CTA posting with an error acceptable for v1, or must the journal convert? — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Migration audits all groups and auto-provisions/repairs elimination entities to the group presentation currency; the refuse-with-actionable-error path remains only as a runtime guard.
+- [x] Unapplied-payment exposure reads `payment.totalAmount` — the convention-normalization spec left base-vs-document denomination of that column as its own open question. Confirm its resolution (spec assumes **base** + derived document amount) before implementing the Payment/Memo exposure types. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Adopt whatever #1030 (FX convention normalization) resolves — this spec reads exposure through a shared helper so either convention works; confirm during #1030 execution (dependency noted).
+
+## Changelog
+
+- 2026-07-04: Created from readiness findings SD-4/SD-5 (`2026-07-03-public-company-readiness.md`), research §Pattern 5 (SAP FAGL_FCV/FAGL_FC_TRANS, NetSuite revalue-open-balances + consolidated rate types), and code verification (`exchangeRateHistory` writer absence, `balance-sheet.tsx` '3200' plug, `translateTrialBalance` rate-1 fallbacks). Resolutions baked in per tracking issue crbnos/carbon#1050.
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/2026-07-04-gapless-numbering-legal-series.md b/.ai/specs/2026-07-04-gapless-numbering-legal-series.md
new file mode 100644
index 0000000000..c0c0ae8901
--- /dev/null
+++ b/.ai/specs/2026-07-04-gapless-numbering-legal-series.md
@@ -0,0 +1,262 @@
+# Gapless Numbering & Legal Series
+
+> Status: in-progress
+> Author: Claude (Phase 0 Spec C), for [email protected]
+> Date: 2026-07-04
+> Tracking issue: [crbnos/carbon#1038](https://github.com/crbnos/carbon/issues/1038)
+> Program: `.ai/specs/2026-07-03-public-company-readiness.md` finding **SD-2**; roadmap `.ai/plans/2026-07-03-public-company-readiness-roadmap.md` Phase 0 Spec C
+> Coordinates with: #1047 record-integrity spec (audit coverage + JE export), #1032 document approvals (`.ai/specs/2026-07-04-document-approvals.md`), #1054 e-invoicing (`.ai/specs/2026-07-04-e-invoicing.md`, written in parallel)
+
+## TLDR
+
+Accounting document numbers (journals `JE-`, payments `PAY-`, memos `CR-`/`DR-`, sales invoices, purchase invoices) become **gapless from a per-company cutover date forward**: the final number is assigned **inside the posting transaction** by an atomic, per-company-per-sequence serialized counter, so a failed post leaves no hole and concurrent posts cannot duplicate. Drafts carry no legal number — they display a placeholder derived from the internal id until posted. `sequence` rows for accounting documents become **immutable after first use** (format frozen, counter monotonic, no delete) via a trigger that binds every role, and their changes are audit-logged. A new **`legalSeries`** table (company × country × document type) provides the statutory gapless-series substrate for customer-facing sales invoices and credit memos in EU/LatAm jurisdictions; the e-invoicing spec wires it to documents. Existing documents are **never renumbered** — historical gaps before the cutover date are documented, not rewritten.
+
+## Problem Statement
+
+SD-2: numbering and dating are not audit-grade. Concretely, in today's code:
+
+1. **Gaps by pre-allocation.** Manual journals get `journalEntryId` at *draft creation* (`functions/create/index.ts:2665`); sales/purchase invoices, payments, and memos get their numbers at draft creation too (`apps/erp/app/modules/invoicing/invoicing.service.ts:431,799`, `accounting.service.ts:2068`). Delete the draft — or fail the insert after the standalone `get_next_sequence` RPC has already committed its increment in its own transaction — and the number is consumed forever. FEC/SAF-T validators and audit JE-population procedures test sequential completeness; every hole is an exception to explain.
+2. **Duplicates by race.** Both `functions/shared/get-next-sequence.ts` and the `get_next_sequence` RPC (`20241115101526`) do an unlocked SELECT followed by an UPDATE. Two concurrent posters can read the same `next`, and the second blindly writes the same computed value — **duplicate document numbers under concurrency**, the opposite failure of gapless.
+3. **Rewind → reuse.** The `sequence` table is editable by any `settings_update` user (`updateSequence` in `settings.service.ts:1113` — plain UPDATE, no guard). Rewinding `next` mints duplicates of already-issued numbers; changing `prefix`/`size` silently forks the number space. None of it is audit-logged (`sequence` is absent from `audit.config.ts`).
+4. **No legal series.** EU/LatAm statutory rules require gapless, per-series numbering of *customer-facing* invoices/credit memos (per establishment/country/document type; Portugal adds ATCUD + registered series). Carbon has one flat `salesInvoice` sequence per company and no series concept.
+5. **Backdating is invisible.** `postingDate ≪ createdAt` within an open period is unrestricted and unflagged anywhere an auditor looks.
+
+**Resolved constraints baked in** (program resolutions 2026-07-03, readiness spec Open Questions): forward-only fix — the `JE-%{yyyy}-%{mm}-` format stays and **existing documents are never renumbered** (retroactive renumbering is itself an audit red flag); gapless applies to **all accounting document sequences in one pass** (Brad accepted the recommendation): `journalEntry`, `payment`, `creditMemo`, `debitMemo`, `salesInvoice`, `purchaseInvoice`.
+
+## Proposed Solution
+
+### 1. Posting-time assignment with a draft placeholder
+
+The legal number is born when the document is posted — never before.
+
+- **System-generated journals** (post-receipt, post-shipment, post-sales-invoice, post-purchase-invoice, post-payment, post-memo, post-production-event, issue, close-job, and the SQL posters in `20260630092517`) already allocate inside their posting transaction. They keep that shape and just switch to the atomic allocator (§2) — the sequence increment commits or rolls back with the journal.
+- **Manual journals, payments, memos, sales invoices, purchase invoices** stop allocating at draft creation. The number column becomes NULL-able while Draft (and while `Pending Approval`, per the approvals spec); the posting path (edge function or `postJournalEntry`) calls the allocator inside its transaction, immediately before flipping status.
+- **Draft display**: drafts render `Draft-{last 6 of internal id}` plus the existing status badge, everywhere the number shows today (document lists, detail headers, related-document links, search). Route URLs already use the internal `id`, so no URL changes. Draft PDFs (sales invoice preview) render a `DRAFT` watermark and the placeholder — a legal number never appears on an unposted artifact.
+
+**Why not keep draft-time allocation and re-assign the legal number at post?** Rejected: (a) a re-assigned number means the reference a user already emailed/quoted changes at post — two identities per document is a reconciliation and support hazard; (b) draft-time allocation still burns numbers on deleted/abandoned drafts, so the sequence is *not* gapless and the whole point is lost; (c) statutory series rules define the number as assigned at issuance — before posting there is legally no document. Posting-time + placeholder gives each document exactly one number for life. (Xero's approve-time invoice numbers and SAP's park→post flow are the reference behaviors.)
+
+### 2. Atomic per-company-per-sequence allocation
+
+Replace read-then-write with a **single-statement atomic increment**; the ordinary row lock taken by `UPDATE` is the serialization point (equivalent to `SELECT ... FOR UPDATE` but race-free by construction and one round trip):
+
+```sql
+-- get_next_sequence_atomic(sequence_name text, company_id text) RETURNS text
+-- SECURITY DEFINER, search_path = public; same permission preamble as
+-- get_next_sequence (has_role('employee') / valid API key).
+UPDATE "sequence"
+ SET "next" = "next" + "step",
+ "firstUsedAt" = COALESCE("firstUsedAt", NOW()),
+ "updatedAt" = NOW(), "updatedBy" = 'system'
+ WHERE "table" = sequence_name AND "companyId" = company_id
+ RETURNING "prefix", "suffix", "next", "size" INTO STRICT ...;
+-- format: interpolated prefix || lpad(next, size, '0') || interpolated suffix
+-- (reuses the %{yyyy}/%{mm}/... interpolation from 20241115101526)
+```
+
+- **Gapless semantics**: called only *inside the posting transaction* (Kysely `trx` in edge functions; the plpgsql posters; `postJournalEntry`). Rollback reverts the increment with the document — no gap. The shared TS helper `functions/shared/get-next-sequence.ts` is rewritten to issue this single statement on the caller's `trx`.
+- **Serialization scope**: the lock is one `sequence` row = one company × one document type. Concurrent posts in the same company/type queue behind each other for the remainder of the posting transaction; different companies (or different document types) touch different rows — **zero cross-company contention**. To keep the hold window short, posters allocate as the **last step** before the status flip, after all lines/validation are written.
+- **Advisory-lock key scheme** (documented for any future path that cannot ride the row lock, e.g. multi-document batch posting that must avoid lock-order deadlocks): `pg_advisory_xact_lock(hashtextextended('sequence:' || company_id || ':' || sequence_name, 0))`, taken before the first allocation in the batch. Not used in v1 — the row lock suffices; single allocation per transaction cannot deadlock on it.
+- **Throughput**: measure before/after with the plan's benchmark (N concurrent `post-payment` + `post-sales-invoice` calls, same company vs. spread across companies). Expected cost is the sequence-row lock held for the tail of a posting transaction (~tens of ms). Per-company serialization of posting is acceptable and is exactly what NetSuite/SAP do per numbering range; record the measured numbers in the run log.
+- The **existing `get_next_sequence` RPC** stays for operational sequences (quotes, jobs, POs, fixed assets, …) but gains a guard: it RAISEs for the six accounting sequences ("allocated at posting") so no PostgREST path can burn an accounting number in a standalone transaction.
+- **Monthly prefix, continuous counter**: `%{yyyy}-%{mm}` interpolation is cosmetic labeling of issuance date; the integer never resets (no reset logic exists today — confirmed). Interpolation keeps using allocation wall-clock time, so numbers are issued in strictly chronological order — the property sequential-issuance checks actually test. `JE-2026-07-000124` following `JE-2026-06-000123` is correct and expected.
+
+### 3. `sequence` immutable-after-first-use
+
+New columns: `firstUsedAt` (stamped by the allocator), `isLegalSequence` (true for the six accounting tables), `gaplessFrom` (the per-company cutover stamp, §6). A plain trigger (fires for **every** role — service role and `SECURITY DEFINER` functions included, following the period-close backstop precedent `20260702044133`):
+
+- Once `isLegalSequence AND firstUsedAt IS NOT NULL`: reject any change to `prefix`, `suffix`, `size`, `step`, `table`, `companyId`; reject any decrease of `next` (**rewind→duplicate hole closed**); `next` increases only.
+- DELETE on a used legal sequence is rejected outright.
+- Operational sequences keep today's editability.
+- The sequences settings UI disables format fields for used accounting sequences with explanatory copy; `updateSequence` returns the trigger error as a form error.
+- **Audit**: `sequence` joins `audit.config.ts` coverage via the record-integrity spec (#1047 owns the `audit.config.ts` ask); this spec's acceptance depends on rejected edits *and* successful pre-first-use edits both appearing there. Allocator increments (`updatedBy = 'system'`) are exempted from audit noise by diff config.
+
+### 4. `legalSeries` — statutory series substrate
+
+Per company × country × document type series for **customer-facing** documents (sales invoices, credit memos — not journals; program resolution). This spec ships the table, the allocator, and nullable document columns; series *selection*, issuance rules, ATCUD/hash-chaining, and format rendering are the e-invoicing spec's job (#1054, `.ai/specs/2026-07-04-e-invoicing.md`).
+
+- One series = one independent gapless counter, allocated by `get_next_legal_series_number(series_id, company_id)` — same atomic UPDATE…RETURNING mechanism, same posting-transaction rule, same immutable-after-first-use trigger (format frozen, `next` monotonic, no delete; retirement is `validTo`/`isActive`, never removal).
+- `salesInvoice` and `memo` (per the memo-refactor model) gain nullable `legalSeriesId` + `legalNumber`. Companies with no series configured are unaffected: `invoiceId` (now gapless) remains the document number, `legalNumber` stays NULL.
+- Per-country validation content (which countries *require* a series, registration formats) is e-invoicing scope; this table stores `registrationRef` opaquely.
+
+### 5. Backdating flag
+
+The rule is defined here; the surface lives in the record-integrity spec's JE population export (#1047): a journal is flagged `isBackdated` when `postingDate < (createdAt AT TIME ZONE company tz)::date - 1 day`. Computed in the export query (no stored column); the export adds the boolean plus the day-delta so auditors can filter materiality themselves. No posting-time restriction in this spec — the period-close trigger already bounds how far back a posting can land.
+
+### 6. Cutover — forward-only
+
+Per program resolution: historical gaps are **documented, never repaired**, and nothing is renumbered.
+
+- Migration stamps `sequence."gaplessFrom" = NOW()` on the six accounting sequences for companies that are accounting-active today; for everyone else, the accounting cutover event (#1057) stamps it at activation.
+- `gaplessFrom` is the auditable assertion: "numbers in this sequence are gapless from this timestamp forward; earlier gaps predate the control." The JE export (#1047) includes it per sequence so an FEC/completeness reviewer sees the boundary instead of discovering it.
+- Existing draft documents that already carry numbers keep them (the CHECK constraints allow numbered drafts); only *new* drafts are born number-less.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Assignment moment | Posting-time, inside the posting transaction; drafts carry a placeholder | Only construction that is actually gapless; one number per document for life; rejected draft-time+reassign (two identities, still gaps on deleted drafts) — §1 |
+| 2 | Serialization mechanism | Single-statement atomic `UPDATE … RETURNING` on the sequence row | Race-free by construction (kills the current SELECT-then-UPDATE duplicate race); row lock = per-company-per-type scope; simpler than FOR UPDATE or advisory locks; advisory-lock key scheme documented for future batch posters — §2 |
+| 3 | Scope | All six accounting sequences in one pass (JE, PAY, CR/DR, sales + purchase invoices) | Program resolution (Brad, recommendation accepted); one allocator, one trigger, one cutover — no second migration wave |
+| 4 | History | Forward-only; never renumber; `gaplessFrom` documents the boundary | Program resolution 2026-07-03: retroactive renumbering is itself an audit red flag; `JE-yyyy-mm-` format is not a violation |
+| 5 | Counter reset | No monthly reset; `%{yyyy}-%{mm}` labels issuance date, interpolated at allocation time | Continuous integer is what completeness checks test; chronological issuance order preserved; matches existing behavior (no reset logic exists) |
+| 6 | Draft placeholder | `Draft-{last 6 of internal id}`, `DRAFT` watermark on preview PDFs | Stable, searchable, unmistakably non-legal; URLs already use internal ids so routing is untouched |
+| 7 | Sequence lockdown mechanism | Trigger (all roles), not RLS | RLS is role-scoped and demonstrably leaky (MW-1 precedent); trigger binds service role and SECURITY DEFINER posters; period-close backstop precedent |
+| 8 | `legalSeries` write permission | `accounting_update` (not `settings_update`) | SD-2's complaint is exactly that settings users control legal numbering; statutory series are an accounting control surface |
+| 9 | Multi-tenancy (H1) | `legalSeries` has `companyId`, composite PK `("id","companyId")`, `id('ls')`; `sequence` keeps its existing shape (columns added only) | Convention; altering `sequence`'s PK is out of scope |
+| 10 | Service shape (H2) | New/changed functions in existing `settings.service.ts` (sequences) and `sales`/`invoicing` services (series CRUD); `client` first, `{data,error}`, never throw | Convention; no new service files needed beyond the module rule |
+| 11 | RLS (H3) | `legalSeries`: 4 policies — SELECT `get_companies_with_employee_role()`, writes `get_companies_with_employee_permission('accounting_*')` | `.ai/rules/conventions-database.md`; trigger provides the immutability layer RLS cannot |
+| 12 | Permissions (H4) | Series routes `requirePermissions({ view: "accounting" })` / `{ update: "accounting" }` | Decision 8 |
+| 13 | Forms (H5) | `LegalSeriesForm` = ValidatedForm + zod validator + route action, per conventions; sequence form gains disabled-state handling | Convention |
+| 14 | Module layout (H6) | Series models/service in `modules/accounting` (`accounting.models.ts` / `accounting.service.ts`); no new module | One service/models file per module rule |
+| 15 | Backward compat (H7) | Additive schema; NOT NULL relaxed only where drafts need it, backstopped by CHECKs; posting edge functions change in one coordinated PR wave (FX-spec precedent); MCP/API create-document tools return the placeholder until post | FROZEN surfaces untouched; existing numbers byte-for-byte stable (acceptance-tested) |
+
+## Data Model Changes
+
+```sql
+-- 1) sequence hardening
+ALTER TABLE "sequence"
+ ADD COLUMN "isLegalSequence" BOOLEAN NOT NULL DEFAULT false,
+ ADD COLUMN "firstUsedAt" TIMESTAMP WITH TIME ZONE,
+ ADD COLUMN "gaplessFrom" TIMESTAMP WITH TIME ZONE;
+
+UPDATE "sequence" SET "isLegalSequence" = true
+WHERE "table" IN ('journalEntry','payment','creditMemo','debitMemo',
+ 'salesInvoice','purchaseInvoice');
+-- gaplessFrom stamped now for accounting-active companies; else at cutover (#1057)
+
+CREATE OR REPLACE FUNCTION "sequenceImmutabilityCheck"() RETURNS TRIGGER AS $$
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ IF OLD."isLegalSequence" AND OLD."firstUsedAt" IS NOT NULL THEN
+ RAISE EXCEPTION 'Used accounting sequences cannot be deleted';
+ END IF;
+ RETURN OLD;
+ END IF;
+ IF OLD."isLegalSequence" AND OLD."firstUsedAt" IS NOT NULL THEN
+ IF NEW."prefix" IS DISTINCT FROM OLD."prefix"
+ OR NEW."suffix" IS DISTINCT FROM OLD."suffix"
+ OR NEW."size" IS DISTINCT FROM OLD."size"
+ OR NEW."step" IS DISTINCT FROM OLD."step"
+ OR NEW."table" IS DISTINCT FROM OLD."table"
+ OR NEW."companyId" IS DISTINCT FROM OLD."companyId" THEN
+ RAISE EXCEPTION 'Sequence format is immutable after first use';
+ END IF;
+ IF NEW."next" < OLD."next" THEN
+ RAISE EXCEPTION 'Sequence cannot be rewound (next % -> %)', OLD."next", NEW."next";
+ END IF;
+ END IF;
+ RETURN NEW;
+END; $$ LANGUAGE plpgsql;
+CREATE TRIGGER "sequenceImmutability" BEFORE UPDATE OR DELETE ON "sequence"
+ FOR EACH ROW EXECUTE FUNCTION "sequenceImmutabilityCheck"();
+
+-- 2) atomic allocators: get_next_sequence_atomic(text, text) per §2;
+-- get_next_sequence gains: IF sequence is legal THEN RAISE 'allocated at posting'.
+
+-- 3) drafts carry no number (existing numbered drafts remain valid)
+ALTER TABLE "journal" ALTER COLUMN "journalEntryId" DROP NOT NULL;
+ALTER TABLE "journal" ADD CONSTRAINT "journal_posted_requires_number"
+ CHECK ("status" = 'Draft' OR "journalEntryId" IS NOT NULL); -- approvals spec adds its parked status here
+CREATE UNIQUE INDEX "journal_journalEntryId_key"
+ ON "journal" ("companyId","journalEntryId") WHERE "journalEntryId" IS NOT NULL;
+-- payment.paymentId, memo id columns, salesInvoice.invoiceId, purchaseInvoice.invoiceId:
+-- same DROP NOT NULL + status CHECK (number required to leave Draft) + partial unique index.
+
+-- 4) legal series substrate
+CREATE TABLE "legalSeries" (
+ "id" TEXT NOT NULL DEFAULT id('ls'),
+ "companyId" TEXT NOT NULL,
+ "countryCode" TEXT NOT NULL, -- ISO 3166-1 alpha-2
+ "documentType" TEXT NOT NULL, -- 'salesInvoice' | 'creditMemo' (CHECK)
+ "code" TEXT NOT NULL, -- series code, e.g. 'FT2026A'
+ "name" TEXT NOT NULL,
+ "prefix" TEXT NOT NULL,
+ "size" INTEGER NOT NULL DEFAULT 6 CHECK ("size" >= 1),
+ "next" INTEGER NOT NULL DEFAULT 0 CHECK ("next" >= 0),
+ "validFrom" DATE NOT NULL,
+ "validTo" DATE,
+ "isDefault" BOOLEAN NOT NULL DEFAULT false,
+ "isActive" BOOLEAN NOT NULL DEFAULT true,
+ "firstUsedAt" TIMESTAMP WITH TIME ZONE,
+ "registrationRef" TEXT, -- e.g. PT ATCUD validation code (opaque here)
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "legalSeries_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "legalSeries_unique" UNIQUE ("companyId","countryCode","documentType","code"),
+ CONSTRAINT "legalSeries_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE UNIQUE INDEX "legalSeries_default_key" ON "legalSeries"
+ ("companyId","countryCode","documentType") WHERE "isDefault" AND "isActive";
+ALTER TABLE "legalSeries" ENABLE ROW LEVEL SECURITY;
+-- SELECT: get_companies_with_employee_role(); INSERT/UPDATE/DELETE:
+-- get_companies_with_employee_permission('accounting_create'/'_update'/'_delete')::text[]
+-- Same immutability trigger family: format frozen + next monotonic + no delete after firstUsedAt.
+
+ALTER TABLE "salesInvoice" ADD COLUMN "legalSeriesId" TEXT, ADD COLUMN "legalNumber" TEXT;
+ALTER TABLE "memo" ADD COLUMN "legalSeriesId" TEXT, ADD COLUMN "legalNumber" TEXT;
+CREATE UNIQUE INDEX "salesInvoice_legalNumber_key"
+ ON "salesInvoice" ("companyId","legalSeriesId","legalNumber") WHERE "legalNumber" IS NOT NULL;
+-- get_next_legal_series_number(series_id, company_id): atomic UPDATE…RETURNING, §4.
+```
+
+`pnpm run generate:types` after the migration, before typechecking.
+
+## API / Service Changes
+
+- `functions/shared/get-next-sequence.ts` → single-statement atomic increment on the caller's `trx` (same signature; all ten edge-function call sites unchanged except moving the call to just before the status flip where it isn't already).
+- `create/index.ts` `journalEntry` case: stop allocating; insert Draft with NULL `journalEntryId`. Same for draft-creation paths of payments/memos (`accounting.service.ts`) and sales/purchase invoices (`invoicing.service.ts` — drop the `get_next_sequence` RPC calls).
+- Posting paths (`post-payment`, `post-memo`, `post-sales-invoice`, `post-purchase-invoice`, `postJournalEntry`, and void/reverse flows which mint *new* journal numbers) allocate in-transaction via the atomic helper/RPC. Void/reversal documents get fresh numbers as today — never reuse.
+- `get_next_sequence` RPC: RAISE on legal sequences; unchanged for operational ones.
+- `updateSequence` surfaces the trigger error; sequence loader returns `firstUsedAt`/`isLegalSequence` for UI disabling.
+- New in `accounting.models.ts`/`accounting.service.ts`: `legalSeriesValidator`, `getLegalSeries`, `getLegalSeriesList`, `upsertLegalSeries` (deactivate-only after use), barrel-exported.
+- Audit coverage for `sequence` + `legalSeries` and the JE export's `isBackdated` column land via the record-integrity spec (#1047); this spec's migration must merge before or with its audit-config PR.
+
+## UI Changes
+
+- Sequences settings page: format fields disabled once a legal sequence is used ("locked after first use" copy); `next` field hidden for legal sequences.
+- New **Legal Series** section under accounting settings: table + `LegalSeriesForm` (country, document type, code, prefix, size, validity, default toggle); used series show frozen format.
+- Draft placeholder rendering (`Draft-{id6}`) in journal/payment/memo/invoice lists, detail headers, and document-reference links; `DRAFT` watermark on unposted sales-invoice PDFs.
+- No changes to posted-document UI: numbers appear exactly where they do today, just later in the lifecycle.
+
+## Acceptance Criteria
+
+- [ ] **No gap on failure**: a posting transaction forced to fail *after* allocation (simulated error before COMMIT) rolls back the increment; the next successful post of the same document type in that company receives the number the failed attempt would have had.
+- [ ] **Concurrency, same company**: N parallel posts of the same document type produce N distinct, consecutive numbers with no duplicates and no gaps (the SELECT-then-UPDATE duplicate race is demonstrably dead — regression test at the allocator level).
+- [ ] **Concurrency, cross-company**: parallel posts in different companies show no lock contention (benchmark recorded in the run log; per-company serialization cost measured and documented).
+- [ ] **Sequence lockdown**: after first use, updating `prefix`/`suffix`/`size`/`step`, rewinding `next`, or deleting an accounting sequence is rejected for every role including service role; the rejected attempt and any permitted pre-first-use edit both appear in the audit log (with #1047's coverage) with actor and before/after.
+- [ ] **Draft lifecycle**: a new manual JE/payment/memo/invoice draft has a NULL number and renders the `Draft-{id6}` placeholder; posting assigns the number in-transaction; the CHECK constraint makes a number-less non-Draft row impossible; pre-existing numbered drafts still post keeping their original numbers.
+- [ ] **History untouched**: after migration, every existing document's number is byte-for-byte identical; `gaplessFrom` is stamped on the six sequences of accounting-active companies.
+- [ ] **Legal series**: allocation from a series is gapless per series under the same failure/concurrency tests; a second active default series for the same company+country+type is rejected; a used series' format is frozen and it cannot be deleted.
+- [ ] **RPC guard**: `get_next_sequence` via PostgREST refuses the six accounting sequences; operational sequences (e.g. `job`, `purchaseOrder`) behave exactly as before.
+- [ ] **Backdating**: the JE export (#1047) flags a journal posted with `postingDate` more than one day before `createdAt` and shows the day delta.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Per-company serialization slows high-volume posting | Med | Lock scope is company × document type only; allocate last in the transaction; benchmark in acceptance; advisory-lock scheme documented for future batch posters |
+| A missed writer keeps draft-time allocation (10+ edge functions + app services touch sequences) | High | Grep-enumerable call sites (`getNextSequence`/`get_next_sequence`); the RPC guard turns any missed accounting-path caller into a loud failure, not a silent gap |
+| Draft placeholder confuses users who reference draft numbers today | Med | Placeholder is stable and searchable; release note; posted behavior unchanged |
+| Interplay with approvals spec (#1032): parked documents must stay number-less | Med | CHECK constraints written status-aware; approvals spec adds `Pending Approval` to the Draft side of each CHECK — coordinated in that PR |
+| External sync (Xero) or MCP tools read the number pre-post | Med | Inventory readers of the five number columns; syncs already operate on posted documents; MCP create tools return the placeholder |
+| `NOT NULL` relaxation weakens integrity if CHECKs are wrong | Low | Partial unique indexes + status CHECKs tested; DB-level, not app-level |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] **Renumber history to close existing gaps?** — Resolved (program, 2026-07-03): **No — forward-only.** Existing documents are never renumbered; `JE-yyyy-mm-` format stays; historical gaps documented via per-company `gaplessFrom` cutover. (Readiness spec, Open Question "Gapless numbering domain".)
+- [x] **Which sequences go gapless?** — Resolved (Brad, recommendation accepted): **all accounting document sequences in one pass** — journals, payments, credit/debit memos, sales invoices, purchase invoices. (Roadmap Phase 0 Spec C; this spec's Decision 3.)
+- [x] **Draft numbering model?** — Resolved (program direction for this spec): **posting-time assignment with a draft placeholder**, not draft-time allocation with re-assignment at post; justification and UI implications in §1/Decision 1/6.
+- [x] **Do journals need statutory legal series?** — Resolved (program, 2026-07-03): no — legal series apply to customer-facing sales invoices/credit memos only; journals need gaplessness, not series. `legalSeries` is the e-invoicing substrate and is wired to documents by #1054.
+- [x] **Where do the JE export and backdating flag live?** — Resolved: the export (and therefore the `isBackdated` surface) belongs to the record-integrity spec (#1047); this spec defines the rule only (§5).
+
+No new blocking questions — every remaining choice is recorded in Design Decisions.
+
+## Changelog
+
+- 2026-07-04: Created (Phase 0 Spec C, tracking crbnos/carbon#1038) with all program resolutions baked in; coordinates with #1047 (audit coverage, JE export), #1032 (parked-status CHECKs), #1054 (legal-series wiring).
diff --git a/.ai/specs/2026-07-04-integration-surface.md b/.ai/specs/2026-07-04-integration-surface.md
new file mode 100644
index 0000000000..4ae205f88f
--- /dev/null
+++ b/.ai/specs/2026-07-04-integration-surface.md
@@ -0,0 +1,255 @@
+# Integration Surface: TB API, JE Export/Import APIs, Accounting Webhooks
+
+> Status: in-progress (open questions resolved pre-writing; Brad: "use our current stuff" — ride the existing API-key/MCP infrastructure, no new gateway)
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1059
+> Research: `.ai/research/public-company-compliance.md` (§Ecosystem — integration surfaces the ERP must expose)
+> Parent: `.ai/specs/2026-07-03-public-company-readiness.md` (finding GAP-E1, Phase 4)
+> Siblings (parallel, referenced): `.ai/specs/2026-07-04-document-approvals.md` (JE approval engine — imported JEs route through it), `.ai/specs/2026-07-04-record-integrity-audit-hardening.md` (JE population export definition + `journal.bookId` book dimension), `.ai/specs/2026-07-02-period-closing.md` (period `closeStatus` lifecycle the import gate and webhooks consume)
+
+## TLDR
+
+Public-company customers surround their ERP with bolt-ons that Carbon will never build (research §Ecosystem: even NetSuite doesn't): BlackLine/FloQast pull the trial balance on a schedule to certify reconciliations, Workiva and FP&A tools (Adaptive/Pigment) pull TB + dimensions, auditors pull the full JE population, and Carta/payroll/lease/provision/expense tools (Carta, ADP, FinQuery, OneSource, Ramp) *push* summarized journal entries in. This spec exposes those four feeds on the existing infrastructure — the `apiKey` table (hashed keys, JSONB scopes, Postgres rate limiting, all already enforced by `requirePermissions`), the module service layer the MCP direct-executor already wraps, and the `eventSystemSubscription` → PGMQ → Inngest webhook pipeline: (1) a **trial balance API** sliceable by company/book/period/date-range/dimension with stable account numbers; (2) a **streaming JE population export API** (the record-integrity spec's export, programmatic); (3) a **controlled JE import API** that is validated, approval-workflow-aware (an active JE rule parks imports in `Pending Approval`), period-status-aware (Closed rejected; Locked requires `accounting_create`), idempotent, and audit-stamped with the API-key principal; (4) **webhooks** for journal posted/reversed, period locked/closed/reopened, and approval decisions, with HMAC-signed payloads and Inngest retries. No new auth system, no new gateway, no new queue — two small tables (idempotency keys, webhook topic registrations layered on `eventSystemSubscription`) and a handful of `api+/v1+/` routes.
+
+## Problem Statement
+
+- There is **no external read surface for balances**: `getTrialBalance` (`apps/erp/app/modules/accounting/accounting.service.ts:122`) wraps the `trialBalance` RPC but is only reachable via session-authenticated UI loaders or the MCP protocol — BlackLine/FloQast/Workiva connectors speak plain REST + API key on a cron, not MCP.
+- There is **no JE population export** an auditor's Excel/IDEA tooling can consume programmatically; the record-integrity sibling spec defines the export columns and UI, but bolt-ons need it as an endpoint with no row caps.
+- There is **no way for Carta/payroll/provision/lease tools to land JEs** except a human rekeying them. `createJournalEntry`/`saveJournalEntryWithLines`/`postJournalEntry` exist but nothing composes them behind validation, idempotency, the approval gate (sibling spec), or the period gate (period-closing spec). An unvalidated import path would be a SOX control bypass — the whole point of the approvals spec.
+- There are **no outbound events** for "journal posted" / "period closed" — FloQast polls for close status; BlackLine wants to know when the period locks. The event system (`.ai/rules/event-system.md`) has a WEBHOOK handler with retries and idempotency, but no accounting tables have event triggers attached, no public registration surface exists, and payloads are unsigned raw row diffs.
+- API keys already carry `accounting_view`/`accounting_create`/`accounting_update`/`accounting_delete` scopes (`20260219162954_api-key-scopes-rate-limits.sql:121`) and `requirePermissions` (`packages/auth/src/services/auth.server.ts:191-260`) already enforces key hash, expiry, per-key rate limits, and scope→permission mapping — the auth substrate is done; nothing accounting-shaped uses it.
+
+## Proposed Solution
+
+### Surface overview
+
+New route namespace `apps/erp/app/routes/api+/v1+/` (flat routes), all authenticated by the existing `requirePermissions(request, {...})` which transparently accepts either a session or a `carbon-key` header. REST/JSON, versioned in the path so the MCP surface and internal loaders stay untouched.
+
+| Endpoint | Method | Scope required | Purpose |
+|---|---|---|---|
+| `/api/v1/accounting/trial-balance` | GET | `accounting_view` | TB by company/book/period or date range, dimension filter/group-by, paginated |
+| `/api/v1/accounting/journal-lines/export` | GET | `accounting_view` | Streaming full-population JE line export (CSV or NDJSON) |
+| `/api/v1/accounting/journal-entries` | POST | `accounting_create` | Controlled JE import — single or batch, idempotent, approval- and period-aware |
+| `/api/v1/accounting/journal-entries/:id` | GET | `accounting_view` | Poll an imported entry's status (Draft / Pending Approval / Posted / Rejected) |
+| `/api/v1/webhooks` | GET/POST | `settings_view`/`settings_update` | List/register webhook endpoints for accounting topics |
+| `/api/v1/webhooks/:id` | DELETE | `settings_update` | Deactivate a webhook registration |
+| `/api/v1/openapi.json` | GET | public (rate-limited) | OpenAPI 3.1 document for the endpoints above |
+
+### 1. Trial balance API
+
+Extends `getTrialBalance` / the `trialBalance` RPC (already being widened by the financial-reporting spec to four-column opening/debits/credits/closing) with optional `p_book_id` and dimension parameters, then exposes it:
+
+```
+GET /api/v1/accounting/trial-balance
+ ?periodId=<accountingPeriodId> -- OR startDate/endDate (ISO); periodId wins
+ &bookId=<bookId> -- default: primary book (journal.bookId, record-integrity spec)
+ &dimension=<dimensionId>:<valueId> -- repeatable; filters lines carrying that journalLineDimension
+ &groupBy=dimension:<dimensionId> -- optional: one row per (account, dimensionValue)
+ &cursor=<opaque>&limit=500 -- keyset pagination on account.number, max 1000
+```
+
+Response rows carry **stable identifiers**: `accountNumber` (the mapping key every bolt-on stores), `accountId`, `accountName`, `class`, `openingBalance`, `debits`, `credits`, `closingBalance`, `currencyCode` (company base), plus `dimensionValueId`/`dimensionValueName` when grouped. Envelope: `{ data, meta: { companyId, bookId, periodId|dateRange, generatedAt, nextCursor } }`. Balances reflect **Posted journals only** (the financial-reporting spec's posted-only default), so an extract pulled mid-approval-cycle never moves retroactively except by posting — which webhooks announce.
+
+### 2. JE population export API
+
+Programmatic form of the record-integrity spec's export — same column set (that spec owns the canonical list: entry/line ids, gapless number, book, period, posting/created dates, account number+name, debit/credit, currency + source amounts, dimensions, source document type/id, preparer, approver, approval timestamps, reversal linkage), same underlying query, different transport:
+
+```
+GET /api/v1/accounting/journal-lines/export
+ ?periodId=... | startDate=...&endDate=... -- required (bounded extracts)
+ &bookId=...&source=...&status=Posted -- filters; status defaults to Posted
+ &format=csv|ndjson -- default csv
+```
+
+Implementation: a `ReadableStream` response (React Router loader returning a streamed `Response`) over a Kysely cursor query ordered by journal number — **no row cap, no pagination**; the research is explicit that auditors need the full population flat. `Content-Disposition` filename embeds company/period/book. Rate-limit note: one export request = one unit against the key's window regardless of row count; a long-running stream holds no DB transaction (cursor batches of 5k).
+
+### 3. Controlled JE import API
+
+The landing path for Carta SBC entries, payroll summaries, FinQuery lease JEs, and provision adjustments. Composes existing service functions — `createJournalEntry` → `saveJournalEntryWithLines` → the approval-aware posting entry point that the document-approvals spec installs in the service layer ("for JEs also the service entry point so the MCP path is covered" — this API is exactly that second consumer).
+
+```jsonc
+POST /api/v1/accounting/journal-entries
+Idempotency-Key: <caller-chosen, per request> // header, required
+{
+ "entries": [ // 1..100 per request
+ {
+ "externalId": "carta-sbc-2026-06", // caller's id, echoed back, indexed
+ "postingDate": "2026-06-30",
+ "description": "June SBC expense per Carta",
+ "bookId": null, // default primary book
+ "autoSubmit": true, // default true: submit for posting after create
+ "lines": [
+ { "accountNumber": "6200", "description": "SBC expense", "debit": 41250.00, "credit": 0,
+ "dimensions": { "dep": "eng" } }, // dimensionId|code : valueId|code
+ { "accountNumber": "3150", "debit": 0, "credit": 41250.00 }
+ ]
+ }
+ ]
+}
+```
+
+**Validation (per entry, all-or-nothing within the entry, entries independent):** lines balance to the cent; every `accountNumber` resolves to an active, direct-posting account in the company's chart; every dimension key/value resolves to an active `dimension`/`dimensionValue`; amounts non-negative with exactly one of debit/credit per line; ≤ 500 lines per entry.
+
+**Period gate:** `postingDate`'s period `closeStatus` is checked via the period-closing spec's service gate — `Closed` → entry rejected (`422 PERIOD_CLOSED`); `Locked` → allowed only because the key carries `accounting_create` (the API principal *is* an accounting actor — mirrors the Locked-period rule for accounting users); `Open` → allowed. The DB trigger backstop from the period-closing spec catches anything this layer misses.
+
+**Approval gate:** with `autoSubmit`, the entry is created as Draft and then submitted through `isApprovalRequired('journalEntry', companyId, baseAmount)`. An active rule matching the amount → status `Pending Approval`, an `approvalRequest` is created, approvers are notified via the existing `ApprovalRequested` event, and the per-entry result reports `status: "Pending Approval"` with `approvalRequestId` — the integration polls `GET .../journal-entries/:id` or subscribes to the `journal_entry.posted` webhook. No matching rule → posts immediately (`status: "Posted"`, journal number returned). `autoSubmit: false` → parks at Draft for human review.
+
+**Idempotency:** the `Idempotency-Key` header is scoped `(companyId, apiKeyId, key)`. First request persists the request-body hash and, on completion, the full per-entry results. Replay with the same key + same body hash → the **stored original response** (200, `replayed: true` in meta) — no new journals, ever. Same key + different body → `409 IDEMPOTENCY_KEY_REUSED`. Keys expire after 30 days. A concurrent duplicate (row exists, response not yet stored) → `409 IDEMPOTENCY_KEY_IN_FLIGHT` with Retry-After.
+
+**Audit stamping:** `createdBy`/`updatedBy` = the key's `createdBy` user (existing `requirePermissions` behavior — the executor identity), and the journal rows carry `externalId`, `sourceSystem` (from the key's name), and `sourceApiKeyId` so the JE export and audit log distinguish "landed via integration X" from "keyed by the user who happens to own the key". The record-integrity spec's audit coverage picks these up with no extra work.
+
+**Batch response:** `207`-style per-entry results — `{ index, externalId, journalEntryId, status, journalNumber?, approvalRequestId?, errors? }`. One invalid entry never blocks its siblings.
+
+### 4. Webhooks
+
+Rides the event system end to end: registration creates `eventSystemSubscription` rows via the existing `create_event_system_subscription` RPC; delivery is the existing PGMQ → Inngest `event-handler-webhook` function (already: 3 retries with backoff, `idempotency: msgId`, per-record concurrency keys). Three additions: **topic semantics**, **payload curation**, and **signing**.
+
+**Topic catalog (v1):**
+
+| Topic | Table / trigger | Filter |
+|---|---|---|
+| `journal_entry.posted` | `journal` UPDATE | `status` → `Posted` |
+| `journal_entry.reversed` | `journal` UPDATE | `status` → `Reversed` |
+| `period.locked` / `period.closed` / `period.reopened` | `accountingPeriod` UPDATE | `closeStatus` transition |
+| `approval.decided` | `approvalRequest` UPDATE | `status` → `Approved`/`Rejected` |
+
+Migration work: `attach_event_trigger('journal', ...)`, `attach_event_trigger('accountingPeriod', ...)`, `attach_event_trigger('approvalRequest', ...)` — none of these tables have async event triggers today (the rule's trigger inventory covers sales/purchasing/etc. only).
+
+**Registration:** `POST /api/v1/webhooks { url, topics: ["journal_entry.posted", ...], description? }` → creates one `webhookRegistration` row (secret generated server-side, returned **once**) plus one `eventSystemSubscription` per topic (handlerType `WEBHOOK`, `config = { url, registrationId, topic }`), named `webhook:<registrationId>:<topic>` for clean teardown via `delete_event_system_subscriptions_by_name`.
+
+**Delivery:** the webhook Inngest handler learns a curated envelope when `config.registrationId` is present (legacy raw-diff behavior preserved otherwise): `{ id: msgId, topic, companyId, occurredAt, data }` where `data` is a per-topic projection (journal id/number/postingDate/book/total/status + externalId; period id/fiscalYear/periodNumber/closeStatus; approval documentType/documentId/decision/decisionBy) — never raw row diffs. Headers: `carbon-webhook-id`, `carbon-webhook-timestamp`, `carbon-signature: v1=<hex HMAC-SHA256(secret, timestamp + "." + body)>`. Consumers verify signature + reject stale timestamps (replay window 5 min). Retries: Inngest's existing 3 attempts; deliveries that exhaust retries set `lastFailureAt`/`failureCount` on the registration, and 20 consecutive failures auto-deactivate it (audit-logged).
+
+### 5. Scopes, rate limits, docs, MCP
+
+- **Scopes:** no new scope values — `accounting_view` covers TB + export + status polling, `accounting_create` covers import, `settings_view`/`settings_update` cover webhook registration (webhook config is company plumbing, not accounting data). The API-keys settings UI already lets admins grant these per key.
+- **Rate limits:** existing per-key `rateLimit`/`rateLimitWindow` columns + `check_api_key_rate_limit` apply unchanged (default 1000/h). Guidance shipped in docs: TB pollers ≤ hourly; use webhooks instead of polling; export counts as one request. The unauthenticated `openapi.json` route reuses the `docs.ts` Redis sliding-window pattern (20/h/IP).
+- **OpenAPI docs:** `/api/v1/openapi.json` serves a hand-maintained OpenAPI 3.1 document (checked into the repo next to the routes; zod validators are the source of truth for shapes — schemas generated from the same `accounting.models.ts` validators via `zod-to-json-schema`, already a transitive dependency). The existing `/api/docs` (PostgREST swagger) is unrelated and untouched.
+- **MCP:** the direct-executor already exposes `accounting.*` service functions, so `accounting_getTrialBalance` and `accounting_getJournalEntries` gain book/dimension parameters for free when the service signatures grow. **Added:** one new service function `importJournalEntries` (the same function the REST route calls — validation, period gate, approval submission, per-entry results) becomes an MCP tool with `createdBy` auth-field enrichment via `tool-metadata.json`. **Reused, not duplicated:** everything else. Raw `postJournalEntry` stays MCP-blocked-list material once the approvals spec lands its gate (that spec owns the entry-point wiring).
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|---|---|---|
+| 1 | Multi-tenancy (heuristic 1) | Both new tables: `companyId`, composite PK `("id","companyId")`, `id()` prefixes, audit columns | House convention; idempotency uniqueness additionally scoped by `apiKeyId` so two integrations can't collide on key names |
+| 2 | Service shape (heuristic 2) | New functions (`getTrialBalanceV2` params fold into `getTrialBalance`, `getJournalLinesExportCursor`, `importJournalEntries`, `upsertWebhookRegistration`, `deleteWebhookRegistration`) live in `accounting.service.ts`/`accounting.models.ts`; webhook registration helpers wrap the existing event-system RPCs | One service file per module; import composes existing create/save/post functions rather than re-implementing posting |
+| 3 | RLS (heuristic 3) | `apiIdempotencyKey`: no direct client access (service-role only — SELECT policy `false`); `webhookRegistration`: `settings` permission policies; secrets column excluded from any view | Idempotency rows are infrastructure, not user data; webhook secrets must never round-trip to the browser |
+| 4 | Permissions (heuristic 4) | Routes call `requirePermissions` with `view:/create: "accounting"` or `settings` — the *same* helper sessions use; scope mapping `{permission}_{action}` is already implemented in `auth.server.ts` | Zero new auth code paths; one enforcement point for expiry, rate limit, and scope |
+| 5 | Forms (heuristic 5) | No new forms in v1 — API-key management UI exists; webhook registrations get a read-only list on the API-keys settings page (registration itself is API-first, matching how integrations onboard) | Bolt-on vendors register programmatically; a create-form is a fast follow if humans want it |
+| 6 | Module layout (heuristic 6) | Routes in `routes/api+/v1+/`; logic in `modules/accounting/`; webhook handler changes in `packages/jobs/src/inngest/functions/events/webhook.ts` | Versioned public namespace keeps internal `api+` loaders and MCP untouched |
+| 7 | Backward compatibility (heuristic 7) | Everything additive: new routes, optional RPC params, new event triggers, envelope-vs-legacy branch in the webhook handler keyed on `config.registrationId` | Existing eventSystemSubscription WEBHOOK users (raw diffs, custom headers) keep exact behavior |
+| 8 | No new gateway/auth | Ride `apiKey` + `requirePermissions` + PostgREST-independent REST routes | Brad's resolution: "use our current stuff"; the substrate already does hashing, scopes, rate limits, expiry |
+| 9 | Import lands as real drafts, not a staging table | Entries are ordinary `journal` rows from creation; approval/period gates are the same ones humans hit | One posting pipeline = one control to audit (the entire point of GAP-E1's "controlled" import); a staging table would fork the SOX surface |
+| 10 | Webhooks over event system, not a new dispatcher | Topics = named `eventSystemSubscription` rows; delivery = existing Inngest fn | Retries, idempotency, and per-record ordering already exist; only signing + payload curation are genuinely new |
+| 11 | Stable account identifier = `accountNumber` | Import addresses accounts by number; TB returns number first | Bolt-on mapping tables store account numbers (BlackLine/FloQast convention); internal ids leak nothing useful and break on COA re-import |
+
+## Data Model Changes
+
+```sql
+-- Idempotency keys for the import API (service-role only; no client RLS access)
+CREATE TABLE "apiIdempotencyKey" (
+ "id" TEXT NOT NULL DEFAULT id('idem'),
+ "companyId" TEXT NOT NULL,
+ "apiKeyId" TEXT NOT NULL REFERENCES "apiKey"("id") ON DELETE CASCADE,
+ "idempotencyKey" TEXT NOT NULL,
+ "requestHash" TEXT NOT NULL, -- sha256 of canonicalized body
+ "status" TEXT NOT NULL DEFAULT 'in_flight' CHECK ("status" IN ('in_flight','completed')),
+ "responseStatus" INTEGER,
+ "responseBody" JSONB, -- stored per-entry results, replayed verbatim
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "expiresAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() + INTERVAL '30 days',
+ CONSTRAINT "apiIdempotencyKey_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "apiIdempotencyKey_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "apiIdempotencyKey_unique" UNIQUE ("companyId", "apiKeyId", "idempotencyKey")
+);
+ALTER TABLE "apiIdempotencyKey" ENABLE ROW LEVEL SECURITY; -- no policies: service-role only
+
+-- Webhook endpoint registrations (topic fan-out lives in eventSystemSubscription)
+CREATE TABLE "webhookRegistration" (
+ "id" TEXT NOT NULL DEFAULT id('wh'),
+ "companyId" TEXT NOT NULL,
+ "url" TEXT NOT NULL,
+ "description" TEXT,
+ "secret" TEXT NOT NULL, -- HMAC secret; returned once at creation
+ "topics" TEXT[] NOT NULL,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "failureCount" INTEGER NOT NULL DEFAULT 0,
+ "lastFailureAt" TIMESTAMP WITH TIME ZONE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "webhookRegistration_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "webhookRegistration_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+ALTER TABLE "webhookRegistration" ENABLE ROW LEVEL SECURITY;
+-- SELECT/INSERT/UPDATE/DELETE policies gated on settings_view / settings_update
+-- via the standard has_company_permission pattern; "secret" never selected client-side.
+
+-- Journal source columns (coordinate with record-integrity spec — additive, IF NOT EXISTS)
+ALTER TABLE "journal"
+ ADD COLUMN IF NOT EXISTS "externalId" TEXT,
+ ADD COLUMN IF NOT EXISTS "sourceSystem" TEXT,
+ ADD COLUMN IF NOT EXISTS "sourceApiKeyId" TEXT;
+CREATE INDEX IF NOT EXISTS "journal_externalId_idx" ON "journal" ("companyId", "externalId");
+
+-- Event triggers for webhook topics (async only; no sync interceptors)
+-- attach_event_trigger('journal', ...), attach_event_trigger('accountingPeriod', ...),
+-- attach_event_trigger('approvalRequest', ...)
+-- trialBalance RPC: optional p_book_id + p_dimension_id/p_dimension_value_id params (additive defaults)
+```
+
+Run `pnpm run generate:types` after the migration, before typechecking.
+
+## API / Service Changes
+
+- `accounting.service.ts`: extend `getTrialBalance` (bookId, dimension filter/group, cursor); add `getJournalLinesExportCursor` (Kysely cursor over the record-integrity export query), `importJournalEntries` (validation → period gate → create → approval-aware submit; returns per-entry results), `getWebhookRegistrations` / `upsertWebhookRegistration` / `deleteWebhookRegistration` (wrapping the event-system RPCs for topic rows).
+- `accounting.models.ts`: `journalEntryImportValidator` (entry + line + dimensions), `trialBalanceQueryValidator`, `webhookRegistrationValidator`, topic enum.
+- Routes: `api+/v1+/accounting.trial-balance.ts`, `accounting.journal-lines.export.ts`, `accounting.journal-entries.ts`, `accounting.journal-entries.$id.ts`, `webhooks.ts`, `webhooks.$id.ts`, `openapi[.]json.ts`.
+- `packages/jobs/.../events/webhook.ts`: curated-envelope branch, HMAC signing, failure bookkeeping on `webhookRegistration`.
+- MCP: `importJournalEntries` registered in `tool-metadata.json` with `createdBy`/`companyId` auth fields; no other tool changes.
+
+## UI Changes
+
+Read-only "Webhooks" card on the API-keys settings page (registration list: url, topics, active, last failure). Nothing else — this spec is deliberately API-first.
+
+## Acceptance Criteria
+
+- [ ] `GET /trial-balance` with a `carbon-key` holding `accounting_view` returns four-column rows keyed by `accountNumber`; the same request with a key lacking the scope returns 403.
+- [ ] TB API slices by `bookId` (adjustment-book rows excluded from the primary-book extract) and by `dimension=<id>:<value>`; `groupBy=dimension:` returns per-value subtotals that sum to the unfiltered TB.
+- [ ] Export streams the full JE population for a period with no row cap; columns match the record-integrity spec's export byte-for-byte for the same filter.
+- [ ] Imported JE in a company with an active journal-entry approval rule lands in `Pending Approval` with an `approvalRequest`; approver notification fires; on approval it posts with `preparedBy` = the key principal and `approvedBy` = the approver.
+- [ ] Import with `postingDate` in a Closed period returns `422 PERIOD_CLOSED` and creates no rows; a Locked period accepts the import (key has `accounting_create`).
+- [ ] Unbalanced entry, unknown `accountNumber`, or unknown dimension value rejects that entry with a line-level error while sibling entries in the batch succeed.
+- [ ] Replaying the same `Idempotency-Key` + body returns the original stored response with `replayed: true` and creates zero new journals; same key + different body returns 409.
+- [ ] Posting a journal fires `journal_entry.posted` to a registered URL with a valid `carbon-signature` HMAC; tampered body fails verification; delivery retries on 5xx; 20 consecutive failures deactivate the registration.
+- [ ] Locking/closing/reopening a period fires the corresponding `period.*` webhook with fiscalYear/periodNumber/closeStatus.
+- [ ] `openapi.json` validates as OpenAPI 3.1 and documents every v1 endpoint, error code, and the signature scheme.
+- [ ] Existing WEBHOOK eventSystemSubscriptions without `registrationId` still deliver legacy payloads unchanged.
+- [ ] Rate limiting: a key over its window receives 429 with `X-RateLimit-*` headers on every v1 route.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Import bypasses a control if the approvals spec's service entry point slips | High | Hard dependency: import ships only after document-approvals lands; `importJournalEntries` calls its `isApprovalRequired` gate, not `postJournalEntry` directly |
+| Webhook payloads leak financial data to a mistyped URL | Med | Secret returned once, HTTPS-only URL validation, curated minimal envelopes (ids + status, not line detail — consumers pull detail via the authenticated API) |
+| Long export streams under load | Med | Cursor batching (5k), bounded date range required, one-request rate-limit cost documented |
+| Idempotency table growth | Low | 30-day `expiresAt` + scheduled Inngest cleanup (piggybacks an existing daily cron) |
+| `journal` event trigger adds write overhead to the posting hot path | Low | AFTER STATEMENT trigger short-circuits when no active subscription exists (existing `dispatch_event_batch` behavior) |
+
+## Open Questions
+
+> Resolutions confirmed before writing (per the spec lifecycle); no blocking questions remain.
+
+- [x] **New API gateway / auth mechanism?** — Resolved (Brad): **"use our current stuff"** — the `apiKey` table (hashed keys, JSONB scopes, `check_api_key_rate_limit`), `requirePermissions`, the MCP direct-executor, and the `api+` route namespace. No Kong/Zuplo/new token format.
+- [x] **Where does the JE export column definition live?** — The record-integrity spec owns it; this API is a transport over the same query (verified: that spec is a parallel sibling on this branch).
+- [x] **Do imports post directly or route through approvals?** — Through approvals, always: same service entry point as the UI/MCP paths (document-approvals spec resolution "the MCP path is covered" extends to this API).
+- [x] **Locked-period semantics for API principals?** — Locked accepts imports when the key carries `accounting_create`, mirroring the period-closing rule that accounting users may post adjustments into Locked periods; Closed always rejects.
+- [x] **New scope values?** — None; existing `accounting_*`/`settings_*` scopes map cleanly (verified against `20260219162954`).
+
+## Changelog
+
+- 2026-07-04: Created (GAP-E1, Phase 4 of the readiness roadmap; tracking issue crbnos/carbon#1059)
diff --git a/.ai/specs/2026-07-04-intercompany-maturity.md b/.ai/specs/2026-07-04-intercompany-maturity.md
new file mode 100644
index 0000000000..3d4e94f998
--- /dev/null
+++ b/.ai/specs/2026-07-04-intercompany-maturity.md
@@ -0,0 +1,269 @@
+# Intercompany Maturity — Tolerance Matching, FX Differences, Document Mirroring, Netting
+
+> Status: in-progress
+> Author: Claude (with Brad)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1058
+> Readiness finding: SD-5.4–.5 remainder (`.ai/specs/2026-07-03-public-company-readiness.md`, Phase 4)
+
+## TLDR
+
+Carbon's intercompany skeleton is real and load-bearing — `journalLine.intercompanyPartnerId`, the `intercompanyTransaction` ledger, auto-synced IC customer/supplier records, elimination entities, and the `matchIntercompanyTransactions` / `generateEliminationEntries` / `getIntercompanyBalance` RPCs (`20260403120000_intercompany-tracking.sql`). But matching is exact-amount only, FX rate differences between the two sides make pairs permanently unmatchable, IC trade requires double data entry (a PO in one company and a hand-keyed SO in the other), and gross IC AR/AP balances can only be relieved by fake cash payments. This spec adds the four maturity layers the research consensus names (SAP trading-partner/ICMR, NetSuite IC framework — `.ai/research/public-company-compliance.md` §Pattern 6): **(1)** tolerance-based matching configurable per company group (default 1.00 base-currency units) with the difference plugged to a dedicated IC difference account, **(2)** document-currency matching for FX-rate mismatches with the base-currency delta posted to the same account, **(3)** opt-in IC document mirroring (PO→SO on release, invoice mirroring at posting; one-way sync, linked statuses, surfaced failures), and **(4)** a netting workbench that turns the existing balance matrix into per-pair netting statements generating paired zero-cash settlement payments riding the existing `payment`/`invoiceSettlement` machinery. Ownership %/NCI stays explicitly deferred per the readiness resolution.
+
+## Problem Statement
+
+Concretely, today:
+
+1. **Exact-amount matching only.** `matchIntercompanyTransactions` joins on `src."amount" = tgt."amount"`. A one-cent rounding difference between the seller's invoice and the buyer's voucher leaves both rows `Unmatched` forever, and close-checklist task 5 (`unmatched-ic`, seeded Warning in the period-closing spec) nags every period with noise no one can clear.
+2. **FX kills matching structurally.** `intercompanyTransaction.amount` is the source company's base-currency amount. When the two sides book the same 1,000 EUR invoice at 1.08 and 1.10, base amounts differ by 20.00 and can never match — there is no document-currency amount on the row to match on, and no account to absorb the difference.
+3. **Double entry for IC trade.** The IC customer/supplier records are auto-synced, but a PO raised on an IC supplier requires someone in the partner company to re-key the same lines as an SO (and later re-key the invoice). Quantities and prices drift, which is where unmatchable IC balances come from in the first place.
+4. **No netting.** `getIntercompanyBalance` renders the gross matrix, but relieving mutual AR/AP requires posting fictitious bank payments in both companies — wrong cash, wrong audit trail.
+5. **No ownership %.** Consolidation is 100%-summation. Per the readiness resolution this is *deferred*, not in scope here — restated below so it isn't re-litigated.
+
+## Proposed Solution
+
+Four workstreams, each independently shippable, all riding existing machinery.
+
+### 1. Tolerance matching
+
+- `companyGroup.intercompanyMatchingTolerance NUMERIC NOT NULL DEFAULT 1` — base-currency units, editable from the existing group management UI (the `companyGroup` table stays service-role-only at the RLS layer, as today).
+- `matchIntercompanyTransactions` becomes a three-pass matcher (same signature, same permission preamble):
+ - **Pass 1 — exact (unchanged):** base amounts equal → `Matched`, difference 0.
+ - **Pass 2 — FX (see §2):** document-currency amounts equal, base amounts differ → `Matched`, `differenceKind = 'FX'`.
+ - **Pass 3 — tolerance:** `ABS(src.amount − tgt.amount) <= tolerance`, greedy closest-first (`ORDER BY ABS(difference) ASC, src.id, tgt.id` for determinism), only when both companies share the same base currency (cross-currency pairs must match via pass 2 — base amounts in different currencies are not comparable) → `Matched`, `differenceKind = 'Tolerance'`, `matchedDifference` recorded.
+- **Posting the difference.** `generateEliminationEntries` already reverses both sides into the elimination entity's journal; with a near-match that journal no longer sums to zero. Add a balancing plug line to the new `accountDefault.intercompanyDifferenceAccount` (resolved **by id** from the elimination entity's `accountDefault`, per `.ai/lessons.md` "Never resolve a control account by number/name"). Subsidiary books are untouched — the difference is a consolidation-level plug, matching the ICMR pattern.
+
+### 2. FX differences on IC pairs
+
+- `intercompanyTransaction` gains `documentAmount NUMERIC` (nullable; document-currency amount — `currencyCode` already holds the document currency). Every posting path that inserts `intercompanyTransaction` rows starts populating it; legacy NULL rows are skipped by pass 2.
+- **Computation.** For a pair on document amount `D` booked at rates `r_s`, `r_t`: source base `b_s = D × r_s`, target base `b_t = D × r_t`. Same-base-currency pair: FX difference `Δ = b_s − b_t`. Different base currencies: each side's reversal lines are translated to the elimination entity's currency at the group closing rate (the same `exchangeRateHistory` closing rates `translateTrialBalance` uses); `Δ` is the residual of the elimination journal after translation. Either way `Δ` posts to `intercompanyDifferenceAccount` as the journal's balancing line, description `IC FX difference: {ict.id}`.
+- Pass 2 has **no tolerance cap** — the document amounts agree exactly; rate variance is legitimate and can exceed the tolerance. `differenceKind` distinguishes `'FX'` from `'Tolerance'` for reporting.
+
+### 3. IC document mirroring (opt-in)
+
+- `companyGroup.intercompanyDocumentMirroring BOOLEAN NOT NULL DEFAULT false`.
+- **PO → SO:** when a purchase order on a supplier with `intercompanyCompanyId` set leaves `Draft` (release: status → `'To Review'`/`'To Receive*'`), and the group setting is on, an event fires (event system → Inngest job in `@carbon/jobs`, service-role — the write crosses a company boundary and must not depend on the releasing user's membership in the partner company). The job drafts a `salesOrder` in the partner company for the auto-synced IC customer, copying lines (item, quantity, unit price, promised date), and records an `intercompanyDocumentLink` row.
+- **Line identity:** items are matched in the partner company by `readableIdWithRevision`. Any unmatched item fails the whole mirror (no partial documents): link `status = 'Failed'` with `failureReason`, notification to the partner company's sales/accounting owners, row surfaced in the Mirroring exceptions panel. (Open question 5 below.)
+- **One-way sync, linked statuses:** the initiating PO is the source of truth for quantities/prices. While the mirrored SO is `Draft`/`Confirmed`, PO line edits re-sync it (`lastSyncedAt` updated). Once the SO is `In Progress` or beyond, a PO edit no longer syncs — it flips the link to `'Exception'` with the diff in `failureReason` for humans to reconcile. PO cancellation cancels a `Draft`/`Confirmed` SO; otherwise it raises an exception. Mirrored documents carry the link and are never themselves mirror *initiators* (loop guard).
+- **Invoice mirroring at posting:** when the seller posts the sales invoice against the mirrored SO (or any sales invoice to an IC customer, if the setting is on), the job drafts the matching purchase invoice in the buyer company, linked the same way. The mirrored invoice stays **Draft** — the receiving company reviews and posts under its own controls (approvals, period status); mirroring never auto-posts.
+
+### 4. Netting workbench
+
+- **Matrix → statement:** the workbench renders `getIntercompanyBalance` per group. For a company pair, "Create netting statement" snapshots the pair's open IC invoices (posted, unpaid, counterparty is the IC customer/supplier) into `intercompanyNettingStatement` + lines. Net amount = min(gross A→B, gross B→A); the residual stays open for real cash settlement.
+- **Settle → paired payments:** settling an `Agreed` statement generates up to four `payment` documents through the existing posting machinery — in each company, a `Receipt` from the IC customer applying its AR invoices and a `Disbursement` to the IC supplier applying its AP invoices, each for the netted amount, each with `bankAccount = accountDefault.intercompanyNettingAccount` (a clearing account — `payment.bankAccount` references `account(id)`, so no schema bend). Within each company the clearing account debits and credits offset to exactly zero: **zero cash movement**, and `invoiceSettlement` rows close the invoices normally. `payment.totalAmount = 0` credit-application shortcut is *not* used — the paired gross payments keep each invoice's settlement trail ordinary and auditable.
+- **Audit trail:** statement → lines → `payment.nettingStatementId` back-reference; statement carries `proposedBy/agreedBy/settledBy` + timestamps; status machine `Draft → Proposed → Agreed → Settled` (or `Cancelled` before settlement). Voiding any generated payment (existing void flow) flips the statement to `Exception`.
+- The netting-generated journal lines carry `intercompanyPartnerId` like any IC posting, so they flow into `intercompanyTransaction` and match under passes 1–3 — netting *feeds* the existing matching control rather than bypassing it.
+
+### 5. NCI / ownership % — deferred
+
+Per the readiness resolution (SD-5.5): consolidation remains 100%-summation. No `ownershipPercent` column, no NCI equity accounts, no goodwill computation in this spec. NetSuite also does 100% summation; sub-100% subsidiaries are SAP-tier and wait for a real customer need.
+
+### 6. Close integration
+
+**No new close task.** Reasoning: the control the close needs is "IC positions are matched and eliminable," which seeded task 5 (`unmatched-ic`, Warning) already evaluates — and this spec makes it *passable* by clearing tolerance/FX noise. Netting is cash-management hygiene, not a close control: unsettled gross IC balances eliminate correctly regardless of netting, and netting-generated settlements land in `intercompanyTransaction` where task 5 already looks. Registering a "run netting" task would gate the close on an optional treasury activity. Instead, task 5's drill-through page links to both the matching page and the netting workbench.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Tolerance scope | Per company group (`companyGroup` column), default 1.00 base-currency units | RESOLVED with user. Group is where matching runs; per-pair tolerance is config sprawl (lesson: no N×M config matrices) |
+| 2 | Where the difference posts | Balancing plug in the elimination entity's journal, to `accountDefault.intercompanyDifferenceAccount` resolved by id | Subsidiary books stay untouched; one plug per elimination journal; obeys the control-account-by-id lesson |
+| 3 | FX matching key | Document-currency amount (`documentAmount` + `currencyCode`), no tolerance cap on the base delta | Doc amounts agreeing exactly proves same economic transaction; rate variance is legitimate FX, not error |
+| 4 | Cross-base-currency tolerance | Pass 3 restricted to same-base-currency pairs | Base amounts in different currencies aren't comparable; cross-currency pairs match on document currency (pass 2) |
+| 5 | Mirroring transport | Event-system trigger → Inngest job (service role), never a synchronous DB trigger | Cross-company writes need service role + item mapping + retry + failure surfacing; sync triggers would couple PO release latency to partner-company state |
+| 6 | Mirrored documents auto-post? | Never — always Draft in the receiving company | Receiving company's approvals/period gates must apply; auto-posting would bypass MW-2 controls |
+| 7 | Netting settlement shape | Paired gross `payment` docs through an IC netting clearing account, existing posting + `invoiceSettlement` | RESOLVED in scope. NetSuite netting-workbench pattern; zero new posting machinery; clearing nets to zero per company |
+| 8 | NCI / ownership % | Deferred | Readiness resolution SD-5.5; restated to prevent scope creep |
+| 9 | Close checklist | No new task; task 5 drill-through links matching + netting | Netting is optional treasury hygiene; the matched-IC control already exists and this spec makes it clearable |
+| 10 | Multi-tenancy (heuristic 1) | New group-level tables follow the `intercompanyTransaction` precedent: single-column PK, `companyGroupId` + explicit company columns, audit columns | Cross-company rows can't carry one `companyId`; precedent already reviewed and shipped |
+| 11 | Service shape (heuristic 2) | All new functions in `accounting.service.ts` / `accounting.models.ts`, `(client, companyGroupId, ...)` → `{data, error}` | Intercompany is accounting-owned; one service file per module |
+| 12 | RLS (heuristic 3) | Four policies per table gated on `get_companies_with_employee_permission('accounting_*')` against source **or** target company, matching `intercompanyTransaction` | Same visibility rule as the existing IC table; either side's accountants may view/manage |
+| 13 | Permission scoping (heuristic 4) | Routes `view/update: "accounting"`; mirroring job runs service-role; settle requires `accounting_update` in *both* companies (checked in RPC preamble) | Settlement writes both companies' books; one-sided permission would let A close B's AR |
+| 14 | Form pattern (heuristic 5) | `ValidatedForm` + zod (`nettingStatementValidator`, `icToleranceValidator`); Drawer overlays for statement detail | House convention |
+| 15 | Module layout (heuristic 6) | No new module; accounting module, `ui/Intercompany/` components, routes under `x+/accounting+/intercompany-*` | Extends the existing intercompany surface |
+| 16 | Backward compatibility (heuristic 7) | All new columns nullable or defaulted to current behavior (`tolerance` default keeps near-matches auto-matching only after upgrade; mirroring default **off**); pass 1 unchanged; legacy rows without `documentAmount` skip pass 2 | Groups that do nothing see exact matching exactly as today, plus tolerance ≤ 1.00 |
+
+## Data Model Changes
+
+```sql
+-- 1) Group settings
+ALTER TABLE "companyGroup"
+ ADD COLUMN "intercompanyMatchingTolerance" NUMERIC NOT NULL DEFAULT 1,
+ ADD COLUMN "intercompanyDocumentMirroring" BOOLEAN NOT NULL DEFAULT false;
+ALTER TABLE "companyGroup"
+ ADD CONSTRAINT "companyGroup_icTolerance_check" CHECK ("intercompanyMatchingTolerance" >= 0);
+
+-- 2) Match difference tracking
+ALTER TABLE "intercompanyTransaction"
+ ADD COLUMN "documentAmount" NUMERIC, -- document-currency amount ("currencyCode" is already the doc currency)
+ ADD COLUMN "matchedDifference" NUMERIC, -- base-currency delta absorbed at elimination
+ ADD COLUMN "differenceKind" TEXT CHECK ("differenceKind" IN ('Tolerance', 'FX'));
+
+-- 3) Account defaults (resolved by id — .ai/lessons.md), seeded accounts backfilled
+-- once by number/parent-group-name per the 20260702181547 precedent
+ALTER TABLE "accountDefault"
+ ADD COLUMN "intercompanyDifferenceAccount" TEXT REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE RESTRICT,
+ ADD COLUMN "intercompanyNettingAccount" TEXT REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE RESTRICT;
+-- Seed "Intercompany Differences" (expense, parent resolved by isGroup+name, never number)
+-- and "Intercompany Netting Clearing" (asset, sibling of 1130) in seed.data.ts + backfill migration.
+
+-- 4) Document mirroring links (group-level: intercompanyTransaction PK/RLS precedent)
+CREATE TABLE "intercompanyDocumentLink" (
+ "id" TEXT NOT NULL DEFAULT id('icdl'),
+ "companyGroupId" TEXT NOT NULL REFERENCES "companyGroup"("id") ON DELETE CASCADE,
+ "sourceCompanyId" TEXT NOT NULL REFERENCES "company"("id"),
+ "targetCompanyId" TEXT NOT NULL REFERENCES "company"("id"),
+ "sourceDocumentType" TEXT NOT NULL CHECK ("sourceDocumentType" IN ('purchaseOrder', 'salesInvoice')),
+ "sourceDocumentId" TEXT NOT NULL,
+ "targetDocumentType" TEXT NOT NULL CHECK ("targetDocumentType" IN ('salesOrder', 'purchaseInvoice')),
+ "targetDocumentId" TEXT, -- null until the mirror is created
+ "status" TEXT NOT NULL DEFAULT 'Pending'
+ CHECK ("status" IN ('Pending', 'Mirrored', 'Failed', 'Exception', 'Detached')),
+ "failureReason" TEXT,
+ "lastSyncedAt" TIMESTAMP WITH TIME ZONE,
+ "createdBy" TEXT REFERENCES "user"("id"), -- null when created by the mirroring job
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "intercompanyDocumentLink_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "icdl_source_unique" UNIQUE ("sourceDocumentType", "sourceDocumentId", "sourceCompanyId")
+);
+-- RLS: 4 policies, source OR target company via get_companies_with_employee_permission('accounting_*'
+-- for writes) / get_companies_with_employee_role() intersection with the two companies for SELECT —
+-- exactly the intercompanyTransaction policy shape.
+
+-- 5) Netting
+CREATE TABLE "intercompanyNettingStatement" (
+ "id" TEXT NOT NULL DEFAULT id('icns'),
+ "statementId" TEXT NOT NULL, -- readable, sequence-assigned per group
+ "companyGroupId" TEXT NOT NULL REFERENCES "companyGroup"("id") ON DELETE CASCADE,
+ "companyAId" TEXT NOT NULL REFERENCES "company"("id"),
+ "companyBId" TEXT NOT NULL REFERENCES "company"("id"),
+ "currencyCode" TEXT NOT NULL,
+ "nettedAmount" NUMERIC NOT NULL CHECK ("nettedAmount" > 0),
+ "residualAmount" NUMERIC NOT NULL DEFAULT 0,
+ "residualPayerCompanyId" TEXT REFERENCES "company"("id"),
+ "status" TEXT NOT NULL DEFAULT 'Draft'
+ CHECK ("status" IN ('Draft', 'Proposed', 'Agreed', 'Settled', 'Exception', 'Cancelled')),
+ "settlementDate" DATE,
+ "proposedBy" TEXT REFERENCES "user"("id"), "proposedAt" TIMESTAMP WITH TIME ZONE,
+ "agreedBy" TEXT REFERENCES "user"("id"), "agreedAt" TIMESTAMP WITH TIME ZONE,
+ "settledBy" TEXT REFERENCES "user"("id"), "settledAt" TIMESTAMP WITH TIME ZONE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "intercompanyNettingStatement_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "icns_statementId_group_key" UNIQUE ("statementId", "companyGroupId"),
+ CONSTRAINT "icns_distinct_companies" CHECK ("companyAId" <> "companyBId")
+);
+
+CREATE TABLE "intercompanyNettingStatementLine" (
+ "id" TEXT NOT NULL DEFAULT id('icnl'),
+ "statementId" TEXT NOT NULL REFERENCES "intercompanyNettingStatement"("id") ON DELETE CASCADE,
+ "companyId" TEXT NOT NULL REFERENCES "company"("id"), -- whose book this open item sits in
+ "salesInvoiceId" TEXT, "purchaseInvoiceId" TEXT, -- exactly one (CHECK)
+ "openAmount" NUMERIC NOT NULL,
+ "appliedAmount" NUMERIC NOT NULL CHECK ("appliedAmount" >= 0),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ CONSTRAINT "intercompanyNettingStatementLine_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "icnl_one_target" CHECK ((("salesInvoiceId" IS NOT NULL)::int + ("purchaseInvoiceId" IS NOT NULL)::int) = 1)
+);
+
+-- Back-reference for the audit trail
+ALTER TABLE "payment" ADD COLUMN "nettingStatementId" TEXT
+ REFERENCES "intercompanyNettingStatement"("id") ON DELETE RESTRICT;
+CREATE INDEX "payment_nettingStatementId_idx" ON "payment"("nettingStatementId")
+ WHERE "nettingStatementId" IS NOT NULL;
+```
+
+RPC changes: `matchIntercompanyTransactions` gains passes 2–3 (reads tolerance from `companyGroup`); `generateEliminationEntries` adds the difference plug line and refuses to post if `intercompanyDifferenceAccount` is unset while any matched pair carries a nonzero `matchedDifference` (explicit error beats silent imbalance). New `settleNettingStatement(p_statement_id, p_user_id)` RPC verifies `accounting_update` in **both** companies, then builds the paired payments + settlements transactionally.
+
+Pass 2/3 sketch (inside the existing RPC, after the exact pass; same self-join shape and `sourceJournalLineId <` de-dup as pass 1):
+
+```sql
+-- Pass 2: FX — document-currency amounts agree, base amounts differ
+... ON src."documentAmount" = tgt."documentAmount"
+ AND src."currencyCode" = tgt."currencyCode"
+ AND src."documentAmount" IS NOT NULL AND tgt."documentAmount" IS NOT NULL
+ AND src."amount" <> tgt."amount" -- else pass 1 took it
+-- sets: status='Matched', differenceKind='FX', matchedDifference = src.amount - tgt.amount
+
+-- Pass 3: tolerance — same base currency only, greedy closest-first
+SELECT DISTINCT ON (src."id") src."id", tgt."id"
+FROM unmatched src JOIN unmatched tgt ON <pair predicate>
+ AND ABS(src."amount" - tgt."amount") <= v_tolerance
+ AND src_company_base_currency = tgt_company_base_currency
+ORDER BY src."id", ABS(src."amount" - tgt."amount") ASC, tgt."id"
+-- second DISTINCT ON (tgt.id) pass drops double-claimed targets before UPDATE;
+-- sets: differenceKind='Tolerance', matchedDifference = src.amount - tgt.amount
+```
+
+Seed/backfill sketch for the two new accounts (follows `20260702181547` + the group-header lesson):
+
+```sql
+-- seed.data.ts adds: 1135 "Intercompany Netting Clearing" (asset, parentKey next to 1130)
+-- 7095 "Intercompany Differences" (expense, parentKey other-expenses)
+-- backfill migration: insert per company group where missing (parent resolved by
+-- "isGroup" = TRUE AND name — group headers have NULL number), then one-time
+-- resolve into accountDefault by seeded number; authoritative by id thereafter:
+UPDATE "accountDefault" ad
+SET "intercompanyDifferenceAccount" = a."id"
+FROM "account" a JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
+WHERE c."id" = ad."companyId" AND a."number" = '7095'
+ AND ad."intercompanyDifferenceAccount" IS NULL;
+-- (same shape for 1135 → intercompanyNettingAccount)
+```
+
+## API / Service Changes
+
+All in `apps/erp/app/modules/accounting/accounting.service.ts` (+ validators in `accounting.models.ts`):
+
+- `updateCompanyGroupIntercompanySettings(client, groupId, {tolerance, mirroring})`
+- `getIntercompanyDocumentLinks(client, groupId, filters)` / `retryIntercompanyMirror(client, linkId)` / `detachIntercompanyLink(client, linkId)`
+- `getNettingMatrix(client, groupId)` (wraps `getIntercompanyBalance`), `createNettingStatement(client, groupId, pairIds)`, `proposeNettingStatement`, `agreeNettingStatement`, `settleNettingStatement`, `cancelNettingStatement`
+- `@carbon/jobs`: `intercompany.mirror.requested` Inngest function (PO release / sales-invoice posted events → mirror creation, retries, `Failed` links + notifications on exhaustion)
+
+## UI Changes
+
+- **Intercompany page** (accounting) grows three tabs: **Matching** (existing, now showing `differenceKind`/`matchedDifference` badges), **Mirroring** (link table with status filter, failure reasons, retry/detach), **Netting** (matrix → statement list → statement Drawer with lines, status actions, generated payment links).
+- **Group settings**: tolerance input + mirroring toggle.
+- **Close drawer task 5** drill-through links to Matching and Netting tabs (no new task).
+- PO/SO/invoice detail views show a "Mirrored from/to" banner with a link when an `intercompanyDocumentLink` exists.
+
+## Acceptance Criteria
+
+- [ ] Two IC transactions differing by 0.40 base units (tolerance 1.00, same base currency) auto-match on the RPC run with `differenceKind = 'Tolerance'`, `matchedDifference = 0.40`; the elimination journal balances via a 0.40 line to `intercompanyDifferenceAccount`; setting group tolerance to 0.10 leaves the same pair `Unmatched`.
+- [ ] The same 1,000 EUR document booked at 1.08 vs 1.10 matches on `documentAmount` with `differenceKind = 'FX'` and a 20.00 base-currency plug to the difference account; the plug exceeds the 1.00 tolerance and still matches (no cap on pass 2).
+- [ ] `generateEliminationEntries` raises a clear error (not an unbalanced journal) when a matched pair has nonzero difference and the elimination entity's `intercompanyDifferenceAccount` is unset.
+- [ ] Mirrored PO→SO round-trip: with mirroring on, releasing a 3-line PO on an IC supplier produces a Draft SO in the partner company with identical items/quantities/prices and a `Mirrored` link; editing a PO quantity while the SO is Draft re-syncs it; posting the seller's sales invoice drafts the buyer's purchase invoice (Draft, not posted); an unmappable item yields a `Failed` link with reason, a notification, and **no** partial SO; mirrored documents never trigger a reverse mirror.
+- [ ] Netting: a pair with 100 AR / 80 AP nets 80 — the settled statement generates four posted payments through `intercompanyNettingAccount`, the clearing account nets to zero in each company, both sides' invoices show 80 settled via ordinary `invoiceSettlement` rows, residual 20 remains open, and `payment.nettingStatementId` traces every payment to the statement.
+- [ ] Settling requires `accounting_update` in both companies; a user with permission in only one gets a permission error and no partial postings.
+- [ ] Close checklist is unchanged (still 9 seeded tasks); task 5 clears once tolerance/FX matching runs; no `ownershipPercent` or NCI artifact exists anywhere.
+- [ ] With mirroring off and tolerance at default, an upgraded group's matching behavior differs from today only by auto-matching pairs within 1.00.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Greedy tolerance matching mis-pairs when many near-identical amounts exist between a pair | Med | Closest-first deterministic ordering; `matchedDifference` visible pre-elimination; manual unmatch action on the Matching tab before eliminating |
+| Mirroring loop (mirrored SO's invoice re-mirrors back) | High | Mirror-created documents carry the link and are excluded as initiators (loop guard, tested) |
+| Netting payments posted into a Locked/Closed period | Med | `settleNettingStatement` posts through the standard payment path — the period-close trigger and accounting-source rules apply unchanged |
+| Difference account absorbs real errors silently (tolerance set too high) | Med | Tolerance floor-checked ≥ 0, no upper bound but the Matching tab totals `Tolerance` differences per period; auditors see one account |
+| Cross-currency elimination translation drift | Med | FX plug computed as the journal residual after translation (never a second independent calculation), so the journal balances by construction |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] Tolerance configurability and default — **RESOLVED:** per company group, default 1.00 base-currency units.
+- [x] Netting in or out of v1 — **RESOLVED:** in scope; workbench → per-pair statements → paired zero-cash settlements riding payment/memo + `invoiceSettlement` machinery.
+- [x] Ownership % / NCI — **RESOLVED:** explicitly deferred (readiness SD-5.5); 100%-summation stands.
+- [x] Close checklist impact — **RESOLVED (this spec):** no new task; existing task 5 covers the control and links to the new surfaces.
+- [x] Mirroring item identity: is `readableIdWithRevision` equality across group companies an acceptable v1 mapping, or do we need an explicit cross-company item reference table before shipping mirroring? (Fails safe today — unmapped items produce a `Failed` link — but silent *wrong* matches are possible if two companies reuse a readable ID for different items.) — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Build the explicit cross-company item reference table now, seeded by `readableIdWithRevision` auto-matching. Back out to pure readableId equality at plan stage.
+- [x] Netting residual: confirm the residual is settled by ordinary cash payment outside the statement (current design), rather than the statement optionally generating the residual cash payment too. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** The statement optionally generates the residual settlement payment document too (ambitious); manual cash settlement remains the fallback path.
+
+## Changelog
+
+- 2026-07-04: Created — resolutions from the readiness review baked in (tolerance default, netting in scope, NCI deferred); grounded in `20260403120000_intercompany-tracking.sql`, `20260702181547` (account-by-id precedent), `20260630093809_ar-ap-payments.sql` (payment/memo/settlement machinery), and research §Pattern 6 (SAP trading-partner/ICMR, NetSuite netting workbench).
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/2026-07-04-inventory-valuation-completeness.md b/.ai/specs/2026-07-04-inventory-valuation-completeness.md
new file mode 100644
index 0000000000..5936025b47
--- /dev/null
+++ b/.ai/specs/2026-07-04-inventory-valuation-completeness.md
@@ -0,0 +1,369 @@
+# Inventory Valuation Completeness — Standard Costing, Revaluation, LCNRV, Adjustment GL, Overhead Absorption, Landed Cost
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: [crbnos/carbon#1040](https://github.com/crbnos/carbon/issues/1040)
+> Parent: `.ai/specs/2026-07-03-public-company-readiness.md` (finding **GAP-3** — the manufacturing credibility core) · meta spec [#1060](https://github.com/crbnos/carbon/issues/1060)
+> Research: `.ai/research/public-company-compliance.md` (§5 — ASC 330 absorption costing + LCNRV; IAS 2 reversal is book-dependent)
+> Companions: `.ai/specs/2026-07-02-period-closing.md` (close-checklist registration surface) · `.ai/specs/2026-07-04-multi-book.md` (IAS 2 reversal consumer, parallel workstream #1052)
+
+## TLDR
+
+Carbon's costing engine has the skeleton of a real manufacturing valuation system — cost layers with `remainingQuantity` (`20260504000000_cost-layers.sql`), a `costLedgerType` enum that has carried `'Revaluation'` since 2023, and a chart reset (`20260315000000`) that seeded six variance accounts — but most of it is dead schema. This spec activates it in six build steps: (1) **standard costing wired end-to-end** (`standardCost` input path + actual-vs-standard variance posting at receipt and production + BOM roll-up), (2) an **inventory revaluation document** that writes cost layers up/down and posts `Revaluation` cost-ledger rows + GL, (3) an **LCNRV write-down run** with NRV auto-proposed from recent selling prices, posting through the revaluation machinery (US GAAP no-reversal in PRIMARY; IAS 2 reversal ships later as a multi-book adjustment generator), (4) **GL posting for manual quantity adjustments** (today itemLedger-only — inventory silently diverges from the GL), (5) **overhead absorption to GL** at `workCenter.overheadRate` with period variance to `overheadVarianceAccount`, and (6) a **landed cost document** allocating freight/duty/brokerage/insurance onto received layers with a GR/IR-style clearing account. Periodic pieces (LCNRV run, overhead variance) register as close-checklist tasks per the period-closing spec. Together these close GAP-3: every inventory balance-sheet movement gets a subledger row and a journal, which is the difference between "has inventory" and "passes an inventory audit".
+
+## Problem Statement
+
+Verified current state (all paths absolute from repo root):
+
+1. **Standard costing is enum-only.** `itemCost.standardCost` exists (`NUMERIC(15,5) DEFAULT 0`, `20230330024716_parts.sql:352`) and `calculate-cogs.ts:38-45` costs Standard items at it — but the validator field is commented out (`apps/erp/app/modules/items/items.models.ts:512`), the UI has no input, and nothing else writes it. **Every Standard-method item ships and consumes at $0.**
+2. **No variance posting except invoice-vs-receipt PPV.** `post-purchase-invoice/index.ts:972-1009` posts invoice-cost-minus-receipt-cost to `purchaseVarianceAccount` — the only live variance. `materialVarianceAccount` (5220), `laborAndMachineVarianceAccount` (5230), `overheadVarianceAccount` (5240), `lotSizeVarianceAccount` (5250), `subcontractingVarianceAccount` (5260) were all seeded NOT NULL by the chart reset and have **zero writers**.
+3. **`'Revaluation'` costLedgerType is dead** (`20230705033432_ledgers.sql:159`) — no revaluation document, no way to change the carrying cost of on-hand inventory with a GL trail.
+4. **No LCNRV.** ASC 330 requires lower-of-cost-or-NRV measurement; there is no write-down machinery, no NRV data path, no E&O rollforward for auditors.
+5. **Quantity adjustments never touch the GL.** `insertManualInventoryAdjustment` (`apps/erp/app/modules/inventory/inventory.service.ts:1417`) writes `itemLedger` rows only — `inventoryAdjustmentVarianceAccount` (5310) has no writer, so every cycle count silently breaks the inventory-account-to-subledger tie.
+6. **Overhead absorption stops at labor.** `post-production-event/index.ts:110-126` absorbs `durationHours × labor/machine rate` (Dr WIP / Cr `laborAbsorptionAccount` 5060); `workCenter.overheadRate` (GENERATED AS `quotingRate - laborRate`, `20240819115702:58`) is used for quoting only. Produced items exclude overhead — a direct ASC 330 absorption-costing violation.
+7. **No landed cost.** Freight/duty/brokerage hit expense when the vendor bill posts; received layers carry PO price only, understating inventory and mistiming COGS.
+
+## Resolved Questions (answered before writing, 2026-07-04)
+
+- [x] **NRV source for the LCNRV run?** — *(Brad)* **Proposed automatically from recent selling prices less costs to complete/sell** — the run queries posted sales invoice prices per item over a configurable lookback (defined in §3 below), applies a costs-to-complete/sell deduction, and proposes a write-down per line; every line is **editable before posting**.
+- [x] **LCNRV reversal?** — Write-downs post in-period; **US GAAP no-reversal in PRIMARY** (write-down establishes a new cost basis, layers physically written down). **IAS 2 reversal ships later** as an adjustment-book delta generator on top of the multi-book spec (#1052 / `.ai/specs/2026-07-04-multi-book.md`) — GL-only deltas in the IFRS book, PRIMARY layers untouched.
+- [x] **PPV vs standard variance?** — Both live. Invoice-vs-receipt PPV (`post-purchase-invoice`) stays exactly as-is; the **receipt-time standard-vs-actual variance is its own journal line**, posted at receipt for Standard-method items.
+- [x] **Close-checklist registration?** — LCNRV run and overhead-variance true-up register `periodCloseTaskDefinition` rows per the period-closing spec's registration rule (its 2026-07-04 changelog names later close tasks as registrants, not retrofitters).
+
+## Proposed Solution
+
+Build order matches dependency order: standard cost feeds revaluation math; revaluation machinery is reused by LCNRV; adjustment GL and overhead are independent posting extensions; landed cost is the largest new document and lands last.
+
+### 1. Standard costing wired end-to-end
+
+**Input path.** Uncomment and wire `standardCost` in `itemCostValidator` (`items.models.ts:512`); add the field to `ItemCostingForm.tsx` (shown only when `costingMethod = 'Standard'`); add a `standardCost` column to the item CSV importer mapping (per `.ai/rules/csv-import-system.md`). Changes are audit-logged via the existing `itemCost` audit coverage.
+
+**Standard-change revaluation guard.** Saving a new `standardCost` for an item with on-hand quantity auto-generates a **Draft inventory revaluation document** (§2) revaluing on-hand layers from old to new standard — the user posts or discards it. This is the BC "revalue on standard change" behavior and prevents the classic drift where the GL carries old-standard inventory forever.
+
+**Variance at receipt (purchase).** In `post-receipt`, when the item's `costingMethod = 'Standard'`: inventory debits at **standard**, GR/IR credits at **actual PO cost**, and the difference posts to `purchaseVarianceAccount` as a separate journal line labeled `Standard Cost Variance` (distinct `description` from the invoice-time `Purchase Price Variance` line, same account — see Design Decisions). The cost layer is written at standard (layers must carry the standard basis so consumption is variance-free).
+
+**Variance at production (job close).** `close-job` computes, for Standard-method output: standard cost of quantity produced (from the item's rolled-up standard) vs actual WIP accumulated (material consumption + labor absorption + overhead absorption). The residual clears WIP and splits by cost element: material delta → `materialVarianceAccount` (5220), labor/machine delta → `laborAndMachineVarianceAccount` (5230), overhead delta → `overheadVarianceAccount` (5240). `lotSizeVarianceAccount`/`subcontractingVarianceAccount` stay dormant in v1 (decision below).
+
+**Standard cost roll-up from BOM.** New `type: "standardCostRollup"` in the `recalculate` edge function + Inngest task (dispatch precedent: `packages/jobs/src/inngest/functions/tasks/recalculate.ts:17-52`), walking `get_method_tree` bottom-up: purchased leaves contribute `standardCost` (or `unitCost` for non-Standard components), operations contribute `laborRate`/`machineRate` × standard hours + `overheadRate` × standard hours. Writes a proposed standard per item; applying it goes through the input path above (and therefore the revaluation guard). Triggered on demand from the costing UI ("Roll up standard cost") — never automatic.
+
+### 2. Inventory revaluation document
+
+A first-class posted document (`inventoryRevaluation`, prefix `ivr`) that changes the unit cost of on-hand inventory:
+
+- Lines select item + location (optionally a specific cost layer for FIFO/LIFO items); show current carrying unit cost and quantity; user enters `newUnitCost`.
+- Posting, per line: writes `costLedger` rows with `costLedgerType = 'Revaluation'`, `adjustment = true`, `cost = (newUnitCost − currentUnitCost) × revaluedQuantity`, linked to the target layer via new column `appliesToCostLedgerId`; updates `itemCost.unitCost` for Average items; for Standard items only reachable via the standard-change guard (§1).
+- Layer effective unit cost becomes `(layer.cost + Σ applied Revaluation rows) / layer.quantity`; `calculate-cogs.ts` FIFO/LIFO branch is taught to include applied rows (one extra query keyed by `appliesToCostLedgerId`). Only **remaining** quantity is revalued — consumed quantity's delta is out of scope for a plain revaluation (unlike landed cost, §6, where the consumed share hits COGS).
+- GL: `Dr/Cr inventoryAccount` vs a **new dedicated `inventoryRevaluationAccount`** (seeded `5320 Inventory Revaluation & Write-Downs` under the `inventory-adjustments` group) — *not* `inventoryAdjustmentVarianceAccount`. Justification in Design Decisions: auditors and the E&O rollforward (§7) need price effects (revaluation, LCNRV) separable from quantity effects (cycle counts, 5310); commingling them makes the LCNRV disclosure unbuildable.
+- Status Draft → Posted; posted docs immutable per the period-closing branch's immutability convention; posting respects period state (operational source).
+
+### 3. LCNRV write-down run
+
+A periodic run (close-checklist task, default cadence: every period, skippable-with-reason as a Warning except at fiscal-year-end where it is required) that generates a pre-populated revaluation document of `type = 'LCNRV'`:
+
+**NRV proposal query** (per item with on-hand quantity):
+
+1. `estimatedSellingPrice` = quantity-weighted average `unitPrice` of **posted sales invoice lines** for the item within the lookback window (`companySettings.nrvLookbackDays`, default **90**);
+2. fallback: weighted average open **sales order line** price in the same window;
+3. fallback: item list/unit sale price; if none exists the line is flagged `No NRV basis` and excluded unless manually priced.
+4. `NRV = estimatedSellingPrice × (1 − costsToCompleteAndSellPct)` — run-level percentage input, default from `companySettings.nrvCostToSellPct` (default 0), **editable per line** along with the proposed NRV itself.
+
+Query sketch (Kysely in `proposeLcnrvRun`; simplified SQL):
+
+```sql
+WITH recent_sales AS (
+ SELECT sil."itemId",
+ SUM(sil."quantity" * sil."unitPrice") / NULLIF(SUM(sil."quantity"), 0) AS "avgPrice"
+ FROM "salesInvoiceLine" sil
+ JOIN "salesInvoice" si ON si."id" = sil."invoiceId" AND si."companyId" = sil."companyId"
+ WHERE si."status" NOT IN ('Draft', 'Voided')
+ AND si."postingDate" >= CURRENT_DATE - (:lookbackDays || ' days')::interval
+ AND sil."companyId" = :companyId
+ GROUP BY sil."itemId"
+),
+carrying AS (
+ SELECT cl."itemId", cl."id" AS "costLedgerId", cl."remainingQuantity",
+ (cl."cost" + COALESCE(adj."applied", 0)) / NULLIF(cl."quantity", 0) AS "unitCost"
+ FROM "costLedger" cl
+ LEFT JOIN LATERAL (
+ SELECT SUM("cost") AS "applied" FROM "costLedger" a
+ WHERE a."appliesToCostLedgerId" = cl."id"
+ ) adj ON TRUE
+ WHERE cl."remainingQuantity" > 0 AND cl."companyId" = :companyId
+)
+SELECT c.*, rs."avgPrice" * (1 - :costToSellPct) AS "proposedNrv"
+FROM carrying c
+LEFT JOIN recent_sales rs ON rs."itemId" = c."itemId"
+WHERE rs."avgPrice" * (1 - :costToSellPct) < c."unitCost";
+-- Average-method items (no layers): compare itemCost.unitCost against proposedNrv instead.
+```
+
+Fallbacks 2–3 fill `avgPrice` when `recent_sales` has no row (open sales-order weighted average, then list price), recording which source won in `nrvSource`.
+
+Lines are proposed only where `NRV < carrying unit cost` (item level — the ASC 330-permitted unit of account). Posting writes layers **down to NRV** through the §2 machinery (`Dr 5320 / Cr inventoryAccount`), establishing a new cost basis: subsequent COGS automatically reflects the written-down cost, and no-reversal falls out structurally — the PRIMARY book has nothing to reverse against. IAS 2 books later get reversal-up-to-original-cost as generated adjustment-book deltas (multi-book spec), reading the write-down history this run leaves behind.
+
+### 4. Quantity-adjustment GL posting
+
+`insertManualInventoryAdjustment` gains a posting leg (service-level, so the MCP path is covered too, per the document-approvals spec's lesson that route-level gates are bypassable):
+
+- **Negative adjustment**: consume layers via `calculateCOGS` → `Dr inventoryAdjustmentVarianceAccount (5310) / Cr inventoryAccount` at consumed-layer cost; costLedger rows decrement `remainingQuantity` as usual.
+- **Positive adjustment**: create a layer at the item's current unit cost (standard for Standard items) → `Dr inventoryAccount / Cr 5310`.
+- Journal `sourceType`/`documentType` reuse the existing `'Inventory Adjustment'`-family enums (add values only if missing); posting is skipped when `accountingEnabled = false`, matching every other poster.
+
+### 5. Overhead absorption to GL
+
+Extend `post-production-event`: alongside the existing labor line, compute `overheadCost = durationHours × workCenter.overheadRate` and post `Dr workInProgressAccount / Cr overheadAbsorptionAccount` (new accountDefault column, seeded `5070 Overhead Absorption` beside 5060). The event's `postedToGL` idempotency flag (`20260504000000:28`) and the existing reversal/repost logic cover the new line for free. Job receipt/close cost of output now includes absorbed overhead, so produced layers carry full absorption cost (ASC 330).
+
+**Period variance true-up** (close-checklist task, Auto-computed + proposed JE): under/over-absorption = actual indirect spend in the overhead cost pool vs period credits to 5070; the proposed journal posts `Dr overheadVarianceAccount (5240) / Cr overheadAbsorptionAccount (5070)` (or reversed) to true absorption up to actual. v1 defines the pool as the accounts mapped to `indirectCostAccount` + maintenance; pool configuration UI is a fast-follow.
+
+### 6. Landed cost
+
+New document set: `landedCost` (header: supplier, currency, status, reference), `landedCostLine` (charge type: `Freight | Duty | Brokerage | Insurance | Other`, amount), `landedCostAllocation` (charge line → target receipt line/cost layer, allocated amount, basis snapshot). Allocation bases: **value** (default), **quantity**, **weight** (disabled when any target item lacks weight data). Targets are posted receipt lines (their layers found via `costLedger` document linkage).
+
+Posting, per allocation:
+- **Capitalized share** (layer remaining fraction): `costLedger` row `costLedgerType = 'Indirect Cost'`, `appliesToCostLedgerId = layer`, raising effective layer cost (§2 mechanics) → `Dr inventoryAccount`.
+- **Consumed share** (already-shipped fraction): posts straight to `Dr costOfGoodsSoldAccount` — landed cost on sold units belongs in COGS now, not smeared over remaining units.
+- Credit side: **new `landedCostClearingAccount`** (seeded `2126 Landed Cost Clearing`, sibling of GR/IR 2125). The freight vendor's purchase invoice adds a `Landed Cost` line type referencing the document and posts `Dr 2126 / Cr AP`, clearing GR/IR-style; the clearing account's open balance is reconcilable per document.
+- For Standard-method items, the capitalized share posts to `purchaseVarianceAccount` instead of the layer (standard basis must not drift from actual charges — standard cost roll-up is where freight standards belong).
+
+### 7. E&O reserve reporting hooks
+
+`getInventoryWriteDownRollforward(client, companyId, fiscalYear)` in `inventory.service.ts` (surfaced under Accounting reports): per period — opening written-down carrying delta, + write-downs posted (LCNRV `Revaluation` rows), − relief through consumption (written-down layers consumed, from `appliesToCostLedgerId` joins), closing. This is the disclosure rollforward auditors request first; CSV export rides the standard table-export convention.
+
+### 8. Close-checklist registration
+
+Two `periodCloseTaskDefinition` registrations (per the period-closing spec's registration rule): **LCNRV run** (Manual + deep link to the run UI; Warning severity, Blocker on the last period of a fiscal year) and **Overhead variance true-up** (Auto check "5070 residual within tolerance" + Action link to the proposed JE). Registration happens in the same migration that creates each feature.
+
+### Build order and PR slicing
+
+| PR | Contents | Depends on |
+|----|----------|------------|
+| 1 | `appliesToCostLedgerId` + `calculate-cogs` applied-rows math (superset, behavior-neutral until a writer exists) + unit tests | — |
+| 2 | Standard cost input path (validator, form, CSV) + receipt-time standard variance + BOM roll-up (`standardCostRollup` recalculate case) | period close #1031 landed (post-* surface) |
+| 3 | Inventory revaluation document + `post-inventory-revaluation` + standard-change guard + new 5320 account/column | PR 1, 2 |
+| 4 | Quantity-adjustment GL leg in `insertManualInventoryAdjustment` | PR 1 |
+| 5 | Overhead absorption in `post-production-event` + 5070 account/column + job-close three-way variance split | PR 2 |
+| 6 | LCNRV run (proposal query, wizard, posting via PR 3 machinery) + close-checklist registrations + rollforward report | PR 3, 5 |
+| 7 | Landed cost documents + `post-landed-cost` + purchase-invoice `Landed Cost` line type + 2126 account/column | PR 1 |
+
+Each PR is independently shippable and verification-gated (`.ai/skills/check-and-commit/SKILL.md`); posting-function changes ship as coordinated PRs per the FX-spec precedent.
+
+## Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Multi-tenancy (heuristic 1) | All new tables (`inventoryRevaluation(Line)`, `landedCost(Line/Allocation)`): `companyId`, composite PK `("id","companyId")`, `id('prefix')`, audit columns, `customFields` | House convention (template + `packages/database/AGENTS.md`); `costLedger` keeps its legacy single-column `xid()` PK — extending it is additive columns only |
+| 2 | Service shape (heuristic 2) | Revaluation/LCNRV services in `inventory.service.ts` + `inventory.models.ts`; landed cost in `purchasing`'s service (document is supplier-facing); posting logic in edge functions (`post-*` family) | One service/models file per module; posting stays in Deno functions with the shared `calculate-cogs`/`get-posting-group` helpers |
+| 3 | RLS (heuristic 3) | Four named policies per new table; SELECT `get_companies_with_employee_role()`, writes `get_companies_with_employee_permission('inventory_*')` (revaluation/LCNRV) and `'purchasing_*'` (landed cost) | Exact package convention; costLedger stays accounting_view-read-only |
+| 4 | Permissions (heuristic 4) | Posting a revaluation/LCNRV requires `inventory_update` **and** the poster runs under period-state checks; no new permission actions | Follows the branch precedent of reusing existing tiers (period-closing: reopen = `delete: accounting`) |
+| 5 | Forms (heuristic 5) | `ValidatedForm` + zod validators (`inventoryRevaluationValidator`, `landedCostValidator`, run-parameter validator); standardCost joins `itemCostValidator` | Standard form system; the commented-out validator line is the activation point |
+| 6 | Module layout (heuristic 6) | Revaluation UI under `modules/inventory/ui/Revaluations/`; landed cost under `modules/purchasing/ui/LandedCosts/`; rollforward report under accounting reports | Matches existing feature-folder layout |
+| 7 | Backward compatibility (heuristic 7) | Everything additive: new enum values via `ADD VALUE IF NOT EXISTS`, new nullable-then-backfilled accountDefault columns, `appliesToCostLedgerId` nullable; `calculate-cogs` change is a superset (no applied rows ⇒ identical result); posting legs no-op when `accountingEnabled = false` | No frozen surface touched; Standard items that cost $0 today start costing at standard only once a standardCost is entered |
+| 8 | Revaluation contra account | **Dedicated `inventoryRevaluationAccount` (5320)**, not `inventoryAdjustmentVarianceAccount` (5310) | 5310 measures *quantity* variances (cycle counts, §4); revaluation/LCNRV are *price* remeasurements. Separating them is what makes the E&O rollforward and the LCNRV disclosure derivable from the GL; the by-id accountDefault pattern (post-`20260315000000`) makes a new column cheap |
+| 9 | LCNRV method: direct write-down, not reserve | Layers physically written to NRV via `Revaluation` rows; seeded `1240 Inventory Reserves` stays available for manual entries but automation never posts to it | ASC 330: write-down establishes a new cost basis — direct method makes no-reversal structural and makes later COGS self-correct; a reserve account would need contra-tracking on every consumption. IAS 2 reversals live in adjustment books (GL deltas), so PRIMARY layer integrity is never bent for IFRS |
+| 10 | Receipt-time standard variance account | `purchaseVarianceAccount` (5210), separate journal line/description from invoice-time PPV | Same economic family (purchase price vs standard); line-level `description` + `documentType` keep the two analyzable separately without a seventh variance account; matches BC (one PPV account, two posting moments) |
+| 11 | Layer adjustments via `appliesToCostLedgerId`, not in-place cost mutation | Posted `costLedger.cost` is never rewritten; adjustments are child rows; effective cost is computed | Auditability — mutating posted rows violates the branch's immutability direction; `remainingQuantity` remains the only mutable column (already the consumption precedent) |
+| 12 | Lot-size + subcontracting variances dormant in v1 | 5250/5260 keep zero writers; job-close residual splits three ways (material/labor/overhead) | The three-way split covers the audit requirement (absorption completeness); finer splits need setup-time standards and subcontract-PO linkage that don't exist yet — deferring is scope discipline, not a gap |
+| 13 | Landed cost on Standard items → PPV | Capitalized share posts to 5210 instead of the layer | Standard basis must stay the standard; charging actuals into a standard layer reintroduces the drift standard costing exists to eliminate |
+| 14 | NRV proposal is data, not doctrine | Auto-proposal (sales-invoice lookback − cost-to-sell %) is a starting point; every line editable pre-posting; overrides audit-logged with the proposed-vs-posted delta retained on the line | Brad's resolution; auditors test management's NRV judgment — the system must show both the mechanical estimate and the human override |
+
+## Data Model Changes
+
+```sql
+-- 1) costLedger: adjustment linkage (additive)
+ALTER TABLE "costLedger"
+ ADD COLUMN IF NOT EXISTS "appliesToCostLedgerId" TEXT REFERENCES "costLedger"("id");
+CREATE INDEX "costLedger_appliesTo_idx" ON "costLedger" ("appliesToCostLedgerId")
+ WHERE "appliesToCostLedgerId" IS NOT NULL;
+
+-- 2) accountDefault: three new columns (by account id, post-20260315 pattern)
+ALTER TABLE "accountDefault"
+ ADD COLUMN "inventoryRevaluationAccount" TEXT REFERENCES "account"("id"),
+ ADD COLUMN "overheadAbsorptionAccount" TEXT REFERENCES "account"("id"),
+ ADD COLUMN "landedCostClearingAccount" TEXT REFERENCES "account"("id");
+-- Seed per companyGroup: 5320 Inventory Revaluation & Write-Downs (inventory-adjustments),
+-- 5070 Overhead Absorption (cogs, beside 5060), 2126 Landed Cost Clearing (current-liabilities);
+-- backfill accountDefault, then SET NOT NULL (reset-chart-of-accounts precedent).
+
+-- 3) Inventory revaluation document
+CREATE TYPE "inventoryRevaluationType" AS ENUM ('Revaluation', 'LCNRV');
+CREATE TABLE "inventoryRevaluation" (
+ "id" TEXT NOT NULL DEFAULT id('ivr'),
+ "revaluationId" TEXT NOT NULL, -- readable sequence
+ "type" "inventoryRevaluationType" NOT NULL DEFAULT 'Revaluation',
+ "status" TEXT NOT NULL DEFAULT 'Draft', -- Draft | Posted
+ "locationId" TEXT,
+ "postingDate" DATE,
+ "nrvLookbackDays" INTEGER, -- LCNRV runs: snapshot of parameters
+ "nrvCostToSellPct" NUMERIC,
+ "postedBy" TEXT REFERENCES "user"("id"),
+ "postedAt" TIMESTAMP WITH TIME ZONE,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "inventoryRevaluation_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "inventoryRevaluation_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE TABLE "inventoryRevaluationLine" (
+ "id" TEXT NOT NULL DEFAULT id('ivrl'),
+ "revaluationId" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+ "costLedgerId" TEXT, -- specific layer (FIFO/LIFO); NULL = all layers
+ "quantity" NUMERIC NOT NULL, -- remaining quantity revalued (snapshot)
+ "currentUnitCost" NUMERIC NOT NULL,
+ "newUnitCost" NUMERIC NOT NULL,
+ "proposedNrv" NUMERIC, -- LCNRV: mechanical proposal (kept for audit)
+ "nrvSource" TEXT, -- 'salesInvoice' | 'salesOrder' | 'listPrice' | 'manual'
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "inventoryRevaluationLine_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "inventoryRevaluationLine_revaluation_fkey" FOREIGN KEY ("revaluationId", "companyId")
+ REFERENCES "inventoryRevaluation"("id", "companyId") ON DELETE CASCADE,
+ CONSTRAINT "inventoryRevaluationLine_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+-- RLS: 4 named policies each; SELECT get_companies_with_employee_role(),
+-- writes get_companies_with_employee_permission('inventory_*')::text[]
+
+-- 4) Landed cost documents (same conventions; abbreviated)
+CREATE TYPE "landedCostChargeType" AS ENUM ('Freight','Duty','Brokerage','Insurance','Other');
+CREATE TYPE "landedCostAllocationBasis" AS ENUM ('Value','Quantity','Weight');
+CREATE TABLE "landedCost" (
+ "id" TEXT NOT NULL DEFAULT id('lc'),
+ "landedCostId" TEXT NOT NULL, -- readable sequence
+ "supplierId" TEXT NOT NULL,
+ "currencyCode" TEXT NOT NULL,
+ "exchangeRate" NUMERIC NOT NULL DEFAULT 1, -- FX helpers from #1030, never hand-rolled
+ "status" TEXT NOT NULL DEFAULT 'Draft', -- Draft | Posted
+ "postingDate" DATE,
+ "supplierReference" TEXT,
+ "postedBy" TEXT REFERENCES "user"("id"),
+ "postedAt" TIMESTAMP WITH TIME ZONE,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "landedCost_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "landedCost_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE TABLE "landedCostLine" (
+ "id" TEXT NOT NULL DEFAULT id('lcl'),
+ "landedCostId" TEXT NOT NULL,
+ "chargeType" "landedCostChargeType" NOT NULL,
+ "amount" NUMERIC NOT NULL,
+ "allocationBasis" "landedCostAllocationBasis" NOT NULL DEFAULT 'Value',
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "landedCostLine_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "landedCostLine_landedCost_fkey" FOREIGN KEY ("landedCostId", "companyId")
+ REFERENCES "landedCost"("id", "companyId") ON DELETE CASCADE,
+ CONSTRAINT "landedCostLine_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE TABLE "landedCostAllocation" (
+ "id" TEXT NOT NULL DEFAULT id('lca'),
+ "landedCostLineId" TEXT NOT NULL,
+ "receiptLineId" TEXT NOT NULL,
+ "costLedgerId" TEXT, -- target layer
+ "allocatedAmount" NUMERIC NOT NULL, -- capitalized + expensed
+ "capitalizedAmount" NUMERIC NOT NULL, -- remaining-fraction share → inventory/layer
+ "expensedAmount" NUMERIC NOT NULL, -- consumed-fraction share → COGS
+ "basisSnapshot" JSONB, -- value/qty/weight inputs at allocation time
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ CONSTRAINT "landedCostAllocation_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "landedCostAllocation_line_fkey" FOREIGN KEY ("landedCostLineId", "companyId")
+ REFERENCES "landedCostLine"("id", "companyId") ON DELETE CASCADE,
+ CONSTRAINT "landedCostAllocation_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+-- RLS on all three: 4 named policies, purchasing_* permission family
+
+-- 5) companySettings: "nrvLookbackDays" INTEGER NOT NULL DEFAULT 90,
+-- "nrvCostToSellPct" NUMERIC NOT NULL DEFAULT 0
+
+-- 6) Enum values (ADD VALUE IF NOT EXISTS): journalEntrySourceType/journalLineDocumentType
+-- + itemLedgerDocumentType gain 'Inventory Revaluation' and 'Landed Cost';
+-- purchaseInvoiceLineType gains 'Landed Cost'
+
+-- 7) Close-checklist: INSERT INTO "periodCloseTaskDefinition" for 'LCNRV run'
+-- and 'Overhead variance true-up' (period-closing spec registration rule)
+```
+
+Run `pnpm run generate:types` after migrations, before typechecking.
+
+## API / Service Changes
+
+- `items.models.ts`: `standardCost` re-enters `itemCostValidator`; costing route action persists it and triggers the standard-change revaluation guard.
+- `recalculate` edge function: new `standardCostRollup` case; Inngest `recalculateFunction` passthrough.
+- `post-receipt`: Standard-method branch (inventory at standard, delta to 5210); landed-cost-aware layer linkage unchanged.
+- `close-job`: three-way variance split posting; clears WIP for Standard output.
+- `post-production-event`: overhead absorption line; reversal path covers it via existing per-account negation.
+- New edge function `post-inventory-revaluation` (shared by revaluation + LCNRV): validates period state, writes `Revaluation` cost-ledger rows + journal in one Kysely transaction (pattern: `post-production-event`'s `db.transaction()` + `getNextSequence` + `getCurrentAccountingPeriod`).
+- New edge function `post-landed-cost`; `post-purchase-invoice` learns the `Landed Cost` line type (Dr 2126 / Cr AP).
+- `inventory.service.ts`: `getInventoryRevaluations`, `insertInventoryRevaluation`, `proposeLcnrvRun` (the NRV query, §3), `getInventoryWriteDownRollforward`; `insertManualInventoryAdjustment` gains the GL leg (§4).
+- `purchasing` service: `getLandedCosts`, `upsertLandedCost`, `allocateLandedCost` (basis math server-side).
+- `calculate-cogs.ts`: FIFO/LIFO layer cost includes applied adjustment rows.
+
+## UI Changes
+
+- Item costing form: `standardCost` input (Standard method only) + "Roll up standard cost" action.
+- Inventory → Revaluations: index table + document editor (lines grid with current/new cost, extended delta); LCNRV run wizard (parameters → proposed lines with NRV source badges, per-line edit, post).
+- Purchasing → Landed Costs: document editor with allocation panel (pick receipts, choose basis, preview per-line capitalized/expensed split).
+- Accounting reports: Inventory Write-Down Rollforward (CSV export).
+- Close drawer: the two new tasks render via the period-closing checklist UI automatically.
+
+## Acceptance Criteria
+
+- [ ] **Standard receipt variance (numeric).** Item STD-100, `standardCost = $10.00`, PO at $11.00, receive 100: journal is Dr Inventory $1,000.00, Dr Purchase Price Variance (line "Standard Cost Variance") $100.00, Cr GR/IR $1,100.00; the cost layer carries `cost = 1000, quantity = 100`. Invoice later arrives at $11.20: existing PPV logic posts Dr GR/IR $1,100.00, Dr PPV $20.00, Cr AP $1,120.00 — unchanged.
+- [ ] **Production variance (numeric).** Job produces 10 × STD-200 (rolled-up standard $50.00 = $30 material + $15 labor + $5 overhead); actual WIP accumulates $540.00 ($325 material, $155 labor, $60 overhead). Job close posts Dr Material Usage Variance $25.00, Dr Labor & Machine Variance $5.00, Dr Overhead Variance $10.00, Cr WIP $40.00; output layer = 10 × $50 = $500.00; WIP nets to zero for the job.
+- [ ] **Standard-change guard.** Editing `standardCost` $10 → $9.50 with 40 on hand generates a Draft revaluation; posting it writes a `Revaluation` cost-ledger row of −$20.00 and Dr 5320 $20.00 / Cr Inventory $20.00.
+- [ ] **LCNRV (numeric).** Item with layers 60 @ $21.00 and 40 @ $18.50 (carrying $2,000.00); posted sales invoices in the 90-day lookback average $19.00; cost-to-sell 5% ⇒ proposed NRV $18.05. Run proposes write-downs 60 × $2.95 = $177.00 and 40 × $0.45 = $18.00; posting yields Dr 5320 $195.00 / Cr Inventory $195.00, both layers' effective unit cost = $18.05, and a subsequent shipment of 10 relieves COGS at $180.50. No reversal path exists in PRIMARY; the write-down rows carry `proposedNrv`/`nrvSource` for the multi-book generator.
+- [ ] **NRV editability.** A proposed line can be edited (NRV and quantity) before posting; the posted line retains both `proposedNrv` and the posted `newUnitCost`; the override appears in the audit log.
+- [ ] **Quantity adjustment GL (numeric).** Negative adjustment of 10 units consuming a $7.00 FIFO layer posts Dr Inventory Adjustment (5310) $70.00 / Cr Inventory $70.00; positive adjustment of 5 at unit cost $7.00 posts the mirror. With `accountingEnabled = false`, itemLedger behavior is byte-identical to today and no journal is written.
+- [ ] **Overhead absorption (numeric).** A 2.0h production event at `workCenter.overheadRate = $15.00/h` posts Dr WIP $30.00 / Cr Overhead Absorption (5070) $30.00 in the same journal as the labor line; editing the event reverses and reposts both lines. Period true-up: absorbed $12,000 vs actual pool $13,000 proposes Dr Overhead Variance $1,000.00 / Cr 5070 $1,000.00.
+- [ ] **Landed cost (numeric).** Freight bill $150.00 allocated by value over receipt lines valued $1,000 (200 units @ $5.00, 50 already consumed) and $500 (fully on hand): allocations $100/$50. Posting: Dr Inventory $75.00 + $50.00, Dr COGS $25.00, Cr Landed Cost Clearing (2126) $150.00; remaining 150 units of layer A now consume at (150 × $5 + $75)/150 = $5.50. Freight vendor invoice posts Dr 2126 $150.00 / Cr AP $150.00; 2126 nets to zero for the document.
+- [ ] **Rollforward.** After the LCNRV example plus the 10-unit shipment, the write-down rollforward shows additions $195.00 and relief $29.50 (10 × $2.95) in the correct periods, and exports to CSV.
+- [ ] **Close integration.** Both task definitions appear in the next opened period's checklist; LCNRV is a Blocker on the fiscal year's final period and a skippable Warning otherwise.
+- [ ] All postings balance (Σ = 0 per journal), respect Locked/Closed period rules, and `pnpm exec turbo run typecheck --filter=...` passes for touched packages after `pnpm run generate:types`.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| `calculate-cogs` change touches every FIFO/LIFO consumption path | High | Superset semantics (no applied rows ⇒ old result); unit tests over layer math incl. applied rows; ship first, alone |
+| Standard cutover on items with existing average-cost history | Med | Standard takes effect only via explicit entry; the revaluation guard posts the transition delta so the GL never jumps silently |
+| NRV proposal quality on low-volume items | Med | Fallback chain + `No NRV basis` flag + mandatory human review before posting (decision 14) |
+| Overhead pool definition too coarse in v1 | Med | True-up is a *proposed* JE a human posts; pool config UI fast-follows |
+| Landed cost across currencies | Med | Charges convert at document `exchangeRate` via the FX-normalization helpers (#1030) — never a hand-rolled operator |
+| Variance-split logic in `close-job` misclassifies elements | Med | Cost elements tagged at absorption time (material/labor/overhead journal lines are already distinct accounts); residual-only fallback to 5220 with a warning |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] NRV source — **auto-proposed from recent selling prices less costs to complete/sell, editable per line** (Brad, 2026-07-04; query defined in §3).
+- [x] LCNRV reversal — **US GAAP no-reversal in PRIMARY; IAS 2 reversal later via multi-book adjustment generator** (`.ai/specs/2026-07-04-multi-book.md`).
+- [x] PPV vs standard variance — **both; invoice-vs-receipt PPV unchanged; receipt-time standard variance is its own line**.
+- [x] Revaluation contra account — **dedicated 5320** (decision 8; `inventoryAdjustmentVarianceAccount` reserved for quantity effects).
+- [x] Periodic pieces on the close checklist — **yes, both registered** per the period-closing registration rule.
+
+No new blocking questions surfaced while writing; judgment calls (direct write-down vs reserve, dormant 5250/5260, landed-cost-on-standard → PPV, overhead pool v1 definition) are baked as Design Decisions 9, 12, 13 and the overhead-pool risk row, and are revisitable without schema churn.
+
+## Changelog
+
+- 2026-07-04: Created — readiness finding GAP-3, tracking issue crbnos/carbon#1040. Grounded in code exploration (`itemCost`/cost layers/`calculate-cogs`, `post-receipt`/`post-purchase-invoice`/`post-production-event`/`close-job` posting paths, `20260315000000` chart reset) and `.ai/research/public-company-compliance.md` (ASC 330 / IAS 2). NRV auto-proposal + per-book reversal split resolved by Brad pre-writing.
diff --git a/.ai/specs/2026-07-04-lease-accounting.md b/.ai/specs/2026-07-04-lease-accounting.md
new file mode 100644
index 0000000000..d50f0cfed8
--- /dev/null
+++ b/.ai/specs/2026-07-04-lease-accounting.md
@@ -0,0 +1,402 @@
+# Lease Accounting (ASC 842 / IFRS 16) — Lessee + Lessor Subledger
+
+> Status: in-progress
+> Author: Claude (readiness program, GAP-2)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1056
+> Readiness finding: GAP-2 (`.ai/specs/2026-07-03-public-company-readiness.md`)
+
+## TLDR
+
+Carbon has **zero lease accounting code** (verified 2026-07-04: `grep -ri lease` across migrations and `modules/accounting` yields only false positives — "release", the Romania ISO code `ROU`). This spec builds a lease subledger beside fixed assets in the accounting module: a lease master with payment structures, IBR, and term options; PV computation producing an ROU asset + lease liability with **effective-interest schedules**; ASC 842 operating/finance classification with the correct expense pattern per class; short-term and low-value practical expedients; **modifications and remeasurements** that re-spread schedules from the effective date; **lessor accounting** (operating / sales-type / direct financing) with full schema, operating-lessor income posting in v1, and net-investment interest posting in v1 (commencement derecognition JE is system-drafted, user-posted — see Lessor section); monthly lease journals generated by a scheduled Inngest run and posted as `accounting`-source entries under the period matrix; a **"Post lease journals"** close-checklist task with an auto-check on due unposted schedule lines; disclosure data (maturity analysis, weighted-average term and discount rate, cash paid); and **IFRS 16 single-model treatment as an adjustment-book delta** consuming the multi-book generator framework (`.ai/specs/2026-07-04-multi-book.md`, parallel spec on this branch).
+
+## Problem Statement
+
+ASC 842 / IFRS 16 put essentially all leases on the balance sheet. A public-company (or audit-ready) manufacturer with facility, equipment, and vehicle leases must produce, per period and per book: ROU asset and lease liability balances tied to effective-interest schedules, the correct expense pattern (single straight-line lease cost for ASC 842 operating leases; interest + amortization for finance leases and *all* IFRS 16 leases), remeasured schedules after modifications, and the ASC 842-20-50 / IFRS 16 ¶51+ disclosure package (maturity analysis by year, weighted-average remaining term and discount rate, cash paid for leases). Carbon has none of this; the interim path (FinQuery-style JE upload via GAP-E1) leaves no subledger tying to the GL. Manufacturers also **lease out** equipment (lessor side) — the ambitious scope Brad approved 2026-07-04 includes lessor classification and posting, not just lessee.
+
+## Research Basis
+
+- `.ai/research/public-company-compliance.md` — "842/IFRS 16: ROU/liability amortization schedules per book, maturity analysis"; leases named as ERP-native at mid-market (NetSuite Fixed Assets Lease Accounting precedent); IFRS 16 vs ASC 842 named as the canonical case where "the same lease produces different P&L per book".
+- `.ai/rules/fixed-asset-lifecycle.md` + `20260524143826/27` migrations — the sibling subledger whose patterns this spec copies: class table with NOT NULL account FKs, Draft→Posted run batches, application-level calculation (no DB functions), `journalEntrySourceType` additions.
+- `.ai/specs/2026-07-02-period-closing.md` — persisted close checklist (`periodCloseTaskDefinition` / `periodCloseTask`); later features "register their own definitions when they ship". This spec registers one.
+- `.ai/specs/2026-07-04-multi-book.md` (parallel agent, same branch) — adjustment-book generator framework; the IFRS 16 delta here is a registered generator, not a fork of the poster.
+
+## Proposed Solution
+
+### 1. Lease master
+
+One `lease` table covers both roles (`role`: `Lessee` | `Lessor`) — counterparty is `supplierId` (lessee) or `customerId` (lessor). Core fields: readable `leaseId` (sequence `lease`), `leaseClassId` (GL mapping + defaults), commencement date, non-cancellable end date, renewal/termination/purchase options (own table, each with a "reasonably certain" flag that extends the accounting term), IBR (`discountRate`, annual %, converted to periodic at computation), payment frequency (`Monthly`/`Quarterly`/`Annual`), timing (`Advance`/`Arrears`), currency, initial direct costs, incentives received, prepaid rent — all feeding ROU = liability + IDC + prepaid − incentives. Classification inputs live on the lease: underlying-asset fair value, remaining economic life (months), ownership-transfer and specialized-asset flags, residual value guaranteed. Status: `Draft` → `Active` (activation computes schedule v1 and posts/drafts the commencement JE) → `Terminated`/`Expired`.
+
+**Payment structure**, not a flat amount: `leasePaymentTerm` rows (date range, amount per period, optional escalation % per annum) generate the dated fixed cashflows; in-substance-fixed payments are entered as fixed. **Variable payments** (usage/sales-based, and index-linked *changes*) are never in the liability — `leaseVariablePayment` rows are recorded as incurred and expensed by the monthly run (ASC 842: index-linked payments stay measured at the commencement index; rate changes hit variable expense. IFRS 16 remeasures on index change — handled as a remeasurement event, see §4, and flagged as IFRS-book-relevant).
+
+### 2. PV computation, schedules, classification
+
+`buildLeaseSchedule()` (in `accounting.utils.ts`, beside `buildDepreciationLines()`) discounts the fixed cashflows at the periodic IBR and emits one `leaseScheduleLine` per period carrying **both expense patterns** so later books/reclassifications never recompute: `openingLiability`, `paymentAmount`, `interestAmount`, `principalAmount`, `closingLiability`, `rouAmortizationFinance` (straight-line ROU/term), `leaseCostOperating` (total cost/term), `rouAmortizationOperating` (plug = operating cost − interest). The last line absorbs rounding so the liability closes to exactly 0.
+
+**Classification (ASC 842-10-25-2)** is computed at activation and stored with its inputs: (a) ownership transfers; (b) purchase option reasonably certain; (c) term ≥ major part of remaining economic life (policy threshold, default **75%**); (d) PV of payments + guaranteed residual ≥ substantially all of fair value (default **90%**); (e) specialized asset. Any test true ⇒ `Finance`, else `Operating`. Thresholds live on `companySettings`; a manual override with required reason is allowed and audit-logged.
+
+**Practical expedients**: `isShortTerm` (term ≤ 12 months, no reasonably-certain purchase option — policy election on `companySettings`, default on) and `isLowValue` (IFRS-only election, threshold default $5,000) bypass capitalization entirely: no liability/ROU, straight-line expense line in the monthly run, and separate disclosure buckets for cash paid.
+
+**Worked example (acceptance baseline).** 36-month lease, $10,000/month in arrears, 6% annual IBR (0.5%/month): initial liability = 10,000 × (1 − 1.005⁻³⁶)/0.005 = **$328,710.16** = initial ROU (no IDC/incentives). Month 1: interest **$1,643.55**, principal **$8,356.45**, closing liability **$320,353.71**. Finance pattern month 1: interest $1,643.55 + ROU amortization $9,130.84 (= 328,710.16/36) = $10,774.39 expense. Operating pattern month 1: single lease cost $10,000.00, ROU amortization plug $8,356.45.
+
+### 3. Journal patterns (lessee)
+
+| Event | Finance | Operating |
+|---|---|---|
+| Commencement | Dr ROU asset / Cr Lease liability (+ Cr Cash for IDC, Dr for incentives) | same |
+| Monthly — payment | Dr Lease liability (principal) + Dr Interest expense / Cr AP‑lease clearing | Dr Operating lease expense (leaseCostOperating) / Cr AP‑lease clearing (payment); Dr Lease liability (principal) / Cr Accumulated ROU amortization (plug) |
+| Monthly — amortization | Dr ROU amortization expense / Cr Accumulated ROU amortization (SL) | (in the plug above — single expense line preserved) |
+| Variable / short-term / low-value | Dr Variable (or Short-term) lease expense / Cr AP‑lease clearing | same |
+
+The credit leg posts to a **lease clearing account** relieved by the existing AP invoice/payment flow (leases are invoiced by real suppliers); companies not entering supplier invoices for rent can map clearing = cash. `journalEntrySourceType` gains `'Lease'` (precedent: `'Asset Depreciation'`).
+
+### 4. Modifications and remeasurements
+
+`leaseEvent` records every reassessment with `reason` (`Term Change`, `Payment Change`, `Index Change (IFRS)`, `Option Reassessment`, `Partial Termination`, `Full Termination`), effective date, revised inputs, and the liability before/after. Processing: schedule lines from the effective period forward are superseded (`scheduleVersion` bump; old lines kept, flagged), the liability is re-PV'd at the **revised** IBR when required (term/option changes) or the original rate (index changes under IFRS), and ROU is adjusted by the liability delta. Partial termination reduces ROU proportionately and posts a gain/loss; full termination derecognizes both and posts gain/loss. Modifications that add an ROU at market rate for an additional asset are a **new lease** (per both standards) — the UI offers "create linked lease". Posted history is never mutated — remeasurement affects only unposted future lines plus one adjustment JE at the effective date (period-close-safe by construction).
+
+### 5. Lessor accounting (the ambitious part)
+
+Same `lease` table, `role = 'Lessor'`, own classification enum (`Operating` / `Sales-Type` / `Direct Financing`) using the mirrored ASC 842-10-25-2/-3 tests (sales-type: any lessee-finance criterion; direct financing: PV + third-party residual guarantee ≥ substantially all + collection probable).
+
+- **Operating lessor — full posting in v1.** Underlying asset stays on `fixedAsset` and depreciates normally (existing runs; the lease links `fixedAssetId`). Monthly run posts straight-line lease income: Dr Lease receivable (clearing → AR invoice) / Cr Lease income; uneven cash vs straight-line income accrues to a straight-line rent receivable/liability account on the class.
+- **Sales-type / direct financing — schema + schedules + interest posting in v1; commencement derecognition system-drafted, user-posted.** The schedule engine reuses `leaseScheduleLine` with lessor semantics (`openingLiability` ≡ opening net investment; `interestAmount` ≡ interest income; residual accretes via a final unguaranteed-residual row). The **monthly interest-income accrual posts automatically in v1** (same poster, Dr Net investment / Cr Interest income; Dr Lease clearing / Cr Net investment for cash). The **commencement JE** (derecognize inventory/asset at carrying amount, recognize net investment, selling profit/COGS for sales-type) is generated as a **Draft journal proposal** the user reviews and posts, because automated derecognition must integrate with item costing/inventory relief that GAP-3 (standard cost, revaluation) has not landed yet — auto-posting a COGS relief against an unfinished costing layer would corrupt inventory valuation. This is a schema-now/auto-post-later cut on **one JE only**; everything downstream (net-investment schedule, interest income, receipts) posts automatically in v1.
+
+### 6. Monthly run + close checklist
+
+An Inngest cron (`packages/jobs`, monthly, per company — pattern GAP-4.1 will reuse for depreciation) creates a Draft **`leaseRun`** (`leaseRunId` readable, `periodEnd`, `status` `Draft|Posted` — mirrors `depreciationRun`) with one `leaseRunLine` per due item: unposted `leaseScheduleLine`s with period ≤ periodEnd, variable payments, short-term/low-value expense lines, operating-lessor income. `postLeaseRun()` (in `accounting.server.ts`, beside `postDepreciationRun()`) posts per lease with `getOrCreateAccountingPeriod(..., source: "accounting")`, stamps `journalId` on lines, and marks schedule lines Posted. Manual "create run now" button exists (depreciation-run parity).
+
+**Close checklist registration**: seed a `periodCloseTaskDefinition` — name **"Post lease journals"**, type Auto, `autoCheckKey: 'unposted-lease-schedules'`, severity **Warning** (parity with "Post depreciation runs"), ordered directly after it. The evaluator flags any Active lease with unposted schedule lines (or an unposted Draft `leaseRun`) dated in the period.
+
+### 7. IFRS 16 delta via adjustment book
+
+Key insight: ASC 842 operating leases are **already capitalized** — the IFRS 16 difference is expense pattern only, no balance-sheet reclass. The multi-book spec's generator framework gets a registered `ifrs16-lease` generator that, for each posted operating-lease period, emits into the IFRS adjustment book: Dr Interest expense (`interestAmount`) + Dr ROU amortization expense (`rouAmortizationFinance`) / Cr Operating lease expense (`leaseCostOperating`), net P&L delta = the front-loading difference. Zero recomputation — both patterns are persisted on every schedule line (§2). Finance leases and lessor leases generate no delta. IFRS-only remeasurements (index changes, low-value threshold differences) post book-specific `leaseEvent` adjustments through the same generator. If multi-book ships later than leases, the generator registers then; nothing here blocks on it.
+
+### 8. Disclosures
+
+Service-computed, no new posting: **maturity analysis** (undiscounted remaining fixed payments by each of the next 5 fiscal years + thereafter, less imputed interest, reconciling to the liability — lessor mirror for net investment), **weighted-average remaining lease term** and **weighted-average discount rate** (liability-weighted, split operating/finance), **cash paid** (operating-lease operating cash, finance principal = financing, finance interest = operating, plus short-term/variable buckets), ROU by class. Rendered on a Leases report route with CSV export (table-csv-export pattern).
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| GL account mapping | **`leaseClass` table** (Real Estate / Equipment / Vehicles seeded), NOT `accountDefault` columns | `fixedAssetClass` precedent is exact: per-class NOT NULL account FKs, seeded classes, class-level defaults. Leases need ~11 accounts × per-class variation (real-estate ROU vs equipment ROU); `accountDefault` is one row per company and already wide — 11 more columns there loses per-class mapping and violates the sibling subledger's pattern. |
+| One `lease` table for both roles | `role` column + role-specific nullable columns + CHECK constraints, two classification enums | Shared 80% (payments, term, IBR, schedules, events, runs); separate tables would duplicate the schedule/event/run machinery. CHECKs keep role integrity (lessee ⇒ `supplierId`, lessor ⇒ `customerId`). |
+| Schedule stores both expense patterns | `rouAmortizationFinance`, `leaseCostOperating`, `rouAmortizationOperating` on every line | Makes the IFRS 16 generator a pure reader; reclassification-on-modification re-spreads without recomputing history; costs 3 numeric columns. |
+| Remeasurement model | Versioned schedule (supersede future lines), never mutate posted lines | Posted-journal immutability (period-closing MW-1 fold-in) makes in-place edits impossible anyway; versions give the auditor the before/after. |
+| Lessor sales-type commencement JE | System-drafted, user-posted in v1; auto-post after GAP-3 costing lands | Auto derecognition needs inventory relief at correct carrying cost; standard costing is dead schema today (GAP-3). One manual-review JE vs corrupting inventory valuation. Interest schedules + posting are fully automatic in v1. |
+| Monthly posting vehicle | `leaseRun`/`leaseRunLine` Draft→Posted batch, Inngest-proposed | `depreciationRun` precedent; approvable batch matches MW-2 approval direction; scheduled proposal fixes the "entirely manual" gotcha fixed assets still have. |
+| Source type | Single `'Lease'` `journalEntrySourceType` value | Terminations/modifications are distinguishable via the lease/event FK on the run line; enum values are irreversible, add sparingly. |
+| Multi-tenancy (heuristic 1) | Every new table: `companyId`, composite PK `("id","companyId")`, `id('prefix')` defaults, audit columns, `customFields` on master tables | House convention; child FKs reference composites (tax-spec precedent). |
+| Service shape (heuristic 2) | All functions in `accounting.service.ts` / models in `accounting.models.ts`; Kysely transactions in `accounting.server.ts` (`postLeaseRun`, `activateLease`, `processLeaseEvent`); calc in `accounting.utils.ts`; `(client, companyId, ...)` → `{data, error}` | Leases live beside fixed assets in the accounting module — one service file per module, no new module. |
+| RLS (heuristic 3) | Four standard policies per table: SELECT `get_companies_with_employee_role()` (or `_permission('accounting_view')` matching fixed-asset tables), writes `get_companies_with_employee_permission('accounting_*')` | AR/AP-payments migration pattern (`20260630093809`). |
+| Permissions (heuristic 4) | Routes `view/create/update/delete: "accounting"`; posting `update: "accounting"` | Fixed-asset and depreciation-run route precedent exactly. |
+| Forms (heuristic 5) | `ValidatedForm` + zod (`leaseValidator`, `leaseClassValidator`, `leasePaymentTermValidator`, `leaseEventValidator`, `leaseRunValidator`); Drawer overlays for detail | House convention. |
+| Module layout (heuristic 6) | `modules/accounting/ui/Leases/`; routes `x+/lease+/` + `x+/lease-run+/` + list pages under `x+/accounting+/` | Mirrors `FixedAssets/` + `fixed-asset+/` + `depreciation-run+/`. |
+| Backward compatibility (heuristic 7) | Purely additive: new tables, one enum value, `companySettings`/checklist-seed additions; no existing surface changes | No frozen surface touched; companies without leases see one new nav item and one auto-passing close task. |
+
+## Data Model Changes
+
+One migration pair (enums + tables, fixed-asset pattern) plus a checklist-seed migration.
+
+```sql
+-- 1) Enum additions (separate migration, fixed-asset precedent)
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Lease';
+
+CREATE TYPE "leaseRole" AS ENUM ('Lessee', 'Lessor');
+CREATE TYPE "leaseStatus" AS ENUM ('Draft', 'Active', 'Terminated', 'Expired');
+CREATE TYPE "lesseeClassification" AS ENUM ('Operating', 'Finance');
+CREATE TYPE "lessorClassification" AS ENUM ('Operating', 'Sales-Type', 'Direct Financing');
+CREATE TYPE "leasePaymentFrequency" AS ENUM ('Monthly', 'Quarterly', 'Annual');
+CREATE TYPE "leasePaymentTiming" AS ENUM ('Advance', 'Arrears');
+CREATE TYPE "leaseEventType" AS ENUM ('Term Change', 'Payment Change', 'Index Change',
+ 'Option Reassessment', 'Partial Termination', 'Full Termination');
+CREATE TYPE "leaseOptionType" AS ENUM ('Renewal', 'Termination', 'Purchase');
+
+-- 2) Policy elections
+ALTER TABLE "companySettings"
+ ADD COLUMN "leaseShortTermExpedientEnabled" BOOLEAN NOT NULL DEFAULT TRUE,
+ ADD COLUMN "leaseLowValueExpedientEnabled" BOOLEAN NOT NULL DEFAULT FALSE, -- IFRS books only
+ ADD COLUMN "leaseLowValueThreshold" NUMERIC NOT NULL DEFAULT 5000,
+ ADD COLUMN "leaseMajorPartThresholdPercent" NUMERIC(5,2) NOT NULL DEFAULT 75,
+ ADD COLUMN "leaseSubstantiallyAllThresholdPercent" NUMERIC(5,2) NOT NULL DEFAULT 90;
+
+-- 3) leaseClass — GL mapping (fixedAssetClass pattern; seeded Real Estate / Equipment / Vehicles)
+CREATE TABLE "leaseClass" (
+ "id" TEXT NOT NULL DEFAULT id('lcls'),
+ "companyId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ -- lessee accounts (NOT NULL — class is unusable without them)
+ "rouAssetAccountId" TEXT NOT NULL REFERENCES "account"("id"),
+ "accumulatedRouAmortizationAccountId" TEXT NOT NULL REFERENCES "account"("id"),
+ "leaseLiabilityAccountId" TEXT NOT NULL REFERENCES "account"("id"),
+ "interestExpenseAccountId" TEXT NOT NULL REFERENCES "account"("id"),
+ "rouAmortizationExpenseAccountId" TEXT NOT NULL REFERENCES "account"("id"),
+ "operatingLeaseExpenseAccountId" TEXT NOT NULL REFERENCES "account"("id"),
+ "variableLeaseExpenseAccountId" TEXT NOT NULL REFERENCES "account"("id"),
+ "leaseClearingAccountId" TEXT NOT NULL REFERENCES "account"("id"),
+ -- lessor accounts (nullable — required only when a lessor lease uses the class; CHECK at activation)
+ "leaseIncomeAccountId" TEXT REFERENCES "account"("id"),
+ "netInvestmentAccountId" TEXT REFERENCES "account"("id"),
+ "interestIncomeAccountId" TEXT REFERENCES "account"("id"),
+ "straightLineRentAccountId" TEXT REFERENCES "account"("id"),
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "leaseClass_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "leaseClass_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+-- 4) lease — master (both roles)
+CREATE TABLE "lease" (
+ "id" TEXT NOT NULL DEFAULT id('lse'),
+ "companyId" TEXT NOT NULL,
+ "leaseId" TEXT NOT NULL, -- readable, from sequence
+ "leaseClassId" TEXT NOT NULL,
+ "role" "leaseRole" NOT NULL DEFAULT 'Lessee',
+ "status" "leaseStatus" NOT NULL DEFAULT 'Draft',
+ "name" TEXT NOT NULL,
+ "supplierId" TEXT, -- lessee role
+ "customerId" TEXT, -- lessor role
+ "fixedAssetId" TEXT, -- lessor underlying asset / lessee finance-to-own link
+ "locationId" TEXT,
+ "commencementDate" DATE NOT NULL,
+ "endDate" DATE NOT NULL, -- non-cancellable; options extend accounting term
+ "discountRate" NUMERIC(8,5) NOT NULL, -- annual IBR % (or rate implicit, lessor)
+ "paymentFrequency" "leasePaymentFrequency" NOT NULL DEFAULT 'Monthly',
+ "paymentTiming" "leasePaymentTiming" NOT NULL DEFAULT 'Arrears',
+ "currencyCode" TEXT NOT NULL,
+ "initialDirectCosts" NUMERIC NOT NULL DEFAULT 0,
+ "incentivesReceived" NUMERIC NOT NULL DEFAULT 0,
+ "prepaidAmount" NUMERIC NOT NULL DEFAULT 0,
+ -- classification inputs + result
+ "fairValue" NUMERIC,
+ "economicLifeMonths" INTEGER,
+ "ownershipTransfers" BOOLEAN NOT NULL DEFAULT FALSE,
+ "specializedAsset" BOOLEAN NOT NULL DEFAULT FALSE,
+ "residualGuaranteed" NUMERIC NOT NULL DEFAULT 0,
+ "unguaranteedResidual" NUMERIC NOT NULL DEFAULT 0, -- lessor
+ "lesseeClassification" "lesseeClassification",
+ "lessorClassification" "lessorClassification",
+ "classificationOverride" BOOLEAN NOT NULL DEFAULT FALSE,
+ "classificationOverrideReason" TEXT,
+ "isShortTerm" BOOLEAN NOT NULL DEFAULT FALSE,
+ "isLowValue" BOOLEAN NOT NULL DEFAULT FALSE,
+ -- computed at activation
+ "initialLiability" NUMERIC, -- lessor: initial net investment
+ "initialRouAsset" NUMERIC,
+ "terminationDate" DATE,
+ "terminationGainLoss" NUMERIC,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "lease_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "lease_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "lease_leaseClass_fkey" FOREIGN KEY ("leaseClassId", "companyId")
+ REFERENCES "leaseClass"("id", "companyId"),
+ CONSTRAINT "lease_role_counterparty_check" CHECK (
+ ("role" = 'Lessee' AND "customerId" IS NULL) OR
+ ("role" = 'Lessor' AND "supplierId" IS NULL)
+ ),
+ CONSTRAINT "lease_leaseId_unique" UNIQUE ("leaseId", "companyId")
+);
+
+-- 5) Payment structure + options + variable actuals
+CREATE TABLE "leasePaymentTerm" ( -- fixed payments, escalations
+ "id" TEXT NOT NULL DEFAULT id('lpt'),
+ "companyId" TEXT NOT NULL,
+ "leaseId" TEXT NOT NULL, -- FK lease(id, companyId)
+ "startDate" DATE NOT NULL,
+ "endDate" DATE NOT NULL,
+ "amountPerPeriod" NUMERIC NOT NULL,
+ "annualEscalationPercent" NUMERIC(5,2) NOT NULL DEFAULT 0,
+ -- audit columns, composite PK, FK, RLS as above
+ CONSTRAINT "leasePaymentTerm_pkey" PRIMARY KEY ("id", "companyId")
+);
+
+CREATE TABLE "leaseOption" ( -- renewal/termination/purchase options
+ "id" TEXT NOT NULL DEFAULT id('lop'),
+ "companyId" TEXT NOT NULL,
+ "leaseId" TEXT NOT NULL,
+ "optionType" "leaseOptionType" NOT NULL,
+ "exerciseDate" DATE NOT NULL,
+ "extensionMonths" INTEGER, -- renewal
+ "optionAmount" NUMERIC, -- purchase price / termination penalty
+ "reasonablyCertain" BOOLEAN NOT NULL DEFAULT FALSE, -- true ⇒ in accounting term/liability
+ CONSTRAINT "leaseOption_pkey" PRIMARY KEY ("id", "companyId")
+);
+
+CREATE TABLE "leaseVariablePayment" ( -- expensed as incurred, picked up by the run
+ "id" TEXT NOT NULL DEFAULT id('lvp'),
+ "companyId" TEXT NOT NULL,
+ "leaseId" TEXT NOT NULL,
+ "paymentDate" DATE NOT NULL,
+ "amount" NUMERIC NOT NULL,
+ "description" TEXT,
+ "leaseRunLineId" TEXT, -- set when posted
+ CONSTRAINT "leaseVariablePayment_pkey" PRIMARY KEY ("id", "companyId")
+);
+
+-- 6) Effective-interest schedule (both roles; lessor: liability columns = net investment)
+CREATE TABLE "leaseScheduleLine" (
+ "id" TEXT NOT NULL DEFAULT id('lsl'),
+ "companyId" TEXT NOT NULL,
+ "leaseId" TEXT NOT NULL,
+ "scheduleVersion" INTEGER NOT NULL DEFAULT 1,
+ "superseded" BOOLEAN NOT NULL DEFAULT FALSE, -- true when a later version replaces this unposted line
+ "periodDate" DATE NOT NULL, -- period end
+ "openingLiability" NUMERIC NOT NULL, -- lessor: opening net investment
+ "paymentAmount" NUMERIC NOT NULL,
+ "interestAmount" NUMERIC NOT NULL, -- lessor: interest income
+ "principalAmount" NUMERIC NOT NULL,
+ "closingLiability" NUMERIC NOT NULL,
+ "rouAmortizationFinance" NUMERIC NOT NULL, -- SL ROU/term (also the IFRS-book pattern)
+ "leaseCostOperating" NUMERIC NOT NULL, -- total cost / term
+ "rouAmortizationOperating" NUMERIC NOT NULL, -- plug = leaseCostOperating − interest
+ "postedAt" TIMESTAMP WITH TIME ZONE,
+ "journalId" TEXT,
+ CONSTRAINT "leaseScheduleLine_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "leaseScheduleLine_unique" UNIQUE ("leaseId", "companyId", "scheduleVersion", "periodDate")
+);
+
+-- 7) Remeasurement / modification events
+CREATE TABLE "leaseEvent" (
+ "id" TEXT NOT NULL DEFAULT id('lev'),
+ "companyId" TEXT NOT NULL,
+ "leaseId" TEXT NOT NULL,
+ "eventType" "leaseEventType" NOT NULL,
+ "effectiveDate" DATE NOT NULL,
+ "revisedDiscountRate" NUMERIC(8,5), -- NULL ⇒ original rate retained (index changes)
+ "liabilityBefore" NUMERIC NOT NULL,
+ "liabilityAfter" NUMERIC NOT NULL,
+ "rouAdjustment" NUMERIC NOT NULL,
+ "gainLoss" NUMERIC, -- partial/full termination
+ "newScheduleVersion" INTEGER NOT NULL,
+ "notes" TEXT,
+ "journalId" TEXT, -- the adjustment JE
+ CONSTRAINT "leaseEvent_pkey" PRIMARY KEY ("id", "companyId")
+);
+
+-- 8) Monthly run batch (depreciationRun pattern)
+CREATE TABLE "leaseRun" (
+ "id" TEXT NOT NULL DEFAULT id('lrun'),
+ "companyId" TEXT NOT NULL,
+ "leaseRunId" TEXT NOT NULL, -- readable
+ "periodEnd" DATE NOT NULL,
+ "status" TEXT NOT NULL DEFAULT 'Draft' CHECK ("status" IN ('Draft', 'Posted')),
+ "postedAt" TIMESTAMP WITH TIME ZONE,
+ "postedBy" TEXT REFERENCES "user"("id"),
+ CONSTRAINT "leaseRun_pkey" PRIMARY KEY ("id", "companyId")
+);
+
+CREATE TABLE "leaseRunLine" ( -- one per lease per component
+ "id" TEXT NOT NULL DEFAULT id('lrl'),
+ "companyId" TEXT NOT NULL,
+ "leaseRunId" TEXT NOT NULL,
+ "leaseId" TEXT NOT NULL,
+ "leaseScheduleLineId" TEXT, -- NULL for variable/short-term/low-value expense lines
+ "lineType" TEXT NOT NULL CHECK ("lineType" IN
+ ('Schedule', 'Variable', 'Short-Term', 'Low-Value', 'Lessor Income', 'Lessor Interest')),
+ "amount" NUMERIC NOT NULL,
+ "journalId" TEXT,
+ CONSTRAINT "leaseRunLine_pkey" PRIMARY KEY ("id", "companyId")
+);
+
+-- RLS: all tables — 4 policies each, e.g.
+ALTER TABLE "lease" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "lease_SELECT" ON "lease" FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_view'))::text[]));
+-- INSERT/UPDATE/DELETE with accounting_create / accounting_update / accounting_delete
+
+-- 9) Seeds: 'lease' + 'leaseRun' sequences; GL accounts per company group
+-- (ROU Asset, Accumulated ROU Amortization, Lease Liability, ROU Amortization Expense,
+-- Operating/Variable Lease Expense, Lease Clearing, Lease Income, Net Investment in Leases,
+-- Interest Income — numbers assigned at implementation to fit the seeded chart, fixed-asset
+-- seed pattern 20260525084319); 3 leaseClass rows per company; periodCloseTaskDefinition
+-- 'Post lease journals' (Auto, autoCheckKey 'unposted-lease-schedules', Warning, after depreciation task)
+```
+
+## API / Service Changes
+
+```ts
+// accounting.service.ts — CRUD + queries (client-first, {data, error})
+get/insert/update/deleteLease, getLeases(filters), getLeaseClass(es) + CRUD,
+getLeasePaymentTerms/Options/VariablePayments + CRUD (Draft-only mutation),
+getLeaseSchedule(leaseId, { version? }), getLeaseEvents(leaseId),
+getLeaseRun(s), getLeaseRunLines,
+getLeaseMaturityAnalysis(companyId, asOfDate) // disclosure §8
+getLeaseWeightedAverages(companyId, asOfDate)
+getLeaseCashPaidSummary(companyId, periodRange)
+
+// accounting.server.ts — Kysely transactions
+activateLease() // classify, PV, schedule v1, commencement JE (lessee auto; lessor sales-type → Draft JE)
+processLeaseEvent() // remeasure: supersede future lines, new version, adjustment JE, gain/loss
+postLeaseRun() // per-lease journals, source 'Lease', getOrCreateAccountingPeriod(source: "accounting")
+
+// accounting.utils.ts
+buildLeaseSchedule(), classifyLease(), presentValue(), expandPaymentTerms()
+
+// accounting.models.ts — validators + enum arrays (leaseRoles, lesseeClassifications, …)
+
+// packages/jobs — inngest cron 'lease-run-proposal' (monthly per company): insert Draft leaseRun + lines
+// close checklist — evaluator 'unposted-lease-schedules' added to getPeriodCloseReadiness auto-check registry
+// multi-book (parallel spec) — register generator 'ifrs16-lease' reading posted schedule lines (§7)
+```
+
+Routes (fixed-asset layout): `x+/accounting+/leases*`, `lease-classes*`, `lease-runs*` (lists/new); `x+/lease+/$leaseId.{tsx,activate,modify,terminate,delete}`; `x+/lease-run+/$leaseRunId.{tsx,post,delete}`; `x+/accounting+/lease-disclosures.tsx`.
+
+## UI Changes
+
+- **Leases table** + New Lease form (role, class, counterparty, dates, IBR, expedient flags); detail Drawer with tabs: Payments (terms + options + variable), Schedule (versioned, posted badges), Classification (test results + override), Events, Disclosures snapshot.
+- **Activate** flow shows computed classification, initial liability/ROU, and the commencement JE preview before confirm; **Modify/Terminate** flows capture the event and preview the re-spread + adjustment JE.
+- **Lease runs**: list + Draft run detail (lines grouped by lease), Post button — depreciation-run parity.
+- **Lease classes** settings page (asset-classes parity). **Disclosures report** page with maturity table, weighted averages, cash-paid summary, CSV export.
+- Flash messages on all transitions; close drawer shows the new task automatically via the checklist substrate.
+
+## Acceptance Criteria
+
+- [ ] Grep baseline: `lease*` tables, services, and routes exist; `journalEntrySourceType` contains `'Lease'`.
+- [ ] **Numeric example**: a Lessee lease, 36 months, $10,000/month in Arrears, 6% IBR → activation computes initial liability = initial ROU = **$328,710.16** (±$0.01); schedule v1 has 36 lines; line 1 = interest **$1,643.55** / principal **$8,356.45** / closing **$320,353.71**; line 36 closes to exactly $0.00 (rounding absorbed on the final line).
+- [ ] Same lease with `fairValue` such that PV/FV ≥ 90% classifies **Finance**; month-1 posted JE set: Dr Interest 1,643.55 + Dr Lease liability 8,356.45 / Cr Lease clearing 10,000.00, and Dr ROU amortization expense 9,130.84 / Cr Accumulated ROU amortization 9,130.84.
+- [ ] Same lease classified **Operating** (tests all false) posts a single $10,000.00 lease cost and reduces liability 8,356.45 / accumulated ROU amortization 8,356.45; total expense over 36 months equals $360,000.00 under both classifications.
+- [ ] Payment-timing Advance and quarterly frequency produce correct PV (annuity-due / quarterly rate) — unit tests on `buildLeaseSchedule()`.
+- [ ] A 12-month lease with the short-term expedient creates no liability/ROU and posts straight-line expense via run lines of type `Short-Term`.
+- [ ] **Modification**: extending the example lease by 12 months at month 12 with a revised rate creates schedule v2 from month 13, marks unposted v1 lines superseded (posted lines untouched), posts one ROU/liability adjustment JE equal to the liability delta, and the v2 schedule closes to $0.00.
+- [ ] **Partial termination** reduces ROU proportionately and posts the gain/loss; **full termination** derecognizes both balances.
+- [ ] **Lessor operating**: monthly run posts Dr Lease clearing / Cr Lease income straight-line; uneven payment terms accrue to the straight-line rent account. **Lessor sales-type**: activation generates a Draft commencement JE (not auto-posted) and a net-investment schedule; monthly interest income posts automatically; net investment closes to unguaranteed residual at term end.
+- [ ] Inngest monthly job creates exactly one Draft `leaseRun` per company per period (idempotent); `postLeaseRun` is blocked in Closed periods and allowed in Locked (source `"accounting"`).
+- [ ] Close checklist for a period with due unposted schedule lines shows "Post lease journals" failing (Warning, skippable with reason); it passes after posting.
+- [ ] Disclosure service: maturity analysis buckets undiscounted payments by the next 5 fiscal years + thereafter and reconciles (total − imputed interest = liability balance); weighted-average term and rate computed liability-weighted split by classification; cash-paid summary splits operating/financing/short-term/variable.
+- [ ] IFRS 16 generator (`ifrs16-lease`) registered per the multi-book spec emits, for a posted operating-lease month, an adjustment-book JE reclassifying 10,000.00 operating cost into 1,643.55 interest + 9,130.84 amortization (net delta 774.39 in month 1); no delta for finance leases.
+- [ ] `pnpm run generate:types` + scoped typecheck pass; RLS verified on all new tables (4 policies each).
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Multi-book spec slips — IFRS delta has no generator surface | Med | §7 is read-only over persisted schedule columns; generator registers whenever multi-book lands, nothing else blocks. |
+| Sales-type derecognition mispriced while costing (GAP-3) is incomplete | Med | v1 keeps the commencement JE as a system-drafted, user-posted entry; auto-post gated on GAP-3. |
+| Rounding drift across 36–120 line schedules | Low | Last-line absorbs residual; unit tests assert exact closure to 0. |
+| Enum values are irreversible | Low | Single `'Lease'` source value; classification enums mirror the standards verbatim. |
+| Index-linked escalations diverge ASC 842 vs IFRS 16 | Med | Modeled as `Index Change` events flagged IFRS-book-only; primary book keeps commencement-index measurement per ASC 842. |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] **Scope: lessee-only vs full?** — **Resolved (Brad, 2026-07-04): "more ambitious — lessor included."** Full lessee accounting incl. modifications/remeasurements + lessor classification with operating-lessor posting and net-investment schedules in v1; sales-type commencement JE system-drafted/user-posted until GAP-3 costing lands (§5).
+- [x] **GL mapping: `accountDefault` columns vs `leaseClass`?** — **Resolved in-spec**: `leaseClass`, on the `fixedAssetClass` precedent (per-class account sets; see Design Decisions).
+- [x] **IFRS 16 treatment** — **Resolved in-spec**: adjustment-book delta via the multi-book generator framework (`.ai/specs/2026-07-04-multi-book.md`); schedule lines persist both expense patterns so the generator is a pure reader.
+- [x] **AP integration depth for lease payments**: v1 posts the payment credit to a lease clearing account relieved by normal supplier invoices. Should activation optionally auto-create recurring purchase-invoice templates for the fixed payments (GAP-6 recurring-journal adjacency), or is clearing + manual invoicing acceptable for v1? (Non-blocking for schema; blocks the payments UX copy.) — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Yes — activation auto-creates recurring purchase-invoice templates for fixed payments (riding the close-automation recurring machinery); the lease-clearing + manual-invoice path remains the fallback.
+- [x] **Seeded account numbers**: the chart blocks 1400/2400/7000 are partially occupied by fixed-asset seeds — confirm the exact numbers for the 9 new lease accounts at implementation (cosmetic, but seeds are hard to renumber later). — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Seed dedicated new accounts; exact numbers assigned at plan stage after a chart-collision audit (mechanical).
+
+## Changelog
+
+- 2026-07-04: Created — GAP-2 remediation spec. Scope resolved by Brad same day ("more ambitious"): full lessee (modifications/remeasurements included) + lessor (operating posting v1; sales-type/direct-financing schedules + interest posting v1, commencement JE drafted not auto-posted pending GAP-3) + IFRS 16 adjustment-book delta (consumes `.ai/specs/2026-07-04-multi-book.md` generator framework) + monthly Inngest-proposed lease runs + "Post lease journals" close task + disclosure services. Verified zero pre-existing lease code.
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/2026-07-04-master-data-controls.md b/.ai/specs/2026-07-04-master-data-controls.md
new file mode 100644
index 0000000000..6e5738f1ff
--- /dev/null
+++ b/.ai/specs/2026-07-04-master-data-controls.md
@@ -0,0 +1,204 @@
+# Master-Data Change Controls: Supplier Bank Details, Gated Bank Changes, Change Alerts
+
+> Status: in-progress (all open questions resolved pre-writing)
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1051
+> Parent: `.ai/specs/2026-07-03-public-company-readiness.md` (finding SD-6)
+> Builds on: `.ai/specs/2026-07-04-document-approvals.md` (approvals engine extension, no-self-approval, SoD report)
+> Audit coverage: rides `.ai/specs/2026-07-04-record-integrity-audit-hardening.md` (referenced, not duplicated here)
+
+## TLDR
+
+Carbon has **no supplier bank details anywhere** (verified by grep: `supplierPayment` carries payment terms, invoicing party, and currency only; the bank-rec spec adds *company* bank accounts only). When AP payment execution lands, unaudited vendor bank-detail changes become the #1 payment-fraud vector — so the control surface is built **now**, as the prerequisite. This spec adds (1) a **`supplierBankAccount`** table with row-versioned, never-live-edited records — sensitive values (account number, IBAN) stored via the Plaid spec's resolved secret-storage pattern (Vault, AES-GCM fallback) with plaintext last-four display columns; (2) a dedicated **`supplierBankChange`** approval document type on the existing engine (resolved, Brad 2026-07-04): every create/update/deactivate produces a *pending proposed-change row* that only goes live on approval by a different user whenever an enabled rule exists — no seeding, opt-in per program posture, with the SoD report flagging companies that have payments but no bank-change rule; (3) **change alerts** — notifications to accounting owners on any change to `accountDefault`, payment terms, tax configuration, or bank details, even where no approval rule gates them; and (4) a **verification-callback record** (`verifiedBy/At/method/notes`) — the call-back-the-vendor control is procedural, but the system records who verified and how, and resets verification on every detail change. Audit-log coverage for all these tables ships in the parallel record-integrity spec.
+
+## Problem Statement
+
+Readiness finding SD-6: `accountDefault` (the entire GL resolution layer), `paymentTerm`, tax codes/components, and counterparty tax data are editable by anyone with module update permission, silently. And the highest-risk master data doesn't exist yet: there is no place to store supplier bank details, which means the first AP-payment-execution feature would otherwise bolt them onto `supplierPayment` as live-editable columns — exactly the shape every BEC/vendor-impersonation fraud exploits (attacker phishes an AP clerk, edits the vendor's account number, next payment run pays the attacker). Controls that must exist *before* the data does:
+
+- **Segregated change flow**: the person who keys a bank-detail change cannot be the person who approves it (extends the document-approvals engine and inherits its `enforceNoSelfApproval`).
+- **No live edits**: an unapproved change must never be visible to any surface that selects a payment destination.
+- **Verification trail**: banks and auditors expect a callback-to-known-number control; the system records the who/when/how.
+- **Visibility without gates**: even companies that configure no rules get change alerts to accounting owners — detective where preventive is opt-in.
+
+## Resolved Questions (answered before writing, 2026-07-04)
+
+- [x] **Gate mechanism?** — **Dedicated `supplierBankChange` approval document type** on the existing engine (Brad, 2026-07-04). Not a generic "master-data change" type: bank details are the fraud surface that justifies a held-pending flow; `accountDefault`/terms/tax get alerts + audit only in v1.
+- [x] **Seed a default enabled rule at migration?** — **No.** Program posture is opt-in (matches document-approvals resolution #3). Instead, the SoD conflict report gains a row: *company has payment activity and no enabled `supplierBankChange` rule*.
+- [x] **Store full account numbers before payment execution exists?** — **Yes, from day one**, via the Plaid spec's resolved secret-storage interface (Vault-backed; app-layer AES-256-GCM fallback where Vault is absent). Re-collecting details from every supplier when payment execution lands is the expensive path, and the callback-verification control needs the full value at entry time. Full values are never returned to the client — masked last-four only.
+- [x] **Are reads of decrypted values in scope?** — Only a server-side `getSupplierBankAccountSecret` exists (service role, no route exposes it); its first real consumer is the future payment-execution spec.
+
+## Proposed Solution
+
+### 1. `supplierBankAccount` — row-versioned, never live-edited
+
+Every create, update, or deactivate produces a **new row** (`changeType` = `Create` / `Update` / `Deactivate`, `replacesId` → prior version). The row starts in `Pending Approval` when an enabled `supplierBankChange` rule exists, otherwise it activates immediately (opt-in posture). On approval: the pending row becomes `Active` (or executes the deactivation), the replaced row becomes `Inactive` with `effectiveTo` stamped — a complete effective-dated history with no UPDATE of business fields, ever. Rejection marks the row `Rejected`; the Active predecessor is untouched. Business-field immutability is structural: the table has **no UPDATE/DELETE RLS policies** (approvalRequest posture) — all status transitions run through service-role Kysely inside `approveRequest`/`rejectRequest`, and inserts are RLS-checked.
+
+Sensitive-field storage (bank-rec `accountNumberLastFour` + Plaid `tokenRef` precedents):
+
+| Field | Storage |
+|---|---|
+| Bank name, account holder name, country, currency | Plaintext columns |
+| SWIFT/BIC, routing number (ABA/sort code) | Plaintext (public identifiers) |
+| Account number, IBAN | `secretRef` JSONB (`{kind:"vault", secretId}` or `{kind:"aes", ciphertext, iv, tag}`) + plaintext `...LastFour` display column; shared `packages/ee`-adjacent secret helper reused from the Plaid token interface |
+
+Verification is a record, not a gate: `verifiedBy`/`verifiedAt`/`verificationMethod` (`Callback` / `Bank Letter` / `Micro-deposit` / `Supplier Portal` / `Other`) + `verificationNotes`, settable post-activation by a user *other than the row's creator*, and **always null on a new version** — changing any detail resets verification. Payment surfaces can later distinguish verified from unverified destinations; v1 shows the badge.
+
+### 2. `supplierBankChange` on the approvals engine
+
+New `approvalDocumentType` value. Amount-less — matches the base tier exactly like the existing `supplier` and `qualityDocument` types (`shared.service.ts:167`). `approvalRequest.documentId` = the pending `supplierBankAccount` row id. The document-approvals spec's machinery applies wholesale: `createApprovalRequest` on propose, `ApprovalRequested` notification, approve/reject from the supplier page, requester withdraw (`canCancelRequest` → row `Rejected`), **no-self-approval enforced server-side** (`canApproveRequest` + `enforceNoSelfApproval`), escalation reminders via the daily cron. `approveRequest`/`rejectRequest` gain a `supplierBankChange` case with the guarded-transition pattern (`WHERE status = 'Pending Approval'`, throw → rollback).
+
+### 3. Change alerts (detective, always on)
+
+New `NotificationEvent.MasterDataChanged = "master-data-changed"` (topic: `General` — additive, no topic rename), dispatched via `trigger("notify", ...)` from the **service functions** that mutate: `accountDefault` (updateDefaultAccounts), `paymentTerm` upsert/delete, `supplierPayment` (terms/currency/invoicing-party changes), tax configuration (`taxCode`/`taxCodeComponent`, `supplierTax`/`customerTax` — post-tax-spec names per the multi-jurisdiction-tax spec), and every `supplierBankAccount` transition (proposed, approved, rejected, auto-activated-no-rule). Recipients — "accounting owners" resolved in order: (1) approvers + `defaultApproverId` of enabled `supplierBankChange` rules; (2) else approvers of enabled `journalEntry` rules; (3) else no notification — and that absence is exactly what the SoD report row surfaces. Payload names the actor, table, entity, and changed-field list (names only — never old/new values for masked fields). Service-layer dispatch means direct PostgREST edits bypass alerts; the backstop is the record-integrity spec's audit coverage of these same tables (its scope, not duplicated here).
+
+### 4. SoD report + audit (deltas to sibling specs)
+
+- Document-approvals SoD matrix (typed constant) gains two rows: **payment activity exists ∧ no enabled `supplierBankChange` rule** (payment activity = any `payment` row for the company); **supplier bank proposer permission (`purchasing_update`) ∧ `supplierBankChange` approver membership** — informational when `enforceNoSelfApproval` is on (runtime block is the mitigating control), violation when off.
+- Record-integrity spec: `supplierBankAccount` joins its audit-coverage table list under the `supplier` entity (extension-style child, `entityIdColumn: supplierId`); `secretRef` joins `skipFields`. One-line addition there, referenced here.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|---|---|---|
+| 1 | Pending-change shape | Row versioning in `supplierBankAccount` itself (`status` + `changeType` + `replacesId`), not a separate staging table | One table = one history; effective dating falls out; payment surfaces filter `status='Active'` and are structurally incapable of seeing pending rows |
+| 2 | Gate | Dedicated `supplierBankChange` document type, amount-less base tier | Resolved (Brad 2026-07-04); reuses tiers/groups/notifications/no-self-approval; `supplier` type is the exact precedent |
+| 3 | Rule seeding | None; SoD report row instead | Resolved — program-wide opt-in posture (document-approvals #3); visibility over coercion |
+| 4 | Sensitive storage | Full value in Vault/AES `secretRef` + plaintext last-four; SWIFT/routing plaintext | Plaid spec's resolved storage decision reused verbatim; bank-rec's `accountNumberLastFour` display precedent; masked-only storage would force supplier re-collection when payment execution lands |
+| 5 | Immutability enforcement | No UPDATE/DELETE RLS policies; transitions via service-role Kysely only | "Never live-edited" must hold against PostgREST, not just the UI; `approvalRequest` already ships this posture |
+| 6 | Verification | Recorded (`verifiedBy/At/method/notes`), not gating; reset on every new version; verifier ≠ creator | Callback control is procedural — the system's job is the trail (SD-6); reset prevents verified-status laundering through edits |
+| 7 | Alerts transport | `trigger("notify")` from service functions, not a new DB-event handler type | Smallest change; MCP flows through services; PostgREST bypass is covered by audit (record-integrity spec), and a queue-side alert handler can be added later without contract change |
+| 8 | Alert recipients | bank-change rule approvers → JE rule approvers → none (reported) | "Accounting owners" without a new settings surface; degradation is itself a reportable finding |
+| 9 | No-rule behavior | Change auto-activates through the same versioned path, alert still fires | Byte-identical control data model whether gated or not; turning a rule on later gates the *next* change with zero migration |
+| 10 | Multi-tenancy (H1) | Composite PK (`id`,`companyId`), `companyId` scoping everywhere, `id('sba')` | House convention |
+| 11 | Service shape (H2) | New functions in `purchasing.service.ts` / models in `purchasing.models.ts` (supplier module owns supplier children); engine cases in `shared.service.ts`; `(client, ...) → {data, error}` | One service/models file per module — no new files |
+| 12 | RLS (H3) | SELECT `purchasing_view`, INSERT `purchasing_update` via `has_company_permission`; no UPDATE/DELETE policies | See #5; matches engine posture |
+| 13 | Permissions (H4) | Propose = `update: purchasing`; approve = `canApproveRequest` (engine); verification record = `update: purchasing` + verifier ≠ creator check | PO/supplier-approval precedent |
+| 14 | Forms (H5) | `ValidatedForm` + zod `supplierBankAccountValidator`; masked inputs render last-four placeholders on update | House convention |
+| 15 | Module layout (H6) | UI in `apps/erp/app/modules/purchasing/ui/Supplier/` (`SupplierBankAccounts.tsx`, `SupplierBankAccountForm.tsx`) alongside `SupplierPaymentForm` | Existing folder |
+| 16 | Backward compat (H7) | Purely additive: new table, new enum value, new event; no rule ⇒ no behavior change to any existing flow | Nothing existing reads bank details (they don't exist) |
+
+## Data Model Changes
+
+One idempotent migration (`pnpm db:migrate:new supplier-bank-accounts`; enum ADD VALUE guarded, not consumed in-transaction per the `20260630093809` pattern), then `pnpm run generate:types`:
+
+```sql
+ALTER TYPE "approvalDocumentType" ADD VALUE IF NOT EXISTS 'supplierBankChange';
+
+CREATE TYPE "supplierBankAccountStatus" AS ENUM ('Pending Approval', 'Active', 'Rejected', 'Inactive');
+CREATE TYPE "supplierBankChangeType" AS ENUM ('Create', 'Update', 'Deactivate');
+CREATE TYPE "bankVerificationMethod" AS ENUM ('Callback', 'Bank Letter', 'Micro-deposit', 'Supplier Portal', 'Other');
+
+CREATE TABLE "supplierBankAccount" (
+ "id" TEXT NOT NULL DEFAULT id('sba'),
+ "companyId" TEXT NOT NULL,
+ "supplierId" TEXT NOT NULL,
+ "status" "supplierBankAccountStatus" NOT NULL DEFAULT 'Pending Approval',
+ "changeType" "supplierBankChangeType" NOT NULL DEFAULT 'Create',
+ "replacesId" TEXT, -- prior version this row supersedes
+ -- Non-sensitive details
+ "bankName" TEXT NOT NULL,
+ "accountHolderName" TEXT NOT NULL,
+ "countryCode" TEXT,
+ "currencyCode" TEXT,
+ "swiftBic" TEXT,
+ "routingNumber" TEXT, -- ABA / sort code: public identifiers
+ -- Sensitive: secret refs (vault | aes per Plaid-spec storage decision) + masked display
+ "accountNumberRef" JSONB,
+ "accountNumberLastFour" TEXT,
+ "ibanRef" JSONB,
+ "ibanLastFour" TEXT,
+ -- Effective dating (stamped by activation/supersession, service-role only)
+ "effectiveFrom" TIMESTAMP WITH TIME ZONE,
+ "effectiveTo" TIMESTAMP WITH TIME ZONE,
+ -- Verification record (procedural callback control; reset = new version starts NULL)
+ "verifiedBy" TEXT REFERENCES "user"("id"),
+ "verifiedAt" TIMESTAMP WITH TIME ZONE,
+ "verificationMethod" "bankVerificationMethod",
+ "verificationNotes" TEXT,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "supplierBankAccount_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "supplierBankAccount_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "supplierBankAccount_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "supplierBankAccount_replacesId_fkey" FOREIGN KEY ("replacesId", "companyId") REFERENCES "supplierBankAccount"("id", "companyId"),
+ CONSTRAINT "supplierBankAccount_details_check" CHECK ("accountNumberRef" IS NOT NULL OR "ibanRef" IS NOT NULL OR "changeType" = 'Deactivate')
+);
+
+CREATE INDEX "supplierBankAccount_supplierId_idx" ON "supplierBankAccount" ("supplierId", "companyId");
+CREATE INDEX "supplierBankAccount_status_idx" ON "supplierBankAccount" ("companyId", "status");
+-- At most one in-flight pending change per supplier (serialize competing edits)
+CREATE UNIQUE INDEX "supplierBankAccount_pending_idx" ON "supplierBankAccount" ("supplierId", "companyId")
+ WHERE "status" = 'Pending Approval';
+
+ALTER TABLE "supplierBankAccount" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "supplierBankAccount_SELECT" ON "supplierBankAccount" FOR SELECT
+ USING (has_company_permission('purchasing_view', "companyId"));
+CREATE POLICY "supplierBankAccount_INSERT" ON "supplierBankAccount" FOR INSERT
+ WITH CHECK (has_company_permission('purchasing_update', "companyId"));
+-- Deliberately NO UPDATE or DELETE policies: business fields are immutable via PostgREST;
+-- status transitions + verification stamps run through service-role Kysely only.
+```
+
+## API / Service Changes
+
+- `purchasing.service.ts`: `getSupplierBankAccounts(supplierId)` (all versions, history view); `getActiveSupplierBankAccounts(supplierId)` (**the only reader future payment surfaces may use** — `status = 'Active'`); `proposeSupplierBankChange(...)` — encrypts sensitive values via the shared secret helper, inserts the versioned row, checks `isApprovalRequired('supplierBankChange', companyId)`, then either parks + `createApprovalRequest` + `ApprovalRequested`, or activates immediately (service-role transition) + fires `MasterDataChanged`; `recordBankVerification(...)` (verifier ≠ `createdBy`, Active rows only); `getSupplierBankAccountSecret(...)` (server-only, service role; no route consumer in v1).
+- `shared.service.ts`: `approveRequest`/`rejectRequest` gain the `supplierBankChange` case — approve: pending row → `Active` + `effectiveFrom`, `replacesId` target → `Inactive` + `effectiveTo` (Deactivate rows: target → `Inactive`, the change row itself → `Active` as the deactivation record), guarded `WHERE status = 'Pending Approval'`; reject/withdraw: row → `Rejected`. `isApprovalRequired` already handles amount-less types.
+- Alert dispatch: `notifyMasterDataChange(...)` helper called from `updateDefaultAccounts`, payment-term upsert/delete, `supplierPayment` update, tax-config services, and the bank flows above; recipient resolution per Design Decision 8.
+- `packages/notifications`: `MasterDataChanged` event → `General` topic; `notify.ts` description + `api+/link.ts` deep links (supplier payment tab / accounting settings).
+- Document-approvals deliverables extended: SoD matrix rows (§4), settings Approval Rules page gains a `supplierBankChange` card (amount-less, like `supplier`).
+
+## UI Changes
+
+- Supplier detail → new **Bank Accounts** section (`SupplierBankAccounts.tsx`): active account(s) with masked numbers (`•••• 1234`), verification badge, pending-change banner with Approve/Reject (eligible approvers, notes) and Withdraw (requester); version history list.
+- `SupplierBankAccountForm.tsx`: full-value inputs on create/update (submitted once, stored as secretRef, never echoed back); Deactivate action with confirm.
+- Verification modal: method, notes; disabled for the row's creator.
+- Settings → Approval Rules: `supplierBankChange` card. SoD report: two new finding rows.
+
+## Acceptance Criteria
+
+- [ ] With an enabled `supplierBankChange` rule: user A proposing a create/update/deactivate parks a `Pending Approval` row + approval request and notifies approvers; **user A cannot approve it** (server-rejected via `canApproveRequest`); user B can; approval activates the new version and inactivates the replaced one with effective dates stamped.
+- [ ] An unapproved (pending or rejected) bank row is **never returned by `getActiveSupplierBankAccounts`** and never appears in any Active-filtered surface; rejecting/withdrawing leaves the prior Active row in force.
+- [ ] `supplierBankAccount` business fields cannot be updated via PostgREST as any authenticated user (no UPDATE policy — verified by attempted direct PATCH); every change is a new row; a second concurrent pending change for the same supplier is rejected by the partial unique index.
+- [ ] Full account number/IBAN appear in no API response, loader payload, or notification — only last-four; secretRef decrypts server-side only (Vault or AES fallback, matching the Plaid token interface).
+- [ ] With **no** rule: the same propose call activates immediately through the identical versioned path, and a `MasterDataChanged` notification still reaches resolved accounting owners.
+- [ ] Changing `accountDefault`, a payment term, `supplierPayment`, or tax config fires `MasterDataChanged` (field names, no values) to rule-approver recipients per the fallback chain.
+- [ ] Recording verification stamps `verifiedBy/At/method`; the row's creator is rejected as verifier; a subsequent approved change produces a new version with verification NULL.
+- [ ] SoD report flags a company with `payment` rows and no enabled `supplierBankChange` rule.
+- [ ] `pnpm run generate:types`, scoped typecheck, lint pass; migration applies idempotently twice.
+
+## Out of Scope (owned by sibling specs)
+
+| Concern | Owner |
+|---|---|
+| Audit-log rows for `supplierBankAccount`, `accountDefault`, `paymentTerm`, tax config (entity config, `skipFields` for `secretRef`/`accountNumberRef`/`ibanRef`) | `.ai/specs/2026-07-04-record-integrity-audit-hardening.md` |
+| Engine mechanics: `canApproveRequest` self-approval block, escalation cron, SoD report chassis, access report | `.ai/specs/2026-07-04-document-approvals.md` (this spec only adds the `supplierBankChange` case + two matrix rows) |
+| Actually paying suppliers (payment execution, file formats, `getSupplierBankAccountSecret` consumption, verified-only payment policy) | Future payment-execution spec — must read via `getActiveSupplierBankAccounts` only |
+| Approval gates on `accountDefault`/terms/tax edits (alerts + audit only in v1) | Revisit post-v1 if audit feedback demands |
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| Vault absent on self-hosted (unverified there) | Med | Same probe + AES-GCM fallback the Plaid spec resolved; shared helper, swappable backend |
+| Sole-proprietor deadlock (only user proposes, nobody can approve) | Med | Same escape as document-approvals: rules are opt-in; `enforceNoSelfApproval` off is an audited standing exception |
+| Alert bypass via direct PostgREST edits to `accountDefault`/terms/tax | Med | Known limitation of service-layer dispatch; audit coverage (record-integrity spec) is the detective backstop; queue-side handler is a compatible later upgrade |
+| Enum ADD VALUE used in same migration | Med | Guarded pattern; table creation references the *new type*, not the new enum value — no in-transaction consumption |
+| Pending row blocks urgent bank correction | Low | Requester withdraw + re-propose; escalation reminders + `defaultApproverId` from the engine |
+| Future payment execution reads the table directly, bypassing the Active filter | Med | Contract stated here + in `getActiveSupplierBankAccounts` docstring; acceptance test in the payment-execution spec must cite it |
+
+## Open Questions
+
+> All resolved before writing (see Resolved Questions) — none blocking.
+
+- [x] Dedicated `supplierBankChange` document type (Brad, 2026-07-04)
+- [x] No rule seeding; SoD report row instead (program posture)
+- [x] Full-value storage from day one via Vault/AES secretRef
+- Non-blocking future note: customer bank details (AR direct debit) should reuse this exact model when needed — out of scope here.
+
+## Changelog
+
+- 2026-07-04: Created. Fieldwork verified: no bank fields exist anywhere in the schema (`supplierPayment` = terms/invoicing-party/currency only); masking precedent `bankAccount.accountNumberLastFour` (bank-rec spec); secret storage resolution inherited from the Plaid spec; `supplier` amount-less approval type is the engine precedent. Resolutions from Brad baked in. Ready for `/plan`.
diff --git a/.ai/specs/2026-07-04-multi-book.md b/.ai/specs/2026-07-04-multi-book.md
new file mode 100644
index 0000000000..c30a4d1ac8
--- /dev/null
+++ b/.ai/specs/2026-07-04-multi-book.md
@@ -0,0 +1,277 @@
+# Multi-Book Accounting — Adjustment-Only Books (GAP-5)
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: [crbnos/carbon#1052](https://github.com/crbnos/carbon/issues/1052)
+> Readiness finding: GAP-5 (`.ai/specs/2026-07-03-public-company-readiness.md`), design decision 5
+> Research: `.ai/research/public-company-compliance.md` §Pattern 2
+> Depends on: #1047 record integrity & audit hardening (seeds `journal.bookId` + `accountingBook` + `accountingBookCompany`; its spec is being written in parallel — the DDL below is the shared contract, reconcile before either implements)
+
+## TLDR
+
+Carbon today has one implicit ledger: every journal is "the book." A multi-national files statutory accounts under local GAAP/IFRS while the group reports US GAAP — the same lease, the same inventory write-down, and the same machine produce different numbers per accounting principle. This spec adds **NetSuite-style adjustment-only books** on the header-level `journal.bookId` seeded by #1047: the PRIMARY book keeps receiving 100% of operational postings, and each adjustment book stores only **deltas** (book-scoped manual JEs, book-specific depreciation deltas, and generator-produced adjustments for IAS 2 NRV reversals and IFRS 16 lease differences). Reports gain a book perspective — PRIMARY, a single book's deltas, or PRIMARY+book combined — labeled by each book's accounting principle (US-GAAP | IFRS | Local | Tax). Books are defined at the company-group level and enabled per company; adjustment books close with the company's period via book-scoped close-checklist tasks. The SAP full-ledger fan-out approach (every posting duplicated per ledger) is explicitly rejected.
+
+## Problem Statement
+
+- **One implicit book.** `journal` has no book dimension (pre-#1047); `trialBalance` / `accountTreeBalancesByCompany` (`20260315000001`) aggregate all journal lines as a single population. There is no way to state "IFRS balance sheet" vs "US GAAP balance sheet" for the same entity.
+- **Concrete divergences already queued.** (a) IAS 2 requires NRV write-down reversals that US GAAP forbids — the inventory valuation spec (#1040) blocks on this. (b) IFRS 16's single lease model vs ASC 842's operating/finance split — the lease spec (#1056) blocks on this. (c) Statutory depreciation (e.g., German tax lives, French statutory rates) diverges from US GAAP book depreciation — today's `fixedAsset` hardcodes exactly two books (book + tax columns) and can express nothing else.
+- **The retrofit is the expensive part.** Research §Pattern 2: bolting a book dimension on later is one of the costliest ERP retrofits; NetSuite provisions Multi-Book via professional services because even they can't retrofit cheaply. #1047 lands the column while the posting surface is already being touched; this spec makes it do real work.
+
+## Proposed Solution
+
+### Book model: PRIMARY + adjustment-only deltas (NetSuite pattern)
+
+- Every company group has exactly one **Primary** book (seeded by #1047's migration). All operational posting paths (edge functions, payments, inventory, production, existing depreciation runs) write it and never anything else.
+- **Adjustment books** (`type = 'Adjustment'`) hold only deltas relative to Primary. A book's standalone TB is *just the adjustments*; the meaningful statements come from the **Combined** view: PRIMARY + book, summed per account.
+- Adjustment books share the Primary book's chart of accounts, base currency, and period calendar. No book-specific COA mapping, calendars, or currencies in v1 (that is NetSuite's full secondary-book tier; adjustment-only books don't need it — research §Pattern 2).
+- Definitions are **group-scoped** (like `account`, `20260228023426` pattern), enabled per company through `accountingBookCompany` — a statutory HGB book is defined once and enabled only for the German entity (resolved, Brad 2026-07-03).
+- Each book carries an `accountingPrinciple` (`US-GAAP | IFRS | Local | Tax`) that drives report labeling ("Balance Sheet — IFRS (Combined: Primary + IFRS Adjustments)") and generator applicability.
+
+### Book-scoped manual journal entries
+
+`JournalEntryForm` gains a book selector (default Primary; adjustment books listed only when enabled for the company and the user has `accounting_create`). Manual JEs into adjustment books flow through the exact same lifecycle as Primary JEs: Draft → (Pending Approval, per #1032's rules — same rules, no per-book routing in v1) → Posted; posted-record immutability, reversal-only correction, gapless numbering, and the period-close trigger all apply identically because they operate on `journal` rows regardless of `bookId`.
+
+### Reporting: three perspectives everywhere
+
+`accountTreeBalancesByCompany` and `trialBalance` (and the financial-reporting spec's four-column TB / GL-detail queries) gain:
+
+- `p_book_id TEXT DEFAULT NULL` — NULL means the group's Primary book.
+- `p_book_mode TEXT DEFAULT 'Primary'` ∈ `('Primary', 'Book', 'Combined')`:
+ - **Primary**: today's numbers — lines where the journal's book is Primary (backward-compatible default; existing callers unchanged).
+ - **Book**: the adjustment book's deltas alone (reviewing what the book adds).
+ - **Combined**: Primary + the selected book (the statutory/IFRS statements auditors receive).
+
+TB, BS, IS, and GL-detail report filter bars gain a book picker (hidden when the company has no adjustment books enabled). GL-detail and the account drill-down drawer pass the same book parameters as their parent so the tie-out contract holds in every mode. The #1047 JE population export gains the same `bookId` filter + a `book` column on every row (already in its column contract); FEC/SAF-T for a statutory entity later export the Combined population of its statutory book (#1053).
+
+### Book-specific depreciation
+
+- New `fixedAssetBook` rows hold per-asset, per-book depreciation settings: method, useful life, residual %, start date, per-book accumulated depreciation. Absence of a row = the asset depreciates identically to Primary in that book (delta 0 — the common case, kept free).
+- Book depreciation posts as **deltas**: for each period, the statutory-depreciation generator computes `bookDepreciation − primaryDepreciation` per asset and posts only the difference into the adjustment book (Dr/Cr depreciation expense / accumulated depreciation from the asset class accounts). Combined view = full statutory depreciation.
+- Reuses the existing `depreciationRun` machinery with a nullable `bookId`: NULL = today's Primary runs (untouched); book runs are created by the generator, carry delta amounts per line, and post journals stamped with the book.
+- The existing hardcoded tax columns on `fixedAsset` (`taxDepreciationMethod`, MACRS, `accumulatedTaxDepreciation`, deferred-tax posting) are untouched in v1; migrating them into a `Tax`-principle adjustment book is a candidate follow-up once this framework is proven (noted in Risks).
+
+### Adjustment-generator framework
+
+A registered-generator contract so subsystems produce book entries without inventing parallel machinery — mirroring the period-close spec's `autoCheckKey` evaluator pattern (code-level registry, persisted runs):
+
+```ts
+// apps/erp/app/modules/accounting/accounting.books.ts (registry)
+type BookAdjustmentGenerator = {
+ key: string; // 'statutory-depreciation' | 'ias2-nrv-reversal' | 'ifrs16-lease-delta'
+ name: string; // display + close-task name
+ appliesTo: (book: AccountingBook) => boolean; // usually by accountingPrinciple
+ generate: (args: {
+ client: SupabaseClient<Database>; // caller's client; RLS applies
+ companyId: string;
+ bookId: string;
+ accountingPeriodId: string;
+ }) => Promise<{ data: DraftAdjustmentJournal[] | null; error: PostgrestError | null }>;
+};
+```
+
+- `generate` is **pure proposal**: it returns balanced draft journal payloads (`sourceType: 'Book Adjustment'`, `bookId`, `postingDate` = period end, line-level document references back to the driving records). It never posts. The framework inserts them as Draft journals, records a `bookAdjustmentRun` row (period × book × generator, journal ids, status), and the normal posting path (with approval gates when a rule matches) takes over.
+- **Idempotent per (period, book, generator)**: re-running while a run is Draft regenerates (delete drafts, re-insert); re-running after Posted is refused — corrections are reversal + regenerate, consistent with immutability.
+- **Named v1 consumers**: `statutory-depreciation` (ships with this spec, defined above); `ias2-nrv-reversal` (registered by the inventory valuation spec #1040 — reverses prior NRV write-downs where IAS 2 requires it and US GAAP posted none); `ifrs16-lease-delta` (registered by the lease spec #1056 — single-model vs 842 P&L difference per lease). The latter two specs own their computation; this spec owns the contract they register against.
+- **Close-checklist integration**: for each enabled (book × applicable generator), the framework registers a `periodCloseTaskDefinition` (per the #1031 coordination rule — never a parallel checklist): Auto task "Generate {generator} adjustments — {book}", `autoCheckKey: 'book-adjustments'`, severity Warning. The auto-check passes when the `bookAdjustmentRun` for that period/book/generator is Posted or Skipped. Skips require a reason, as usual.
+
+### Book-aware close
+
+Adjustment books have **no separate period lifecycle** in v1: they close when the company's period closes (same `accountingPeriod.closeStatus`; the period-close trigger already blocks every journal, book journals included). Book-scoped readiness = the generator tasks above plus a `book-balanced` auto-check (each adjustment book's period delta sums to zero — every book is internally double-entry; the #1047 balance trigger enforces this per journal, the check surfaces it per book). SAP-style special periods 13–16 are explicitly not adopted — adjustment JEs into an open period 12 achieve the same end under Carbon's model.
+
+### Guardrails (the v1 boundary)
+
+1. **System posting paths always write PRIMARY.** No edge function, payment builder, or inventory poster accepts a `bookId`; the `journal` BEFORE INSERT trigger stamps the group's Primary book when `bookId` is NULL.
+2. **Adjustment books never receive operational postings.** DB trigger: a journal whose book is `type = 'Adjustment'` must have `sourceType IN ('Manual', 'Book Adjustment', 'Asset Depreciation')` and its book must be enabled for the journal's company (`accountingBookCompany`). Everything else is raised at the DB, binding the service role.
+3. **Consolidation and translation read PRIMARY only in v1.** `translateTrialBalance`, eliminations, and consolidated statements are unchanged (they see Primary because that's the default mode). Consolidated Combined views (translate Primary+book per subsidiary, e.g., group IFRS consolidation) are explicitly deferred to the FX/consolidation completeness work (#1050/#1058) — the RPC parameters added here make that a parameter-plumbing exercise, not a schema change.
+4. **Integrations (Xero sync, MCP posting tools, JE import #1059) read/write PRIMARY** unless they explicitly pass an enabled adjustment book with `accounting_create`; the trigger in (2) backstops them regardless.
+5. **Virtual year-end needs nothing:** RE/Net-Income are computed from lines at report time, so each book mode's equity computes correctly by construction.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Ledger architecture | NetSuite **adjustment-only books** (deltas on Primary), not SAP ledger fan-out (every posting duplicated per ledger) | Readiness DD-5 + research §Pattern 2; deltas keep operational posting single-path (no N× journal volume, no fan-out bugs); SAP's extension ledgers are themselves the delta admission; full secondary books (own COA/currency/calendar) are a later tier if ever |
+| 2 | Book placement | Header-level `journal.bookId` (one journal = one book), never line-level | Readiness DD-5; matches NetSuite book JEs / SAP ledger-group posting; keeps the per-journal balance trigger (#1047) meaningful per book |
+| 3 | Book scoping | Group-scoped `accountingBook` + per-company `accountingBookCompany` enablement | Resolved Brad 2026-07-03; mirrors the shared-COA pattern (`account.companyGroupId`) |
+| 4 | Primary default mechanics | BEFORE INSERT trigger resolves the group's Primary book when `bookId` IS NULL (not a static column DEFAULT) | A static `DEFAULT 'PRIMARY'` (readiness sketch) can't point at per-group seeded rows; trigger keeps every existing writer correct with zero code changes |
+| 5 | Generator registry | Code-level registry + persisted `bookAdjustmentRun` rows | Same shape as close-checklist `autoCheckKey` evaluators; generators need code anyway; runs table gives idempotency + close evidence |
+| 6 | Generators propose, posting disposes | Generators emit Draft journals; normal post path (approvals, immutability, numbering, period gates) applies | One posting pipeline; adjustment entries get the full Phase-0 control stack for free |
+| 7 | Book depreciation vehicle | Reuse `depreciationRun` with nullable `bookId`; lines carry **delta** amounts | Existing UI/posting machinery; NULL keeps current behavior byte-identical; delta semantics follow decision 1 |
+| 8 | Book close lifecycle | Shared with the company period; book-scoped tasks on the existing close checklist | #1031 coordination rule (register task definitions, never parallel checklists); a per-book period state machine is complexity with no v1 consumer |
+| 9 | Multi-tenancy heuristic | `accountingBook` group-scoped (single-col PK + `companyGroupId`, like `account`); `accountingBookCompany`/`fixedAssetBook`/`bookAdjustmentRun` company-scoped with composite PK `("id","companyId")`, `id('prefix')`, audit columns | Repo conventions; definitions shared, activity per-tenant |
+| 10 | Service shape | New functions in `modules/accounting/accounting.service.ts` + `accounting.models.ts` (`(client, companyId, ...)` → `{data, error}`, never throw); generator registry + posting transaction in `accounting.server.ts` | One service/models file per module — never scattered |
+| 11 | RLS | Four named policies per new table; SELECT via `get_companies_with_employee_role()` (group tables: group-membership helper per `20260228023426`), writes via `get_companies_with_employee_permission('accounting_*')` | `packages/database/AGENTS.md` conventions |
+| 12 | Permissions | Book definitions/enablement = `accounting_update` (settings-tier); book JEs/generator runs = existing `accounting_create`/`accounting_update`; no new permission actions | Follows period-closing precedent of reusing accounting tiers |
+| 13 | Forms/UI pattern | `ValidatedForm` + zod validators; book picker as a `Select` on existing report filter bars; new settings page under `routes/x+/accounting+/books*` | `conventions-forms.md` / existing accounting settings precedent |
+| 14 | Backward compatibility | Additive only: RPC params default to `'Primary'` mode reproducing today's numbers; `depreciationRun.bookId` NULL = today; no operational poster changes | The whole point of adjustment-only: PRIMARY is untouched |
+
+## Data Model Changes
+
+One migration (`pnpm db:migrate:new multi-book-adjustment-books`, randomized HHMMSS, idempotent), then `pnpm run generate:types`. The first block is the **shared #1047 contract** — whichever spec's migration lands first creates these; this spec's migration guards with IF NOT EXISTS.
+
+```sql
+-- ── Shared with #1047 (record integrity) — the book seed ─────────────────
+CREATE TABLE IF NOT EXISTS "accountingBook" (
+ "id" TEXT NOT NULL DEFAULT id('book'),
+ "companyGroupId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "type" TEXT NOT NULL DEFAULT 'Adjustment', -- 'Primary' | 'Adjustment'
+ "accountingPrinciple" TEXT NOT NULL DEFAULT 'Local', -- 'US-GAAP' | 'IFRS' | 'Local' | 'Tax'
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "accountingBook_pkey" PRIMARY KEY ("id"), -- group-scoped like "account"
+ CONSTRAINT "accountingBook_companyGroupId_fkey" FOREIGN KEY ("companyGroupId")
+ REFERENCES "companyGroup"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "accountingBook_name_key" UNIQUE ("name", "companyGroupId"),
+ CONSTRAINT "accountingBook_type_check" CHECK ("type" IN ('Primary','Adjustment')),
+ CONSTRAINT "accountingBook_principle_check"
+ CHECK ("accountingPrinciple" IN ('US-GAAP','IFRS','Local','Tax'))
+);
+-- Exactly one Primary per group
+CREATE UNIQUE INDEX IF NOT EXISTS "accountingBook_one_primary_idx"
+ ON "accountingBook" ("companyGroupId") WHERE "type" = 'Primary';
+-- Seed: one Primary book per existing companyGroup (accountingPrinciple 'US-GAAP')
+
+CREATE TABLE IF NOT EXISTS "accountingBookCompany" (
+ "id" TEXT NOT NULL DEFAULT id('bkco'),
+ "companyId" TEXT NOT NULL,
+ "bookId" TEXT NOT NULL REFERENCES "accountingBook"("id") ON DELETE CASCADE,
+ "effectiveFrom" DATE, -- book adoption date (see decision below)
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "accountingBookCompany_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "accountingBookCompany_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "accountingBookCompany_book_company_key" UNIQUE ("bookId", "companyId")
+);
+-- Seed: Primary book enabled for every company in its group
+
+ALTER TABLE "journal" ADD COLUMN IF NOT EXISTS "bookId" TEXT REFERENCES "accountingBook"("id");
+CREATE INDEX IF NOT EXISTS "journal_bookId_idx" ON "journal" ("bookId", "companyId");
+-- Backfill existing journals to the group's Primary book; then SET NOT NULL.
+-- BEFORE INSERT trigger "journal_default_book": when NEW."bookId" IS NULL,
+-- resolve the company's group Primary book (design decision 4).
+
+-- ── This spec ─────────────────────────────────────────────────────────────
+-- Guardrail trigger (SECURITY DEFINER, binds service role — period-close precedent):
+-- on journal INSERT/UPDATE where the book is type 'Adjustment':
+-- * sourceType must be IN ('Manual', 'Book Adjustment', 'Asset Depreciation')
+-- * (bookId, companyId) must exist in "accountingBookCompany"
+-- else RAISE EXCEPTION.
+
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Book Adjustment';
+
+CREATE TABLE IF NOT EXISTS "fixedAssetBook" (
+ "id" TEXT NOT NULL DEFAULT id('fab'),
+ "companyId" TEXT NOT NULL,
+ "fixedAssetId" TEXT NOT NULL,
+ "bookId" TEXT NOT NULL REFERENCES "accountingBook"("id") ON DELETE CASCADE,
+ "depreciationMethod" "depreciationMethod" NOT NULL DEFAULT 'Straight Line',
+ "usefulLifeMonths" INTEGER NOT NULL,
+ "residualValuePercent" NUMERIC NOT NULL DEFAULT 0,
+ "depreciationStartDate" DATE,
+ "accumulatedDepreciation" NUMERIC NOT NULL DEFAULT 0, -- full book-basis accumulated
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "fixedAssetBook_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "fixedAssetBook_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "fixedAssetBook_asset_book_key" UNIQUE ("fixedAssetId", "bookId", "companyId")
+);
+
+ALTER TABLE "depreciationRun" ADD COLUMN IF NOT EXISTS "bookId" TEXT
+ REFERENCES "accountingBook"("id"); -- NULL = Primary run (unchanged)
+
+CREATE TABLE IF NOT EXISTS "bookAdjustmentRun" (
+ "id" TEXT NOT NULL DEFAULT id('bar'),
+ "companyId" TEXT NOT NULL,
+ "bookId" TEXT NOT NULL REFERENCES "accountingBook"("id"),
+ "accountingPeriodId" TEXT NOT NULL REFERENCES "accountingPeriod"("id"),
+ "generatorKey" TEXT NOT NULL, -- registry key
+ "status" TEXT NOT NULL DEFAULT 'Draft', -- 'Draft' | 'Posted' | 'Skipped'
+ "journalIds" TEXT[] NOT NULL DEFAULT '{}',
+ "skippedReason" TEXT,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "bookAdjustmentRun_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "bookAdjustmentRun_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "bookAdjustmentRun_unique_key"
+ UNIQUE ("accountingPeriodId", "bookId", "generatorKey", "companyId"),
+ CONSTRAINT "bookAdjustmentRun_status_check" CHECK ("status" IN ('Draft','Posted','Skipped'))
+);
+```
+
+RLS per conventions on all new tables; all are added to audit-log coverage (they are accounting entities — #1047's always-on synchronous class). RPC changes: `accountTreeBalancesByCompany` + `trialBalance` gain `p_book_id TEXT DEFAULT NULL, p_book_mode TEXT DEFAULT 'Primary'` (filter joins `journal."bookId"`; coordinate with the financial-reporting redefinition that adds `p_include_drafts`). **Book enablement mid-life:** enabling a book for a company sets `effectiveFrom`; divergence before that date enters as an opening catch-up — the statutory-depreciation generator's first run posts the accumulated delta as a flagged catch-up line, and other openings are book-scoped manual JEs.
+
+## API / Service Changes
+
+- `accounting.models.ts`: `accountingBookValidator`, `accountingBookCompanyValidator`, `fixedAssetBookValidator`, `bookAdjustmentRunValidator`; `bookModes` / `accountingPrinciples` const arrays.
+- `accounting.service.ts`: book CRUD (`getAccountingBooks`, `upsertAccountingBook`, `getEnabledBooks(client, companyId)`), enablement toggle, `getFixedAssetBooks`/`upsertFixedAssetBook`, `getBookAdjustmentRuns`; balance/TB/GL-detail service callers pass `bookId`/`bookMode` through to the RPCs.
+- `accounting.server.ts`: generator registry + `runBookAdjustmentGenerator(client, {companyId, bookId, periodId, key})` (Kysely transaction: idempotency check → `generate` → insert Draft journals + `bookAdjustmentRun`); `statutory-depreciation` generator (wraps `buildDepreciationLines` twice — book settings vs primary settings — and emits the per-asset delta as a `depreciationRun` with `bookId` + `'Book Adjustment'`-sourced draft journals); `postDepreciationRun` stamps `journal.bookId` from the run.
+- `postJournalEntry`: accepts and preserves `bookId` (guardrail trigger backstops); approval gate (#1032) applies unchanged.
+- Close: register `periodCloseTaskDefinition` rows per enabled (book × applicable generator) + the `book-balanced` auto-check in `getPeriodCloseReadiness`.
+- Routes: `x+/accounting+/books.tsx` (+ `books.new`, `books.$bookId`), enablement intent actions; report loaders read `book`/`bookMode` search params.
+
+## UI Changes
+
+- **Settings → Accounting → Books**: list/create/edit books (name, principle, active), per-company enablement with `effectiveFrom`.
+- **Journal entry form**: book `Select` (enabled adjustment books + Primary), badge on JE tables/detail for non-Primary journals.
+- **Reports (TB/BS/IS/GL-detail)**: book picker + mode toggle (Primary / Book only / Combined) on the filter bars; report headers label the perspective and the book's accounting principle; drill-down drawer inherits parent parameters.
+- **Fixed asset detail**: "Books" section listing per-book depreciation settings (add/edit `fixedAssetBook` rows).
+- **Period close drawer**: generator tasks appear per enabled book with Generate/Skip actions and links to the produced draft journals.
+
+## Acceptance Criteria
+
+- [ ] With no adjustment books enabled, every report, RPC result, and posting path is byte-identical to pre-migration behavior (Primary default mode reproduces today's numbers; regression: TB/BS/IS snapshots match).
+- [ ] An operational posting (e.g., `post-purchase-invoice`) lands on the Primary book with no code passing `bookId`; a direct service-role INSERT of an `'Purchase Invoice'`-sourced journal into an adjustment book is rejected by the guardrail trigger.
+- [ ] A manual JE posted into an enabled IFRS adjustment book: appears in Book mode TB as the only rows; Combined TB = Primary TB + those rows per account; Primary TB unchanged. Posting into a non-enabled book is rejected at the DB.
+- [ ] Book JEs respect the full control stack: approval rule gates posting, posted book journals are immutable (reversal-only), period-close trigger blocks book postings into a Closed period.
+- [ ] An asset with `fixedAssetBook` settings (e.g., 60-month statutory life vs 120-month primary) gets a generator-created book depreciation run whose line amount equals bookDepreciation − primaryDepreciation for the period; posting it yields a Combined accumulated depreciation equal to the full statutory schedule; an asset with no `fixedAssetBook` row produces no delta line.
+- [ ] Enabling a book mid-asset-life produces a flagged catch-up delta equal to the accumulated divergence through the prior period on the first generator run.
+- [ ] Generator idempotency: re-running a Draft run regenerates (no duplicate drafts); re-running a Posted run is refused with a reversal-first error.
+- [ ] Close checklist for a company with an enabled book shows the generator task(s); the task auto-passes only when the run is Posted/Skipped; `book-balanced` fails if an adjustment book's period delta ≠ 0 (constructible only pre-#1047-balance-trigger; test via fixture).
+- [ ] Report headers label perspective + principle (e.g., "IFRS — Combined"); CSV/PDF exports carry the same label; JE export rows carry the correct book and filter by it.
+- [ ] Consolidated statements and `translateTrialBalance` outputs are unchanged regardless of enabled books (v1 boundary).
+- [ ] `pnpm exec turbo run typecheck --filter=erp` (+ database package) passes after `pnpm run generate:types`.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Contract drift with the parallel #1047 spec (shared `accountingBook`/`accountingBookCompany`/`journal.bookId` DDL) | High | This section is the canonical DDL; both specs cite it; idempotent IF NOT EXISTS guards; reconcile in whichever PR lands second |
+| RPC redefinition collision (financial-reporting adds `p_include_drafts` to the same functions) | Med | Coordinate parameter order in one migration wave after #1035 lands (meta-spec coordination rule for shared surfaces) |
+| Delta semantics misunderstood by users (Book-only TB "looks wrong") | Med | Default mode is Combined when a book is selected; Book-only labeled "Adjustments only"; docs + report captions |
+| Statutory depreciation catch-up posts a large first-period delta | Med | Catch-up line flagged + surfaced in the run review before posting; `effectiveFrom` documented as "diverge from this date" |
+| Existing tax-depreciation columns now overlap conceptually with a `Tax` book | Low | Untouched in v1; consolidation of the two models is a named follow-up, not silent behavior change |
+| Report query cost of the extra `journal.bookId` join/filter | Low | `journal_bookId_idx (bookId, companyId)`; Primary mode uses the same plan shape as today |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+Program-level resolutions (recorded — no re-litigation):
+
+- [x] **Scope: minimal (manual book JEs only) vs ambitious (depreciation + generator framework + book reporting)?** — **Resolved (Brad, 2026-07-04): "yes / more ambitious."** Full cut as spec'd: adjustment books + book reporting modes, book-specific depreciation, the generator framework with three named consumers, book-aware close, principle labeling, and the PRIMARY-only guardrails.
+- [x] **Ledger architecture** — **Resolved (readiness DD-5 + research §Pattern 2):** NetSuite adjustment-only books on header-level `journal.bookId`; SAP full-ledger fan-out rejected.
+- [x] **Book scoping** — **Resolved (Brad, 2026-07-03):** group-scoped definitions with per-company enablement (`accountingBookCompany`), mirroring the shared-COA pattern.
+- [x] **Accounting principle attribute** — **Resolved (program scope, 2026-07-04):** `accountingPrinciple ∈ (US-GAAP | IFRS | Local | Tax)` per book, driving report labeling and generator applicability.
+- [x] **Consolidation boundary** — **Resolved (program scope, 2026-07-04):** v1 consolidation/translation reads PRIMARY only; consolidated book overlays deferred to #1050/#1058 with the RPC parameters as the ready substrate.
+
+No genuinely new blocking questions — the two judgment calls surfaced while writing (mid-life book enablement catch-up mechanics; reuse of `depreciationRun` for book runs) are resolved as design decisions 7 and the `effectiveFrom` catch-up rule above, both reversible before implementation review.
+
+## Changelog
+
+- 2026-07-04: Created. Scope resolved "more ambitious" by Brad 2026-07-04; book scoping resolved 2026-07-03. Shared-seed DDL contract published for #1047 (parallel spec) to adopt. Generator consumers #1040 (IAS 2 NRV) and #1056 (IFRS 16) register against the contract defined here.
diff --git a/.ai/specs/2026-07-04-record-integrity-audit-hardening.md b/.ai/specs/2026-07-04-record-integrity-audit-hardening.md
new file mode 100644
index 0000000000..ba4a6b9619
--- /dev/null
+++ b/.ai/specs/2026-07-04-record-integrity-audit-hardening.md
@@ -0,0 +1,295 @@
+# Record Integrity & Audit Hardening (Phase 0 Spec A)
+
+> Status: in-progress (all open questions resolved pre-writing — program resolutions 2026-07-03/04)
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1047
+> Program: `.ai/specs/2026-07-03-public-company-readiness.md` (MW-1 remainder + SD-1 remainder + GAP-5 step 1) · `.ai/plans/2026-07-03-public-company-readiness-roadmap.md` §Phase 0 Spec A
+> Companions: `.ai/specs/2026-07-02-period-closing.md` (journal immutability fold-in — prerequisite trigger wave) · `.ai/specs/2026-07-04-document-approvals.md` (Spec B — preparedBy/approvedBy) · Spec C (gapless numbering — separate)
+
+## TLDR
+
+This spec completes the MW-1 material-weakness remediation that the period-closing fold-in started. Five deliverables, one theme — make the ledger evidence-grade for a SOX auditor: (1) SECURITY DEFINER immutability triggers freezing posted `payment`/`memo` rows (only `Posted → Voided` transitions) and `invoiceSettlement` rows once their funding source is posted, mirroring the period-closing journal trigger and binding the service role; (2) a deferred constraint trigger asserting Σ(signed `journalLine.amount`) = 0 per posted journal at COMMIT (±0.01), covering every writer including edge functions (SD-1 remainder); (3) audit hardening — **synchronous, trigger-based, in-transaction audit writes for accounting tables** (replacing the async PGMQ path for those tables only), always-on regardless of the company toggle, with append-only audit tables and a 7-year retention floor for accounting entities; (4) a full-population **JE export** (streaming, no row caps) that reconciles opening TB + export = closing TB — the SOX AS 2401 / FEC / SAF-T / GoBD workhorse; (5) the GAP-5 schema seed — `journal.bookId` + a group-scoped `accountingBook` table with per-company enablement (`accountingBookCompany`), seeded `PRIMARY` book, and book filtering on the balance RPCs. Plus the sanctioned data-fix channel: a `'Repair'` journal source type — permissioned, reason required, correcting-entries only, itself immutable.
+
+## Problem Statement
+
+The period-closing spec (§Enforcement item 4) makes posted `journal`/`journalLine` rows immutable, but the rest of the record-integrity surface from readiness finding MW-1 is still open:
+
+- **Posted payments and memos are mutable.** `payment`/`memo` UPDATE RLS has no status condition (`20260630093809_ar-ap-payments.sql:274-280` — the migration's own comment says "App-side service rejects illegal transitions"). Any `invoicing_update` user via PostgREST, and any service-role writer unconditionally, can rewrite a posted payment's amount, bank account, or counterparty. `invoiceSettlement` write policies check the funding source is Draft — but the service role bypasses RLS entirely, so nothing at the DB actually freezes a posted settlement.
+- **Nothing at the DB guarantees a journal balances.** Debits=credits is asserted only in app code (`postJournalEntry`, the payment journal builder); the invoice/receipt/shipment/production posting edge functions have no balance assertion at all. One unbalanced journal breaks the opening→closing TB identity every report and tie-out depends on.
+- **The audit log cannot serve as ICFR evidence.** It is opt-in per company (default off), writes asynchronously through PGMQ (rows are lost if the pipeline fails — fatal for evidence), retains 30 days hot, has `USING (true)` policies on its own tables (tamperable), and its ~26-entity coverage (`packages/database/src/audit.config.ts`) excludes every accounting table: `journal`, `journalLine`, `account`, `accountingPeriod`, `payment`, `memo`, `invoiceSettlement`, `sequence`, `userPermission`, `apiKey`, `approvalRequest`/`approvalRule`, `accountDefault`, `paymentTerm`, `bankAccount`. The period-closing and approvals specs route their transition audit through this same system — their control trail inherits every weakness.
+- **No JE population export.** An auditor cannot obtain the complete journal-entry population with preparer/approver/timestamps; France FEC requires it on 15 days' notice.
+- **No book dimension.** `journal` has no `bookId`; retrofitting one after more posters/reports ship is the single most expensive retrofit in the readiness research (§Pattern 2).
+- **No sanctioned repair path.** Once immutability lands, historical data fixes (e.g. the invoice/payment audit's deferred repairs) have no legal channel — teams would be tempted to bypass triggers with SQL.
+
+## Proposed Solution
+
+### 1. Posted-record immutability: `payment`, `memo`, `invoiceSettlement`
+
+Same pattern as the period-closing journal trigger (`20260702044133` wave): `BEFORE UPDATE OR DELETE` row triggers whose functions are `SECURITY DEFINER`, so they bind PostgREST users, edge functions, and service-role jobs alike. Semantics derived from the actual void path (`packages/database/supabase/functions/post-payment/index.ts:150-207` — void posts a NEW reversing journal and updates only `status`/`voidedAt`/`voidedBy`/`updatedAt`/`updatedBy`):
+
+| Table | Draft | Posted | Voided |
+|---|---|---|---|
+| `payment` | freely editable/deletable (existing RLS) | UPDATE allowed **only** for the transition `status: Posted → Voided` + `voidedAt`/`voidedBy`/`updatedAt`/`updatedBy`; every other column must be byte-identical. DELETE rejected. | Terminal — all UPDATE/DELETE rejected. |
+| `memo` | same | same (`Posted → Voided` only) | same |
+| `invoiceSettlement` | editable while funding source (`paymentId` → `payment.status` / `memoId` → `memo.status`) is `Draft` | frozen — all UPDATE/DELETE rejected once the source is `Posted` or `Voided` | frozen |
+
+Settlement rows are **never deleted on void**: the derived invoice balance views already filter `p."status" = 'Posted'` (`20260630095023_invoice-derived-status.sql:64,167`), so voiding the source releases the invoices while the settlement history survives as evidence. The column-set comparison is implemented as `to_jsonb(OLD) - allowed_keys = to_jsonb(NEW) - allowed_keys` so future column additions are frozen by default. The Repair channel (§6) and reversal flows never need in-place edits — void/repair always post new documents.
+
+### 2. DB-level double-entry enforcement (SD-1 remainder)
+
+A **deferred constraint trigger** asserting per-journal balance at COMMIT, tolerance ±0.01 (base currency; matches the app-layer assertion in the manual-JE service):
+
+- `AFTER INSERT OR UPDATE OR DELETE ON "journalLine"` — `CONSTRAINT TRIGGER ... DEFERRABLE INITIALLY DEFERRED`, re-checks the parent journal's Σ(`amount`) when the parent `journal.status = 'Posted'`. Deferral means posters that insert the header and lines across multiple statements in one transaction are validated once, at COMMIT, when all lines exist.
+- `AFTER UPDATE OF "status" ON "journal"` — same deferred check when `NEW.status = 'Posted'`, catching the Draft→Posted transition of manual JEs (whose lines predate the flip and may legitimately be unbalanced while Draft).
+
+Draft journals stay exempt (the draft editor saves lines incrementally); the period-close readiness blocker "TB balanced" remains as the report-level control. Both functions are `SECURITY DEFINER` and raise `EXCEPTION 'Journal % does not balance: sum of line amounts is %'` — every writer, including edge functions and Inngest service-role jobs, is covered. No existing data risk: an implementation pre-check `SELECT "journalId" FROM "journalLine" GROUP BY 1 HAVING abs(sum(amount)) >= 0.01` runs before the migration ships; any hits are repaired via the Repair channel first.
+
+### 3. Audit hardening: synchronous, always-on, append-only, 7-year floor
+
+**Resolved (program resolution 2026-07-03/04, Brad): synchronous trigger-based in-transaction audit writes for accounting tables**, replacing the async PGMQ path *for those tables only*. Operational entities keep the existing PGMQ → Inngest pipeline unchanged.
+
+**Mechanism.** A new `SECURITY DEFINER` trigger function `audit_accounting_change()` + registration helper `attach_audit_trigger(table_name, entity_type, entity_id_column DEFAULT NULL)`:
+
+- `AFTER INSERT OR UPDATE OR DELETE FOR EACH ROW`, computes the diff in SQL (`to_jsonb(OLD)`/`to_jsonb(NEW)`, skipping `updatedAt`/`updatedBy`/`embedding` per `auditConfig.skipFields`), resolves `entityId` (own PK for roots; the named column for children, e.g. `journalLine.journalId`), captures `actorId` from `auth.uid()` (NULL = service role/system), and INSERTs directly into `auditLog_{companyId}` **in the same transaction**. If the posting transaction rolls back, so does its audit row; if the audit insert fails, the posting fails — the trail can never be missing for a committed change. No snapshot-FK resolution in v1 sync path (that stays an async-path nicety); `metadata.origin = 'sync'` distinguishes provenance.
+- Group-scoped tables without `companyId` (`account`, `accountingBook`) fan the row out to each company in the group (companies resolved inside the definer function) so per-company audit tables stay self-contained.
+
+**Coverage** (triggers attached in the migration; the future-proof rows are registered by their own specs' migrations calling `attach_audit_trigger` when the tables land):
+
+| Entity (audit.config key) | Tables (role) | When |
+|---|---|---|
+| `journalEntry` ("Journal Entry") | `journal` (root), `journalLine` (child via `journalId`) | now |
+| `account` ("Account") | `account` (root, group-scoped fan-out) | now |
+| `accountingPeriod` ("Accounting Period") | `accountingPeriod` (root), `periodCloseTask` (child via `accountingPeriodId`) | now (task table lands with period-closing) |
+| `periodCloseTaskDefinition` | `periodCloseTaskDefinition` (root) | with period-closing |
+| `payment` ("Payment") | `payment` (root), `invoiceSettlement` (child via `paymentId`) | now |
+| `memo` ("Memo") | `memo` (root), `invoiceSettlement` (child via `memoId`) | now |
+| `sequence` ("Sequence") | `sequence` (root) | now |
+| `userPermission` ("User Permissions") | `userPermission` (root) | now |
+| `apiKey` ("API Key") | `apiKey` (root) | now |
+| `approval` ("Approval") | `approvalRequest` (root), `approvalRule` (root) | now |
+| `accountDefault` ("Account Defaults") | `accountDefault` (root) | now |
+| `paymentTerm` ("Payment Term") | `paymentTerm` (root) | now |
+| `bankAccount` ("Bank Account") | `bankAccount` (root) | with bank-rec spec |
+| `taxCode` ("Tax Code") | `taxCode` (root), `taxCodeComponent` (child) | with tax spec |
+| `customerTax` / `supplierTax` | move from async extension coverage to sync roots | now |
+| `accountingBook` ("Accounting Book") | `accountingBook` (root, fan-out), `accountingBookCompany` (child via `bookId`) | now (§5) |
+
+`audit.config.ts` gains these entities plus a per-entity `mode: "sync"` flag and `retentionClass: "accounting"`; sync entities are excluded from `attach_event_trigger`/`syncAuditSubscriptions` (no double-write) but keep driving the UI (labels, entity drawer, `getEntityPath` prefixes `je`→journal entry, `pay`→payment). **`audit.config.ts` is ask-first per `packages/database/AGENTS.md` — this spec is the ask.**
+
+**Always-on.** The accounting sync triggers are attached unconditionally in the migration and are NOT managed by `enableAuditLog`/`disableAuditLog` — the company toggle governs operational entities only. Consequence: `auditLog_{companyId}` must exist for every company — the migration runs `create_audit_log_table` for all companies missing one, and `seed-company` creates it at company creation.
+
+**Append-only lockdown.** On all `auditLog_%` tables (existing + created): `REVOKE UPDATE, DELETE ON ... FROM authenticated, anon, service_role`; restrictive RLS policies denying UPDATE/DELETE for belt-and-braces; `create_audit_log_table` updated to apply both to future tables. INSERT flows only through the `SECURITY DEFINER` writers (`audit_accounting_change()`, `insert_audit_log_batch`). Deletion happens exclusively inside a hardened `delete_old_audit_logs` (SECURITY DEFINER, owner postgres), which now enforces retention classes internally.
+
+**Retention.** Per-class: operational keeps `retentionDays: 30` → archive → delete. Accounting-class rows (`retentionClass: "accounting"`) have a **7-year floor (2,557 days)**: the nightly archive job (`audit-log-archive`) still archives them to the `private` bucket on the hot-retention schedule and may delete hot rows *only after* the archive row is recorded in `auditLogArchive`, and `delete_old_audit_logs` refuses to touch accounting-class rows younger than the floor when no verified archive exists. Archive objects for accounting entities are excluded from any cleanup for 7 years (config: `auditConfig.retentionByClass = { operational: 30, accounting: 2557 }`). The audit-settings UI loses the disable affordance for accounting entities, with explanatory copy.
+
+### 4. JE population export
+
+The single flat export behind SOX AS 2401 sampling, FEC (Phase 3 renders its 18-field layout over this), SAF-T, and GoBD data access. **Streaming, no row caps.**
+
+- **Route:** `apps/erp/app/routes/x+/accounting+/exports.journal-entries.tsx` — loader gated `requirePermissions({ view: "accounting" })`; GET params `fiscalYear` or `fromDate`/`toDate`, `bookId` (default: the group's Primary book), `format` (`csv` default, `jsonl`), `status` (default `Posted,Reversed`; `all` includes Draft for internal review, flagged in the header row).
+- **Service:** `getJournalEntryExportStream(client, companyId, options)` in `accounting.service.ts` — Kysely batched keyset pagination (via `fetchRecordsInBatches` semantics: order by `journal.postingDate, journal.id, journalLine.id`), piped into a `ReadableStream` returned as `Response` with `Content-Disposition: attachment`. Memory-flat at any population size.
+- **Columns (one row per journal line):** `journalId`, `journalEntryId`, `journalLineId`, `accountId`, `accountNumber`, `accountName`, `amount` (signed, base currency), `debit`, `credit` (presentation split of `amount`), `postingDate`, `accountingPeriod` (FY·period), `createdAt`, `postedAt`, `createdBy` (line — from the period-closing fold-in), `preparedBy`, `approvedBy` (from Spec B; blank until it lands), `status`, `sourceType`, `documentType`, `documentId`, `externalDocumentId`, `documentLineReference`, `reversalOfId`, `reversedById`, `sourceCurrencyCode`, `sourceAmount`, `exchangeRate` (from the bank-rec fold-in; blank where predating it), `bookId`, `description`, `repairReason` (§6). Spec C later adds the `isBackdated` flag column.
+- **Reconciliation contract:** for any `[from, to]` with default filters, per-account `openingBalance(from − 1 day)` + Σ(export `amount`) = `closingBalance(to)`, where both balances come from `accountTreeBalancesByCompany` with `p_include_drafts = false` (financial-reporting fold-in) and the same `p_book_id`. This identity is a shipped test, not documentation.
+- **UI:** an Exports card on the accounting section (page `/x/accounting/exports/journal-entries`): fiscal-year/date-range picker, book picker, format toggle, download button; row-count preview via a cheap `count(*)` before streaming.
+
+### 5. `journal.bookId` + `accountingBook` (GAP-5 step 1)
+
+**Resolved scoping (program resolution 2026-07-03, Brad): group-scoped definitions with per-company enablement.** `accountingBook` mirrors the `account`/`currency`/`accountCategory` group-scoped master-data pattern (`20260228023426`): single-column PK, `companyGroupId NOT NULL`, group RLS helpers. `accountingBookCompany` is the standard company-scoped enablement table. Seeds: one `Primary`-type book named "Primary" per `companyGroup` (migration for existing groups; `seed-company` for new), enabled for every company in the group.
+
+`journal.bookId` is added nullable → backfilled to the group's Primary book id → `SET NOT NULL`. A tiny `BEFORE INSERT` trigger fills `bookId` with the company's group Primary book when the poster passes none — every existing posting path keeps working unchanged, and adjustment-book posters (Phase 3) pass it explicitly. Balance RPCs (`accountTreeBalances`, `accountTreeBalancesByCompany`, `translateTrialBalance` — being redefined by the financial-reporting spec anyway) gain `p_book_id TEXT DEFAULT NULL`, where NULL resolves to the group's Primary book; the `journalLines` view exposes `bookId`. Index: `journal ("bookId", "companyId")`.
+
+### 6. `'Repair'` journal source type — the only sanctioned data-fix channel
+
+**Resolved (program resolution 2026-07-03, Brad): reversal-only plus a controlled repair channel — no in-place edits ever, for anyone including the service role.**
+
+- `ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Repair';` — classified as an **accounting** source under the period-closing matrix (postable into Locked periods, never Closed ones).
+- `journal.repairReason TEXT` + CHECK constraint: `sourceType = 'Repair'` ⟹ `repairReason IS NOT NULL` (and `repairReason` only on Repair journals). The reason lands in the JE export and audit log.
+- **Permissioned:** posting a Repair journal requires `delete: "accounting"` — the de-facto module-admin tier, following the period-closing precedent (reopen = `delete: accounting`; no new RBAC action, which is ask-first territory).
+- **Correcting-entries only:** a Repair journal is an ordinary balanced journal (the §2 trigger applies) posted through `postJournalEntry`; it never edits existing rows. Once posted it is immutable like any journal (period-closing trigger) — a wrong repair is itself corrected by reversal or another repair.
+- The invoice/payment audit's deferred historical-repair work, and any future data-fix script (service role included), flows through this channel; direct SQL fixes on posted rows are physically blocked by the §1/§2 and period-closing triggers.
+- UI: `sourceType = 'Repair'` selectable in the journal-entry form only for users with `delete: accounting`, revealing a required Reason field; Repair entries render a distinct badge in the journal list and GL detail.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Multi-tenancy heuristic | New tables: `accountingBookCompany` has `companyId` + composite PK + `id('abc')` + audit columns. **Deviations:** `accountingBook` is group-scoped (single PK + `companyGroupId`, like `account`); `payment`/`memo`/`invoiceSettlement`/`journal` keep their existing single-column PKs untouched | Group master data follows the `20260228023426` precedent, not the company template; churning existing PKs = high risk, zero gain (period-closing made the same call for `accountingPeriod`) |
+| 2 | Service shape heuristic | All new functions in `accounting.service.ts` (`getJournalEntryExportStream`, `getAccountingBooks`, `upsertAccountingBook`, `setBookCompanyEnablement`), `(client, ...)` → `{data, error}`, never throw; the export loader consumes the stream variant | `.ai/rules/conventions-services.md`; one module service file |
+| 3 | RLS coverage heuristic | `accountingBook`: SELECT `get_company_groups_for_employee()`, writes `get_company_groups_for_root_permission('accounting_*')` (the `account` pattern). `accountingBookCompany`: the four standard policies, SELECT role / writes `accounting_*`. Audit tables: existing permissive policies replaced by SELECT-only + restrictive deny on UPDATE/DELETE | Matches `20260228023426:781-804` exactly; audit tables must be tamper-evident |
+| 4 | Permission scoping heuristic | Export + book read: `view: accounting`; book management: `update: accounting`; Repair posting: `delete: accounting`; audit settings unchanged (`settings_update`) | Follows the branch precedent of reusing `accounting_*` tiers; no new RBAC actions (ask-first) |
+| 5 | Form pattern heuristic | Book settings + Repair reason use `ValidatedForm` + zod validators in `accounting.models.ts` + route actions with `intent`; export page is a GET form (no mutation) | `.ai/rules/conventions-forms.md` |
+| 6 | Module layout heuristic | Everything in `modules/accounting` (`accounting.models.ts`/`accounting.service.ts`/`ui/`); DB-side helpers in migrations; `audit.config.ts` edits in `packages/database` | No new files outside existing module structure except routes |
+| 7 | Backward compatibility heuristic | Additive schema only; no FROZEN surface touched. Behavior changes (frozen posted payments, balance rejection, always-on audit) activate for existing companies at the readiness cutover event; posting-function changes ship as coordinated PRs per the FX-spec precedent | Readiness spec Design Decision 15; the §1 semantics were reverse-engineered from the live void path so no legitimate flow breaks |
+| 8 | Immutability mechanism | Status-transition-only `SECURITY DEFINER` triggers, all period states, JSONB column-set comparison | Period-close trigger precedent; RLS demonstrably failed (`WITH CHECK (true)`, service-role bypass); JSONB diff freezes future columns by default |
+| 9 | Settlement void semantics | Settlements are never deleted/updated after source posts; void flips only the source status | Derived balance views already filter `status = 'Posted'` (`20260630095023`) — history survives, invoices release, no schema change |
+| 10 | Balance enforcement point | Deferred constraint trigger at COMMIT, Posted journals only, ±0.01 | Drafts are legitimately unbalanced mid-edit; deferral tolerates multi-statement posters; COMMIT-time is the only point that binds every writer |
+| 11 | Audit write mechanism | Synchronous DB trigger writing `auditLog_{companyId}` in-transaction; PGMQ retained for operational entities | Program resolution 2026-07-03/04 (Brad): never fire-and-forget for accounting entities; same-transaction = atomic with the change; outbox rejected as it re-introduces a loss window |
+| 12 | Audit always-on + retention | Accounting entities non-disablable; per-class retention `{ operational: 30, accounting: 2557 }`; archives are the 7-year system of record; append-only via REVOKE + restrictive policies + hardened delete RPC | Program resolution: company toggle governs operational entities only; ICFR evidence must be complete and tamper-evident |
+| 13 | Book scoping | Group-scoped `accountingBook` + `accountingBookCompany` enablement; seeded Primary per group; NULL `p_book_id` = Primary | Program resolution 2026-07-03 (Brad): matches the shared-COA pattern; a statutory book is defined once per group, enabled per entity |
+| 14 | `bookId` population | Nullable→backfill→NOT NULL + BEFORE INSERT default-fill trigger; no poster signature changes in this spec | Minimal impact: zero coordinated poster PRs now; Phase 3 adjustment-book posters opt in explicitly |
+| 15 | Export delivery | Streaming loader Response (keyset-batched Kysely), CSV/JSONL, Posted+Reversed default | No row caps is the auditor requirement; PostgREST 1000-row limit and in-memory CSV both disqualified |
+| 16 | Repair channel | New `'Repair'` sourceType + required `repairReason` + `delete: accounting` gate; correcting entries only | Program resolution 2026-07-03 (Brad); enum value is additive; permission reuses the established admin tier |
+
+## Data Model Changes
+
+One migration wave (`pnpm db:migrate:new record-integrity-audit-hardening`, randomized HHMMSS; then `pnpm run generate:types`). Sketches (representative, idempotent like `20260630093809`):
+
+```sql
+-- 1. Payment/memo immutability (invoiceSettlement analogous, checking source status)
+CREATE OR REPLACE FUNCTION enforce_posted_payment_immutability()
+RETURNS TRIGGER SECURITY DEFINER SET search_path = public AS $$
+DECLARE allowed CONSTANT TEXT[] := ARRAY['status','voidedAt','voidedBy','updatedAt','updatedBy'];
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ IF OLD."status" <> 'Draft' THEN
+ RAISE EXCEPTION '% % is %; posted records are immutable — void it instead', TG_TABLE_NAME, OLD."id", OLD."status";
+ END IF;
+ RETURN OLD;
+ END IF;
+ IF OLD."status" = 'Voided' THEN
+ RAISE EXCEPTION '% % is Voided (terminal)', TG_TABLE_NAME, OLD."id";
+ END IF;
+ IF OLD."status" = 'Posted' THEN
+ IF NOT (NEW."status" = 'Voided'
+ AND to_jsonb(OLD) - allowed = to_jsonb(NEW) - allowed) THEN
+ RAISE EXCEPTION '% % is Posted; only the Posted -> Voided transition is allowed', TG_TABLE_NAME, OLD."id";
+ END IF;
+ END IF;
+ RETURN NEW;
+END; $$ LANGUAGE plpgsql;
+
+CREATE TRIGGER "payment_immutability" BEFORE UPDATE OR DELETE ON "payment"
+ FOR EACH ROW EXECUTE FUNCTION enforce_posted_payment_immutability();
+CREATE TRIGGER "memo_immutability" BEFORE UPDATE OR DELETE ON "memo"
+ FOR EACH ROW EXECUTE FUNCTION enforce_posted_payment_immutability();
+-- invoiceSettlement: enforce_settlement_immutability() rejects UPDATE/DELETE when
+-- the funding source (payment/memo by paymentId/memoId) is not 'Draft'.
+
+-- 2. Deferred double-entry constraint (±0.01), Posted journals only
+CREATE OR REPLACE FUNCTION assert_journal_balanced() -- shared by both constraint triggers
+RETURNS TRIGGER SECURITY DEFINER SET search_path = public AS $$ ... $$; -- Σ(amount) check
+CREATE CONSTRAINT TRIGGER "journalLine_balance" AFTER INSERT OR UPDATE OR DELETE ON "journalLine"
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION assert_journal_balanced();
+CREATE CONSTRAINT TRIGGER "journal_post_balance" AFTER UPDATE OF "status" ON "journal"
+ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION assert_journal_balanced();
+
+-- 3. Synchronous audit: attach_audit_trigger(...) + audit_accounting_change();
+-- create_audit_log_table for companies missing one; on all auditLog_% tables:
+-- REVOKE UPDATE, DELETE FROM authenticated, anon, service_role; restrictive
+-- deny policies; delete_old_audit_logs gains per-class retention enforcement.
+SELECT attach_audit_trigger('journal', 'journalEntry');
+SELECT attach_audit_trigger('journalLine', 'journalEntry', 'journalId');
+SELECT attach_audit_trigger('payment', 'payment');
+-- ... (full coverage table in §3; account/accountingBook use the group fan-out variant)
+
+-- 5. Books (group-scoped, mirrors "account" per 20260228023426)
+CREATE TABLE IF NOT EXISTS "accountingBook" (
+ "id" TEXT NOT NULL DEFAULT id('bk') PRIMARY KEY,
+ "companyGroupId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "type" TEXT NOT NULL DEFAULT 'Primary', -- 'Primary' | 'Adjustment' (Phase 3)
+ "accountingPrinciple" TEXT, -- 'US-GAAP' | 'IFRS' | 'Local' | 'Tax'
+ "baseBookId" TEXT REFERENCES "accountingBook"("id"),
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "accountingBook_companyGroupId_fkey" FOREIGN KEY ("companyGroupId")
+ REFERENCES "companyGroup"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "accountingBook_group_name_key" UNIQUE ("companyGroupId", "name")
+);
+CREATE UNIQUE INDEX "accountingBook_one_primary_per_group"
+ ON "accountingBook" ("companyGroupId") WHERE "type" = 'Primary';
+-- RLS: SELECT get_company_groups_for_employee();
+-- writes get_company_groups_for_root_permission('accounting_*').
+
+CREATE TABLE IF NOT EXISTS "accountingBookCompany" (
+ "id" TEXT NOT NULL DEFAULT id('abc'),
+ "companyId" TEXT NOT NULL,
+ "bookId" TEXT NOT NULL REFERENCES "accountingBook"("id") ON DELETE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "accountingBookCompany_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "accountingBookCompany_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "accountingBookCompany_book_company_key" UNIQUE ("bookId", "companyId")
+);
+-- Standard four RLS policies: SELECT role; writes accounting_*.
+-- Indexes on companyId, bookId, createdBy. Seed: Primary book per group,
+-- enablement row per company; seed-company does both for new tenants.
+
+-- journal.bookId: add nullable -> backfill to group Primary -> SET NOT NULL;
+-- BEFORE INSERT default-fill trigger; index ("bookId","companyId");
+-- balance RPCs gain p_book_id TEXT DEFAULT NULL (NULL = Primary).
+
+-- 6. Repair channel
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Repair';
+ALTER TABLE "journal" ADD COLUMN IF NOT EXISTS "repairReason" TEXT;
+ALTER TABLE "journal" ADD CONSTRAINT "journal_repairReason_check" CHECK (
+ ("sourceType" = 'Repair') = ("repairReason" IS NOT NULL)
+);
+```
+
+## API / Service Changes
+
+- `accounting.service.ts`: `getJournalEntryExportStream(client, companyId, { fiscalYear?, fromDate?, toDate?, bookId?, format, status })`; `getAccountingBooks(client, companyGroupId)`; `upsertAccountingBook(client, ...)`; `setBookCompanyEnablement(client, ...)`; `postJournalEntry` gains the Repair gate (`sourceType === 'Repair'` ⟹ `requirePermissions` checked `delete: accounting` at the route + `repairReason` required in the validator) — all `(client, ...)` → `{data, error}`.
+- `accounting.models.ts`: `journalEntryValidator` extended with optional `sourceType`/`repairReason` (zod refinement pairs them); `accountingBookValidator`; `journalEntryExportValidator`.
+- Routes: `x+/accounting+/exports.journal-entries.tsx` (streaming loader, `view: accounting`); `x+/accounting+/books.tsx` (loader + action with `intent`: `upsert` | `enable` | `disable`, `update: accounting`).
+- `packages/database`: `audit.config.ts` entity additions + `mode`/`retentionClass` knobs (this spec is the ask); `audit.ts` — `enableAuditLog`/`disableAuditLog`/`syncAuditSubscriptions` skip sync-mode entities; `packages/jobs` archive function reads `retentionByClass` and the archive-before-delete rule.
+- Balance RPCs: `p_book_id` parameter (coordinated with the financial-reporting spec's `p_include_drafts` redefinition — one RPC rewrite, both parameters).
+- No posting edge-function changes required by this spec (bookId defaults via trigger; balance/immutability are backstops). The tax and bank-rec specs each add one `attach_audit_trigger` call in their own migrations.
+
+## UI Changes
+
+- **JE export page** (`/x/accounting/exports/journal-entries`): date/fiscal-year picker, book picker, format toggle, Posted+Reversed default badge, download (streams).
+- **Books settings** (`/x/accounting/books`): group-level book list (Primary badge, principle), per-company enablement toggles; Adjustment-type creation disabled with "Phase 3" hint.
+- **Journal entry form:** Repair source option visible only with `delete: accounting`; required Reason field; Repair badge in journal list + GL detail drill-down.
+- **Audit-log settings:** disable toggle removed for accounting entities with explanatory copy ("Accounting audit is always on and retained 7 years"); entity list shows sync/async + retention class.
+- Flash messages on all mutations per `.ai/rules/flash-system.md`.
+
+## Acceptance Criteria
+
+- [ ] A Posted `payment` rejects, via PostgREST with `invoicing_update` credentials AND via a direct service-role UPDATE: any change to `totalAmount`, `bankAccount`, `customerId`, or `postingDate`; the void flow (post-payment edge function) still succeeds and the settlement rows remain untouched; a Voided payment rejects all further UPDATEs; DELETE of a Posted payment is rejected while Draft delete still works. Same matrix passes for `memo`.
+- [ ] An `invoiceSettlement` UPDATE/DELETE succeeds while its funding payment is Draft and is rejected (all roles, including service role) once that payment is Posted; after voiding the payment, the target invoice's derived balance is restored without any settlement row changing.
+- [ ] A transaction that inserts a Posted journal with lines summing to +0.02 fails at COMMIT with the balance error, from (a) SQL as service role, (b) the post-purchase-invoice edge function patched in a test to skew one line; the same transaction with |Σ| ≤ 0.01 commits. A Draft journal with unbalanced lines saves fine, and flipping it to Posted fails at COMMIT until balanced.
+- [ ] With the company audit toggle OFF, an UPDATE to `journal`, `payment`, `account`, `sequence`, `accountDefault`, `paymentTerm`, and `userPermission` each produce an `auditLog_{companyId}` row with actor + field diff, visible in the same transaction's read (synchronous); rolling back the transaction leaves no audit row; an operational entity (e.g. `salesOrder`) writes nothing while the toggle is off.
+- [ ] UPDATE and DELETE on `auditLog_{companyId}` fail for authenticated users AND for the service role; `delete_old_audit_logs` refuses accounting-class rows younger than 2,557 days without a recorded archive, and the archive job's uploaded object + `auditLogArchive` row precede any hot delete of accounting rows.
+- [ ] The JE export for a fiscal year streams >100k lines without OOM, contains every journal line of every source type (manual, invoices, receipts, shipments, payments, memos, depreciation, Repair), and per account: opening TB (day before range, `p_include_drafts=false`, same book) + Σ(export amounts) = closing TB — asserted by an automated test on seeded data.
+- [ ] Every `companyGroup` has exactly one Primary `accountingBook` after migration; every company has an enablement row; every existing and newly posted `journal` row carries that book's `bookId` without any poster change; `accountTreeBalancesByCompany(p_book_id => NULL)` equals pre-migration results exactly; a second (Adjustment) book's journals are excluded from default balances and included when its id is passed.
+- [ ] A user with `update: accounting` but not `delete: accounting` cannot post a Repair journal (server-side rejection); with `delete: accounting`, posting without a reason fails validation, posting with a reason succeeds, the reason appears in the JE export and audit log, and the posted Repair journal is immutable (period-closing trigger) and reversal-correctable only.
+- [ ] `pnpm run generate:types`, scoped `typecheck`, and `pnpm run lint` pass; the migration applies idempotently twice.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| An unknown writer legitimately mutates Posted payments/memos beyond the void transition | Med | Writer inventory pre-implementation (`grep` posting/edge/Xero-sync surfaces); §1 semantics were derived from the live void path; Xero sync errors surface via the existing integration error queue (period-closing precedent) |
+| Existing unbalanced journals in production make the constraint trigger a landmine on any later line UPDATE | Med | Pre-migration balance sweep; repairs posted via the Repair channel before triggers activate; migration NOTICE lists offenders |
+| Synchronous audit writes slow posting hot paths | Med | One indexed INSERT per changed row in the same transaction; benchmark post-payment/post-invoice before+after in the plan; row-level JSONB diff is O(columns); accounting inserts are not high-frequency |
+| Audit fan-out for group-scoped tables (`account`) multiplies rows across large groups | Low | Groups are small (subsidiary counts); COA edits are rare; measured in the same benchmark |
+| REVOKE on `auditLog_%` breaks the Inngest archive/delete jobs | Med | Jobs already operate through SECURITY DEFINER RPCs (`get_audit_logs_for_archive`, `delete_old_audit_logs`); verify no direct table DML in `packages/jobs` before shipping |
+| `bookId` NOT NULL backfill on a large `journal` table locks writes | Low | Add column nullable + backfill in batches + `SET NOT NULL` last (validated constraint pattern); journals table is moderate-sized |
+| Interplay with in-flight branch specs (period-closing trigger wave, financial-reporting RPC rewrite, Spec B approval columns) | Med | Sequencing: this spec's migration lands after the period-closing migration; the RPC `p_book_id` addition is coordinated into the financial-reporting RPC rewrite PR; export columns tolerate NULL `preparedBy`/`approvedBy` until Spec B lands |
+| Always-on audit surprises existing companies (storage growth) | Low | Accounting-entity write volume is modest; 30-day hot window unchanged (archives carry the 7 years); release note at the cutover event |
+
+## Open Questions
+
+> All resolved before writing — recorded per the spec lifecycle (resolutions carry the program decisions; this section is the audit trail, not a to-do list).
+
+- [x] **Audit write mechanism for accounting tables (sync trigger vs transactional outbox vs hardened PGMQ)?** — **Answer: synchronous, trigger-based, in-transaction writes for accounting tables; operational tables keep PGMQ** — program resolution 2026-07-03/04 (Brad). Never fire-and-forget for ICFR evidence; the outbox alternative re-introduces a loss window between commit and drain.
+- [x] **Is audit logging disablable for accounting entities, and what retention applies?** — **Answer: always-on for accounting entities (company toggle governs operational entities only); append-only tables; retention floor 7 years for accounting entities, 30-day default stays operational** — program resolution 2026-07-03/04 (Brad).
+- [x] **`audit.config.ts` is an ask-first file (`packages/database/AGENTS.md`) — is the entity extension approved?** — **Answer: yes — this spec IS the ask**, per the roadmap Phase 0 Spec A item; coverage list fixed as §3's table (including future-proof `taxCode`/`taxCodeComponent`/`bankAccount` registered by their own specs).
+- [x] **Sanctioned repair path under immutability?** — **Answer: reversal-only plus a controlled `'Repair'` journal source type — permissioned (`delete: accounting`), reason required, correcting-entries only, itself immutable and audit-logged; no in-place edits ever, including service role** — program resolution 2026-07-03 (Brad).
+- [x] **Book scoping (company vs group)?** — **Answer: group-scoped `accountingBook` definitions with a per-company enablement table (`accountingBookCompany`), like the shared chart of accounts; seeded `PRIMARY` book per group enabled for all companies; balance RPCs filter by book with Primary as default** — program resolution 2026-07-03 (Brad).
+- [x] **Payment/memo immutability semantics?** — **Answer: `Posted → Voided` status transitions only, SECURITY DEFINER binding the service role, mirroring the period-closing journal trigger** — program resolution 2026-07-03/04 (Brad); the allowed column set (`voidedAt`/`voidedBy`/`updatedAt`/`updatedBy`) verified against the live void path in `post-payment/index.ts`.
+- [x] **Balance enforcement shape?** — **Answer: deferred constraint trigger asserting Σ(signed `journalLine.amount`) = 0 per journal at COMMIT, ±0.01 tolerance, all writers** — program resolution 2026-07-03/04 (Brad); Posted-only scoping (Drafts exempt) follows from the existing draft-editing workflow and the financial-reporting Posted-only fold-in.
+- [x] **JE export scope?** — **Answer: streaming route + service, no row caps; columns per §4 (ids, account, signed amount + debit/credit presentation, posting date, createdAt/postedAt, createdBy/preparedBy/approvedBy, source type, document reference, reversal linkage, source currency/amount, bookId); must reconcile opening TB + export = closing TB** — program resolution 2026-07-03/04 (Brad).
+
+## Changelog
+
+- 2026-07-04: Created (Phase 0 Spec A, tracking crbnos/carbon#1047). All open questions resolved before writing via the 2026-07-03/04 program resolutions recorded in `.ai/specs/2026-07-03-public-company-readiness.md` §Open Questions and `.ai/plans/2026-07-03-public-company-readiness-roadmap.md` §Governing decision 5. Immutability semantics grounded in `20260630093809_ar-ap-payments.sql` + `post-payment/index.ts` void path; settlement freeze relies on the `status='Posted'` filter in `20260630095023_invoice-derived-status.sql`; book RLS mirrors `20260228023426_company-groups.sql:781-804`; audit design extends `20260212152709_audit_log_system.sql` + `packages/database/src/audit.config.ts`.
diff --git a/.ai/specs/2026-07-04-revenue-recognition.md b/.ai/specs/2026-07-04-revenue-recognition.md
new file mode 100644
index 0000000000..72a7ecfbde
--- /dev/null
+++ b/.ai/specs/2026-07-04-revenue-recognition.md
@@ -0,0 +1,344 @@
+# Revenue Recognition (ASC 606 / IFRS 15)
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1048
+> Readiness finding: `.ai/specs/2026-07-03-public-company-readiness.md` GAP-1
+> Research: `.ai/research/public-company-compliance.md` (§ASC 606 answers, §NetSuite ARM)
+
+## TLDR
+
+Carbon recognizes revenue in full the moment a sales invoice posts — `post-sales-invoice` credits `accountDefault.salesAccount` with the gross line total ([post-sales-invoice/index.ts:381-398](packages/database/supabase/functions/post-sales-invoice/index.ts)); the seeded Deferred Revenue account **2160** has no writer, and no schedule, obligation, deposit, or percent-of-completion concept exists anywhere (verified by grep — GAP-1). This spec builds the full ASC 606 five-step model using NetSuite ARM's proven vocabulary: a **revenue arrangement** (the contract, one per sales order) containing **revenue elements** (performance obligations, one per sales order line) that receive a **relative-SSP allocation** of the transaction price from a standalone-selling-price catalog (with residual fallback), and **recognition schedules** per element — point-in-time on shipment/invoice, straight-line over a service period, and **cost-to-cost percent-of-completion driven by Carbon's existing job-costing actuals** (WIP journal lines by `documentId = jobId` over the estimate-at-completion from `jobMaterial`/`jobOperation`) — the differentiator no AI-GL competitor can copy, because they have no cost basis to recognize against. Billing for deferrable elements credits 2160 instead of revenue; a monthly recognition run generates an *accounting*-source journal (`Dr 2160 / Cr 4010` + auto-reversing contract-asset reclass) that posts under the period-close matrix and registers a seeded `periodCloseTaskDefinition` ("Recognize revenue for the period") with an auto-check on due unposted schedules. Customer deposits post to the existing Customer Prepayments liability (2110) until performance; contract modifications re-spread prospectively or with cumulative catch-up per ASC 606-10-25-12/13; reports ship the deferred-revenue waterfall, contract asset/liability rollforward, and remaining-performance-obligations backlog.
+
+## Problem Statement
+
+- **Revenue is all point-in-time, at invoice.** A 9-month machine build invoiced 50% up front books half the contract as revenue on day one; a 12-month service contract books 100% at invoicing. Both are wrong under ASC 606 and both are audit findings that force customers off Carbon before an IPO (readiness GAP-1; research §market timing — "rev-rec shadow spreadsheets" is a top-3 QuickBooks-graduation trigger).
+- **Account 2160 "Deferred Revenue" is dead schema.** Seeded in [20260315000000_reset-chart-of-accounts.sql:206](packages/database/supabase/migrations/20260315000000_reset-chart-of-accounts.sql) but mapped to no `accountDefault` column and written by no posting path.
+- **No deposits.** A customer's 30% down payment on a `payment` with no invoice application sits as a credit inside AR — understating both cash-collected liability and gross AR; there is no contract-liability presentation.
+- **No obligations or allocation.** A bundled order (machine + install + 1-year support) has no way to split the price by fair value; discounts land wherever the salesperson typed them.
+- **The raw material for POC already exists and is unused for revenue.** Job actuals accumulate in the GL WIP account keyed by `documentId = jobId` (`issue` → *Job Consumption*, `post-production-event` → *Production Event*), estimates live on `jobMaterial`/`jobOperation`, and `close-job` already computes the WIP balance per job — everything cost-to-cost POC needs, with no progress-billing or percent-complete concept on top of it (verified: zero hits for `milestone`/`percentOfCompletion`).
+
+Scope resolved 2026-07-04 (Brad): **the full model** — arrangements, SSP allocation, all three methods, deposits, modifications, reports — not the reduced deferral-only cut GAP-1 sketched.
+
+## Proposed Solution
+
+### Object model — NetSuite ARM vocabulary (research §NetSuite ARM)
+
+| Carbon table | ARM concept | Meaning |
+|---|---|---|
+| `revenueArrangement` | Revenue Arrangement | The ASC 606 contract. One per sales order (v1); holds status + transaction price. |
+| `revenueElement` | Revenue Element | One performance obligation, 1:1 with a `salesOrderLine`; carries SSP, allocated amount, method, job link. |
+| `revenueRecognitionSchedule` | Revenue Plan lines | Dated recognition rows per element; `planType` `Forecast` (unbilled projection) vs `Actual` (billed, postable). A separate plan header table is deliberately collapsed into element + schedule while Carbon has a single book — reintroduce per-book plans when GAP-5 multi-book lands. |
+| `itemStandaloneSellingPrice` | Fair Value Price List | SSP catalog per item with configurable determination and effective dating. |
+
+**Creation.** When `companySettings.revenueRecognitionEnabled` is on, releasing a sales order (status leaves Draft) creates the arrangement + elements from its lines (service hook in `convertQuoteToOrder`/order release path; idempotent). Transaction price = Σ line extended prices **net of tax** (the multi-jurisdiction tax spec removes tax from revenue; the element snapshot uses the same pre-tax base `quantity × unitPrice + setup + addOn`). Flag off (default) ⇒ zero new rows, zero posting changes — full backward compatibility.
+
+**Lifecycle.** `Draft → Approved → Closed`. Allocation runs at approval; single-element arrangements auto-approve (no allocation judgment to review). Invoicing a line whose element belongs to an unapproved multi-element arrangement is blocked with a flash error. `Closed` when all elements are fully recognized and billed.
+
+### SSP and relative-SSP allocation
+
+- `itemStandaloneSellingPrice`: per item + currency, `price`, `method` (`Stated` — entered by accounting; `List Price` — derived from `itemUnitSalePrice.unitSalePrice` at arrangement creation), `effectiveDate`/`expirationDate` (rate-change pattern from the tax spec's components).
+- Element SSP resolution order: Stated SSP row → company fallback per `companySettings.sspFallback` (`List Price` default | `Invoice Price` — treats the stated line price as SSP, i.e. no reallocation) → **Residual**: permitted when exactly *one* element in the arrangement lacks SSP (ASC 606-10-32-34(c)); its allocation = transaction price − Σ other allocations. Two or more SSP-less elements block approval with a named-item error.
+- Allocation: `allocated_i = transactionPrice × (SSP_i × qty_i) / Σ(SSP × qty)`, rounded largest-remainder so Σ allocated = transaction price to the cent.
+- **Range expedient** (NetSuite range checking): if every element's stated line price is within `sspTolerancePercent` (company setting, default 5%) of its SSP, allocation keeps stated prices — no churn when sales prices at fair value.
+- `sspSource` snapshots on the element (`Stated` / `List Price` / `Invoice Price` / `Residual`) — the allocation is explainable from the row forever, config edits never restate it.
+
+### Recognition methods (per element; default from new `item.revenueRecognitionMethod`, overridable per line pre-approval)
+
+1. **Point in Time** (default — today's behavior, made allocation-aware). Recognition event = shipment posting for inventory lines (control transfers), invoice posting otherwise. If billing and the event land in the same period and allocated = billed, the invoice credits revenue directly (no deferral churn). Otherwise billing defers (below) and one `Actual` schedule row dated at the event releases it.
+2. **Straight Line.** New `salesOrderLine.serviceStartDate/serviceEndDate` define the period; schedule rows generated per accounting period, first/last prorated by days. Billing converts Forecast rows to Actual up to the billed amount (oldest first).
+3. **Percent of Completion (cost-to-cost)** — for elements whose sales order line spawned a job (`job.salesOrderLineId` linkage, [20250124174744_add-sales-order-line-to-jobs.sql](packages/database/supabase/migrations/20250124174744_add-sales-order-line-to-jobs.sql)):
+ - **Actual cost to date** = Σ `journalLine.amount` where `accountId = accountDefault.workInProgressAccount` AND `documentId = job.id` AND `amount > 0` — the *debit inflows* (Job Consumption material, Production Event labor/machine), deliberately excluding WIP relief credits so shipping to stock doesn't un-earn revenue. Same subledger query `close-job` already trusts.
+ - **Estimate at completion (EAC)** = Σ `jobMaterial.estimatedQuantity × unitCost` + Σ `jobOperation` (setup/labor/machine hours × `laborRate`/`machineRate` + `overheadRate`) — the `JobEstimatesVsActuals.tsx` math, extracted into a `getJobCostProgress` RPC — floored at actual-to-date (EAC can only grow past estimate, never fall below cost incurred).
+ - `pctComplete = LEAST(actual / NULLIF(EAC, 0), 1)`; cumulative revenue = `pctComplete × allocatedAmount`; the run posts the delta vs previously recognized. EAC drift therefore self-corrects as a **cumulative catch-up in the current open period** — closed periods are never restated.
+ - Job `Completed` or closed via `close-job` ⇒ force 100% (remaining allocation recognizes in that period's run).
+ - POC schedule rows are not pre-spread: each run inserts the period's `Actual` delta row; `Forecast` rows for RPO/waterfall are projected from `job.dueDate` and replaced as actuals post.
+
+### Posting model
+
+**Accounts** (per the control-account lesson — resolved by id via `accountDefault`, never by number at posting time):
+- `accountDefault.deferredRevenueAccount` → backfilled to seeded **2160 Deferred Revenue** (finally gets its writer).
+- `accountDefault.contractAssetAccount` → new seeded **1145 Contract Assets** (current-assets group, parent resolved by `isGroup = TRUE AND name`, per lesson `20260630093809` precedent).
+- Deposits use existing `accountDefault.prepaymentAccount` → **2110 Customer Prepayments** (already seeded and mapped, currently writerless on the AR side).
+
+**Billing (deferral).** `post-sales-invoice` change: for a line whose element defers (any method when the recognition event hasn't fully occurred), the revenue credit swaps `salesAccount` → `deferredRevenueAccount` for the pre-tax amount; AR debit unchanged; COGS logic untouched (v1 — see OQ-N1). Lines with no element (flag off, or non-arrangement companies) post exactly as today. Base-currency amounts freeze at the invoice `exchangeRate` — deferred revenue is nonmonetary, released at historical rate.
+
+**Recognition run (monthly).** `runRevenueRecognition(client, { companyId, accountingPeriodId, userId })`:
+1. Refresh POC deltas (`getJobCostProgress`) and convert billed Forecast → Actual rows.
+2. Select due rows: `planType = 'Actual'`, `status = 'Planned'`, `scheduledDate ≤ period end`.
+3. Generate **one Draft journal** — `sourceType: 'Revenue Recognition'` (new `journalEntrySourceType` value, an *accounting* source under the period-close matrix, so it posts into Locked periods with `update: accounting`) — lines `Dr deferredRevenueAccount / Cr salesAccount` per element, `documentId = revenueArrangementId`, dimensions copied from the source invoice lines (Customer/Item/Location, `journalLineDimension`).
+4. **Contract-asset reclass** (NetSuite deferred-revenue reclassification pattern): per arrangement, when cumulative recognized > cumulative billed (POC ahead of billing), append auto-reversing lines `Dr contractAssetAccount / Cr deferredRevenueAccount` for the excess, so 2160 never presents a debit balance and 1145 rolls forward per period.
+5. Stamp `journalId` on the rows; posting the journal through the existing `postJournalEntry` surface (which already carries the period gate, immutability triggers, and — when readiness MW-2 lands — the approval engine) flips rows to `Posted`. Voiding/deleting the Draft journal un-stamps.
+
+Corrections are reversal-only, inheriting the period-closing spec's rules (reversals date into the current open period).
+
+### Customer deposits
+
+`payment` (type `Receipt`) gains nullable `salesOrderId`. A posted receipt with `salesOrderId` and no invoice applications credits `prepaymentAccount` (2110) instead of AR — a true contract liability, per-order traceable. Applying the deposit to a posted invoice (`paymentApplication`) posts `Dr 2110 / Cr receivablesAccount`. Deposits are *not* revenue events — they never touch 2160 or schedules; they appear in the contract-liability rollforward as their own column. Unapplied ordinary receipts (no `salesOrderId`) keep today's AR-credit behavior; the rollforward footnotes them (v1 reports-only; auto-reclass deferred).
+
+### Contract modifications (ASC 606-10-25-12/13)
+
+Editing an approved arrangement's sales order (line added/removed, qty/price change) triggers `reallocateArrangement`:
+- **Prospective (separate-contract treatment):** a *new* line for a distinct good/service priced within `sspTolerancePercent` of its SSP becomes a new element with its own allocation; existing elements untouched.
+- **Cumulative catch-up:** everything else — re-run relative-SSP allocation over the updated transaction price; posted schedule rows are immutable; unposted rows regenerate; the difference between the new required-cumulative and posted-to-date lands as catch-up lines in the next recognition run, in the current open period.
+- The system proposes the treatment from the rules above; an accountant with `update: accounting` can override before confirming; the choice + before/after allocation snapshot is audit-logged (`.ai/rules/audit-log-system.md`).
+
+### Reports (all read schedules + `journalLine`, tie to GL)
+
+1. **Deferred revenue waterfall** — opening 2160 balance per element/arrangement, then future-period columns from unposted Actual + Forecast rows. Answers "when does the balance sheet unwind."
+2. **Contract asset/liability rollforward** — per period, per arrangement: opening, + billings deferred, + deposits received, − revenue recognized, ± reclass, closing; split asset (1145) / liability (2160 + 2110); totals tie to the trial balance (auditors' first request — GAP-1).
+3. **Remaining performance obligations** — Σ unrecognized allocated amount per arrangement, bucketed by expected timing from Forecast rows (≤1yr / 1–2yr / >2yr) — the ASC 606-10-50-13 backlog disclosure, which for Carbon doubles as a financially-credible production backlog.
+
+### Close integration (registration, never a parallel mechanism)
+
+Per the period-closing spec §NetSuite-style close checklist: this feature **seeds a `periodCloseTaskDefinition`** — name "Recognize revenue for the period", `taskType: 'Auto'`, `autoCheckKey: 'unposted-revenue-schedules'`, `severity: 'Warning'`, `isSystem: true`, sorted after depreciation (task 4) — via migration for existing companies + `seed-company` for new ones. The evaluator joins `getPeriodCloseReadiness`: fails when Actual schedule rows with `scheduledDate ≤ period end` are unposted (companies with the flag off trivially pass). Warning severity means skip-with-reason is possible (matches depreciation's posture); the row records the sign-off in the close binder.
+
+### Interplay
+
+- **Tax:** transaction price and all deferral/recognition amounts are **net of tax** — the tax spec strips tax from the revenue credit; this spec consumes the same pre-tax base. No tax rows ever touch 2160.
+- **Period close & immutability:** recognition journals are *accounting*-source, period-gated, immutable once posted, reversal-only — all inherited, nothing re-implemented.
+- **IFRS 15:** converged with ASC 606 at this feature's altitude; residual differences (licensing nuances, contract-cost impairment reversal) become policy switches when GAP-5 multi-book lands — no schema here precludes them.
+- **Multi-book:** schedules and journals are book-agnostic v1; `journal.bookId` (readiness Phase 0) stamps them into `PRIMARY` automatically.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | Multi-tenancy (heuristic 1) | All four new tables: `companyId`, composite PK `("id","companyId")`, `id()` prefixes, audit columns; child FKs reference composites | House convention; tax-spec precedent |
+| 2 | Service shape (heuristic 2) | All service functions in **`accounting.service.ts`/`accounting.models.ts`**, `(client, ...)` → `{data, error}`, never throw | **Module ownership call: accounting, not sales.** The outputs are journals, control accounts, a close task, and financial reports — all accounting-owned; the tax spec set the precedent of accounting owning cross-cutting financial config while stamping sales documents. Sales/invoicing get only thin hooks (arrangement creation on release, deferral swap at posting). |
+| 3 | RLS (heuristic 3) | Four standard policies per table; SELECT `get_companies_with_employee_role()`, writes `get_companies_with_employee_permission('accounting_*')`; schedule/element writes flow through service-role posting paths but policies defined for completeness | Tax-ledger precedent |
+| 4 | Permissions (heuristic 4) | Arrangement/SSP/report routes `view/update: "accounting"`; arrangement creation + deferral run inside existing sales/invoicing document permissions; reallocation override `update: "accounting"` | Matches tax determination posture: config audited, document flow unblocked |
+| 5 | Forms (heuristic 5) | `ValidatedForm` + zod (`revenueArrangementValidator`, `standaloneSellingPriceValidator`, …) + route actions with `intent`; Drawer overlays for arrangement detail | House convention |
+| 6 | Module layout (heuristic 6) | No new module; `modules/accounting/ui/RevenueRecognition/`, routes `x+/accounting+/revenue-*`; hooks in `post-sales-invoice`, `post-payment`, order-release service | One service/models file per module |
+| 7 | Backward compatibility (heuristic 7) | Gated by `companySettings.revenueRecognitionEnabled` (default **false**): flag off ⇒ posting byte-identical to today; new columns nullable/defaulted; enum values additive; views untouched; enablement is prospective (open orders get arrangements only via an explicit backfill action, not automatically) | Frozen posting surfaces change only behind the flag |
+| 8 | Vocabulary & shape | NetSuite ARM (arrangement/element/plan/SSP), with the plan header collapsed into element + schedule until multi-book | Research: ARM is the system mid-market companies actually IPO on; collapsing the plan removes a join with zero information v1 |
+| 9 | Arrangement granularity | One arrangement per sales order; element per line | The SO is Carbon's contract document; multi-SO combination (ASC 606-10-25-9) deferred until demanded |
+| 10 | POC actuals source | GL WIP debit inflows by `documentId = jobId` (close-job's own query, debit-side only) | Single source of truth already trusted for variance relief; no parallel job-cost ledger to reconcile |
+| 11 | EAC source | `jobMaterial`/`jobOperation` estimate math via `getJobCostProgress` RPC, floored at actuals | Same numbers the Estimates-vs-Actuals UI shows planners; floor prevents >100% |
+| 12 | Deferral timing | Billing defers to 2160; recognition run releases; contract asset via auto-reversing reclass | NetSuite ARM pattern exactly; keeps 2160 credit-normal and 1145 roll-forwardable |
+| 13 | Deposits | `payment.salesOrderId` → post to existing 2110 `prepaymentAccount`; application relieves to AR | Reuses seeded account + AR/AP payment machinery (`20260630093809`); no new document type |
+| 14 | Control accounts | New `accountDefault.deferredRevenueAccount` (→2160) + `contractAssetAccount` (→ new 1145), seeded + backfilled, resolved by id | `.ai/lessons.md` control-account rule |
+| 15 | Recognition journal surface | Generate Draft JE, post via existing `postJournalEntry` | Inherits period gate, immutability, numbering, and future MW-2 approval for free — no parallel poster |
+
+## Data Model Changes
+
+One migration (`pnpm db:migrate:new revenue-recognition`), then `pnpm run generate:types`:
+
+```sql
+CREATE TYPE "revenueRecognitionMethod" AS ENUM ('Point in Time', 'Straight Line', 'Percent of Completion');
+CREATE TYPE "revenueArrangementStatus" AS ENUM ('Draft', 'Approved', 'Closed');
+CREATE TYPE "revenuePlanType" AS ENUM ('Forecast', 'Actual');
+CREATE TYPE "revenueScheduleStatus" AS ENUM ('Planned', 'Posted');
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Revenue Recognition';
+
+CREATE TABLE "revenueArrangement" (
+ "id" TEXT NOT NULL DEFAULT id('rvar'),
+ "companyId" TEXT NOT NULL,
+ "arrangementId" TEXT NOT NULL, -- readable, from sequence
+ "salesOrderId" TEXT NOT NULL,
+ "customerId" TEXT NOT NULL,
+ "status" "revenueArrangementStatus" NOT NULL DEFAULT 'Draft',
+ "currencyCode" TEXT NOT NULL,
+ "exchangeRate" NUMERIC(10,5) NOT NULL DEFAULT 1,
+ "transactionPrice" NUMERIC(16,5) NOT NULL DEFAULT 0, -- net of tax, document currency
+ "approvedBy" TEXT REFERENCES "user"("id"),
+ "approvedAt" TIMESTAMP WITH TIME ZONE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "revenueArrangement_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "revenueArrangement_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "revenueArrangement_salesOrder_key" UNIQUE ("companyId", "salesOrderId")
+);
+ALTER TABLE "revenueArrangement" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "revenueArrangement_SELECT" ON "revenueArrangement" FOR SELECT USING (
+ "companyId" = ANY (get_companies_with_employee_role())
+);
+CREATE POLICY "revenueArrangement_INSERT" ON "revenueArrangement" FOR INSERT WITH CHECK (
+ "companyId" = ANY (get_companies_with_employee_permission('accounting_create'))
+);
+CREATE POLICY "revenueArrangement_UPDATE" ON "revenueArrangement" FOR UPDATE USING (
+ "companyId" = ANY (get_companies_with_employee_permission('accounting_update'))
+);
+CREATE POLICY "revenueArrangement_DELETE" ON "revenueArrangement" FOR DELETE USING (
+ "companyId" = ANY (get_companies_with_employee_permission('accounting_delete'))
+);
+
+CREATE TABLE "revenueElement" (
+ "id" TEXT NOT NULL DEFAULT id('rvel'),
+ "companyId" TEXT NOT NULL,
+ "arrangementId" TEXT NOT NULL,
+ "salesOrderLineId" TEXT NOT NULL,
+ "itemId" TEXT,
+ "jobId" TEXT, -- POC linkage via job.salesOrderLineId
+ "recognitionMethod" "revenueRecognitionMethod" NOT NULL DEFAULT 'Point in Time',
+ "extendedPrice" NUMERIC(16,5) NOT NULL, -- stated, net of tax
+ "ssp" NUMERIC(16,5),
+ "sspSource" TEXT, -- 'Stated' | 'List Price' | 'Invoice Price' | 'Residual'
+ "allocatedAmount" NUMERIC(16,5),
+ "serviceStartDate" DATE,
+ "serviceEndDate" DATE,
+ "recognizedAmount" NUMERIC(16,5) NOT NULL DEFAULT 0, -- maintained on posting, base currency
+ "billedAmount" NUMERIC(16,5) NOT NULL DEFAULT 0,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "revenueElement_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "revenueElement_arrangement_fkey" FOREIGN KEY ("arrangementId", "companyId")
+ REFERENCES "revenueArrangement"("id", "companyId") ON DELETE CASCADE,
+ CONSTRAINT "revenueElement_line_key" UNIQUE ("companyId", "salesOrderLineId")
+);
+-- + same four RLS policies (accounting_*)
+
+CREATE TABLE "itemStandaloneSellingPrice" (
+ "id" TEXT NOT NULL DEFAULT id('ssp'),
+ "companyId" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+ "currencyCode" TEXT NOT NULL,
+ "price" NUMERIC(16,5) NOT NULL,
+ "method" TEXT NOT NULL DEFAULT 'Stated', -- 'Stated' | 'List Price'
+ "effectiveDate" DATE NOT NULL DEFAULT CURRENT_DATE,
+ "expirationDate" DATE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "itemStandaloneSellingPrice_pkey" PRIMARY KEY ("id", "companyId")
+);
+-- + four RLS policies (accounting_*)
+
+CREATE TABLE "revenueRecognitionSchedule" (
+ "id" TEXT NOT NULL DEFAULT id('rvsc'),
+ "companyId" TEXT NOT NULL,
+ "elementId" TEXT NOT NULL,
+ "planType" "revenuePlanType" NOT NULL DEFAULT 'Forecast',
+ "status" "revenueScheduleStatus" NOT NULL DEFAULT 'Planned',
+ "scheduledDate" DATE NOT NULL,
+ "accountingPeriodId" TEXT REFERENCES "accountingPeriod"("id"),
+ "amount" NUMERIC(16,5) NOT NULL, -- base currency, historical rate
+ "isCatchUp" BOOLEAN NOT NULL DEFAULT false, -- POC/EAC drift or modification re-spread
+ "journalId" TEXT, -- stamped by the recognition run
+ "salesInvoiceId" TEXT, -- billing that funded this Actual row
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "revenueRecognitionSchedule_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "revenueRecognitionSchedule_element_fkey" FOREIGN KEY ("elementId", "companyId")
+ REFERENCES "revenueElement"("id", "companyId") ON DELETE CASCADE
+);
+CREATE INDEX "rvsc_due_idx" ON "revenueRecognitionSchedule"
+ ("companyId", "status", "planType", "scheduledDate");
+-- + four RLS policies (accounting_*)
+
+-- Column additions
+ALTER TABLE "item" ADD COLUMN "revenueRecognitionMethod" "revenueRecognitionMethod" NOT NULL DEFAULT 'Point in Time';
+ALTER TABLE "salesOrderLine" ADD COLUMN "serviceStartDate" DATE, ADD COLUMN "serviceEndDate" DATE;
+ALTER TABLE "payment" ADD COLUMN "salesOrderId" TEXT REFERENCES "salesOrder"("id") ON DELETE SET NULL;
+ALTER TABLE "companySettings"
+ ADD COLUMN "revenueRecognitionEnabled" BOOLEAN NOT NULL DEFAULT false,
+ ADD COLUMN "sspFallback" TEXT NOT NULL DEFAULT 'List Price',
+ ADD COLUMN "sspTolerancePercent" NUMERIC(5,4) NOT NULL DEFAULT 0.05;
+ALTER TABLE "accountDefault"
+ ADD COLUMN "deferredRevenueAccount" TEXT,
+ ADD COLUMN "contractAssetAccount" TEXT;
+
+-- Seeds/backfills: insert account 1145 'Contract Assets' per company (parent by
+-- "isGroup" = TRUE AND name, per lessons); backfill deferredRevenueAccount → account 2160
+-- and contractAssetAccount → 1145 by id; mirror both in seed.data.ts + seed-company.
+-- Seed periodCloseTaskDefinition ('Recognize revenue for the period', 'Auto',
+-- 'unposted-revenue-schedules', severity 'Warning', isSystem TRUE) per company + seed-company.
+-- Sequence row for arrangementId ('RA-%{yyyy}-') per company.
+```
+
+Notes: `revenueElement.recognizedAmount`/`billedAmount` are maintained denormalizations (updated in the same transaction as posting/stamping) so reports and RPO don't re-aggregate schedules on every render. No views select from the touched tables' changed columns (verify at implementation; DROP/recreate with `SELECT *` if any do).
+
+## API / Service Changes
+
+All in `apps/erp/app/modules/accounting/accounting.service.ts` + `accounting.models.ts`:
+
+```ts
+createRevenueArrangement(client, { companyId, salesOrderId, userId }) // idempotent; hook on order release
+allocateRevenueArrangement(client, { arrangementId, companyId, userId }) // SSP resolve + relative allocation + residual + range expedient
+approveRevenueArrangement(client, { arrangementId, companyId, userId }) // blocks on unresolvable SSP; auto for single-element
+reallocateArrangement(client, { arrangementId, companyId, userId, treatment?: "prospective" | "catchUp" })
+getJobCostProgress(client, { jobId, companyId }) // → { actualToDate, eac, pctComplete } (RPC-backed)
+generateRecognitionSchedules(client, { elementId, companyId }) // straight-line spread / PIT event row / POC forecast
+runRevenueRecognition(client, { companyId, accountingPeriodId, userId }) // → { data: draftJournalId } (steps in §Posting model)
+get/upsert/deleteStandaloneSellingPrice(...)
+getRevenueArrangements / getRevenueArrangement / getDeferredRevenueWaterfall /
+getContractBalanceRollforward / getRemainingPerformanceObligations(client, companyId, ...)
+```
+
+Callers/hooks to update:
+- **`post-sales-invoice`** (edge fn): line-level deferral swap (`salesAccount` → `deferredRevenueAccount`) when a `revenueElement` defers; converts Forecast → Actual schedule rows for the billed amount; bumps `billedAmount`. VOID reverses symmetrically.
+- **`post-shipment`**: marks the point-in-time recognition event for inventory elements (dates the Actual row).
+- **`post-payment`** (edge fn): deposit branch — `salesOrderId` set + no applications ⇒ credit `prepaymentAccount`; application posting relieves 2110 → AR.
+- **Order release / `convertQuoteToOrder` path** (sales service): `createRevenueArrangement` hook behind the flag.
+- **`close-job` / job completion**: emits the existing job-status change; the recognition run reads status — no new posting inside `close-job`.
+- **`getPeriodCloseReadiness`**: new evaluator `unposted-revenue-schedules`.
+
+Routes (new, `apps/erp/app/routes/x+/accounting+/`): `revenue-arrangements.tsx` (+ `$arrangementId.tsx` drawer with elements/allocation/schedules, actions `approve | reallocate`), `revenue-recognition.run.tsx` (period picker → generate Draft JE), `ssp.tsx` (SSP catalog CRUD), `revenue-reports.(waterfall|rollforward|rpo).tsx`. All `view/update: "accounting"`.
+
+## UI Changes
+
+- **Revenue Arrangements** table + drawer: status badge, transaction price, allocation table (stated vs SSP vs allocated, `sspSource` chip), per-element method/progress bars (billed vs recognized), POC elements show `pctComplete` with actual/EAC drill to the job.
+- **Recognition run** page: due-schedule preview grouped by arrangement (incl. catch-up rows flagged), "Generate journal" → links to the Draft JE for review/post.
+- **SSP catalog** settings page; **item form** gains the recognition-method select; **sales order line** form gains service dates (visible when method = Straight Line).
+- **Sales order** side panel: arrangement status card (accounting-linked, read-only for sales roles); **payment form** gains optional Sales Order (deposit) field.
+- **Reports**: three report pages per §Reports, CSV export via the standard table-export surface.
+- Flash messages on all transitions per `.ai/rules/flash-system.md`.
+
+## Acceptance Criteria
+
+- [ ] With `revenueRecognitionEnabled = false`, posting a sales invoice produces journal lines byte-identical to today (revenue to `salesAccount`); no arrangement rows are created.
+- [ ] Releasing a 3-line order (machine $80k SSP $90k, install $10k SSP $15k, 12-mo support $10k SSP $15k) creates one arrangement with 3 elements and allocates $75k/$12.5k/$12.5k (relative SSP, largest-remainder, Σ = $100k exactly).
+- [ ] An element without SSP takes the residual when it is the only one missing; two missing SSPs block approval with a named-item error.
+- [ ] Invoicing a Straight Line element (service 2026-07-15 → 2027-01-14) credits 2160, and schedules 7 rows with first/last prorated by days, summing exactly to the allocated amount.
+- [ ] A POC element whose job has $40k actual WIP debits against a $100k EAC recognizes 40% × allocated in the run; raising material actuals to $60k next period recognizes exactly the 20-point delta (cumulative catch-up, no restatement of the prior posted journal).
+- [ ] Completing the job (or `close-job`) forces the element to 100% in that period's run.
+- [ ] `runRevenueRecognition` creates one Draft journal (`sourceType 'Revenue Recognition'`) with `Dr 2160 / Cr 4010` lines carrying Customer/Item/Location dimensions; posting it flips schedule rows to `Posted`; running twice for the same period generates nothing the second time (idempotent via `journalId` stamps).
+- [ ] When recognized > billed on an arrangement, the run adds auto-reversing `Dr 1145 / Cr 2160` lines; the balance-sheet 2160 line never shows a debit balance.
+- [ ] With June **Locked**, the recognition journal posts (accounting source); with June **Closed**, posting fails with the period error.
+- [ ] A Receipt payment with `salesOrderId` and no applications credits 2110 (not AR); applying it to the order's posted invoice posts `Dr 2110 / Cr 1110` and the deposit disappears from the rollforward's deposit column.
+- [ ] Adding a new distinct line at SSP to an approved arrangement leaves existing allocations untouched (prospective); a 10% price cut on an existing line re-spreads with a catch-up row in the next run and writes an audit-log entry with before/after allocations.
+- [ ] The close checklist shows "Recognize revenue for the period" auto-failing while due unposted schedules exist and passing after the run's journal posts; a flag-off company sees it pass trivially.
+- [ ] Rollforward closing balances tie to the trial balance for 2160, 2110, and 1145 for a period with mixed activity; RPO buckets sum to Σ(allocated − recognized).
+- [ ] `pnpm run generate:types`, scoped `typecheck`, and `pnpm run lint` pass; migration applies idempotently twice.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| EAC garbage-in (jobs with $0 or stale estimates) → wild POC swings | High | `pctComplete` guards (EAC floored at actuals, capped 100%); run preview shows per-element deltas before journal generation; elements with EAC = 0 recognize nothing and surface a warning row |
+| Deferral swap in `post-sales-invoice` regresses non-rev-rec companies | High | Behavior strictly behind element existence + company flag; AC #1 pins byte-identical output; VOID path covered in tests |
+| WIP debit-inflow query double-counts reversal/void journals | Med | Exclude journals with `reversalOfId`/VOID descriptions from the actuals sum; AC test with a voided consumption |
+| Schedule/GL drift (journal posted but rows not flipped, or vice versa) | Med | Stamp + flip in one transaction keyed by `journalId`; rollforward report reconciles schedules vs 2160 and flags variances |
+| Modification re-spread on heavily-billed arrangements produces large catch-ups users don't expect | Med | Confirmation dialog shows the catch-up amount before accepting; audit log snapshot; treatment override |
+| FX: deferral frozen at invoice rate diverges from current-rate intuition | Low | Documented (nonmonetary liability, ASC 830-consistent); per-invoice `salesInvoiceId` on rows makes rate provenance traceable |
+
+## Open Questions
+
+> Resolutions recorded; two genuinely-new blocking questions at the end remain open.
+
+- [x] **Scope: reduced cut (deferral + deposits + POC, no SSP) vs full ASC 606 model?** — **Answer:** Brad, 2026-07-04: "the more complete plan" — full model including arrangements, performance obligations, and relative-SSP allocation with configurable determination + residual fallback. GAP-1's deferred-SSP note is superseded.
+- [x] **Is cost-to-cost POC in v1, and what drives it?** — **Answer:** Brad, 2026-07-04: full model incl. SSP allocation; POC ships v1 driven by existing job-costing actuals (GL WIP inflows by `documentId = jobId`) over `jobMaterial`/`jobOperation` EAC — Carbon's differentiator vs AI-GL startups (research §market timing).
+- [x] **Contract modifications in v1?** — **Answer:** Yes (full model) — prospective vs cumulative catch-up per ASC 606-10-25-12/13, system-proposed with accountant override; closed periods never restated.
+- [x] **Close-checklist integration mechanism** — **Answer:** Register a seeded `periodCloseTaskDefinition` with `autoCheckKey 'unposted-revenue-schedules'` — the period-closing spec's 2026-07-04 revision built the registration surface precisely so features like this never build a parallel mechanism.
+- [x] **Are recognized amounts gross or net of tax?** — **Answer:** Net — the multi-jurisdiction tax spec removes tax from the revenue credit; transaction price, allocation, deferral, and recognition all operate on the pre-tax base.
+- [x] **IFRS 15 divergences now?** — **Answer:** Policy switches later; ASC 606/IFRS 15 are converged at this altitude, and per readiness GAP-5 phasing, book-level divergences wait for multi-book (adjustment books).
+- [x] **Deposit modeling: new document type vs payment extension?** — **Answer:** Extend `payment` with `salesOrderId` and post to the existing seeded 2110 `prepaymentAccount` — reuses the week-old AR/AP payment machinery; no new document.
+
+- [x] **OQ-N1 (blocking): POC cost matching — does v1 also move COGS timing?** Recognizing POC *revenue* monthly while COGS still posts at shipment (today's `post-shipment`/MTO flow) misstates in-period margin: months with recognition but no shipment show 100% margin, the shipment month shows a cost cliff. Proper ASC 606 over-time treatment expenses costs as incurred (`Dr COGS / Cr WIP` for the period's incurred cost in the same recognition run, with shipment/`close-job` skipping COGS for POC elements to avoid double-posting) — but that changes the WIP/inventory flow, which is GAP-3 (inventory valuation) territory and production-critical schema behavior. **Recommendation:** ship COGS-as-incurred for POC elements in v1 (auditors will not accept the mismatch), coordinated with the GAP-3 spec. Needs Brad's call before implementation. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Yes — v1 moves COGS to as-incurred for POC elements (Dr COGS / Cr WIP inside the recognition run; shipment skips COGS for POC elements). Coordinate with the inventory-valuation workstream (#1040).
+- [x] **OQ-N2 (blocking): revenue timing vs invoice for point-in-time inventory elements.** When shipment (control transfer) and invoicing land in *different* periods, v1 as specified defers at invoice and releases at the shipment-dated event — but if shipment precedes the invoice (ship June, invoice July), recognizing in June requires accruing unbilled revenue (`Dr 1145 / Cr 4010`) *before any invoice exists*, i.e. recognition entirely decoupled from billing for ordinary goods. **Recommendation:** v1 recognizes at the *later* of shipment/invoice for point-in-time elements (conservative, zero unbilled-accrual machinery for the common flow; the contract-asset reclass already covers POC); full ship-then-bill accrual in v1.1. Confirm the simplification is acceptable for the first release. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Ambitious — recognize at shipment (control transfer) with unbilled-receivable/contract-asset accrual machinery in v1. Back out to later-of-shipment-and-invoice at plan stage.
+
+## Changelog
+
+- 2026-07-04: Created — full ASC 606 model per Brad's 2026-07-04 scope resolution ("the more complete plan", incl. SSP allocation). Grounded in codebase exploration (post-sales-invoice revenue posting, dead 2160 seed, accountDefault/prepayment plumbing, job WIP-by-documentId costing, close-job, jobMaterial/jobOperation estimates, AR/AP payment tables) and `.ai/research/public-company-compliance.md` (NetSuite ARM vocabulary and reclass pattern). Registers into the period-closing spec's checklist substrate. Two new blocking questions (POC COGS timing; ship-before-bill recognition) recorded unchecked.
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/2026-07-04-segment-reporting.md b/.ai/specs/2026-07-04-segment-reporting.md
new file mode 100644
index 0000000000..f85717bd2b
--- /dev/null
+++ b/.ai/specs/2026-07-04-segment-reporting.md
@@ -0,0 +1,350 @@
+# Segment Reporting (ASC 280 / ASU 2023-07) + Dimension Enforcement
+
+> Status: in-progress
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1049
+> Readiness finding: GAP-7 (`.ai/specs/2026-07-03-public-company-readiness.md`)
+> Research: `.ai/research/public-company-compliance.md` (SAP §S/4HANA; ASU 2023-07)
+
+## TLDR
+
+A reserved, system-managed **Segment** dimension that every posting derives
+automatically — users never key segments (the SAP rule: segment derived from
+profit-center master data). Segments are defined once per company group as
+values under a seeded `Segment` dimension; at posting time each journal line
+resolves its segment through a fixed precedence chain — cost center's segment
+attribute (walking up `parentCostCenterId`) → item posting group's segment
+attribute → document-type default → company default — implemented in one SQL
+function and enforced by a deferred DB trigger, so **every** posting path
+(nine edge functions, `accounting.server.ts` Kysely transactions, plpgsql
+posting functions, manual JEs) is covered identically. The same trigger
+finally enforces `dimension.required` server-side (today a stored flag the
+server never reads): posting with a missing required dimension fails with an
+error naming the dimension. Reporting extends the financial-reporting spec's
+surfaces: segment filter + per-segment columns on TB/BS/IS, a segment column
++ filter on GL detail, and a new **Segment Disclosure** report (ASU 2023-07):
+revenue, significant expense categories (from the existing expense
+account-tree headings), other segment items, and segment profit per segment,
+with an **Unassigned / Eliminations** reconciliation column so segment totals
+tie to consolidated totals by construction. History is never rewritten —
+pre-segment lines report as Unassigned. SAP document splitting /
+zero-balancing is explicitly out of scope v1: segment balance sheets are
+best-effort from natural postings.
+
+## Problem Statement
+
+- **No segment concept.** ASC 280 (as amended by ASU 2023-07, effective for
+ all public filers *including single-segment filers*) requires reportable
+ segments with segment profit/loss, significant expense categories regularly
+ provided to the CODM, and reconciliation to consolidated totals. Carbon has
+ dimensions (`20260228024512_dimensions.sql`) but nothing plays the segment
+ role, and no report groups by any dimension.
+- **`dimension.required` is decorative.** The flag exists on the table and in
+ UI types but no posting path reads it. Nine edge functions
+ (`post-purchase-invoice`, `post-sales-invoice`, `post-payment`,
+ `post-receipt`, `post-shipment`, `post-memo`, `post-production-event`,
+ `close-job`, `issue`), the Kysely paths in
+ `apps/erp/app/modules/accounting/accounting.server.ts`, the plpgsql posting
+ functions (`backflush_job_materials`, `complete_job_to_inventory` —
+ `20260630092517_job-costing-item-dimension.sql`), and manual JE posting all
+ insert `journalLineDimension` rows opportunistically ("if the dimension
+ exists, tag it"); none fails when a required dimension is absent. An
+ auditor testing dimension completeness finds a paper control.
+- **If users key segments, segments are wrong.** SAP's hard-won lesson: keyed
+ segment fields drift immediately; derivation from master data is the only
+ pattern that yields a complete, consistent segment population. Carbon's
+ posting paths already stamp CostCenter / ItemPostingGroup dimensions on
+ lines, so derivation's inputs are already on every line at commit time.
+
+## Proposed Solution
+
+### 1. Reserved Segment dimension + segment master data
+
+- `ALTER TYPE "dimensionEntityType" ADD VALUE 'Segment'` (own migration —
+ enum values cannot be used in the transaction that adds them).
+- Seed one system dimension per company group: `name = 'Segment'`,
+ `entityType = 'Segment'`, `required = false` (flips on first configuration,
+ §2). Segment values are plain `dimensionValue` rows under it — **no new
+ segment table**; `dimensionValue` is already group-scoped with RLS and
+ `journalLineDimension.valueId` already points at `dimensionValue.id` for
+ non-entity dimensions. The `dimensionValues` view's `entityType = 'Custom'`
+ filter widens to `IN ('Custom', 'Segment')`.
+- Reserved semantics, service-enforced: it cannot be renamed, deleted, or
+ deactivated, and is hidden from the manual-JE selector — derivation owns it.
+- **Segment attributes as columns** (no mapping tables):
+ - `costCenter."segmentId"` — nullable FK to `dimensionValue`. Effective
+ segment = own value, else nearest ancestor's via `parentCostCenterId`
+ (hierarchy already exists, `20260317233050_cost-centers.sql`).
+ - `itemPostingGroup."segmentId"` — nullable FK to `dimensionValue`.
+ - `accountDefault."defaultSegmentId"` — nullable FK; `accountDefault` is
+ the existing one-row-per-company posting-defaults table
+ (`20230820020844_posting-groups.sql`), the natural home for the
+ company-level fallback.
+- Document-type defaults need a map (source type → segment), which cannot be
+ a column: one small table `documentSegmentDefault` — see Data Model.
+
+### 2. Derivation + server-side required-dimension enforcement
+
+One SQL function, one trigger pair — DB-level so every path is bound, per the
+readiness audit's Decision 1 precedent (`20260702044133_period-close-lifecycle.sql`).
+
+- **`resolve_segment(p_company_id, p_cost_center_id, p_item_posting_group_id,
+ p_source_type)`** — the precedence chain: cost center's effective segment
+ (recursive CTE up `parentCostCenterId`) → `itemPostingGroup."segmentId"` →
+ `documentSegmentDefault` for the source type →
+ `accountDefault."defaultSegmentId"` → NULL.
+- **Deferred constraint trigger on `journalLine`** (`AFTER INSERT …
+ DEFERRABLE INITIALLY DEFERRED`), firing at transaction commit — by which
+ point the posting path has written the line's CostCenter /
+ ItemPostingGroup `journalLineDimension` rows (system posters write
+ journal → lines → dimensions inside one transaction: Kysely
+ `db.transaction()` in the edge functions and `accounting.server.ts`; one
+ plpgsql call for the job-costing functions). Skips lines whose journal is
+ `Draft`. For `Posted` journals it:
+ 1. **Derives Segment** — if the group has ≥1 segment value and the line has
+ no Segment row: read the line's CostCenter / ItemPostingGroup dimension
+ values from `journalLineDimension`, call `resolve_segment` with them +
+ `journal."sourceType"`, insert the Segment `journalLineDimension` row.
+ NULL result ⇒ `RAISE EXCEPTION` ("No segment could be derived for line
+ %; set a company default segment in Account Defaults").
+ 2. **Enforces `required`** — for every `active AND required` dimension in
+ the company group, assert a `journalLineDimension` row exists for the
+ line; else `RAISE EXCEPTION` naming the missing dimension(s) and the
+ `journalLineReference`.
+- **Trigger on `journal` status transition to `Posted`** runs the same two
+ checks across all of the journal's lines — covers manual JEs, whose lines
+ and dimensions are written in earlier `Draft` transactions with posting as
+ a later status flip.
+- **Segment becomes required-by-default once configured**: creating the first
+ segment value flips the Segment dimension's `required` to `true`
+ (service-side, with a UI notice); the admin may untoggle. Independent of
+ that flag, derivation runs whenever any segment values exist — `required`
+ only governs whether a NULL derivation errors or lands unassigned.
+- Client-side validation stays as UX; the DB is the control.
+
+### 3. Segment reporting (extends `.ai/specs/2026-07-02-financial-reporting.md`)
+
+- **Balance RPCs**: `accountTreeBalancesByCompany` and `trialBalance` gain
+ `p_segment_value_id TEXT DEFAULT NULL` and `p_segment_unassigned BOOLEAN
+ DEFAULT FALSE` (fork the newest definitions, additive — same convention the
+ financial-reporting spec used for `p_include_drafts`). Filtered mode joins
+ `journalLineDimension` on the group's Segment dimension; unassigned mode
+ anti-joins. Exactly one of total / one-segment / unassigned per call, so
+ Total = Σ segments + Unassigned by construction.
+- **Statement screens** (TB / BS / IS): `ReportFilters` gains a Segment
+ select — a single segment filters the report; **"By segment"** renders one
+ column per segment plus an **Unassigned / Eliminations** reconciliation
+ column and the existing Total. Loader = one balance call per column zipped
+ by account id — the N-call-zip mechanism the financial-reporting spec built
+ for comparatives (§5 there); ASC 280 segment counts are small (2–10).
+ Elimination-entity journals carry no cost center / posting group, so they
+ derive the company default or land in Unassigned — either way the
+ reconciliation column absorbs them and columns tie.
+- **GL detail** (`getGeneralLedgerLines`): Segment display column and filter
+ (join through `journalLineDimension`), incl. `segment=unassigned`;
+ statement segment-column amounts drill to GL detail pre-filtered to
+ account + window + segment. CSV export inherits via the shared `Table`.
+- **Segment Disclosure report** (new route, the ASU 2023-07 artifact): rows =
+ Revenue, one row per top-level expense heading of the account tree (the
+ significant expense categories the CODM sees — no new category entity),
+ Other segment items (plug), Segment profit (ties to the income statement
+ bottom line per column); columns = each segment,
+ Unassigned/Eliminations, consolidated Total. Works single-company and
+ consolidated (translated balances, same as the other statements); CSV.
+- **Segment balance sheet is best-effort** and labeled as such in the UI:
+ without document splitting, cash, AR/AP settlement, tax, and equity lines
+ do not fully allocate; the Unassigned column absorbs the remainder and
+ each row still ties to the consolidated total. Honest > fake.
+
+### 4. Backfill posture
+
+None. Historical `journalLine` rows without a Segment row report as
+Unassigned forever; `journalLineDimension` is append-only and posted journals
+are immutable — we do not rewrite history. The Unassigned column is the
+honest representation of pre-segment data.
+
+### Out of scope (v1)
+
+- **SAP document splitting / zero-balancing per segment** — inheriting the
+ segment onto offsetting lines (cash, AR/AP) and posting zero-balancing
+ clearing lines so each segment's balance sheet balances independently. A
+ full sub-ledger rework; explicitly deferred. Consequence stated in §3.
+- A dedicated Eliminations segment value / segment-aware IC eliminations.
+- Segment budgeting (budgeting spec owns budget columns), segment PDF pages,
+ ASU 2023-07 interim-disclosure checklists, and generalizing per-segment
+ columns to arbitrary dimensions (the join is by dimension id, so a future
+ "by any dimension" mode reuses the shape).
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Segment storage | `dimensionValue` rows under a seeded, reserved `entityType='Segment'` dimension — no new table | Machinery (group scoping, RLS, `journalLineDimension.valueId`, UI selectors) already exists; a `segment` table would duplicate all of it |
+| Who keys segments | Nobody — derivation only, selector hidden | SAP rule (research §S/4HANA): keyed segments drift; derivation from master data gives a complete population |
+| Derivation precedence | costCenter (hierarchical) → itemPostingGroup → documentSegmentDefault → accountDefault.defaultSegmentId | Resolved by Brad 2026-07-04 (ambitious/full derivation). Cost center is the org-structure signal (SAP profit-center analog); posting group covers product-line segmentation; defaults guarantee termination |
+| Enforcement point | Deferred constraint trigger on `journalLine` + status-transition trigger on `journal`, both SECURITY DEFINER | Only DB-level covers all nine edge functions, Kysely paths, plpgsql posters, and PostgREST at once; commit-time deferral is when dimension rows exist; readiness Decision 1 precedent |
+| `required` semantics | Enforced at Posted only (Draft exempt); error names dimension + line | Drafts are workpads; posting is the control gate (matches period-close and posted-immutability gates) |
+| Segment auto-required | First segment value flips `required=true` (notice shown, admin may untoggle) | "Required once configured" without a special case in the trigger — Segment goes through the same required check as every dimension |
+| Reporting mechanism | Additive RPC params (`p_segment_value_id` / `p_segment_unassigned`) + N-call zip in loaders | Same additive-fork and column-zip conventions the financial-reporting spec established; Total = Σ segments + Unassigned by construction |
+| Expense categories (ASU 2023-07) | Top-level expense headings of the existing account tree | The tree already encodes the groupings statements render; a parallel category entity would drift from it |
+| Multi-tenancy (heuristic 1) | Segment values group-scoped (`dimensionValue.companyGroupId` — chart-of-accounts pattern); attributes on company-scoped tables (`costCenter`, `itemPostingGroup`, `accountDefault`); `documentSegmentDefault` composite-PK `("id","companyId")` | Segments must be shared across a group for consolidated segment reporting; assignment is per company |
+| Service shape (heuristic 2) | `getSegments`, `upsertSegment`, `deactivateSegment`, `getDocumentSegmentDefaults`, `upsertDocumentSegmentDefault`, `getSegmentDisclosure` in `accounting.service.ts`; costCenter/itemPostingGroup services gain the column | One `{module}.service.ts`; no new files beyond routes/UI |
+| RLS (heuristic 3) | `documentSegmentDefault`: four policies, SELECT `get_companies_with_employee_role()`, writes `get_companies_with_employee_permission('accounting_*')`; everything else inherits existing policies | Standard company-scoped template; dimension/dimensionValue policies already correct |
+| Permissions (heuristic 4) | Segment config = `update: "accounting"`; reports = `view: "accounting"` + `role: "employee"` (matches `balance-sheet.tsx`) | Segment master data is accounting configuration |
+| Forms (heuristic 5) | Segment select added to existing costCenter / itemPostingGroup / account-defaults `ValidatedForm`s; new small forms for segment values + doc-type defaults | Extend existing forms before creating new ones |
+| Module layout (heuristic 6) | Everything in `apps/erp/app/modules/accounting/` + `routes/x+/accounting+/`; report UI under `ui/Reports/` | Segments are an accounting concept even though attributes live on items/production entities |
+| Backward compatibility (heuristic 7) | RPCs extended additively; new columns nullable; trigger inert until segment values exist and no dimension is `required`; existing posters unmodified (derivation reads what they already write) | Zero behavior change for unconfigured companies — the entire feature is opt-in by configuring it |
+
+## Data Model Changes
+
+Two migrations (`pnpm db:migrate:new …`, randomized HHMMSS), then
+`pnpm run generate:types`. Migration 1 (enum only):
+
+```sql
+ALTER TYPE "dimensionEntityType" ADD VALUE IF NOT EXISTS 'Segment';
+```
+
+Migration 2 (everything else):
+
+```sql
+-- Seed the reserved Segment dimension per company group (idempotent);
+-- seed-company edge function gains the same row for new groups
+INSERT INTO "dimension" ("name", "entityType", "companyGroupId", "createdBy")
+SELECT 'Segment', 'Segment', cg."id", 'system' FROM "companyGroup" cg
+ON CONFLICT ("name", "companyGroupId") DO NOTHING;
+
+-- Segment attributes: columns, not tables
+ALTER TABLE "costCenter" ADD COLUMN IF NOT EXISTS "segmentId" TEXT
+ REFERENCES "dimensionValue"("id") ON DELETE SET NULL;
+ALTER TABLE "itemPostingGroup" ADD COLUMN IF NOT EXISTS "segmentId" TEXT
+ REFERENCES "dimensionValue"("id") ON DELETE SET NULL;
+ALTER TABLE "accountDefault" ADD COLUMN IF NOT EXISTS "defaultSegmentId" TEXT
+ REFERENCES "dimensionValue"("id") ON DELETE SET NULL;
+
+-- Document-type fallback (a map, so a table; company-scoped template)
+CREATE TABLE IF NOT EXISTS "documentSegmentDefault" (
+ "id" TEXT NOT NULL DEFAULT id('dsd'),
+ "companyId" TEXT NOT NULL,
+ "sourceType" "journalEntrySourceType" NOT NULL,
+ "segmentId" TEXT NOT NULL REFERENCES "dimensionValue"("id") ON DELETE CASCADE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "documentSegmentDefault_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "documentSegmentDefault_companyId_sourceType_key"
+ UNIQUE ("companyId", "sourceType"),
+ CONSTRAINT "documentSegmentDefault_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+ALTER TABLE "documentSegmentDefault" ENABLE ROW LEVEL SECURITY;
+-- Policies SELECT/INSERT/UPDATE/DELETE: SELECT via
+-- get_companies_with_employee_role(); writes via
+-- get_companies_with_employee_permission('accounting_<action>'); ::text[] casts
+
+-- resolve_segment(p_company_id, p_cost_center_id, p_item_posting_group_id,
+-- p_source_type) RETURNS TEXT — STABLE, SECURITY DEFINER, search_path=public:
+-- recursive CTE up costCenter.parentCostCenterId for the first non-null
+-- segmentId → itemPostingGroup → documentSegmentDefault → accountDefault → NULL
+
+-- enforce_line_dimensions(): derive Segment (§2.1) then assert required
+-- dimensions (§2.2); SECURITY DEFINER.
+CREATE CONSTRAINT TRIGGER "journalLine_dimension_enforcement"
+ AFTER INSERT ON "journalLine"
+ DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION enforce_line_dimensions();
+CREATE TRIGGER "journal_post_dimension_enforcement"
+ AFTER UPDATE OF "status" ON "journal"
+ FOR EACH ROW WHEN (NEW."status" = 'Posted' AND OLD."status" = 'Draft')
+ EXECUTE FUNCTION enforce_journal_dimensions();
+
+-- Widen the custom-values view to include Segment
+CREATE OR REPLACE VIEW "dimensionValues" WITH(SECURITY_INVOKER=true) AS
+ SELECT … WHERE d."entityType" IN ('Custom', 'Segment');
+
+-- Fork newest trialBalance + accountTreeBalancesByCompany definitions
+-- (post-financial-reporting versions) adding:
+-- p_segment_value_id TEXT DEFAULT NULL, p_segment_unassigned BOOLEAN DEFAULT FALSE
+-- Join/anti-join journalLineDimension jld ON jld."journalLineId" = jl."id"
+-- AND jld."dimensionId" = (group's Segment dimension id)
+-- Partial index to serve it:
+CREATE INDEX IF NOT EXISTS "journalLineDimension_dimensionId_valueId_idx"
+ ON "journalLineDimension" ("dimensionId", "valueId", "journalLineId");
+```
+
+## API / Service Changes
+
+`apps/erp/app/modules/accounting/accounting.service.ts` (+ zod in
+`accounting.models.ts`): `getSegments`, `upsertSegment` (flips
+`dimension.required` on first value), `getDocumentSegmentDefaults` /
+`upsertDocumentSegmentDefault`, `getSegmentDisclosure(client, companyGroupId,
+companyIds, { startDate, endDate })` (per-segment IS balances folded into
+revenue / expense-heading / profit rows), and `p_segment_*` pass-throughs on
+`getTrialBalance` / `getFinancialStatementBalances` /
+`getGeneralLedgerLines`. Existing `costCenter` / `itemPostingGroup` upserts
+gain `segmentId`; `accountDefault` upsert gains `defaultSegmentId`.
+Reserved-dimension guard in `updateDimension` / `deleteDimension`.
+
+Routes (`routes/x+/accounting+/`): `settings.segments.tsx` (one settings
+screen: values, doc-type defaults, company default); `segment-disclosure.tsx`;
+TB / BS / IS / GL loaders accept `segment` / `bySegment` search params.
+`path.to` additions: `segments`, `segmentDisclosure`. Edge functions are
+**unchanged** — derivation and enforcement live in the database.
+
+## UI Changes
+
+- **`Reports/ReportFilters.tsx`**: Segment select (All / each segment /
+ Unassigned) + "By segment" columns toggle on TB/BS/IS.
+- **`Reports/FinancialStatementTree.tsx` / `TrialBalanceTable.tsx`**:
+ per-segment columns + Unassigned/Eliminations + Total when `bySegment`;
+ best-effort banner on the segmented balance sheet (§3).
+- **`Reports/SegmentDisclosure.tsx`**: the ASU 2023-07 grid; CSV export.
+- **`GeneralLedger/GeneralLedgerTable.tsx`**: Segment column + filter.
+- **Settings — Segments screen**: value list, doc-type default rows, company
+ default select; notice when the first value flips Segment to required.
+- **Cost center / item posting group / account defaults forms**: Segment
+ select added to the existing `ValidatedForm`s.
+- **`JournalEntries/DimensionSelector.tsx`**: hides the Segment dimension;
+ posting-failure toasts surface the trigger's missing-dimension message.
+
+## Acceptance Criteria
+
+- [ ] With segments A and B configured, a cost center under a parent whose `segmentId = A`, and a purchase invoice posted against that cost center: every journal line of the posting carries a Segment `journalLineDimension` row with value A (hierarchy walk proven), with **no changes to the edge function**.
+- [ ] A posting with no cost-center segment but an item posting group assigned to B derives B; with neither, a `documentSegmentDefault` for the source type wins; with none of the three, `accountDefault."defaultSegmentId"` wins — precedence proven by four postings.
+- [ ] With segments configured but no company default and no other rule matching, posting fails with an error naming the line and pointing at Account Defaults; nothing is committed (the whole posting transaction rolls back).
+- [ ] With a custom dimension marked `required`, posting a journal (via edge function AND via manual JE draft→post) whose lines lack that dimension fails naming the dimension; adding the dimension row lets the same posting succeed. Draft journals save freely either way.
+- [ ] With no segment values and no required dimensions, all posting paths behave byte-for-byte as today (trigger inert) — regression run on the demo dataset.
+- [ ] Creating the first segment value flips the Segment dimension to `required = true` and the settings screen says so; untoggling it makes unresolvable postings fall through to Unassigned instead of erroring.
+- [ ] The Segment dimension cannot be renamed, deleted, or deactivated via the dimension UI/service, and never appears in the manual-JE dimension selector.
+- [ ] Income statement "By segment": columns for each segment + Unassigned/Eliminations + Total, where each row's segment cells sum to its Total cell exactly; historical (pre-segment) activity appears in Unassigned; single-segment filter matches that segment's column.
+- [ ] Segmented balance sheet renders with the best-effort banner; every row ties across columns; unallocated cash/AR/AP sits in Unassigned.
+- [ ] GL detail filtered to account + window + segment sums to the corresponding statement cell; `segment=unassigned` returns exactly the lines with no Segment row; CSV matches the visible rows.
+- [ ] Segment Disclosure report: per segment — revenue, one row per top-level expense heading, other segment items, segment profit; Total column equals the consolidated income statement for the same window (single-company and consolidated/translated modes).
+- [ ] Four-column trial balance with a segment filter still foots (total debits = credits); `pnpm run generate:types`, scoped typechecks (`--filter=@carbon/erp`, `--filter=@carbon/database`), and `pnpm run lint` pass; both migrations apply idempotently twice.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| A posting path writes lines and dimensions in **separate transactions** (like manual JEs) while status = Posted → deferred trigger fires before dimensions exist → false failures | Med | Audit at implementation: all nine edge functions + `accounting.server.ts` use single transactions today; the status-transition trigger is the sanctioned two-phase path; add a lesson + test per poster |
+| Deferred per-row trigger cost on large postings (backflush with many lines) | Low | Checks are index-served lookups per line (new partial index); posting sizes are tens of lines; measure on `close-job` in staging |
+| Trigger exception text lost/blurred through PostgREST → unclear user error | Med | Use `ERRCODE` + stable message prefix; edge functions and services map it to a flash message; acceptance criterion covers the toast |
+| Segment join slows balance RPCs on large ledgers when segment params are NULL | Low | Join only added inside the branch where a segment param is set; unfiltered plans unchanged |
+| Concurrent redefinition of the same RPCs as financial-reporting spec | Med | This spec forks the **post-financial-reporting** definitions (per `.ai/lessons.md` fork-newest rule); sequencing noted in the meta spec `2026-07-04-accounting-implementation-meta.md` |
+| Companies segment by geography, not cost center / product line | Low | Assign segments to per-location cost centers; a `location.segmentId` attribute is a cheap follow-up if demanded |
+
+## Open Questions
+
+> All questions resolved 2026-07-04 with Brad: **ambitious scope — full
+> derivation**, not cost-center-only.
+
+- [x] **Scope: cost-center-only vs full derivation?** — **Answer (Brad 2026-07-04):** Ambitious. Full precedence chain (cost center → item posting group → document-type default → company default), server-side required-dimension enforcement for all posting paths, and the full reporting surface incl. ASU 2023-07 disclosure, in v1.
+- [x] **Segment storage** — **Answer:** `dimensionValue` rows under a reserved seeded dimension; no new segment table (machinery reuse; see Design Decisions).
+- [x] **Enforcement mechanism** — **Answer:** DB triggers (deferred constraint trigger + status-transition trigger), not per-path TS checks — only the DB covers all nine edge functions, Kysely paths, and plpgsql posters uniformly.
+- [x] **Document splitting / zero-balancing** — **Answer:** Out of scope v1; segment balance sheets best-effort with an explicit UI banner and the Unassigned reconciliation column (limitation stated honestly).
+- [x] **Backfill** — **Answer:** None. Historical lines report as Unassigned; posted journals and `journalLineDimension` stay immutable.
+
+## Changelog
+
+- 2026-07-04: Created — readiness finding GAP-7 (ASC 280 / ASU 2023-07); grounded in the dimension machinery (`20260228024512_dimensions.sql` + enum extensions), the nine dimension-writing edge functions, `accounting.server.ts` Kysely paths, plpgsql posters (`20260630092517`), `costCenter` (`20260317233050`), `itemPostingGroup` (`20230330024716`), `accountDefault` (`20230820020844`), `journal.sourceType`/`status` (`20260402000000`), and the SAP segment-derived-from-master-data pattern (research §S/4HANA). Extends the financial-reporting spec's surfaces and RPC-fork conventions. Scope resolved ambitious/full-derivation by Brad 2026-07-04.
diff --git a/.ai/specs/2026-07-04-withholding-ecsl-intrastat-mtd.md b/.ai/specs/2026-07-04-withholding-ecsl-intrastat-mtd.md
new file mode 100644
index 0000000000..7adfad42f5
--- /dev/null
+++ b/.ai/specs/2026-07-04-withholding-ecsl-intrastat-mtd.md
@@ -0,0 +1,256 @@
+# Withholding Tax, EC Sales List, Intrastat, and UK MTD VAT Submission
+
+> Status: in-progress
+> Author: Claude (readiness program GAP-D1 remainder), for [email protected]
+> Date: 2026-07-04
+> Tracking issue: crbnos/carbon#1055
+> Parent finding: `.ai/specs/2026-07-03-public-company-readiness.md` §GAP-D1
+> Builds on: `.ai/specs/2026-07-03-multi-jurisdiction-tax.md` (tax codes/components/authorities/registrations, `taxLedger`, `taxReturn` + layouts + settlement — this spec EXTENDS that machinery, never parallels it)
+> Research: `.ai/research/public-company-compliance.md` (§7 tax engine, §regulatory VAT/trade reporting, MTD reference)
+
+## TLDR
+
+The tax spec delivers determination, the tax subledger, returns with settlement, and a seeded UK 9-box layout. Four statutory obligations remain for Carbon's EU/UK/US footprint, and all four are built as extensions of that machinery. (1) **AP withholding tax**: WHT codes ride `taxCode` (`calculationType = 'Withholding'`, income type, authority component) with treaty-rate overrides gated on tracked supplier residency certificates; purchase-invoice posting adds Dr AP / Cr WHT liability for the withheld portion (supplier payable becomes net), writes `taxLedger` rows with the new `'Withholding'` source, and WHT returns + supplier certificates extract per authority through the existing `taxReturn` settlement/remittance path. (2) **EC Sales List**: a `tradeDeclaration` document extracts intra-EU B2B supplies (customer VAT number, country, value, indicator code from the tax code) from `taxLedger` + invoice location data, per registration per period, exported as HMRC CSV and generic XML. (3) **Intrastat**: arrivals/dispatches declarations built from posted receipts/shipments using new item trade fields (CN8 commodity code, net mass, supplementary units, country of origin) and nature-of-transaction codes, gated by per-country threshold config with rolling-12-month warnings. (4) **UK MTD VAT**: an HMRC connector in `packages/ee` (OAuth, obligations/returns/liabilities endpoints, fraud-prevention headers) submits the UK layout's 9 boxes straight from the finalized `taxReturn` — an unbroken digital link with no rekeying — sandbox-tested before production. Delivery order follows live customer need: MTD first (UK entities file quarterly today), ECSL/Intrastat second (intra-EU trade is live), WHT third — unless a customer's cross-border payments carry live withholding obligations, in which case WHT jumps the queue; all four are fully spec'd here.
+
+## Problem Statement
+
+Customers operate across Europe and the US (geography resolved in the readiness spec). With the tax spec implemented, a UK or EU entity can compute its VAT return boxes — but cannot legally file or trade-report:
+
+- **UK**: HMRC's Making Tax Digital mandates API submission of the 9-box return with *unbroken digital links* — retyping Carbon's numbers into a bridging spreadsheet breaks the legal chain. The tax spec produces the boxes; nothing submits them.
+- **Intra-EU B2B supplies** must be declared on an EC Sales List (customer VAT number, member state, value, indicator code) per registration per period. `taxLedger` has the values and `customerTax.vatNumber`/EORI exist (`20260430000001_tax-status.sql`, `20260429001730_eori.sql`), but no extract exists.
+- **Intrastat**: entities crossing per-country arrival/dispatch thresholds must declare physical goods movements with CN8 commodity codes, net mass, supplementary units, country of origin/destination, and nature of transaction. Carbon's `item`, `shipmentLine`, and `receiptLine` carry **none** of these fields (verified: no commodity/weight/origin columns in any migration), so the data cannot even be captured.
+- **Withholding tax**: cross-border AP (royalties, technical services, interest) requires withholding at source at domestic or treaty rates, remitting to the authority, and issuing certificates to suppliers. Carbon's AP posts gross with no withholding concept; treaty rates are only valid while a supplier's residency certificate is — nothing tracks validity.
+
+## Proposed Solution
+
+### 1. AP withholding tax — new calculation type on the existing tax machinery
+
+- **WHT codes are `taxCode` rows**: `taxCalculationType` gains `'Withholding'` (additive enum). A WHT code carries a new `incomeType` (`Services` | `Royalties` | `Interest` | `Dividends` | `Rent` | `Other`) and 1..n `taxCodeComponent` rows (authority + domestic rate + effective dates + liability account with `accountDefault."withholdingTaxPayableAccount"` fallback) — reusing rate-change, authority, and account-fallback machinery wholesale.
+- **Assignment**: `supplierTax.withholdingTaxCodeId` (the supplier tax table is the natural home). At purchase-invoice creation, the supplier's WHT code defaults onto every line (`purchaseInvoiceLine.withholdingTaxCodeId`, nullable); users clear it on lines it doesn't apply to (e.g. goods) — the tax spec's direct-assignment philosophy, no matrix.
+- **Treaty rates ride certificates**: `withholdingCertificate` rows per supplier (country, income type, treaty rate, validity window, certificate number + file). Effective rate at posting = the treaty rate of a certificate **valid on the posting date** matching the code's income type, else the component's domestic rate. Expired certificate ⇒ automatic fallback to domestic rate — the compliance-safe default.
+- **Posting** (in `post-purchase-invoice`): AP still credits **gross**; for each withheld line the poster adds Dr AP / Cr WHT liability for `whtBase × effectiveRate` (WHT base = line net amount, exclusive of VAT). The supplier's open payable is therefore **net** — payment flows need no change. One `taxLedger` row per withheld line with new source `'Withholding'` (additive `taxLedgerSource` value), snapshotting rate, treaty flag, certificate number, authority. VOID re-posting writes reversing rows, matching the existing pattern.
+- **Returns & certificates**: a WHT return is an ordinary `taxReturn` scoped to the WHT authority — finalize stamps the `'Withholding'` ledger rows, posts settlement (Dr WHT liability / Cr `taxSettlementAccount`), and offers the draft AP remittance invoice via the authority's linked supplier. New extract: per-supplier **WHT certificate PDF** (period, income type, gross, rate, withheld) from `packages/documents`, plus a CSV authority extract.
+
+### 2. EC Sales List — extract over `taxLedger`
+
+- **Row source**: sales-side `taxLedger` rows in period whose tax code has a non-null **`ecslIndicator`** (new nullable SMALLINT on `taxCode`: `0` = goods, `2` = triangulation, `3` = services) — set on the company's intra-EU Reverse Charge / Zero-Rated codes. Joined to `customerTax.vatNumber` and ship-to country (`salesInvoiceLocations`).
+- **Document**: `tradeDeclaration` (type `'EC Sales List'`), scoped to a `taxRegistration` + period. Draft computes lines live (VAT number, country, summed value, indicator); Finalize snapshots lines to JSONB (immutable filing record — the `taxReturn.totals` pattern). No GL impact, hence a separate lightweight document rather than `taxReturn`.
+- **Validation before finalize**: missing/malformed customer VAT numbers and non-EU ship-to rows carrying an ECSL-flagged code are surfaced as blocking exceptions.
+- **Exports**: HMRC ECSL CSV (UK layout) and a generic XML/CSV per member state; format renderers live beside the declaration service.
+
+### 3. Intrastat — declarations from receipts and shipments
+
+- **Item trade fields** (new, nullable): `item.commodityCode` (CN8, 8 digits), `item.countryOfOriginId`, `item.netWeight` (kg per inventory unit, bare NUMERIC), `item.supplementaryUnitConversion` (supplementary units per inventory unit, for CN8 chapters that require them).
+- **Movement data**: `shipment.natureOfTransactionCode` and `receipt.natureOfTransactionCode` (TEXT, default from config, standard code list seeded — `11` sale, `21` return, etc.).
+- **Config**: `intrastatConfiguration` per company per country — arrivals/dispatches enabled flags, threshold amounts (seeded with current EU per-country thresholds as reference data), default nature of transaction. A rolling-12-month arrivals/dispatches value banner warns when an unconfigured country crosses its threshold.
+- **Declarations**: `tradeDeclaration` types `'Intrastat Arrivals'` (posted receipts from EU suppliers) and `'Intrastat Dispatches'` (posted shipments to EU customers) where counterparty country ≠ company country and both are EU. Draft lines aggregate by CN8 × partner country × origin country × nature of transaction: value (from invoice/order line pricing), net mass (qty × `item.netWeight`), supplementary units. Missing commodity codes/weights are blocking exceptions listing the offending items (fix on the item, refresh). Finalize snapshots; CSV export per national format (generic layout v1).
+
+### 4. UK MTD VAT submission — connector in `packages/ee`
+
+- **Integration**: `companyIntegration` entry "HMRC MTD VAT" (the Xero/Avalara precedent): OAuth 2.0 authorization-code flow against HMRC, encrypted token storage + refresh, sandbox/production environment switch, VRN taken from the UK `taxRegistration`.
+- **Endpoints**: retrieve VAT obligations (open/fulfilled period keys), submit return, view liabilities and payments. All calls send the mandatory **fraud-prevention headers** (`Gov-Client-Connection-Method: WEB_APP_VIA_SERVER`, device/user/timezone/vendor headers assembled server-side from the session).
+- **Digital links**: the submission payload is built **only** from the finalized `taxReturn`'s UK-layout box totals — the submit UI displays the 9 boxes read-only with a declaration checkbox; no manual entry anywhere between `taxLedger` and HMRC. `taxReturn` gains `hmrcPeriodKey` (bound when the user matches the return to an open obligation), and `taxReturnStatus` gains `'Submitted'` (additive). The HMRC receipt (`formBundleNumber`, `chargeRefNumber`, processing date) is stored on the return; submitted returns cannot be reopened.
+- **Sandbox-tested**: the full obligation→submit→receipt cycle runs against HMRC's sandbox (with its `Gov-Test-Scenario` headers) as an acceptance gate before production credentials are requested.
+
+### Delivery phases (ordered by live customer need)
+
+| Phase | Scope | Depends on |
+|-------|-------|-----------|
+| **1 — MTD** | HMRC connector, fraud headers, obligations/submit/liabilities, `taxReturn` submission columns, sandbox suite | Tax spec Phase 2 (returns + UK layout) |
+| **2 — ECSL + Intrastat** | `taxCode.ecslIndicator`, item trade fields, nature-of-transaction, `intrastatConfiguration`, `tradeDeclaration` + exports | Tax spec Phase 1 (`taxLedger`) |
+| **3 — WHT** | Withholding calculation type, certificates, posting change, WHT returns + supplier certificate PDFs | Tax spec Phases 1–2 |
+
+**Sequencing rule (resolved)**: WHT moves to Phase 1 only if a customer has live cross-border payments with withholding obligations; today's confirmed live needs are UK MTD filing and intra-EU trade, so MTD leads. All three phases are independently shippable and fully spec'd here.
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|----------|--------|-----------|
+| 1 | WHT model | Extend `taxCode`/`taxCodeComponent` with `calculationType = 'Withholding'` + `incomeType`; **new `taxLedgerSource` value `'Withholding'`** (not a flag) | One codes/components/authority/ledger machine (parent-spec mandate: extend, never parallel); a distinct source keeps VAT returns and liability reports from ever mingling WHT rows by accident — a flag on `Purchase` rows would require every existing consumer to add a filter |
+| 2 | Treaty rate gating | Certificate-with-validity required for treaty rate; expired ⇒ silent fallback to domestic rate + document warning | Treaty relief is only defensible with a valid residency certificate on file; failing *open* (under-withholding) creates issuer liability — fail safe |
+| 3 | WHT posting shape | AP credits gross, then Dr AP / Cr WHT liability per withheld line; base = line net of VAT | Supplier statement shows gross invoice and net payable (standard certificate math); payments/settlement/tie-outs untouched because the AP *balance* is net |
+| 4 | WHT returns | Reuse `taxReturn` scoped to the WHT authority (stamp + settle + AP remittance) | Settlement and remittance rails already exist; only certificates/extracts are new |
+| 5 | ECSL/Intrastat document | New `tradeDeclaration` (Draft computes live, Finalize snapshots JSONB) — not `taxReturn` | These filings have no settlement JE and no GL impact; forcing them through `taxReturn` would bolt no-op posting onto a pure extract |
+| 6 | ECSL row selection | `taxCode.ecslIndicator` set on intra-EU codes; extract = ledger rows carrying flagged codes | Deterministic and auditable from the posted ledger; avoids re-inferring place-of-supply at report time |
+| 7 | Intrastat data placement | Master data on `item` (CN8/mass/origin/supplementary), movement code on shipment/receipt header, aggregation at declaration time | CN8 and mass are item facts; nature of transaction is a movement fact; keeping lines computed-then-snapshotted avoids double-keying every shipment line |
+| 8 | Thresholds | Per-country `intrastatConfiguration` with seeded reference thresholds + rolling-12-month crossing warning; declarations only for enabled flows | Thresholds change annually per member state — config, not code; the warning prevents silent non-compliance |
+| 9 | MTD digital link | Submission payload built exclusively from the finalized return's layout totals; read-only submit UI; `Submitted` returns locked | The unbroken-digital-link requirement is the point of MTD; any editable box is a compliance break |
+| 10 | MTD placement | `packages/ee` connector behind `companyIntegration` (Xero/Avalara precedent); fraud headers assembled server-side | Established integration pattern; HMRC vendor credentials are licensed, i.e. ee-gated |
+| 11 | Multi-tenancy (heuristic 1) | Every new table: `companyId`, composite PK `("id","companyId")`, `id('prefix')`, audit columns, `customFields` on config tables; composite child FKs | House convention |
+| 12 | Service shape (heuristic 2) | All functions in `accounting.models.ts` / `accounting.service.ts`, `(client, companyId, …) → {data, error}`; HMRC client in `packages/ee` | Tax is accounting-owned (parent-spec precedent); one service file per module |
+| 13 | RLS (heuristic 3) | Four standard policies; SELECT via `get_companies_with_employee_role()`, writes via `get_companies_with_employee_permission('accounting_*')`; ledger writes via service-role posting functions | Package AGENTS.md convention (no deprecated `has_role`) |
+| 14 | Permissions (heuristic 4) | Declarations/returns/config: `view/update: "accounting"`; item trade fields ride `parts` permissions; certificate upload rides purchasing (the `supplierTax` storage precedent) | Matches tax-spec scoping; no new permission actions |
+| 15 | Forms (heuristic 5) | `ValidatedForm` + zod (`withholdingCertificateValidator`, `tradeDeclarationValidator`, `intrastatConfigurationValidator`); Drawer detail views | House convention |
+| 16 | Module layout (heuristic 6) | No new module: accounting module + `ui/Tax/`; routes `x+/accounting+/tax-*`; MTD in `packages/ee/src/hmrc/`; PDFs in `packages/documents` | Tax config is accounting settings; integrations live in ee |
+| 17 | Backward compatibility (heuristic 7) | All columns nullable/defaulted; enum values additive; zero behavior change for companies with no WHT code, no ECSL indicator, no Intrastat config, no HMRC integration; views recreated DROP + `SELECT *`; idempotent DDL | Unconfigured companies post byte-identically to the tax-spec baseline |
+
+## Data Model Changes
+
+Three migrations (one per phase; `pnpm db:migrate:new <name>`, randomized HHMMSS, never `000000`), `pnpm run generate:types` after each. Standard audit columns, indexes on `companyId` + FKs, and the four RLS policies apply throughout; abbreviated:
+
+```sql
+-- Additive enum values (Phase 1 / 3)
+ALTER TYPE "taxReturnStatus" ADD VALUE IF NOT EXISTS 'Submitted'; -- Phase 1
+ALTER TYPE "taxCalculationType" ADD VALUE IF NOT EXISTS 'Withholding'; -- Phase 3
+ALTER TYPE "taxLedgerSource" ADD VALUE IF NOT EXISTS 'Withholding'; -- Phase 3
+CREATE TYPE "withholdingIncomeType" AS ENUM
+ ('Services', 'Royalties', 'Interest', 'Dividends', 'Rent', 'Other'); -- Phase 3
+CREATE TYPE "tradeDeclarationType" AS ENUM
+ ('EC Sales List', 'Intrastat Arrivals', 'Intrastat Dispatches'); -- Phase 2
+CREATE TYPE "tradeDeclarationStatus" AS ENUM ('Draft', 'Finalized');
+
+-- Phase 1: MTD submission columns on the existing return
+ALTER TABLE "taxReturn"
+ ADD COLUMN IF NOT EXISTS "hmrcPeriodKey" TEXT,
+ ADD COLUMN IF NOT EXISTS "submittedAt" TIMESTAMP WITH TIME ZONE,
+ ADD COLUMN IF NOT EXISTS "submittedBy" TEXT REFERENCES "user"("id"),
+ ADD COLUMN IF NOT EXISTS "submissionReceipt" JSONB; -- formBundleNumber, chargeRefNumber, processingDate
+
+-- Phase 2: item trade fields, movement codes, config, declarations
+ALTER TABLE "item"
+ ADD COLUMN IF NOT EXISTS "commodityCode" TEXT, -- CN8
+ ADD COLUMN IF NOT EXISTS "countryOfOriginId" INTEGER REFERENCES "country"("id"),
+ ADD COLUMN IF NOT EXISTS "netWeight" NUMERIC, -- kg per inventory unit
+ ADD COLUMN IF NOT EXISTS "supplementaryUnitConversion" NUMERIC;
+ALTER TABLE "shipment" ADD COLUMN IF NOT EXISTS "natureOfTransactionCode" TEXT;
+ALTER TABLE "receipt" ADD COLUMN IF NOT EXISTS "natureOfTransactionCode" TEXT;
+ALTER TABLE "taxCode" ADD COLUMN IF NOT EXISTS "ecslIndicator" SMALLINT; -- 0 | 2 | 3
+
+CREATE TABLE IF NOT EXISTS "intrastatConfiguration" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "companyId" TEXT NOT NULL,
+ "countryId" INTEGER NOT NULL REFERENCES "country"("id"),
+ "arrivalsEnabled" BOOLEAN NOT NULL DEFAULT FALSE,
+ "dispatchesEnabled" BOOLEAN NOT NULL DEFAULT FALSE,
+ "arrivalsThreshold" NUMERIC, -- seeded reference values, editable
+ "dispatchesThreshold" NUMERIC,
+ "defaultNatureOfTransaction" TEXT NOT NULL DEFAULT '11',
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ CONSTRAINT "intrastatConfiguration_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "intrastatConfiguration_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "intrastatConfiguration_unique" UNIQUE ("companyId", "countryId")
+);
+ALTER TABLE "intrastatConfiguration" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."intrastatConfiguration";
+CREATE POLICY "SELECT" ON "public"."intrastatConfiguration" FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+-- INSERT/UPDATE/DELETE via get_companies_with_employee_permission('accounting_*'),
+-- same four-policy shape on every table below.
+
+CREATE TABLE IF NOT EXISTS "tradeDeclaration" (
+ "id" TEXT NOT NULL DEFAULT id('td'),
+ "companyId" TEXT NOT NULL,
+ "declarationId" TEXT NOT NULL, -- readable id via get_next_sequence
+ "type" "tradeDeclarationType" NOT NULL,
+ "taxRegistrationId" TEXT, -- ECSL: required; Intrastat: the filing country's registration
+ "periodStart" DATE NOT NULL,
+ "periodEnd" DATE NOT NULL,
+ "status" "tradeDeclarationStatus" NOT NULL DEFAULT 'Draft',
+ "lines" JSONB, -- snapshot at finalize (immutable filing record)
+ "totals" JSONB,
+ "finalizedAt" TIMESTAMP WITH TIME ZONE,
+ "finalizedBy" TEXT REFERENCES "user"("id"),
+ -- audit columns, customFields …
+ CONSTRAINT "tradeDeclaration_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "tradeDeclaration_taxRegistrationId_fkey" FOREIGN KEY ("taxRegistrationId", "companyId")
+ REFERENCES "taxRegistration"("id", "companyId")
+);
+
+-- Phase 3: withholding
+ALTER TABLE "taxCode" ADD COLUMN IF NOT EXISTS "incomeType" "withholdingIncomeType";
+ALTER TABLE "supplierTax" ADD COLUMN IF NOT EXISTS "withholdingTaxCodeId" TEXT;
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN IF NOT EXISTS "withholdingTaxCodeId" TEXT;
+ALTER TABLE "accountDefault" ADD COLUMN IF NOT EXISTS "withholdingTaxPayableAccount" TEXT;
+ALTER TABLE "taxLedger"
+ ADD COLUMN IF NOT EXISTS "treatyRateApplied" BOOLEAN NOT NULL DEFAULT FALSE,
+ ADD COLUMN IF NOT EXISTS "withholdingCertificateId" TEXT;
+
+CREATE TABLE IF NOT EXISTS "withholdingCertificate" (
+ "id" TEXT NOT NULL DEFAULT id('whc'),
+ "companyId" TEXT NOT NULL,
+ "supplierId" TEXT NOT NULL,
+ "countryId" INTEGER NOT NULL REFERENCES "country"("id"), -- supplier residency
+ "incomeType" "withholdingIncomeType" NOT NULL,
+ "treatyRate" NUMERIC NOT NULL, -- 0..1; may be 0 (full relief)
+ "certificateNumber" TEXT,
+ "certificatePath" TEXT, -- private bucket, tax-certificates prefix
+ "validFrom" DATE NOT NULL,
+ "validTo" DATE NOT NULL,
+ -- audit columns, customFields …
+ CONSTRAINT "withholdingCertificate_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "withholdingCertificate_supplierId_fkey" FOREIGN KEY ("supplierId")
+ REFERENCES "supplier"("id") ON DELETE CASCADE,
+ CONSTRAINT "withholdingCertificate_validity" CHECK ("validTo" >= "validFrom")
+);
+```
+
+Affected views (`suppliers`, purchase-invoice line views, item views) recreated via DROP + `SELECT *` from their newest definitions; all DDL idempotency-guarded. HMRC OAuth tokens live in `companyIntegration` metadata (encrypted, ee package) — no new auth tables.
+
+## API / Service Changes
+
+`apps/erp/app/modules/accounting/` (models + service, no new files) unless noted:
+
+- **Phase 1 (`packages/ee/src/hmrc/`)**: `HmrcMtdClient` — OAuth authorize/callback/refresh; `getObligations(vrn, from, to)`; `submitVatReturn(vrn, periodKey, boxes, declarationConfirmed)`; `getLiabilities` / `getPayments`; fraud-prevention header assembly from request context. App-side: `matchReturnToObligation`, `submitTaxReturnToHmrc` (validates status `Finalized` + UK layout, builds boxes from stored totals only, persists receipt, sets `Submitted`); `reopenTaxReturn` gains a `Submitted` guard.
+- **Phase 2**: `getEcslLines(client, companyId, {registrationId, periodStart, periodEnd})` (ledger join to `customerTax`/locations, exceptions list); `getIntrastatLines(client, companyId, {type, countryId, period})` (posted receipts/shipments aggregation, exceptions list); `upsert/finalizeTradeDeclaration` (finalize = validate exceptions empty, snapshot lines/totals); `exportTradeDeclaration` (HMRC ECSL CSV, generic XML, generic Intrastat CSV); `getIntrastatThresholdStatus` (rolling 12-month values vs config); `intrastatConfiguration` CRUD.
+- **Phase 3**: `resolveWithholding(client, companyId, {supplierId, taxCodeId, date})` → `{rate, treatyRateApplied, certificateId}` (valid-certificate lookup, domestic fallback); `withholdingCertificate` CRUD with expiry-warning list; `post-purchase-invoice` edge function gains the withheld-line journal pair + `'Withholding'` ledger rows inside the existing transaction (shared logic in `functions/shared/resolve-taxes.ts`); `getWithholdingCertificateData` feeding the supplier certificate PDF (`packages/documents`); WHT authority extract CSV. Zod validators for all new forms.
+
+## UI Changes
+
+- **Phase 1**: HMRC integration card (connect/disconnect, environment) in settings integrations; tax-return detail gains an MTD panel — obligation matching, read-only 9 boxes, declaration checkbox, Submit, receipt display; `Submitted` badge in the returns table.
+- **Phase 2**: `x+/accounting+/trade-declarations` list + detail (period/registration picker, live draft lines, blocking-exception panel with links to offending items/customers, Finalize, Export); Intrastat config page under tax settings with threshold-crossing banner; item Purchasing/Trade panel gains commodity code, origin, net weight, supplementary conversion; shipment/receipt drawers gain nature-of-transaction (defaulted, editable pre-post); ECSL indicator select on the tax-code form.
+- **Phase 3**: supplier tax form gains WHT code select + certificates section (validity badges, expiring-soon warning); purchase-invoice line drawer shows resolved WHT (rate, treaty/domestic, certificate) with clear-per-line; WHT return detail gains supplier-certificate PDF generation; authority extract download.
+
+## Acceptance Criteria
+
+Phase 1 — MTD (sandbox, mocked in CI):
+- [ ] Connecting HMRC stores tokens per company; obligations list shows sandbox period keys; a finalized UK-layout return matched to an open obligation submits successfully and stores `formBundleNumber`; the return shows `Submitted` and cannot be reopened.
+- [ ] The submitted box values byte-match the finalized return's stored layout totals (no recomputation, no editable inputs anywhere in the submit path — asserted in test).
+- [ ] Every HMRC call carries the mandatory fraud-prevention headers; a non-UK-layout or non-finalized return cannot reach the submit action.
+- [ ] A generic (non-UK) company sees no MTD UI and posts returns exactly as the tax spec specifies.
+
+Phase 2 — ECSL/Intrastat:
+- [ ] Given posted intra-EU invoices on an `ecslIndicator = 0` zero-rated code, an ECSL declaration for the period lists one line per customer VAT number × indicator with summed values; a customer missing a VAT number blocks finalize with a named exception; the HMRC CSV export matches the snapshot.
+- [ ] A finalized declaration's lines never change when later documents post into the period; the late rows appear in the next period's draft.
+- [ ] With dispatches enabled for DE, posted shipments to EU customers aggregate by CN8 × destination × origin × nature code with net mass = Σ(qty × `item.netWeight`); an item missing a commodity code blocks finalize; arrivals mirror from receipts.
+- [ ] The threshold banner fires when rolling-12-month arrivals exceed the configured threshold for a country with arrivals disabled.
+
+Phase 3 — WHT:
+- [ ] A supplier with a 15% Royalties WHT code and no certificate: posting a 1,000 purchase invoice (no VAT) credits AP 1,000, debits AP 150, credits WHT liability 150; the open payable is 850; one `'Withholding'` ledger row carries rate 0.15, `treatyRateApplied = false`.
+- [ ] With a certificate (10%, valid on posting date): withheld = 100, `treatyRateApplied = true`, certificate id snapshotted; the same invoice posted one day after `validTo` withholds 150.
+- [ ] WHT lines never appear in VAT liability reports or VAT return previews; a WHT-authority `taxReturn` stamps exactly the `'Withholding'` rows, posts Dr liability / Cr settlement, and offers the AP remittance invoice.
+- [ ] The supplier certificate PDF totals tie to the stamped ledger rows; a supplier with no WHT code posts byte-identically to today (existing golden-master tests unchanged).
+- [ ] `pnpm exec turbo run typecheck --filter=@carbon/erp` + scoped tests green after `pnpm run generate:types` (every phase).
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| HMRC production credentials require vendor approval (demo + fraud-header review) — calendar risk outside Carbon's control | High | Start the application at Phase-1 kickoff; sandbox acceptance is the code gate; production go-live decoupled |
+| Fraud-prevention header non-compliance triggers HMRC rejection/penalties | Med | Server-side assembly with HMRC's header-validation sandbox endpoint in CI |
+| WHT posting touches `post-purchase-invoice` concurrently with tax-spec and immutability work on the same function | Med | Phase 3 sequenced last; rebases on merged tax-spec posting; golden-master tests for no-WHT paths |
+| Under/over-withholding from stale certificates | Med | Validity-date gating with domestic-rate fallback (decision 2); expiring-certificate warnings |
+| Intrastat data quality (missing CN8/weights) stalls first filings | Med | Blocking exceptions name items; CSV item import covers commodity fields for bulk backfill |
+| Per-country ECSL/Intrastat format drift (generic exports insufficient somewhere) | Low | Snapshot JSONB keeps data format-independent; renderers are additive per country on demand |
+| Enum extensions (`taxLedgerSource`, `taxReturnStatus`) ripple through tax-spec consumers | Low | Additive values only; every existing consumer filters explicitly on `Sales`/`Purchase`/status — verified before merge |
+
+## Open Questions
+
+> 🛑 HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] **Geography** — **Resolved (readiness spec, 2026-07-03): customers across Europe and the US.** ECSL, Intrastat, and MTD are live needs for EU/UK entities; US filing stays with Avalara behind the tax spec's connector.
+- [x] **Extend or parallel the tax machinery?** — **Resolved: extend.** WHT rides `taxCode`/`taxCodeComponent`/`taxAuthority`/`taxLedger`/`taxReturn`; ECSL reads `taxLedger`; MTD submits the tax spec's UK return. No parallel tax structures anywhere in this spec.
+- [x] **WHT ledger representation** — **Resolved in this spec: new `taxLedgerSource` value `'Withholding'`** (decision 1), not a flag on `Purchase` rows — existing VAT consumers stay correct without modification.
+- [x] **Sequencing** — **Resolved: MTD → ECSL/Intrastat → WHT**, per live customer need (UK filing and intra-EU trade are live today); WHT jumps to first if a customer confirms live cross-border withholding obligations. All phases fully spec'd regardless of order.
+- [x] **HMRC vendor registration**: who owns the HMRC developer-hub application and production-credentials process (company action, ~weeks of lead time, demo required)? Needed before Phase-1 production go-live; sandbox work is unblocked. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Company action, Brad owns the kickoff; start it at #1055's plan stage (weeks of lead time); build against HMRC sandbox credentials meanwhile.
+- [x] **WHT gross-up contracts**: do any live supplier contracts require net-of-tax (gross-up) treatment, where Carbon must compute a grossed-up base so the supplier receives the full invoice amount? v1 assumes standard deduct-from-payment only. — **Answer (Brad, 2026-07-04, ambition heuristic — be ambitious and thorough; back out at /plan stage if needed):** Yes — support a gross-up flag per supplier WHT assignment in v1 schema + calculation. Back out at plan stage if no live contract needs it.
+
+## Changelog
+
+- 2026-07-04: Created — GAP-D1 remainder from the public-company readiness spec; verified against the tax spec's machinery, `20260429001730_eori.sql` / `20260430000001_tax-status.sql` (VAT/EORI capture exists), and shipment/receipt/item schemas (no commodity/weight/origin fields exist today). Tracking issue crbnos/carbon#1055.
+- 2026-07-04: Remaining open questions resolved under the program ambition heuristic (ambitious scope now; back-out valves at plan stage).
diff --git a/.ai/specs/AGENTS.md b/.ai/specs/AGENTS.md
index 866aef1e57..42d6f611f3 100644
--- a/.ai/specs/AGENTS.md
+++ b/.ai/specs/AGENTS.md
@@ -22,11 +22,13 @@ Check `.ai/specs/` before modifying any module. Create or update specs when the
## Spec Lifecycle
```
-1. Idea → spec draft in .ai/specs/{YYYY-MM-DD}-{title}.md
-2. Open questions resolved (hard stop until answered)
-3. Implementation proceeds phase-by-phase
-4. Completed spec moves to .ai/specs/implemented/
-5. PR links back to spec via "Tracking spec:" line
+1. Idea → research + design decisions; open questions collected
+2. Open questions resolved with the user (hard stop — BEFORE the spec is written)
+3. Spec written in .ai/specs/{YYYY-MM-DD}-{title}.md with resolutions baked in
+ (questions surfaced while writing go back to step 2 before the spec is final)
+4. Implementation proceeds phase-by-phase
+5. Completed spec moves to .ai/specs/implemented/
+6. PR links back to spec via "Tracking spec:" line
```
## File Naming Convention
diff --git a/packages/database/supabase/migrations/20260702044133_period-close-lifecycle.sql b/packages/database/supabase/migrations/20260702044133_period-close-lifecycle.sql
new file mode 100644
index 0000000000..3db4ed6efc
--- /dev/null
+++ b/packages/database/supabase/migrations/20260702044133_period-close-lifecycle.sql
@@ -0,0 +1,137 @@
+-- Period close lifecycle: Open → Locked → Closed on accountingPeriod,
+-- fiscal-year identity, and a hard trigger backstop on journal.
+-- Tracking spec: .ai/specs/2026-07-02-period-closing.md
+
+-- 1. Close lifecycle enum (separate axis from the legacy Active/Inactive status)
+DO $$ BEGIN
+ CREATE TYPE "periodCloseStatus" AS ENUM ('Open', 'Locked', 'Closed');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- 2. New columns
+ALTER TABLE "accountingPeriod"
+ ADD COLUMN IF NOT EXISTS "closeStatus" "periodCloseStatus" NOT NULL DEFAULT 'Open',
+ ADD COLUMN IF NOT EXISTS "fiscalYear" INTEGER,
+ ADD COLUMN IF NOT EXISTS "periodNumber" INTEGER,
+ ADD COLUMN IF NOT EXISTS "lockedAt" TIMESTAMP WITH TIME ZONE,
+ ADD COLUMN IF NOT EXISTS "lockedBy" TEXT REFERENCES "user"("id") ON DELETE RESTRICT;
+
+CREATE INDEX IF NOT EXISTS "accountingPeriod_lockedBy_idx" ON "accountingPeriod" ("lockedBy");
+
+-- 3. Backfill closeStatus from closedAt (column existed but was never populated;
+-- be safe in case any environment has data)
+UPDATE "accountingPeriod"
+SET "closeStatus" = 'Closed'
+WHERE "closedAt" IS NOT NULL AND "closeStatus" = 'Open';
+
+-- 4. Backfill fiscalYear/periodNumber from the period's own startDate and the
+-- company's fiscal start month. Fiscal years are named by the calendar year
+-- in which they END (a FY starting Jul 2025 is FY2026); for January starts
+-- the fiscal year equals the calendar year.
+UPDATE "accountingPeriod" ap
+SET
+ "periodNumber" = ((EXTRACT(MONTH FROM ap."startDate")::int - s.start_month + 12) % 12) + 1,
+ "fiscalYear" = CASE
+ WHEN s.start_month = 1 THEN EXTRACT(YEAR FROM ap."startDate")::int
+ WHEN EXTRACT(MONTH FROM ap."startDate")::int >= s.start_month THEN EXTRACT(YEAR FROM ap."startDate")::int + 1
+ ELSE EXTRACT(YEAR FROM ap."startDate")::int
+ END
+FROM (
+ SELECT
+ c."id" AS company_id,
+ COALESCE(
+ (SELECT array_position(enum_range(NULL::"month")::text[], fys."startMonth"::text)
+ FROM "fiscalYearSettings" fys
+ WHERE fys."companyId" = c."id"),
+ 1
+ ) AS start_month
+ FROM "company" c
+) s
+WHERE s.company_id = ap."companyId"
+ AND (ap."fiscalYear" IS NULL OR ap."periodNumber" IS NULL);
+
+-- 5. Uniqueness of (companyId, fiscalYear, periodNumber). The lazy period
+-- auto-creation has a historical race that could have produced duplicate
+-- months; fall back to a plain index rather than failing the deploy.
+DO $$ BEGIN
+ CREATE UNIQUE INDEX IF NOT EXISTS "accountingPeriod_company_fy_period_idx"
+ ON "accountingPeriod" ("companyId", "fiscalYear", "periodNumber");
+EXCEPTION WHEN unique_violation THEN
+ RAISE WARNING 'Duplicate (companyId, fiscalYear, periodNumber) rows exist; creating non-unique index instead';
+ CREATE INDEX IF NOT EXISTS "accountingPeriod_company_fy_period_idx"
+ ON "accountingPeriod" ("companyId", "fiscalYear", "periodNumber");
+END $$;
+
+-- 6. Hard backstop: nothing enters, leaves, or gets posted into a Closed
+-- period. Locked-period semantics (who may post) require actor identity and
+-- are enforced at the service layer; this trigger only guards the invariant
+-- that Closed-period financials never change. Posted → Reversed status flips
+-- are intentionally allowed (the offsetting entry lands in an open period).
+CREATE OR REPLACE FUNCTION public.check_accounting_period_open()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+SECURITY DEFINER SET search_path = public
+AS $$
+DECLARE
+ v_new_status "periodCloseStatus";
+ v_old_status "periodCloseStatus";
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ IF OLD."status" <> 'Draft' THEN
+ SELECT "closeStatus" INTO v_old_status
+ FROM "accountingPeriod"
+ WHERE ("id" = OLD."accountingPeriodId")
+ OR (OLD."accountingPeriodId" IS NULL
+ AND "companyId" = OLD."companyId"
+ AND OLD."postingDate" BETWEEN "startDate" AND "endDate")
+ LIMIT 1;
+ IF v_old_status = 'Closed' THEN
+ RAISE EXCEPTION 'Cannot delete journal %: accounting period is closed', OLD."id";
+ END IF;
+ END IF;
+ RETURN OLD;
+ END IF;
+
+ -- Skip UPDATEs that neither move the journal between periods nor post a draft
+ IF TG_OP = 'UPDATE'
+ AND NEW."postingDate" IS NOT DISTINCT FROM OLD."postingDate"
+ AND NEW."accountingPeriodId" IS NOT DISTINCT FROM OLD."accountingPeriodId"
+ AND NOT (OLD."status" = 'Draft' AND NEW."status" = 'Posted') THEN
+ RETURN NEW;
+ END IF;
+
+ -- Moving a journal OUT of a closed period changes closed financials too
+ IF TG_OP = 'UPDATE'
+ AND (NEW."postingDate" IS DISTINCT FROM OLD."postingDate"
+ OR NEW."accountingPeriodId" IS DISTINCT FROM OLD."accountingPeriodId") THEN
+ SELECT "closeStatus" INTO v_old_status
+ FROM "accountingPeriod"
+ WHERE ("id" = OLD."accountingPeriodId")
+ OR (OLD."accountingPeriodId" IS NULL
+ AND "companyId" = OLD."companyId"
+ AND OLD."postingDate" BETWEEN "startDate" AND "endDate")
+ LIMIT 1;
+ IF v_old_status = 'Closed' THEN
+ RAISE EXCEPTION 'Cannot move journal % out of a closed accounting period', OLD."id";
+ END IF;
+ END IF;
+
+ SELECT "closeStatus" INTO v_new_status
+ FROM "accountingPeriod"
+ WHERE ("id" = NEW."accountingPeriodId")
+ OR (NEW."accountingPeriodId" IS NULL
+ AND "companyId" = NEW."companyId"
+ AND NEW."postingDate" BETWEEN "startDate" AND "endDate")
+ LIMIT 1;
+
+ IF v_new_status = 'Closed' THEN
+ RAISE EXCEPTION 'Accounting period is closed for posting date %', NEW."postingDate";
+ END IF;
+
+ RETURN NEW;
+END;
+$$;
+
+DROP TRIGGER IF EXISTS "journal_check_period_open" ON "journal";
+CREATE TRIGGER "journal_check_period_open"
+ BEFORE INSERT OR DELETE OR UPDATE OF "postingDate", "accountingPeriodId", "status" ON "journal"
+ FOR EACH ROW EXECUTE FUNCTION public.check_accounting_period_open();