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.

perf: ledger query performance — indexes, draft exclusion, snapshot + delta (#1021)

Brad Barbin81494bea8363
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 46f7316a29..25605b98f5 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -328,3 +328,23 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** When creating item fixtures via SQL, create the type's companion row too (`material` keyed by `readableId` for Materials; check the `get_{type}_details` RPC joins for the type). Prefer creating fixtures through the UI or service functions when the item will be used in UI flows, not just ledger posting.
**Applies to:** any psql/SQL test-fixture item creation; `get_material_details` / `get_part_details` / `get_tool_details` consumers; `apps/erp/app/routes/x+/items+/$itemId.properties.tsx`.
+
+## Journal debit/credit is derived from account class + amount sign, not the raw sign
+
+**Context:** Seeding a Cash sale as a journal via SQL, I used Cash (Asset) `amount = +1000` and Sales (Revenue) `amount = -1000`, assuming `+ = debit, - = credit` (which the `journal` AGENTS.md states for the *stored* value). The `journalEntries` view then reported the entry as `totalDebits = 2000, totalCredits = 0` — unbalanced — and the period-close "Trial balance in balance" auto-check (`tb-balanced`) refused the close.
+
+**Problem:** `journalEntries.totalDebits`/`totalCredits` are computed from **account class AND amount sign**: Asset/Expense `amount>0` OR Liability/Equity/Revenue `amount<0` → debit; the mirror → credit. So a *positive* amount on a Revenue account is a **credit**, not a debit. A correctly-balanced sale is Cash (Asset) `+1000` and Sales (Revenue) `+1000` — both positive. The raw `SUM(amount)` the balance RPCs use is a separate, class-agnostic signed sum; don't conflate the two.
+
+**Rule:** When hand-seeding `journalLine` rows, set the sign to move the account toward its natural balance: `+` increases an Asset/Expense (debit) and increases a Liability/Equity/Revenue (credit). Verify against the `journalEntries` view (`totalDebits == totalCredits` per `journalEntryId`) before relying on the data — an unbalanced entry silently blocks period close. Posted `journal`/`journalLine` rows are immutable (`journal_posted_immutable` / `journalLine_posted_immutable`); to correct seeded mistakes you must disable those triggers on the local DB (superuser), never in a migration.
+
+**Applies to:** any SQL journal fixtures; the `journalEntries` view; the `tb-balanced` close check in `computePeriodReadiness` (`accounting.service.ts`).
+
+## A period snapshot written at close races Locked-period postings unless the posting guard locks the period row
+
+**Context:** `closeAccountingPeriod` writes the `accountingPeriodBalance` snapshot inside its transaction, after flipping the period to `Closed`. `check_accounting_period_open` only *rejects* postings when a period is already `Closed`; a `Locked` period still accepts them (Locked is a soft freeze for adjustments). A period only becomes Closed on COMMIT.
+
+**Problem:** In the window between the close txn's snapshot `SELECT` and its COMMIT, a concurrent posting reads the period as still-Locked (the flip is uncommitted under READ COMMITTED), is allowed, and commits a line with `postingDate <= endDate` that the snapshot never captured. The read path's delta only adds `postingDate > endDate`, so that line is silently dropped from the optimized balance until reopen+reclose — a wrong financial figure with no error.
+
+**Rule:** When a cache/snapshot is written inside a state-flip transaction and a concurrent writer keys off the *committed* state, make the writer take a lock that conflicts with the flip. Here: the posting guard reads the target `accountingPeriod` row `FOR SHARE` (migration `20260713235930`), which blocks behind the close's row lock — postings before the flip commit first (and land in the snapshot); postings after block, then see `Closed` and are rejected. `FOR SHARE` is shared, so normal concurrent postings don't block each other; only an in-flight close serializes them. Verify with two psql sessions + `lock_timeout`.
+
+**Applies to:** `check_accounting_period_open`; `snapshotAccountingPeriodBalances` / `accountingPeriodBalance`; any close/snapshot-on-commit pattern.
diff --git a/.ai/plans/2026-07-02-ledger-query-performance.md b/.ai/plans/2026-07-02-ledger-query-performance.md
new file mode 100644
index 0000000000..15fb057f06
--- /dev/null
+++ b/.ai/plans/2026-07-02-ledger-query-performance.md
@@ -0,0 +1,244 @@
+# Ledger Query Performance — Audit & Optimization Plan
+
+Date: 2026-07-02
+Status: Phases 1-3 implemented on `perf/ledger-queries` (migrations
+`20260713224517`, `20260713225803`, `20260713231142`, `20260713232634`,
+`20260713233919`, `20260713235406`). Deviations: 2f
+(`count: "exact"`) deferred — the journal-entries filters can hit view-only
+columns, so a side-count query is fragile, and the new `journalLine_journalId_idx`
+makes the view aggregation cheap; 2g dropped — `StockMovementsTable` subscribes to
+`itemLedger` realtime, so the publication stays. Phase 3 details + deviations:
+`.ai/plans/2026-07-02-ledger-snapshot-delta.md` (the period-close hook for
+`snapshotAccountingPeriodBalances` lands with the period-closing branch).
+Scope: `itemLedger`, `costLedger`, `journal`/`journalLine` (GL), and the read paths built on them (financial statements, quantity-on-hand, COGS, tie-out). Goal: keep read latency flat as ledgers grow, **without** introducing heavy machinery (no partitioning, no CQRS, no event-sourced projections).
+
+## How the system works today (audit summary)
+
+All three ledgers are **append-only, aggregated-on-read since inception**:
+
+- **GL balances**: every trial balance / balance sheet / income statement render calls
+ `accountTreeBalancesByCompany` (`migrations/20260315000001_per-company-balance-rpc.sql:4`),
+ which computes `balance` (SUM of all `journalLine` history) and `balanceAtDate`
+ (SUM of everything with `journal.postingDate <= to_date` — also since inception).
+ There is **no period-balance table**; `accountingPeriod` stores no balances.
+- **Quantity on hand**: `get_inventory_quantities` (`20260512130000_inventory-storage-unit-filter.sql:14`)
+ makes **three full-history passes** over `itemLedger` per call (on-hand sums,
+ storage types, storage units). The old trigger-maintained `itemInventory` rollup was
+ dropped (`20250209170952_shipment.sql:391,681`). The `itemStockQuantities`
+ materialized view exists (30-min pg_cron refresh) but the hot read paths don't use it.
+- **Costs**: Average/Standard read the cached `itemCost.unitCost` (good). FIFO/LIFO read
+ open layers via the partial index `costLedger(itemId, remainingQuantity) WHERE > 0` (good),
+ but consume layers with one UPDATE per layer (`functions/shared/calculate-cogs.ts:95-101`).
+
+### Verified index inventory (the core problem)
+
+| Table | Has | Missing (hot columns) |
+|---|---|---|
+| `itemLedger` | PK(id), partial `trackedEntityId`, `(companyId, createdAt DESC, entryNumber DESC)` | **`itemId`, `locationId`, `storageUnitId`, `documentId` — nothing** |
+| `journalLine` | `companyId`, `accountId`, `intercompanyPartnerId` | **`journalId` (FK!)**, `documentId`, `documentLineReference` |
+| `journal` | `companyId`, `accountingPeriodId`, `postingDate` (single-col), `(status, companyId)` | `(companyId, postingDate)` composite |
+| `costLedger` | `itemId`, `companyId`, partial `(itemId, remainingQuantity)` | `supplierId`, `documentId` |
+| `supplierLedger` | PK only | everything (`companyId`, `supplierId`) |
+
+Consequences, ranked by severity:
+
+1. **Cross-tenant sequential scans on `itemLedger`.** The `issue` edge function
+ (`functions/issue/index.ts:234-252`) and `lib/storage-units.ts:36-70` run
+ `SUM(quantity) ... WHERE itemId = ? AND locationId = ?` **per material issued**, with
+ no usable index — each is a seq scan of the entire multi-tenant table, inside the
+ posting transaction. This is the single worst scaling cliff: MES issue/pick latency
+ degrades linearly with *total* ledger size across all companies.
+2. **`journalLine.journalId` unindexed** — hits the `journalEntries` view
+ (`20260402000000_journal-entries.sql:136`, group-join per journal), journal→line
+ cascade deletes, void/reverse reads in `post-memo`/`post-payment`, and the per-row
+ Draft-check RLS on journalLine UPDATE/DELETE.
+3. **Statements re-scan everything, twice per company.** `getConsolidatedBalances`
+ (`accounting.service.ts:1329`) runs `getFinancialStatementBalances` *and*
+ `translateCompanyBalances` per company — each a full `journalLine` scan → **2 scans × N
+ companies per render**. Also `accountTreeBalancesByCompany` has no `journal.status`
+ filter, so Draft journals leak into statements (correctness, and it forecloses a
+ `status='Posted'` partial-index strategy).
+4. **Single-item reads pay whole-location cost.** `getItemQuantities`
+ (`items.service.ts:740`) runs the full `get_inventory_quantities` RPC (3 ledger passes
+ + PO/SO/job CTEs for every item at the location) and then filters to one `itemId` in
+ PostgREST. Item detail pages get slower with every ledger row anywhere at the location.
+5. **AR/AP tie-out** sums the full control-account history per call plus a correlated
+ `invoiceSettlement` subquery per invoice (`20260630104012_tie-out-aging-from-view-total.sql`).
+6. Smaller: `update-purchased-prices` fetches 12 months of `costLedger` with `select("*")`
+ and no pagination — silently capped at PostgREST's 1000 rows (**correctness bug**, will
+ skew average costs for high-volume items); `getItemCostHistory` has no LIMIT;
+ inventory/journal list pages use `count: "exact"` over aggregating views; `itemLedger`
+ is in the realtime publication (WAL fan-out per posting).
+
+What's already good and should be left alone: bulk array inserts for all ledger writes;
+keyset pagination in `getItemLedgerActivity`; cached `itemCost` for Average/Standard;
+the FIFO partial index; `getNextSequence`'s per-company lock (correct serialization
+for journal numbering).
+
+---
+
+## The plan
+
+Three phases, ordered by impact-per-complexity. Phase 1 is pure SQL (one migration).
+Phase 2 is small, local query-shape fixes. Phase 3 is the one structural pattern that
+keeps things flat forever — **snapshot + delta** — applied identically to GL and inventory.
+Explicit non-goals at the end.
+
+### Phase 1 — Indexes (one migration, zero code changes, biggest win)
+
+One idempotent migration (guard everything with `IF NOT EXISTS`; per repo lesson, the
+deploy runner retries files over partial state):
+
+```sql
+-- itemLedger: per-item and per-location aggregation paths
+CREATE INDEX IF NOT EXISTS "itemLedger_itemId_locationId_idx"
+ ON "itemLedger" ("itemId", "locationId") INCLUDE ("storageUnitId", "quantity", "trackedEntityStatus");
+CREATE INDEX IF NOT EXISTS "itemLedger_companyId_locationId_itemId_idx"
+ ON "itemLedger" ("companyId", "locationId", "itemId");
+CREATE INDEX IF NOT EXISTS "itemLedger_documentId_idx"
+ ON "itemLedger" ("documentId") WHERE "documentId" IS NOT NULL;
+
+-- journalLine: FK join path + document lookups
+CREATE INDEX IF NOT EXISTS "journalLine_journalId_idx" ON "journalLine" ("journalId");
+CREATE INDEX IF NOT EXISTS "journalLine_documentId_idx"
+ ON "journalLine" ("documentId") WHERE "documentId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "journalLine_documentLineReference_idx"
+ ON "journalLine" ("documentLineReference") WHERE "documentLineReference" IS NOT NULL;
+
+-- journal: company-scoped date filters (tie-out, statements)
+CREATE INDEX IF NOT EXISTS "journal_companyId_postingDate_idx"
+ ON "journal" ("companyId", "postingDate");
+
+-- costLedger / supplierLedger: unindexed FKs
+CREATE INDEX IF NOT EXISTS "costLedger_supplierId_idx"
+ ON "costLedger" ("supplierId") WHERE "supplierId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "supplierLedger_companyId_supplierId_idx"
+ ON "supplierLedger" ("companyId", "supplierId");
+```
+
+Notes:
+- The `INCLUDE` on the first index makes the per-item SUMs in `issue`,
+ `storage-units.ts`, and `get_item_quantities_by_tracking_id` index-only scans —
+ they never touch the heap even as the table grows.
+- The `(companyId, locationId, itemId)` index serves `get_inventory_quantities`,
+ `get_inventory_value_by_location`, `get_job_quantity_on_hand`, and the matview refresh.
+- Directly fixes finding #1 and #2 with zero application changes. This alone converts
+ MES issue/pick posting from O(total ledger) to O(rows for that item).
+- Run `pnpm run generate:types` after (no type changes expected, but per workflow).
+
+### Phase 2 — Query-shape fixes (small, local diffs)
+
+2a. **Add `journal.status = 'Posted'` to balance RPCs.**
+`accountTreeBalancesByCompany`, `accountTreeBalances`, and (transitively) `trialBalance` /
+`translateTrialBalance` should exclude Draft/Reversed journals. Correctness fix first,
+performance enabler second. Redefine via the fork-latest-version + `DROP IF EXISTS`
+convention.
+
+2b. **Stop double-scanning in `getConsolidatedBalances`** (`accounting.service.ts:1329`).
+`translateCompanyBalances` re-runs the same underlying `accountTreeBalancesByCompany`
+scan that `getFinancialStatementBalances` just did for the same company/dates. Change
+`translateTrialBalance` to accept the already-computed balances (or compute translation
+in TS from the one RPC result + rate lookup). Halves statement cost in consolidated mode.
+
+2c. **Single-item variant for quantities.** Add an optional `item_id` parameter to
+`get_inventory_quantities` (default NULL = current behavior) and pass it from
+`getItemQuantities` (`items.service.ts:740`). All three `itemLedger` CTEs and the
+PO/SO/job CTEs then filter to one item, using the new `(itemId, locationId)` index.
+~10-line SQL change, one TS call-site change.
+
+2d. **Fix `update-purchased-prices` 1000-row truncation** (`functions/update-purchased-prices/index.ts:239-246`).
+Replace the `select("*")` + JS aggregation with a single SQL aggregate
+(`SUM(cost)/SUM(quantity)` grouped by item, 12-month bound). Fixes the silent cap and
+removes the transfer of a year of rows per invoice post.
+
+2e. **Bound `getItemCostHistory`** (`items.service.ts:477`) with a LIMIT (e.g. 200) or
+keyset pagination like `getItemLedgerActivity`.
+
+2f. **Drop `count: "exact"` where it hurts**: `getJournalEntries` (aggregating view) and
+`getInventoryItems` should use `count: "estimated"` or a separate cheap count query
+(the pattern `getInventoryItemsCount` already uses).
+
+2g. **Take `itemLedger` out of the realtime publication** unless something actually
+subscribes to it (`20260624153001:35-45` added it for the stock-movements view; verify
+a subscriber exists — if the UI only revalidates on navigation, this is pure WAL cost
+on every posting).
+
+### Phase 3 — Snapshot + delta (the structural answer, one pattern used twice)
+
+The reason everything degrades with growth is "SUM since inception." The lowest-complexity
+durable fix is a **watermarked snapshot + tiny delta scan**, exploiting the fact that both
+ledgers are append-only and monotonic (`entryNumber` SERIAL on `itemLedger`;
+`postingDate`/period on GL). No triggers on the hot insert path, no dual-write logic —
+snapshots are built out-of-band and reads self-correct via the delta.
+
+**3a. GL: `accountingPeriodBalance` table.**
+
+```
+accountingPeriodBalance (
+ accountId, companyId, accountingPeriodId,
+ endingBalance NUMERIC(19,4),
+ endingBalanceAtDate DATE, -- period endDate
+ PK (accountId, companyId, accountingPeriodId)
+)
+```
+
+- Written when a period is **closed** (extend the existing close flow), and backfillable
+ by a one-shot statement per period: `INSERT ... SELECT accountId, SUM(amount) FROM
+ journalLine JOIN journal ... WHERE postingDate <= period.endDate` (cumulative, not
+ per-period net — so a read needs exactly one snapshot row).
+- Read path: `accountTreeBalancesByCompany` becomes
+ `snapshot.endingBalance + SUM(journalLine since snapshot date)` — pick the latest
+ closed-period snapshot ≤ `to_date`, scan only open-period lines. Falls back to the
+ current full scan when no snapshot exists (new companies work unchanged).
+- Because closed periods are immutable (posting into a closed period is already
+ disallowed), the snapshot can never drift; there is no invalidation problem. If a
+ reopen feature ever lands, "delete snapshots ≥ reopened period" is the entire
+ invalidation story.
+- This makes trial balance / balance sheet / income statement / tie-out GL-side cost
+ proportional to **one open period's lines**, forever.
+
+**3b. Inventory: watermark the existing `itemStockQuantities` matview.**
+
+- Add `MAX("entryNumber") AS "maxEntryNumber"` per group (or a single global watermark
+ row) to the matview definition (`20260420112047:359-385`). Refresh cadence unchanged.
+- Change the `item_ledgers` CTE in `get_inventory_quantities` (and
+ `get_inventory_value_by_location`) to:
+ `matview quantities + SUM(itemLedger WHERE entryNumber > watermark)` — exact,
+ real-time correct, and the live scan is only the last ≤30 minutes of postings.
+- The 30/90-day usage columns in `get_inventory_quantities` are already date-bounded;
+ they ride on the Phase 1 indexes and can stay live.
+- This reuses infrastructure that already exists (matview + pg_cron) rather than
+ resurrecting the dropped trigger-maintained `itemInventory` cache — no write-path
+ contention, no trigger complexity, and correctness doesn't depend on the refresh
+ succeeding (a stale matview just means a slightly bigger delta scan).
+
+**3c. (Optional, only if tie-out/aging pages are measurably slow after 3a):** replace the
+per-invoice correlated `invoiceSettlement` subqueries in `get_ar_tie_out`/`get_ap_tie_out`
+with a pre-aggregated `LEFT JOIN (SELECT invoiceId, SUM(...) GROUP BY invoiceId)`.
+
+### Explicit non-goals (rejected for complexity)
+
+- **Table partitioning** — operational burden, complicates RLS/FKs/PostgREST; snapshot+delta
+ removes the need.
+- **Trigger-maintained balance/quantity rollups on the insert path** — the project already
+ tried and removed this (`itemInventory`); it adds write contention and drift risk.
+- **Denormalizing `postingDate`/`status` onto `journalLine`** — helps, but Phase 3a makes
+ the full-history scan disappear anyway, so the dual-write isn't worth it.
+- **Composite `(id, companyId)` PK retrofit on ledger tables** — repo-standard elsewhere,
+ but a disruptive rewrite of FKs for no read-path benefit here.
+- **CQRS / event projections / read replicas** — out of proportion to the problem.
+
+## Sequencing & verification
+
+| Order | Item | Risk | Verification |
+|---|---|---|---|
+| 1 | Phase 1 migration | none (additive) | `EXPLAIN ANALYZE` the issue-path SUM and `journalEntries` view before/after on a seeded DB; confirm index-only scan on `itemLedger_itemId_locationId_idx` |
+| 2 | 2d (correctness) + 2a (correctness) | low | unit-compare weighted avg vs full-history SQL; trial balance excludes a Draft journal fixture |
+| 3 | 2b, 2c, 2e, 2f, 2g | low | statement pages return identical numbers; item detail loader issues single-item RPC |
+| 4 | 3a GL snapshots | medium | snapshot+delta trial balance === full-scan trial balance on seeded history; close/backfill idempotent |
+| 5 | 3b matview watermark | medium | `get_inventory_quantities` delta result === current full-scan result, before and after a fresh posting |
+
+Rules to follow while implementing: `.ai/rules/workflow-database-migration.md`,
+`.ai/rules/database-migration-patterns.md` (view/function redefinition),
+migrations idempotent, randomized HHMMSS in filenames, `pnpm run generate:types`
+after any schema change, and function redefinitions forked from the latest version.
diff --git a/.ai/plans/2026-07-02-ledger-snapshot-delta.md b/.ai/plans/2026-07-02-ledger-snapshot-delta.md
new file mode 100644
index 0000000000..37b4064f3b
--- /dev/null
+++ b/.ai/plans/2026-07-02-ledger-snapshot-delta.md
@@ -0,0 +1,302 @@
+# Phase 3: Snapshot + Delta for Ledger Balances
+
+Date: 2026-07-02
+Status: IMPLEMENTED on `perf/ledger-queries` (migrations `20260713232634`,
+`20260713233919`, `20260713235406`), with two deviations from the design below:
+
+1. **Inventory watermark is `createdAt < now() - 1 hour`, not `entryNumber`.**
+ SERIAL values don't respect commit order, so an entryNumber watermark can
+ permanently miss a row that commits after the matview refresh with a lower
+ sequence value. `createdAt` is transaction start time, so the 1-hour cutoff
+ is race-free as long as no write transaction runs longer than an hour.
+2. **New private `itemLedgerSnapshot` matview instead of modifying
+ `itemStockQuantities`** — RealtimeDataProvider consumes `itemStockQuantities`
+ directly as the UI item-store on-hand total, so its shape and semantics must
+ not change. The new matview is REVOKEd from anon/authenticated and only read
+ inside the SECURITY DEFINER functions.
+
+What remains for the period-closing branch (workstream A's close hook):
+- Call `snapshotAccountingPeriodBalances(companyId, periodId, userId)` inside
+ the close transaction.
+- Enforce the two invariants (postingDate cannot land in a closed period —
+ checked on postingDate, not just accountingPeriodId; periods close in order).
+- On reopen: `DELETE FROM "accountingPeriodBalance" WHERE "companyId" = ? AND
+ "endingBalanceDate" >= (SELECT "endDate" FROM "accountingPeriod" WHERE "id" = ?)`.
+
+Until snapshots are written, the read path takes the identical full-scan
+fallback (verified by equivalence tests) — zero behavior change. Original
+design follows.
+
+Prerequisite: the Phase 1/2 migrations (`20260713224517_ledger-performance-indexes.sql`, `20260713225803_ledger-balance-posted-filter.sql`, `20260713231142_inventory-quantities-item-filter.sql`) — the read-path changes below assume the `Draft`-exclusion semantics and the new indexes.
+Context: `.ai/plans/2026-07-02-ledger-query-performance.md` (the audit). The problem being solved: every GL balance and every on-hand quantity is a SUM over the full ledger history, so statement/inventory reads degrade linearly with ledger size. The fix is one pattern used twice — **an immutable snapshot plus a small live delta** — with no triggers on the posting path and no dual writes.
+
+---
+
+## Workstream A — GL: `accountingPeriodBalance`
+
+### Design
+
+One row per (leaf account, company, closed period) holding the **cumulative** balance through that period's `endDate` (not the per-period net — so a read needs exactly one snapshot row, not a running sum of them).
+
+Correctness rests on two invariants the period-closing branch must enforce:
+
+1. **Closed periods are immutable** — posting into a closed period is rejected (the ERP-side `getOrCreateAccountingPeriod` already checks this; make sure the edge functions' `getCurrentAccountingPeriod` path can't land in a closed period either).
+2. **Periods close in order** — a period cannot be closed while an earlier period for the same company is still open. Without this, a snapshot could be taken while backdated postings are still possible before its `endDate`.
+
+Given those, a snapshot can never drift. If reopen is supported: reopening period N deletes snapshots for **all periods ≥ N** for that company (they're cumulative, so later snapshots embed period N's data). That one DELETE is the entire invalidation story.
+
+### Task A1 — Table migration
+
+`pnpm db:migrate:new accounting-period-balance` (randomize HHMMSS; never `000000`).
+
+```sql
+CREATE TABLE "accountingPeriodBalance" (
+ "id" TEXT NOT NULL DEFAULT id('apb'),
+ "companyId" TEXT NOT NULL,
+ "accountingPeriodId" TEXT NOT NULL,
+ "accountId" TEXT NOT NULL REFERENCES "account"("id"),
+ -- cumulative balance through the period's endDate, Draft journals excluded
+ "endingBalance" NUMERIC NOT NULL DEFAULT 0,
+ -- denormalized period endDate so reads don't join accountingPeriod
+ "endingBalanceDate" DATE 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,
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("accountingPeriodId") REFERENCES "accountingPeriod"("id") ON DELETE CASCADE
+);
+
+CREATE UNIQUE INDEX "accountingPeriodBalance_account_period_key"
+ ON "accountingPeriodBalance" ("accountId", "accountingPeriodId", "companyId");
+-- the read path's lookup: latest snapshot per account at or before a date
+CREATE INDEX "accountingPeriodBalance_companyId_date_idx"
+ ON "accountingPeriodBalance" ("companyId", "accountId", "endingBalanceDate" DESC);
+CREATE INDEX "accountingPeriodBalance_companyId_idx" ON "accountingPeriodBalance" ("companyId");
+CREATE INDEX "accountingPeriodBalance_accountingPeriodId_idx" ON "accountingPeriodBalance" ("accountingPeriodId");
+CREATE INDEX "accountingPeriodBalance_createdBy_idx" ON "accountingPeriodBalance" ("createdBy");
+```
+
+RLS: standard four policies, `accounting_view` for SELECT (match `journal`'s tightened read, not the generic employee-role read), `accounting_create/update/delete` for writes. Bare `NUMERIC` (house rule — no precision spec).
+
+### Task A2 — Snapshot function, called from the close action
+
+Same migration or a sibling. SECURITY DEFINER so the close action (route → Kysely transaction) can call it via `trx` or `client.rpc`:
+
+```sql
+CREATE OR REPLACE FUNCTION "snapshotAccountingPeriodBalances" (
+ p_company_id TEXT,
+ p_period_id TEXT,
+ p_user_id TEXT
+) RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path = public
+AS $$
+DECLARE
+ v_end_date DATE;
+BEGIN
+ SELECT "endDate" INTO v_end_date FROM "accountingPeriod"
+ WHERE "id" = p_period_id AND "companyId" = p_company_id;
+
+ INSERT INTO "accountingPeriodBalance"
+ ("companyId", "accountingPeriodId", "accountId", "endingBalance", "endingBalanceDate", "createdBy")
+ SELECT
+ p_company_id, p_period_id, a."id",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" <= v_end_date
+ THEN jl."amount" ELSE 0 END), 0),
+ v_end_date, p_user_id
+ FROM "account" a
+ LEFT JOIN "journalLine" jl ON jl."accountId" = a."id" AND jl."companyId" = p_company_id
+ LEFT JOIN "journal" j ON j."id" = jl."journalId"
+ WHERE a."isGroup" = false AND a."active" = true
+ AND a."companyGroupId" = (SELECT "companyGroupId" FROM "company" WHERE "id" = p_company_id)
+ GROUP BY a."id"
+ ON CONFLICT ("accountId", "accountingPeriodId", "companyId")
+ DO UPDATE SET "endingBalance" = EXCLUDED."endingBalance",
+ "endingBalanceDate" = EXCLUDED."endingBalanceDate",
+ "updatedBy" = p_user_id, "updatedAt" = NOW();
+END;
+$$;
+```
+
+This is the **last** full-history scan a period will ever need — it runs once, at close time, inside the close transaction. Wire it into the period-close action (wherever the close flow sets `closedAt`/`closedBy`/status), in the same Kysely transaction, after the in-order + no-open-drafts checks. If reopen exists, the reopen action runs:
+`DELETE FROM "accountingPeriodBalance" WHERE "companyId" = ? AND "endingBalanceDate" >= (SELECT "endDate" FROM "accountingPeriod" WHERE "id" = ?)`.
+
+### Task A3 — Read path: snapshot + delta in `accountTreeBalancesByCompany`
+
+New migration forking the Phase-2 definition (`20260713225803_ledger-balance-posted-filter.sql`). Signature and return type unchanged. Replace `leafBalances` with:
+
+```sql
+ "latestSnapshot" AS (
+ -- newest snapshot per account (for `balance`, which is unbounded)
+ SELECT DISTINCT ON (s."accountId")
+ s."accountId", s."endingBalance", s."endingBalanceDate"
+ FROM "accountingPeriodBalance" s
+ WHERE s."companyId" = p_company_id
+ ORDER BY s."accountId", s."endingBalanceDate" DESC
+ ),
+ "snapshotAtDate" AS (
+ -- newest snapshot per account at or before to_date (for balanceAtDate)
+ SELECT DISTINCT ON (s."accountId")
+ s."accountId", s."endingBalance", s."endingBalanceDate"
+ FROM "accountingPeriodBalance" s
+ WHERE s."companyId" = p_company_id AND s."endingBalanceDate" <= to_date
+ ORDER BY s."accountId", s."endingBalanceDate" DESC
+ ),
+ "snapshotBeforeFrom" AS (
+ -- newest snapshot per account strictly before from_date (for netChange)
+ SELECT DISTINCT ON (s."accountId")
+ s."accountId", s."endingBalance", s."endingBalanceDate"
+ FROM "accountingPeriodBalance" s
+ WHERE s."companyId" = p_company_id AND s."endingBalanceDate" < from_date
+ ORDER BY s."accountId", s."endingBalanceDate" DESC
+ ),
+ "leafBalances" AS (
+ SELECT
+ a."id" AS "accountId",
+ COALESCE(ls."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN j."status" <> 'Draft'
+ AND (ls."endingBalanceDate" IS NULL OR j."postingDate" > ls."endingBalanceDate")
+ THEN jl."amount" ELSE 0 END), 0) AS "balance",
+ COALESCE(sad."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN j."status" <> 'Draft'
+ AND (sad."endingBalanceDate" IS NULL OR j."postingDate" > sad."endingBalanceDate")
+ AND j."postingDate" <= to_date
+ THEN jl."amount" ELSE 0 END), 0) AS "balanceAtDate",
+ -- netChange(from,to) = balanceAtDate(to) − balance just before from_date
+ (COALESCE(sad."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN j."status" <> 'Draft'
+ AND (sad."endingBalanceDate" IS NULL OR j."postingDate" > sad."endingBalanceDate")
+ AND j."postingDate" <= to_date
+ THEN jl."amount" ELSE 0 END), 0))
+ - (COALESCE(sbf."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN j."status" <> 'Draft'
+ AND (sbf."endingBalanceDate" IS NULL OR j."postingDate" > sbf."endingBalanceDate")
+ AND j."postingDate" < from_date
+ THEN jl."amount" ELSE 0 END), 0)) AS "netChange"
+ FROM "account" a
+ LEFT JOIN "latestSnapshot" ls ON ls."accountId" = a."id"
+ LEFT JOIN "snapshotAtDate" sad ON sad."accountId" = a."id"
+ LEFT JOIN "snapshotBeforeFrom" sbf ON sbf."accountId" = a."id"
+ LEFT JOIN "journalLine" jl ON jl."accountId" = a."id"
+ AND jl."companyId" = p_company_id
+ -- delta only: rows can be skipped once they're inside the oldest snapshot needed
+ AND ... -- see note below
+ 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", ls."endingBalance", ls."endingBalanceDate",
+ sad."endingBalance", sad."endingBalanceDate",
+ sbf."endingBalance", sbf."endingBalanceDate"
+ )
+```
+
+Implementation notes the executor must respect:
+
+- **Scope guard**: apply the snapshot path only when `p_company_id IS NOT NULL`. When it's NULL (group-wide, and in `accountTreeBalances` used by the chart of accounts), keep the Phase-2 full-scan body — snapshots are per company. All the hot statement paths (`getFinancialStatementBalances`, `getConsolidatedBalances`, `trialBalance`) pass a company id. Easiest structure: `IF p_company_id IS NULL THEN RETURN QUERY <phase-2 body>; ELSE RETURN QUERY <snapshot body>; END IF;`
+- **The join pruning is the whole point**: the `journalLine` join must be restricted so Postgres only reads lines after the oldest snapshot date used by that query, i.e. `j."postingDate" > LEAST(ls/sad/sbf dates)` — in practice, since journalLine has no postingDate, express it via the join to `journal` using the `journal_companyId_postingDate_idx` from Phase 1: pre-filter journals in a CTE (`SELECT id FROM journal WHERE companyId = p_company_id AND postingDate > <min snapshot date> AND status <> 'Draft'`) and join lines through it. If every account's needed snapshot exists, the min snapshot date is the last closed period boundary — the delta is one open period's lines. Verify with `EXPLAIN ANALYZE` that the plan reads the journal date index, not all of `journalLine`.
+- **Fallback**: an account with no snapshot rows (new company, never closed a period) gets `endingBalanceDate NULL` and the CASE degrades to the full scan — current behavior, no regression.
+- Consider denormalizing `postingDate`/`status` onto `journalLine` ONLY if the journal-id-list join proves awkward in EXPLAIN — it was rejected in the audit as unnecessary; re-justify before doing it.
+
+### Task A4 — Verification
+
+On a seeded DB with history (or a restored backup):
+
+```sql
+-- 1. Close a period, snapshot, then compare snapshot+delta vs brute force:
+SELECT * FROM "accountTreeBalancesByCompany"('<group>', '<company>', '<from>', '<to>')
+EXCEPT
+SELECT * FROM <phase-2 full-scan variant with same args>;
+-- expected: 0 rows, both directions (run EXCEPT both ways)
+
+-- 2. EXPLAIN ANALYZE the new function's query at a date after the last closed period:
+-- expected: journalLine rows read ≈ open-period line count, not total line count.
+
+-- 3. Reopen (if supported) → snapshots for ≥ that period deleted → results still match brute force.
+```
+
+Plus `pnpm run generate:types` after migrations, `pnpm exec turbo run typecheck --filter=./apps/erp`, and existing accounting tests.
+
+---
+
+## Workstream B — Inventory: watermarked snapshot for on-hand
+
+### Design
+
+`itemLedger.entryNumber` is a global monotonic SERIAL, so any row not in a materialized snapshot has `entryNumber` greater than the snapshot's per-group max. That makes `matview + delta WHERE entryNumber > watermark` **exact** for immutable rows.
+
+The wrinkle: itemLedger rows are *not* all immutable — `sync_item_ledger_on_tracked_entity_status_change_trigger` (migration `20260420112047`) rewrites `trackedEntityStatus` on existing rows when a tracked entity's status flips, and the status-aware sums (`quantityOnHand` excludes `Rejected`, `quantityOnHold`, `quantityRejected`) depend on it. Snapshotting those rows would serve up-to-30-minute-stale status math, which is not acceptable for on-hand (it could hide a rejection from an issue/pick decision).
+
+So split by mutability:
+
+- **Untracked rows (`trackedEntityId IS NULL`) are append-only and immutable** → snapshot them in the matview with a watermark; live reads add only the delta.
+- **Tracked rows (`trackedEntityId IS NOT NULL`) are mutable** → always computed live. They're already the smaller, better-indexed subset (partial `itemLedger_trackedEntityId_idx`, plus the Phase-1 composite indexes), and tracked-entity quantities are inherently bounded by physical serial/batch counts.
+
+### Task B1 — Redefine the matview with scope + watermark
+
+New migration. Current definition: `20260420112047_inventory-quantity-status-aware.sql:359-385`; pg_cron job `refresh-item-stock-quantities` (every 30 min, CONCURRENTLY) stays as is.
+
+```sql
+DROP MATERIALIZED VIEW IF EXISTS "itemStockQuantities";
+CREATE MATERIALIZED VIEW "itemStockQuantities" AS
+SELECT
+ "itemId",
+ "companyId",
+ COALESCE("locationId", '') AS "locationId",
+ SUM("quantity") AS "quantityOnHand", -- untracked rows have no status; plain sum
+ MAX("entryNumber") AS "maxEntryNumber",
+ -- usage snapshots (informational; see note)
+ SUM(CASE WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND "createdAt" >= CURRENT_DATE - INTERVAL '30 days' THEN -"quantity" ELSE 0 END) AS "consumed30",
+ SUM(CASE WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND "createdAt" >= CURRENT_DATE - INTERVAL '90 days' THEN -"quantity" ELSE 0 END) AS "consumed90"
+FROM "itemLedger"
+WHERE "trackedEntityId" IS NULL
+GROUP BY "itemId", "companyId", COALESCE("locationId", '');
+-- recreate the UNIQUE index (needed for REFRESH CONCURRENTLY) + companyId index
+```
+
+Check for other consumers of the matview's current columns before changing its shape (as of the audit it was refreshed by cron but not read by the hot RPCs — grep first).
+
+### Task B2 — Snapshot + delta in `get_inventory_quantities`
+
+Fork the latest definition (`20260713231142_inventory-quantities-item-filter.sql` after Phase 2). Replace the `item_ledgers` CTE's on-hand terms with:
+
+```
+quantityOnHand = COALESCE(matview.quantityOnHand, 0) -- untracked snapshot
+ + SUM(untracked delta rows: trackedEntityId IS NULL
+ AND entryNumber > COALESCE(matview.maxEntryNumber, 0))
+ + SUM(tracked rows live, status != 'Rejected') -- always live
+quantityOnHold = SUM(tracked rows live, status = 'On Hold') -- unchanged, tracked-only
+quantityRejected= SUM(tracked rows live, status = 'Rejected') -- unchanged, tracked-only
+```
+
+The tracked-rows scan and the untracked delta both filter `companyId + locationId (+ itemId)` — served by the Phase-1 `itemLedger_companyId_locationId_itemId_idx` / `itemLedger_itemId_locationId_idx` indexes; the tracked subset additionally benefits from being small. `usageLast30Days/90Days`: take `consumed30/90` from the matview + the same terms over delta + tracked rows. These are informational metrics; the snapshot's window edge is up to 30 minutes stale (rows aging out of the 30/90-day window between refreshes are still counted) — acceptable, document it in the function header comment.
+
+Apply the same pattern to `get_inventory_value_by_location` (`20260325031223`) and — only if EXPLAIN shows it matters — `get_job_quantity_on_hand`. Do NOT change the `issue`/`storage-units` per-item SUMs in the edge functions: after Phase 1 they're index-only scans and they need exact per-storage-unit math; revisit only with production EXPLAIN evidence.
+
+### Task B3 — Verification
+
+```sql
+-- 1. Equivalence, before and after a fresh posting (i.e. with a non-empty delta):
+SELECT * FROM get_inventory_quantities('<company>', '<location>')
+EXCEPT SELECT * FROM <old definition run side-by-side>; -- 0 rows, both directions
+-- 2. Flip a tracked entity to Rejected → quantityOnHand reflects it IMMEDIATELY (no refresh).
+-- 3. EXPLAIN ANALYZE: untracked scan reads only rows above the watermark.
+-- 4. REFRESH MATERIALIZED VIEW CONCURRENTLY "itemStockQuantities" still works (unique index present).
+```
+
+Browser check per house rule: item detail page and Inventory quantities table show identical numbers before/after, including immediately after posting a receipt (delta path) and after a matview refresh.
+
+---
+
+## Sequencing
+
+1. A1 + A2 land with the period-close feature itself (snapshot written at close).
+2. A3 read path next — it's a pure optimization; ship after A4's equivalence proof.
+3. B1/B2 are independent of A entirely and can land in a separate PR.
+4. Update `.ai/rules/accounting-sync-handlers.md` / `modules/accounting/AGENTS.md` / `inventory-system.md` for the new table, function behavior, and matview shape (keep-sources-in-sync rule).
+
+## Non-goals (carried from the audit)
+
+No partitioning, no trigger-maintained rollups on the insert path (the dropped `itemInventory` cache is the cautionary precedent), no `postingDate` denormalization onto `journalLine` unless A3's EXPLAIN forces the question, no CQRS.
diff --git a/.ai/rules/inventory-system.md b/.ai/rules/inventory-system.md
index be00025904..65dd836a7b 100644
--- a/.ai/rules/inventory-system.md
+++ b/.ai/rules/inventory-system.md
@@ -46,8 +46,14 @@ Validators in `inventory.models.ts`: `inventoryAdjustmentValidator`, `receiptVal
`documentType` (`itemLedgerDocumentType`), `postingDate`, `itemId`, `locationId`,
`storageUnitId`, `quantity`, `trackedEntityId`, and `trackedEntityStatus` (denormalized from
`trackedEntity.status` — added `20260420112047`, lets reads filter status without a JOIN).
-- **`itemInventory`** — denormalized per-(item, location, storageUnit) aggregate (`quantityOnHand`,
- `quantityOnPurchase`, `quantityOnSalesOrder`, `quantityOnProductionOrder`), trigger-maintained.
+- **`itemLedgerSnapshot`** (matview, `20260713235406`) — snapshot of the immutable UNTRACKED
+ ledger rows (`trackedEntityId IS NULL`, `createdAt` older than 1h) per item/company/location:
+ `quantity`, `consumed30/90`, `storageUnitIds`, `snapshotCutoff`. pg_cron refresh every 30 min.
+ Read only inside the SECURITY DEFINER quantity functions (REVOKEd from PostgREST roles); live
+ reads add rows past `snapshotCutoff` plus ALL tracked rows, so results stay exact. Distinct
+ from `itemStockQuantities` (the approximate UI item-store matview used by RealtimeDataProvider).
+ The old `itemInventory` rollup table is DEAD — its maintaining trigger was dropped in
+ `20250209170952_shipment.sql`; don't read or write it.
- **`storageUnit`** — bins/locations. Renamed from `shelf` (`20260417000100`); supports nesting via
`parentId` and `storageTypeIds TEXT[]` (`20260417000200`). Cols: `id`, `name`, `locationId`,
`warehouseId`, `parentId`, `storageTypeIds`, `active`.
@@ -62,8 +68,9 @@ Validators in `inventory.models.ts`: `inventoryAdjustmentValidator`, `receiptVal
- **`itemPlanning`** / **`itemReplenishment`** — reorder/planning params and replenishment strategy.
- **`storageRule`** + assignment tables — renamed from `customRule`/`itemRule` (`20260603130000`).
-`get_inventory_quantities(company_id TEXT, location_id TEXT)` — the central read. Newest definition is
-`20260512130000_inventory-storage-unit-filter.sql` (NOT the old-doc's 2025 migration). Returns ~52 cols:
+`get_inventory_quantities(company_id TEXT, location_id TEXT, item_id TEXT DEFAULT NULL)` — the central
+read. Newest definition is `20260713235406_item-ledger-snapshot.sql` (snapshot + delta via
+`itemLedgerSnapshot`; `item_id` restricts to one item for detail-page loads). Returns ~52 cols:
item identity + material props, planning fields, and quantities `quantityOnHand`, `quantityOnHold`,
`quantityRejected` (status-aware: excludes `Rejected`, surfaces `On Hold`), `quantityOnSalesOrder`,
`quantityOnPurchaseOrder`, `quantityOnProductionOrder`, `quantityOnProductionDemand`, `demandForecast`,
@@ -81,10 +88,12 @@ Relevant enums: `itemLedgerType`, `itemLedgerDocumentType`, `trackedEntityStatus
`customRule`→`storageRule`. Grep the NEWEST migration for the real name; never trust an older one or the
old cache. The `shelf`→`storageUnit` rename was split across paired migrations
`20260417000100` (rename, M2) + `..000300` (recreate dependents, M4) — they must apply together.
-- **`get_inventory_quantities` has many revisions.** Always read the newest (`20260512130000`), not the
- first match. `quantityOnHand` is status-aware: `Rejected` tracked entities are excluded.
+- **`get_inventory_quantities` has many revisions.** Always read the newest (`20260713235406`), not the
+ first match. `quantityOnHand` is status-aware: `Rejected` tracked entities are excluded, and tracked
+ rows are always computed live (never from `itemLedgerSnapshot`) so status flips are never stale.
- **The auto-generated MCP reference (`.ai/rules/mcp-tools-reference.md`) is stale** for storage units —
it still lists `getShelf`/`getDefaultShelfForJob`. The real service exports `getStorageUnit*` /
`getDefaultStorageUnitForJob`. Trust the service file.
- On-hand math comes from `itemLedger` (and the `get_inventory_quantities` RPC), not from summing
- `trackedEntity` directly; `itemInventory` is a trigger-maintained cache, not authoritative.
+ `trackedEntity` directly. The old `itemInventory` table is orphaned (trigger dropped
+ `20250209170952`) — never read or write it.
diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.md
index c3470ac8ce..e085927036 100644
--- a/apps/erp/app/modules/accounting/AGENTS.md
+++ b/apps/erp/app/modules/accounting/AGENTS.md
@@ -49,6 +49,7 @@ pnpm --filter @carbon/erp test -- --testPathPattern=accounting
| `journal` / `journalLine` | Double-entry transactions; lines carry dimension assignments |
| `journalLineDimension` | Dimension values assigned to journal lines |
| `accountingPeriod` | Fiscal periods. `closeStatus` (`periodCloseStatus`: Open→Locked→Closed lifecycle), `fiscalYear`/`periodNumber` (identity from the fiscal start month), `lockedAt`/`lockedBy`. Legacy `status` (Active/Inactive) is deprecated. |
+| `accountingPeriodBalance` | Cumulative per-account GL balance snapshots. `closeAccountingPeriod` calls `snapshotAccountingPeriodBalances` inside its close transaction (after the flip to Closed) to write them; `reopenAccountingPeriod` deletes them (`endingBalanceDate` ≥ period `endDate`) before flipping back to Open. Read by `accountTreeBalancesByCompany` (snapshot + delta; full-scan fallback when empty). Balance RPCs exclude Draft journals. |
| `periodCloseTaskDefinition` / `periodCloseTask` | NetSuite-style close checklist: company-level task templates + per-period instances (seeded via `seed-company`) |
| `accountDefault` | Default GL account mappings (AR, AP, inventory, etc.) |
| `currency` / `currencyCode` / `exchangeRateHistory` | Multi-currency with historical rates |
diff --git a/apps/erp/app/modules/accounting/accounting.periods.test.ts b/apps/erp/app/modules/accounting/accounting.periods.test.ts
index 0da8e5b80d..0e297c0ccf 100644
--- a/apps/erp/app/modules/accounting/accounting.periods.test.ts
+++ b/apps/erp/app/modules/accounting/accounting.periods.test.ts
@@ -120,6 +120,37 @@ function makeRecordingClient(responses: Scripted[]) {
// result and returns `{ id: periodId }` on a clean transaction.
function makeKyselyRecorder() {
const updates: { table: string; values: any }[] = [];
+ // Raw statements executed on the transaction. The close path snapshots GL
+ // balances via `sql`SELECT "snapshotAccountingPeriodBalances"(...)`.execute(trx)`
+ // after the period flip, so `tx` must satisfy Kysely's RawBuilder.execute
+ // (which reads `trx.getExecutor()`). We don't parse the SQL — recording that a
+ // raw statement ran is enough to assert the snapshot fired. The executor is a
+ // Proxy so it tolerates whatever internal methods RawBuilder.execute calls.
+ const rawExecutions: unknown[] = [];
+ const executor = new Proxy(
+ {},
+ {
+ get(_t, prop) {
+ if (prop === "executeQuery")
+ return async (compiled: unknown) => {
+ rawExecutions.push(compiled);
+ return { rows: [] };
+ };
+ if (prop === "transformQuery") return (node: unknown) => node;
+ if (prop === "compileQuery")
+ return (node: unknown) => ({ sql: "", parameters: [], query: node });
+ if (prop === "provideConnection")
+ return async (fn: (c: unknown) => unknown) =>
+ fn({
+ executeQuery: async (compiled: unknown) => {
+ rawExecutions.push(compiled);
+ return { rows: [] };
+ }
+ });
+ return () => undefined;
+ }
+ }
+ );
const tx = {
updateTable(table: string) {
const builder: any = {
@@ -131,7 +162,8 @@ function makeKyselyRecorder() {
execute: () => Promise.resolve([])
};
return builder;
- }
+ },
+ getExecutor: () => executor
};
const db: any = {
transaction: () => ({
@@ -140,7 +172,7 @@ function makeKyselyRecorder() {
}
})
};
- return { db, updates };
+ return { db, updates, rawExecutions };
}
const args = { periodId: "P2", companyId: "C1", userId: "U1" };
@@ -332,13 +364,17 @@ describe("closePeriodWithChecklist — Blocker gate + Auto-task persistence", ()
{ count: 0 } // readiness: draft memos
]);
// The task persist + period flip both run inside the Kysely transaction.
- const { db, updates: txUpdates } = makeKyselyRecorder();
+ const { db, updates: txUpdates, rawExecutions } = makeKyselyRecorder();
const result = await closePeriodWithChecklist(client, db, args);
expect(result.error).toBeNull();
expect(result.data).toEqual({ id: "P2" });
+ // The GL balance snapshot is written (snapshotAccountingPeriodBalances) via a
+ // raw statement inside the same transaction, after the period is flipped.
+ expect(rawExecutions.length).toBeGreaterThan(0);
+
// Final Auto-task state persisted to periodCloseTask as Done.
const taskUpdate = txUpdates.find((u) => u.table === "periodCloseTask");
expect(taskUpdate?.values.status).toBe("Done");
@@ -508,8 +544,16 @@ describe("reopenAccountingPeriod — reverse-sequential reopen", () => {
it("allows reopening when no later period is Closed", async () => {
const client = makeClient([
- { data: { id: "P2", startDate: "2026-02-01", closeStatus: "Closed" } },
+ {
+ data: {
+ id: "P2",
+ startDate: "2026-02-01",
+ endDate: "2026-02-28",
+ closeStatus: "Closed"
+ }
+ },
{ count: 0 }, // no later closed periods
+ { error: null }, // delete cumulative snapshots (invariant #3)
{ data: { id: "P2" }, error: null } // update
]);
@@ -518,6 +562,86 @@ describe("reopenAccountingPeriod — reverse-sequential reopen", () => {
expect(result.error).toBeNull();
expect(result.data).toEqual({ id: "P2" });
});
+
+ // Records which table each terminal op hit, so we can assert the reopen both
+ // deletes the stale cumulative snapshots and orders the delete before the flip.
+ function makeReopenTracker(responses: Scripted[]) {
+ const ops: string[] = [];
+ let i = 0;
+ const next = () => responses[i++] ?? { data: null, error: null };
+ const makeBuilder = (table: string) => {
+ const builder: any = {
+ select: () => builder,
+ update: () => {
+ ops.push(`update:${table}`);
+ return builder;
+ },
+ delete: () => {
+ ops.push(`delete:${table}`);
+ return builder;
+ },
+ eq: () => builder,
+ neq: () => builder,
+ gt: () => builder,
+ gte: () => builder,
+ lt: () => builder,
+ lte: () => builder,
+ or: () => builder,
+ order: () => builder,
+ limit: () => builder,
+ single: () => Promise.resolve(next()),
+ then: (resolve: (v: Scripted) => unknown) => resolve(next())
+ };
+ return builder;
+ };
+ return { client: { from: (t: string) => makeBuilder(t) } as any, ops };
+ }
+
+ it("deletes cumulative snapshots at/after the period end before flipping to Open", async () => {
+ const { client, ops } = makeReopenTracker([
+ {
+ data: {
+ id: "P2",
+ startDate: "2026-02-01",
+ endDate: "2026-02-28",
+ closeStatus: "Closed"
+ }
+ },
+ { count: 0 }, // no later closed periods
+ { error: null }, // delete snapshots
+ { data: { id: "P2" }, error: null } // update
+ ]);
+
+ const result = await reopenAccountingPeriod(client, args);
+
+ expect(result.error).toBeNull();
+ // Snapshot rows are cleared, and the delete precedes the status flip.
+ expect(ops).toEqual([
+ "delete:accountingPeriodBalance",
+ "update:accountingPeriod"
+ ]);
+ });
+
+ it("aborts the reopen (period stays Closed) if snapshot deletion fails", async () => {
+ const { client, ops } = makeReopenTracker([
+ {
+ data: {
+ id: "P2",
+ startDate: "2026-02-01",
+ endDate: "2026-02-28",
+ closeStatus: "Closed"
+ }
+ },
+ { count: 0 }, // no later closed periods
+ { error: { message: "snapshot delete failed" } } // delete fails
+ ]);
+
+ const result = await reopenAccountingPeriod(client, args);
+
+ expect(result.error?.message).toBe("snapshot delete failed");
+ // The period was never flipped — no update issued after the failed delete.
+ expect(ops).toEqual(["delete:accountingPeriodBalance"]);
+ });
});
// ---------------------------------------------------------------------------
diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.ts
index 5b5a65bdd7..b91770536d 100644
--- a/apps/erp/app/modules/accounting/accounting.service.ts
+++ b/apps/erp/app/modules/accounting/accounting.service.ts
@@ -10,6 +10,7 @@ import {
toStoredAmount
} from "@carbon/utils";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
+import { sql } from "kysely";
import type { z } from "zod";
import { getNextSequence } from "~/modules/settings";
import type { GenericQueryFilters } from "~/utils/query";
@@ -157,14 +158,15 @@ export async function getAccountLedger(
offset: number;
}
) {
- // The journalLines view excludes Draft journals so that the lines shown
- // always sum to the balances from accountTreeBalancesByCompany (which also
- // excludes Draft journals).
+ // Draft journals are excluded so the lines shown always sum to the balances
+ // from accountTreeBalancesByCompany, which excludes them too — unposted
+ // entries belong in the Journal Entries list, not the account ledger.
// TODO: remove the cast once cloud-generated DB types include the view.
let query = client
.from("journalLines" as any)
.select("*", { count: "exact" })
.eq("accountId", args.accountId)
+ .neq("status", "Draft")
.gte(
"postingDate",
args.startDate ?? getDateNYearsAgo(50).toISOString().split("T")[0]
@@ -1034,6 +1036,28 @@ export async function closeAccountingPeriod(
.where("id", "=", args.periodId)
.where("companyId", "=", args.companyId)
.execute();
+
+ // Write the per-account cumulative GL balance snapshot for this period
+ // *inside* the close transaction, after the flip to Closed. The snapshot
+ // is what makes accountTreeBalancesByCompany read "latest snapshot +
+ // lines after it" instead of scanning all history. It runs here (not as
+ // a supabase RPC) so it stays private to the service-role/Kysely path —
+ // the function is SECURITY DEFINER and takes companyId as an argument, so
+ // exposing it via PostgREST would be a cross-tenant write. The function
+ // asserts the period is Closed (true within this tx's view), so it can
+ // never snapshot a still-postable period.
+ //
+ // Race safety: the flip above holds the accountingPeriod row lock until
+ // commit, and check_accounting_period_open reads that row FOR SHARE on
+ // every posting (migration 20260713235930), so no journal can land in the
+ // period between this snapshot and the commit. Keeping the snapshot in the
+ // same transaction is deliberate: close ⇔ snapshot is atomic, so a snapshot
+ // failure rolls the whole close back cleanly rather than leaving a Closed
+ // period with a stale/absent snapshot. Any period without a snapshot is
+ // still correct — the read path falls back to the full-history scan.
+ await sql`SELECT "snapshotAccountingPeriodBalances"(${args.companyId}, ${args.periodId}, ${args.userId})`.execute(
+ trx
+ );
});
} catch (err) {
return {
@@ -1101,6 +1125,24 @@ export async function reopenAccountingPeriod(
};
}
+ // Invariant #3 (accountingPeriodBalance migration): snapshots are cumulative
+ // through their period's endDate, so reopening this period invalidates its own
+ // snapshot and any later one that embeds it. Delete them BEFORE flipping to
+ // Open: if the delete fails we abort with the period still Closed (snapshots
+ // intact, consistent); if the flip later fails, the period stays Closed with
+ // no snapshots, so reads fall back to the full scan (correct, just slower)
+ // rather than trusting a stale snapshot once postings resume in the period.
+ // accountingPeriodBalance is not in the cloud-generated DB types yet, so the
+ // client is cast to reach it (same reason the period reads above use `as any`).
+ const deletedSnapshots = await (client as any)
+ .from("accountingPeriodBalance")
+ .delete()
+ .eq("companyId", args.companyId)
+ .gte("endingBalanceDate", period.data.endDate);
+ if (deletedSnapshots.error) {
+ return { data: null, error: deletedSnapshots.error };
+ }
+
return (client.from("accountingPeriod") as any)
.update({
closeStatus: "Open",
@@ -2633,46 +2675,93 @@ export async function translateCompanyBalances(
companyId: string,
targetCurrency: string,
periodEnd: string,
- periodStart?: string
+ periodStart: string | undefined,
+ // Rows from getFinancialStatementBalances for the same company/dates —
+ // translation only needs balanceAtDate + consolidatedRate, so re-running
+ // the full journalLine scan through the translateTrialBalance RPC would
+ // double the cost of every translated statement.
+ balances: Array<{
+ id: string;
+ balanceAtDate: number;
+ consolidatedRate: string | null;
+ isGroup: boolean | null;
+ class: string | null;
+ }>
): Promise<{
data: TranslatedBalance[] | null;
cta: number;
error: string | null;
}> {
- const { data, error } = await client.rpc("translateTrialBalance", {
+ // getConsolidationRates is defined in migration
+ // 20260713225803_ledger-balance-posted-filter.sql; the committed DB types
+ // regenerate from the cloud DB after deploy, hence the cast.
+ const { data: ratesData, error: ratesError } = await (
+ client.rpc as unknown as (
+ fn: string,
+ args: Record<string, unknown>
+ ) => PromiseLike<{ data: unknown; error: { message: string } | null }>
+ )("getConsolidationRates", {
p_company_group_id: companyGroupId,
- p_company_id: companyId ?? undefined,
- p_target_currency: targetCurrency,
+ p_company_id: companyId,
p_period_end: periodEnd,
- p_period_start: periodStart ?? undefined
+ p_period_start: periodStart
});
- if (error) {
- return { data: null, cta: 0, error: error.message };
+ if (ratesError) {
+ return { data: null, cta: 0, error: ratesError.message };
}
- const rows = (data ?? []) as unknown as TranslatedBalance[];
-
- // Look up each account's class to compute CTA
- const accountIds = rows.map((r) => r.accountId);
- const { data: accounts } = await client
- .from("account")
- .select("id, class")
- .in("id", accountIds);
-
- const classById = new Map((accounts ?? []).map((a) => [a.id, a.class]));
+ const rates = (Array.isArray(ratesData) ? ratesData[0] : ratesData) as
+ | {
+ sourceCurrency: string | null;
+ closingRate: number;
+ averageRate: number;
+ historicalRate: number;
+ }
+ | undefined;
+
+ const sameCurrency = rates?.sourceCurrency === targetCurrency;
+ const rateFor = (consolidatedRate: string | null): number => {
+ if (sameCurrency || !rates) return 1;
+ switch (consolidatedRate) {
+ case "Average":
+ return Number(rates.averageRate);
+ case "Historical":
+ return Number(rates.historicalRate);
+ default:
+ // 'Current' (the column default)
+ return Number(rates.closingRate);
+ }
+ };
+ const rows: TranslatedBalance[] = [];
let totalTranslatedAssets = 0;
let totalTranslatedLiabilitiesAndEquity = 0;
- for (const row of rows) {
- const cls = classById.get(row.accountId);
- if (cls === "Asset") {
- totalTranslatedAssets += Number(row.translatedBalance);
+ for (const account of balances) {
+ // Leaf accounts only, and never the synthetic Net Income line — its
+ // income-statement components are already in the rows, so translating it
+ // too would double-count net income in the CTA.
+ if (account.isGroup || account.id === NET_INCOME_ACCOUNT_ID) continue;
+
+ const exchangeRate = rateFor(account.consolidatedRate);
+ const localBalance = Number(account.balanceAtDate ?? 0);
+ const translatedBalance =
+ Math.round(localBalance * exchangeRate * 10000) / 10000;
+
+ rows.push({
+ accountId: account.id,
+ localBalance,
+ exchangeRate,
+ translatedBalance
+ });
+
+ if (account.class === "Asset") {
+ totalTranslatedAssets += translatedBalance;
} else {
// Liability, Equity, Revenue, Expense (but income statement
// accounts net to retained earnings on balance sheet)
- totalTranslatedLiabilitiesAndEquity += Number(row.translatedBalance);
+ totalTranslatedLiabilitiesAndEquity += translatedBalance;
}
}
@@ -2729,29 +2818,43 @@ export async function getConsolidatedBalances(
// All companies whose balances we need (operating + elimination entities)
const allIds = [...companyIds, ...eliminationIds];
- // Get balances for all companies and translate to target currency
- const [allBalances, translations] = await Promise.all([
- Promise.all(
- allIds.map((id) =>
- getFinancialStatementBalances(client, companyGroupId, id, {
+ // Get balances for all companies, then translate the already-computed
+ // balances to the target currency (one ledger scan per company, not two).
+ const results = await Promise.all(
+ allIds.map(async (id) => {
+ const balances = await getFinancialStatementBalances(
+ client,
+ companyGroupId,
+ id,
+ {
startDate: periodStart ?? null,
endDate: periodEnd
- })
- )
- ),
- Promise.all(
- allIds.map((id) =>
- translateCompanyBalances(
- client,
- companyGroupId,
- id,
- targetCurrency,
- periodEnd,
- periodStart
- )
- )
- )
- ]);
+ }
+ );
+
+ const translation =
+ balances.error || !balances.data
+ ? {
+ data: null,
+ cta: 0,
+ error: balances.error?.message ?? "Failed to load balances"
+ }
+ : await translateCompanyBalances(
+ client,
+ companyGroupId,
+ id,
+ targetCurrency,
+ periodEnd,
+ periodStart,
+ balances.data
+ );
+
+ return { balances, translation };
+ })
+ );
+
+ const allBalances = results.map((r) => r.balances);
+ const translations = results.map((r) => r.translation);
// Build a map of translated balances per account, summed across companies
const translationByAccount = new Map<
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index e4bea10b4c..3011849e5b 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -508,7 +508,8 @@ export async function getItemCostHistory(
.eq("itemId", itemId)
.eq("companyId", companyId)
.gte("postingDate", dateOneYearAgo)
- .order("postingDate", { ascending: false });
+ .order("postingDate", { ascending: false })
+ .limit(500);
}
export async function getItemCustomerPart(
@@ -762,11 +763,16 @@ export async function getItemQuantities(
companyId: string,
locationId: string
) {
+ // item_id restricts the RPC to one item so it doesn't aggregate the whole
+ // location's ledger/PO/SO/job history for a single detail page (added in
+ // migration 20260713231142; the committed DB types regenerate from the
+ // cloud DB after deploy, hence the cast).
return client
.rpc("get_inventory_quantities", {
location_id: locationId,
- company_id: companyId
- })
+ company_id: companyId,
+ item_id: itemId
+ } as { location_id: string; company_id: string })
.eq("id", itemId)
.maybeSingle();
}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 077f333d38..ad31947b2d 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-07-13T15:52:44.850Z",
+ "generated": "2026-07-14T01:23:55.918Z",
"totalTools": 1327,
"modules": 15,
"tools": [
@@ -1486,13 +1486,13 @@
"schema": {
"type": "object",
"properties": {
- "inventoryAccount": {
+ "rawMaterialsAccount": {
"type": "string"
},
- "goodsReceivedNotInvoicedAccount": {
+ "finishedGoodsAccount": {
"type": "string"
},
- "inventoryShippedNotInvoicedAccount": {
+ "goodsReceivedNotInvoicedAccount": {
"type": "string"
},
"workInProgressAccount": {
@@ -1551,9 +1551,9 @@
}
},
"required": [
- "inventoryAccount",
+ "rawMaterialsAccount",
+ "finishedGoodsAccount",
"goodsReceivedNotInvoicedAccount",
- "inventoryShippedNotInvoicedAccount",
"workInProgressAccount",
"receivablesAccount",
"bankCashAccount",
@@ -2197,14 +2197,16 @@
"module": "accounting",
"classification": "WRITE",
"description": "translate company balances",
- "paramCount": 3,
+ "paramCount": 5,
"serviceParams": [
"client",
"companyGroupId",
"companyId",
"targetCurrency",
"periodEnd",
- "periodStart"
+ "periodStart",
+ "// Rows from getFinancialStatementBalances for the same company/dates —\n // translation only needs balanceAtDate + consolidatedRate",
+ "so re-running\n // the full journalLine scan through the translateTrialBalance RPC would\n // double the cost of every translated statement.\n balances"
],
"injectAuth": [
"companyId"
@@ -2218,13 +2220,16 @@
"periodEnd": {
"type": "string"
},
- "periodStart": {
- "type": "string"
- }
+ "periodStart": {},
+ "// Rows from getFinancialStatementBalances for the same company/dates —\n // translation only needs balanceAtDate + consolidatedRate": {},
+ "so re-running\n // the full journalLine scan through the translateTrialBalance RPC would\n // double the cost of every translated statement.\n balances": {}
},
"required": [
"targetCurrency",
- "periodEnd"
+ "periodEnd",
+ "periodStart",
+ "// Rows from getFinancialStatementBalances for the same company/dates —\n // translation only needs balanceAtDate + consolidatedRate",
+ "so re-running\n // the full journalLine scan through the translateTrialBalance RPC would\n // double the cost of every translated statement.\n balances"
]
}
},
diff --git a/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx b/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx
index 87fb276fdf..cca975d25a 100644
--- a/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx
+++ b/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx
@@ -136,7 +136,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
companyGroupId,
selectedCompanyId!,
parentCurrency,
- periodEnd
+ periodEnd,
+ undefined,
+ balances.data ?? []
);
if (translation.data) {
diff --git a/apps/erp/app/routes/x+/accounting+/income-statement.tsx b/apps/erp/app/routes/x+/accounting+/income-statement.tsx
index 01a9708a42..fa5f0397c0 100644
--- a/apps/erp/app/routes/x+/accounting+/income-statement.tsx
+++ b/apps/erp/app/routes/x+/accounting+/income-statement.tsx
@@ -130,7 +130,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
selectedCompanyId!,
parentCurrency,
periodEnd,
- startDate ?? undefined
+ startDate ?? undefined,
+ balances.data ?? []
);
if (translation.data) {
diff --git a/apps/erp/app/routes/x+/accounting+/trial-balance.tsx b/apps/erp/app/routes/x+/accounting+/trial-balance.tsx
index 770e340f7d..ee81867a87 100644
--- a/apps/erp/app/routes/x+/accounting+/trial-balance.tsx
+++ b/apps/erp/app/routes/x+/accounting+/trial-balance.tsx
@@ -127,7 +127,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
selectedCompanyId!,
parentCurrency,
periodEnd,
- startDate ?? undefined
+ startDate ?? undefined,
+ balances.data ?? []
);
if (translation.data) {
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 6e5345d665..91fd8479c1 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -1448,6 +1448,165 @@ export type Database = {
},
]
}
+ accountingPeriodBalance: {
+ Row: {
+ accountId: string
+ accountingPeriodId: string
+ companyId: string
+ createdAt: string
+ createdBy: string
+ endingBalance: number
+ endingBalanceDate: string
+ id: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ accountId: string
+ accountingPeriodId: string
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ endingBalance?: number
+ endingBalanceDate: string
+ id?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ accountId?: string
+ accountingPeriodId?: string
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ endingBalance?: number
+ endingBalanceDate?: string
+ id?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "accountingPeriodBalance_accountId_fkey"
+ columns: ["accountId"]
+ isOneToOne: false
+ referencedRelation: "account"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_accountId_fkey"
+ columns: ["accountId"]
+ isOneToOne: false
+ referencedRelation: "accounts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_accountingPeriodId_fkey"
+ columns: ["accountingPeriodId"]
+ isOneToOne: false
+ referencedRelation: "accountingPeriod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
address: {
Row: {
addressLine1: string | null
@@ -57443,6 +57602,90 @@ export type Database = {
},
]
}
+ itemLedgerSnapshot: {
+ Row: {
+ companyId: string | null
+ consumed30: number | null
+ consumed90: number | null
+ itemId: string | null
+ locationId: string | null
+ quantity: number | null
+ snapshotCutoff: string | null
+ storageUnitIds: string[] | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "partLeger_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "partLeger_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "partLeger_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "partLeger_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ ]
+ }
itemStockQuantities: {
Row: {
companyId: string | null
@@ -65635,7 +65878,7 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -65649,7 +65892,7 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -66197,14 +66440,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -70160,7 +70403,7 @@ export type Database = {
}[]
}
get_inventory_quantities: {
- Args: { company_id: string; location_id: string }
+ Args: { company_id: string; item_id?: string; location_id: string }
Returns: {
active: boolean
daysRemaining: number
@@ -71320,6 +71563,20 @@ export type Database = {
thumbnailPath: string
}[]
}
+ getConsolidationRates: {
+ Args: {
+ p_company_group_id: string
+ p_company_id: string
+ p_period_end: string
+ p_period_start?: string
+ }
+ Returns: {
+ averageRate: number
+ closingRate: number
+ historicalRate: number
+ sourceCurrency: string
+ }[]
+ }
getIntercompanyBalance: {
Args: { p_company_group_id: string }
Returns: {
@@ -71519,6 +71776,10 @@ export type Database = {
}
show_limit: { Args: never; Returns: number }
show_trgm: { Args: { "": string }; Returns: string[] }
+ snapshotAccountingPeriodBalances: {
+ Args: { p_company_id: string; p_period_id: string; p_user_id: string }
+ Returns: undefined
+ }
storage_unit_block_location_change_with_children: {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 6e5345d665..91fd8479c1 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -1448,6 +1448,165 @@ export type Database = {
},
]
}
+ accountingPeriodBalance: {
+ Row: {
+ accountId: string
+ accountingPeriodId: string
+ companyId: string
+ createdAt: string
+ createdBy: string
+ endingBalance: number
+ endingBalanceDate: string
+ id: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ accountId: string
+ accountingPeriodId: string
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ endingBalance?: number
+ endingBalanceDate: string
+ id?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ accountId?: string
+ accountingPeriodId?: string
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ endingBalance?: number
+ endingBalanceDate?: string
+ id?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "accountingPeriodBalance_accountId_fkey"
+ columns: ["accountId"]
+ isOneToOne: false
+ referencedRelation: "account"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_accountId_fkey"
+ columns: ["accountId"]
+ isOneToOne: false
+ referencedRelation: "accounts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_accountingPeriodId_fkey"
+ columns: ["accountingPeriodId"]
+ isOneToOne: false
+ referencedRelation: "accountingPeriod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "accountingPeriodBalance_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
address: {
Row: {
addressLine1: string | null
@@ -57443,6 +57602,90 @@ export type Database = {
},
]
}
+ itemLedgerSnapshot: {
+ Row: {
+ companyId: string | null
+ consumed30: number | null
+ consumed90: number | null
+ itemId: string | null
+ locationId: string | null
+ quantity: number | null
+ snapshotCutoff: string | null
+ storageUnitIds: string[] | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "partLeger_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "partLeger_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "partLeger_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "partLeger_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ ]
+ }
itemStockQuantities: {
Row: {
companyId: string | null
@@ -65635,7 +65878,7 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -65649,7 +65892,7 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -66197,14 +66440,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -70160,7 +70403,7 @@ export type Database = {
}[]
}
get_inventory_quantities: {
- Args: { company_id: string; location_id: string }
+ Args: { company_id: string; item_id?: string; location_id: string }
Returns: {
active: boolean
daysRemaining: number
@@ -71320,6 +71563,20 @@ export type Database = {
thumbnailPath: string
}[]
}
+ getConsolidationRates: {
+ Args: {
+ p_company_group_id: string
+ p_company_id: string
+ p_period_end: string
+ p_period_start?: string
+ }
+ Returns: {
+ averageRate: number
+ closingRate: number
+ historicalRate: number
+ sourceCurrency: string
+ }[]
+ }
getIntercompanyBalance: {
Args: { p_company_group_id: string }
Returns: {
@@ -71519,6 +71776,10 @@ export type Database = {
}
show_limit: { Args: never; Returns: number }
show_trgm: { Args: { "": string }; Returns: string[] }
+ snapshotAccountingPeriodBalances: {
+ Args: { p_company_id: string; p_period_id: string; p_user_id: string }
+ Returns: undefined
+ }
storage_unit_block_location_change_with_children: {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.ts
index d5341bb430..b47b4e586c 100644
--- a/packages/database/supabase/functions/update-purchased-prices/index.ts
+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts
@@ -1,6 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
+import { sql } from "kysely";
import z from "npm:zod@^3.24.1";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsHeaders } from "../lib/headers.ts";
@@ -239,13 +240,26 @@ serve(async (req: Request) => {
[];
if (shouldUpdatePrices && itemIds.length > 0) {
- const [costLedgers, supplierParts] = await Promise.all([
- client
- .from("costLedger")
- .select("*")
- .in("itemId", itemIds)
- .eq("companyId", companyId)
- .gte("postingDate", dateOneYearAgo),
+ // Aggregate in SQL: fetching raw rows through PostgREST silently caps
+ // at 1000, which skewed the weighted average for high-volume items.
+ const [costLedgerTotals, supplierParts] = await Promise.all([
+ db
+ .selectFrom("costLedger")
+ .select(({ fn }) => [
+ "itemId",
+ // Adjustment child rows (invoice-vs-receipt price corrections)
+ // carry cost but no additional physical quantity, so they count
+ // toward cost but not quantity.
+ sql<number>`sum(case when "adjustment" then 0 else "quantity" end)`.as(
+ "quantity"
+ ),
+ fn.sum<number>("cost").as("cost"),
+ ])
+ .where("itemId", "in", itemIds)
+ .where("companyId", "=", companyId)
+ .where("postingDate", ">=", dateOneYearAgo)
+ .groupBy("itemId")
+ .execute(),
client
.from("supplierPart")
.select("*")
@@ -254,30 +268,18 @@ serve(async (req: Request) => {
.eq("companyId", companyId),
]);
- if (costLedgers.error) {
- throw new Error("Failed to fetch historical cost ledger entries");
- }
if (supplierParts.error) {
throw new Error("Failed to fetch supplier parts");
}
supplierPartRows = supplierParts.data ?? [];
- costLedgers.data?.forEach((ledger) => {
- if (ledger.itemId) {
- if (!historicalPartCosts[ledger.itemId]) {
- historicalPartCosts[ledger.itemId] = {
- quantity: 0,
- cost: 0,
- };
- }
-
- // Adjustment child rows (invoice-vs-receipt price corrections)
- // carry cost but no additional physical quantity
- if (!ledger.adjustment) {
- historicalPartCosts[ledger.itemId].quantity += ledger.quantity;
- }
- historicalPartCosts[ledger.itemId].cost += ledger.cost;
+ costLedgerTotals.forEach((row) => {
+ if (row.itemId) {
+ historicalPartCosts[row.itemId] = {
+ quantity: Number(row.quantity ?? 0),
+ cost: Number(row.cost ?? 0),
+ };
}
});
}
diff --git a/packages/database/supabase/migrations/20260713224517_ledger-performance-indexes.sql b/packages/database/supabase/migrations/20260713224517_ledger-performance-indexes.sql
new file mode 100644
index 0000000000..c11992a3b5
--- /dev/null
+++ b/packages/database/supabase/migrations/20260713224517_ledger-performance-indexes.sql
@@ -0,0 +1,62 @@
+-- ============================================================
+-- Ledger performance indexes.
+--
+-- The ledger tables are append-only and aggregated on read, but the hottest
+-- read paths had no matching indexes:
+--
+-- 1. itemLedger had NO index on itemId/locationId at all. The issue edge
+-- function (functions/issue/index.ts) and lib/storage-units.ts run
+-- `SUM(quantity) WHERE "itemId" = ? AND "locationId" = ?` per material
+-- issued — with no companyId filter — so each was a sequential scan of the
+-- entire multi-tenant table, inside the posting transaction.
+-- 2. journalLine.journalId is a NOT NULL FK (20260402000000) but was never
+-- indexed — hit by the journalEntries view (GROUP BY journal), journal
+-- cascade deletes, void/reverse reads, and the per-row Draft-check RLS on
+-- journalLine UPDATE/DELETE.
+-- 3. Void paths look up ledger rows by documentId / documentLineReference;
+-- tie-out and statement queries filter journal by companyId + postingDate.
+-- 4. supplierLedger had zero indexes beyond its PK.
+--
+-- Nullable FKs use partial indexes, matching the style of
+-- 20260630111923_ar-ap-fk-indexes.sql. All statements are idempotent.
+-- ============================================================
+
+-- itemLedger: per-item aggregation paths (issue, storage-unit defaults,
+-- get_item_quantities_by_tracking_id). INCLUDE makes the per-item SUMs
+-- index-only scans — they never touch the heap as the table grows.
+CREATE INDEX IF NOT EXISTS "itemLedger_itemId_locationId_idx"
+ ON "itemLedger" ("itemId", "locationId")
+ INCLUDE ("storageUnitId", "quantity", "trackedEntityStatus");
+
+-- itemLedger: company/location-scoped aggregation paths
+-- (get_inventory_quantities, get_inventory_value_by_location,
+-- get_job_quantity_on_hand, itemStockQuantities matview refresh).
+CREATE INDEX IF NOT EXISTS "itemLedger_companyId_locationId_itemId_idx"
+ ON "itemLedger" ("companyId", "locationId", "itemId");
+
+-- itemLedger: void/reverse paths fetch a document's ledger rows.
+CREATE INDEX IF NOT EXISTS "itemLedger_documentId_idx"
+ ON "itemLedger" ("documentId") WHERE "documentId" IS NOT NULL;
+
+-- journalLine: FK join path (journalEntries view, cascades, RLS Draft check).
+CREATE INDEX IF NOT EXISTS "journalLine_journalId_idx"
+ ON "journalLine" ("journalId");
+
+-- journalLine: void/reverse + GR/IR accrual netting lookups.
+CREATE INDEX IF NOT EXISTS "journalLine_documentId_idx"
+ ON "journalLine" ("documentId") WHERE "documentId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "journalLine_documentLineReference_idx"
+ ON "journalLine" ("documentLineReference") WHERE "documentLineReference" IS NOT NULL;
+
+-- journal: company-scoped date filters (tie-out, financial statements).
+-- The existing journal_postingDate_idx is single-column.
+CREATE INDEX IF NOT EXISTS "journal_companyId_postingDate_idx"
+ ON "journal" ("companyId", "postingDate");
+
+-- costLedger: unindexed FK (added 20250116182231).
+CREATE INDEX IF NOT EXISTS "costLedger_supplierId_idx"
+ ON "costLedger" ("supplierId") WHERE "supplierId" IS NOT NULL;
+
+-- supplierLedger: no indexes existed beyond the PK.
+CREATE INDEX IF NOT EXISTS "supplierLedger_companyId_supplierId_idx"
+ ON "supplierLedger" ("companyId", "supplierId");
diff --git a/packages/database/supabase/migrations/20260713225803_ledger-balance-posted-filter.sql b/packages/database/supabase/migrations/20260713225803_ledger-balance-posted-filter.sql
new file mode 100644
index 0000000000..4a886a4b52
--- /dev/null
+++ b/packages/database/supabase/migrations/20260713225803_ledger-balance-posted-filter.sql
@@ -0,0 +1,232 @@
+-- ============================================================
+-- 1. Exclude Draft journals from financial statement balances.
+--
+-- accountTreeBalancesByCompany / accountTreeBalances /
+-- journalLinesByAccountNumber summed every journalLine regardless of
+-- journal.status, so unposted Draft journal entries leaked into the trial
+-- balance, balance sheet, and income statement. Reversed journals still
+-- count: a reversal keeps the original entry on the books and offsets it
+-- with the reversing entry, so excluding them would unbalance the ledger.
+--
+-- Forked from the latest definitions:
+-- accountTreeBalancesByCompany / trialBalance → 20260315000001_per-company-balance-rpc.sql
+-- accountTreeBalances / journalLinesByAccountNumber → 20260229000003_chart-of-accounts-tree.sql
+-- Signatures and return types are unchanged (CREATE OR REPLACE is safe);
+-- only the SUM expressions gained the status gate.
+--
+-- 2. getConsolidationRates: rate lookups for currency translation, extracted
+-- from translateTrialBalance so the app can translate already-computed
+-- balances in one pass instead of re-scanning journalLine per company.
+-- ============================================================
+
+CREATE OR REPLACE FUNCTION "accountTreeBalancesByCompany" (
+ 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,
+ "balance" NUMERIC,
+ "balanceAtDate" NUMERIC,
+ "netChange" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH RECURSIVE "accountTree" AS (
+ SELECT
+ a."id",
+ a."id" AS "rootId",
+ a."isGroup"
+ FROM "account" a
+ WHERE a."companyGroupId" = p_company_group_id AND a."active" = true
+
+ UNION ALL
+
+ SELECT
+ child."id",
+ t."rootId",
+ child."isGroup"
+ FROM "accountTree" t
+ INNER JOIN "account" child ON child."parentId" = t."id"
+ WHERE t."isGroup" = true
+ AND child."companyGroupId" = p_company_group_id
+ AND child."active" = true
+ ),
+ "leafBalances" AS (
+ SELECT
+ a."id" AS "accountId",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' THEN jl."amount" ELSE 0 END), 0) AS "balance",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "balanceAtDate",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" >= from_date AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "netChange"
+ 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
+ t."rootId" AS "accountId",
+ COALESCE(SUM(lb."balance"), 0)::NUMERIC AS "balance",
+ COALESCE(SUM(lb."balanceAtDate"), 0)::NUMERIC AS "balanceAtDate",
+ COALESCE(SUM(lb."netChange"), 0)::NUMERIC AS "netChange"
+ FROM "accountTree" t
+ LEFT JOIN "leafBalances" lb ON lb."accountId" = t."id" AND t."isGroup" = false
+ GROUP BY t."rootId";
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION "accountTreeBalances" (
+ p_company_group_id TEXT,
+ from_date DATE DEFAULT (now() - INTERVAL '100 year'),
+ to_date DATE DEFAULT now()
+)
+RETURNS TABLE (
+ "accountId" TEXT,
+ "balance" NUMERIC,
+ "balanceAtDate" NUMERIC,
+ "netChange" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH RECURSIVE "accountTree" AS (
+ -- Base case: all accounts in the company group
+ SELECT
+ a."id",
+ a."id" AS "rootId",
+ a."isGroup"
+ FROM "account" a
+ WHERE a."companyGroupId" = p_company_group_id AND a."active" = true
+
+ UNION ALL
+
+ -- Recursive case: for group accounts, include all descendants
+ SELECT
+ child."id",
+ t."rootId",
+ child."isGroup"
+ FROM "accountTree" t
+ INNER JOIN "account" child ON child."parentId" = t."id"
+ WHERE t."isGroup" = true
+ AND child."companyGroupId" = p_company_group_id
+ AND child."active" = true
+ ),
+ "leafBalances" AS (
+ SELECT
+ a."id" AS "accountId",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' THEN jl."amount" ELSE 0 END), 0) AS "balance",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "balanceAtDate",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" >= from_date AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "netChange"
+ FROM "account" a
+ LEFT JOIN "journalLine" jl ON jl."accountId" = a."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"
+ )
+ -- For each account, sum up all descendant leaf balances
+ SELECT
+ t."rootId" AS "accountId",
+ COALESCE(SUM(lb."balance"), 0)::NUMERIC AS "balance",
+ COALESCE(SUM(lb."balanceAtDate"), 0)::NUMERIC AS "balanceAtDate",
+ COALESCE(SUM(lb."netChange"), 0)::NUMERIC AS "netChange"
+ FROM "accountTree" t
+ LEFT JOIN "leafBalances" lb ON lb."accountId" = t."id" AND t."isGroup" = false
+ GROUP BY t."rootId";
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION "journalLinesByAccountNumber" (
+ from_date DATE DEFAULT (now() - INTERVAL '100 year'),
+ to_date DATE DEFAULT now()
+)
+RETURNS TABLE (
+ "number" TEXT,
+ "companyGroupId" TEXT,
+ "balance" NUMERIC,
+ "balanceAtDate" NUMERIC,
+ "netChange" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+ BEGIN
+ RETURN QUERY
+ SELECT
+ a."number",
+ a."companyGroupId",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' THEN jl."amount" ELSE 0 END), 0) AS "balance",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "balanceAtDate",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" >= from_date AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "netChange"
+ FROM "account" a
+ LEFT JOIN "journalLine" jl ON jl."accountId" = a."id"
+ LEFT JOIN "journal" j ON j."id" = jl."journalId"
+ WHERE a."isGroup" = false
+ GROUP BY a."number", a."companyGroupId";
+ END;
+$$;
+
+-- Rate lookups for currency translation, extracted verbatim from
+-- translateTrialBalance (20260315000002_exchange-rate-history.sql). Returns a
+-- single row; no ledger access. The app multiplies already-computed
+-- balanceAtDate values by the rate matching each account's consolidatedRate,
+-- which replaces the translateTrialBalance call (and its second full
+-- journalLine scan per company) in the statement/consolidation loaders.
+CREATE OR REPLACE FUNCTION "getConsolidationRates" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_period_end DATE,
+ p_period_start DATE DEFAULT NULL
+)
+RETURNS TABLE (
+ "sourceCurrency" TEXT,
+ "closingRate" NUMERIC,
+ "averageRate" NUMERIC,
+ "historicalRate" NUMERIC
+)
+LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+DECLARE
+ v_source_currency TEXT;
+ v_closing_rate NUMERIC;
+ v_average_rate NUMERIC;
+ v_historical_rate NUMERIC;
+BEGIN
+ SELECT "baseCurrencyCode" INTO v_source_currency
+ FROM "company" WHERE "id" = p_company_id;
+
+ -- Closing rate: latest daily rate on or before period end
+ SELECT "rate" INTO v_closing_rate
+ FROM "exchangeRateHistory"
+ WHERE "currencyCode" = v_source_currency
+ AND "companyGroupId" = p_company_group_id
+ AND "effectiveDate" <= p_period_end
+ ORDER BY "effectiveDate" DESC LIMIT 1;
+
+ -- Average rate: mean of daily rates over the period
+ SELECT AVG("rate") INTO v_average_rate
+ FROM "exchangeRateHistory"
+ WHERE "currencyCode" = v_source_currency
+ AND "companyGroupId" = p_company_group_id
+ AND "effectiveDate" >= COALESCE(p_period_start, p_period_end - INTERVAL '1 year')
+ AND "effectiveDate" <= p_period_end;
+
+ -- Historical rate: from currency table (manually set for equity)
+ SELECT "historicalExchangeRate" INTO v_historical_rate
+ FROM "currency"
+ WHERE "code" = v_source_currency
+ AND "companyGroupId" = p_company_group_id;
+
+ -- Defaults: average falls back to closing, historical falls back to closing, all fall back to 1
+ v_average_rate := COALESCE(v_average_rate, v_closing_rate, 1);
+ v_historical_rate := COALESCE(v_historical_rate, v_closing_rate, 1);
+ v_closing_rate := COALESCE(v_closing_rate, 1);
+
+ RETURN QUERY
+ SELECT v_source_currency, v_closing_rate, v_average_rate, v_historical_rate;
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260713231142_inventory-quantities-item-filter.sql b/packages/database/supabase/migrations/20260713231142_inventory-quantities-item-filter.sql
new file mode 100644
index 0000000000..f726112f46
--- /dev/null
+++ b/packages/database/supabase/migrations/20260713231142_inventory-quantities-item-filter.sql
@@ -0,0 +1,289 @@
+-- Add an optional `item_id` parameter to get_inventory_quantities so
+-- single-item callers (getItemQuantities on the item detail loaders) don't
+-- force the function to aggregate the entire location's itemLedger history
+-- plus every open PO/SO/job just to read one item's quantities.
+--
+-- item_id defaults to NULL, which preserves the whole-location behavior for
+-- the Inventory table. When set, every CTE and the final item scan are
+-- restricted to that item.
+--
+-- Body otherwise identical to 20260512130000_inventory-storage-unit-filter.sql
+-- (the prior latest definition) — only the new parameter + filters differ.
+
+DROP FUNCTION IF EXISTS get_inventory_quantities(TEXT, TEXT);
+
+CREATE OR REPLACE FUNCTION get_inventory_quantities(company_id TEXT, location_id TEXT, item_id TEXT DEFAULT NULL)
+ RETURNS TABLE (
+ "id" TEXT,
+ "readableId" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "active" BOOLEAN,
+ "type" "itemType",
+ "itemTrackingType" "itemTrackingType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "materialSubstanceId" TEXT,
+ "materialFormId" TEXT,
+ "dimensionId" TEXT,
+ "dimension" TEXT,
+ "finishId" TEXT,
+ "finish" TEXT,
+ "gradeId" TEXT,
+ "grade" TEXT,
+ "materialType" TEXT,
+ "materialTypeId" TEXT,
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "leadTime" INTEGER,
+ "lotSize" INTEGER,
+ "reorderingPolicy" "itemReorderingPolicy",
+ "demandAccumulationPeriod" INTEGER,
+ "demandAccumulationSafetyStock" NUMERIC,
+ "reorderPoint" INTEGER,
+ "reorderQuantity" INTEGER,
+ "minimumOrderQuantity" INTEGER,
+ "maximumOrderQuantity" INTEGER,
+ "maximumInventoryQuantity" NUMERIC,
+ "orderMultiple" INTEGER,
+ "quantityOnHand" NUMERIC,
+ "quantityOnHold" NUMERIC,
+ "quantityRejected" NUMERIC,
+ "quantityOnSalesOrder" NUMERIC,
+ "quantityOnPurchaseOrder" NUMERIC,
+ "quantityOnProductionOrder" NUMERIC,
+ "quantityOnProductionDemand" NUMERIC,
+ "demandForecast" NUMERIC,
+ "usageLast30Days" NUMERIC,
+ "usageLast90Days" NUMERIC,
+ "daysRemaining" NUMERIC,
+ "storageTypeIds" TEXT[],
+ "storageUnitIds" TEXT[]
+ ) AS $$
+ BEGIN
+ RETURN QUERY
+
+WITH
+ open_purchase_orders AS (
+ SELECT
+ pol."itemId",
+ SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"
+ FROM
+ "purchaseOrder" po
+ INNER JOIN "purchaseOrderLine" pol
+ ON pol."purchaseOrderId" = po."id"
+ WHERE
+ po."status" IN (
+ 'Planned',
+ 'To Receive',
+ 'To Receive and Invoice'
+ )
+ AND po."companyId" = company_id
+ AND pol."locationId" = location_id
+ AND (item_id IS NULL OR pol."itemId" = item_id)
+ GROUP BY pol."itemId"
+ ),
+ open_sales_orders AS (
+ SELECT
+ sol."itemId",
+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"
+ FROM
+ "salesOrder" so
+ INNER JOIN "salesOrderLine" sol
+ ON sol."salesOrderId" = so."id"
+ WHERE
+ so."status" IN (
+ 'Confirmed',
+ 'To Ship and Invoice',
+ 'To Ship',
+ 'To Invoice',
+ 'In Progress'
+ )
+ AND so."companyId" = company_id
+ AND sol."locationId" = location_id
+ AND (item_id IS NULL OR sol."itemId" = item_id)
+ GROUP BY sol."itemId"
+ ),
+ open_job_requirements AS (
+ SELECT
+ jm."itemId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ AND (item_id IS NULL OR jm."itemId" = item_id)
+ GROUP BY jm."itemId"
+ ),
+ open_jobs AS (
+ SELECT
+ j."itemId",
+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"
+ FROM job j
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ AND (item_id IS NULL OR j."itemId" = item_id)
+ GROUP BY j."itemId"
+ ),
+ item_ledgers AS (
+ SELECT
+ "itemId",
+ SUM("quantity") FILTER (
+ WHERE "trackedEntityStatus" IS NULL
+ OR "trackedEntityStatus" != 'Rejected'
+ ) AS "quantityOnHand",
+ SUM("quantity") FILTER (WHERE "trackedEntityStatus" = 'On Hold')
+ AS "quantityOnHold",
+ SUM("quantity") FILTER (WHERE "trackedEntityStatus" = 'Rejected')
+ AS "quantityRejected",
+ SUM(CASE
+ WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND "createdAt" >= CURRENT_DATE - INTERVAL '30 days'
+ THEN -"quantity"
+ ELSE 0
+ END) / 30 AS "usageLast30Days",
+ SUM(CASE
+ WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND "createdAt" >= CURRENT_DATE - INTERVAL '90 days'
+ THEN -"quantity"
+ ELSE 0
+ END) / 90 AS "usageLast90Days"
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND (item_id IS NULL OR "itemId" = item_id)
+ GROUP BY "itemId"
+ ),
+ -- Distinct storage types the item is stocked in, joined via the storage
+ -- units referenced by its ledger rows. NULL storageUnitId rows are
+ -- excluded — they don't belong to any unit so they can't carry types.
+ item_storage_types AS (
+ SELECT
+ il."itemId",
+ ARRAY_AGG(DISTINCT t) AS "storageTypeIds"
+ FROM "itemLedger" il
+ INNER JOIN "storageUnit" su
+ ON su."id" = il."storageUnitId"
+ AND su."companyId" = company_id
+ CROSS JOIN LATERAL unnest(su."storageTypeIds") AS t
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ GROUP BY il."itemId"
+ ),
+ -- Distinct storage units the item is stocked in. NULL storageUnitId rows
+ -- are excluded so the array only contains real units.
+ item_storage_units AS (
+ SELECT
+ il."itemId",
+ ARRAY_AGG(DISTINCT il."storageUnitId") AS "storageUnitIds"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND il."storageUnitId" IS NOT NULL
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ GROUP BY il."itemId"
+ ),
+ demand_forecast AS (
+ SELECT combined."itemId", SUM(qty) AS "demandForecast"
+ FROM (
+ SELECT da."itemId", da."actualQuantity" AS qty
+ FROM "demandActual" da
+ WHERE da."companyId" = company_id AND da."locationId" = location_id
+ AND (item_id IS NULL OR da."itemId" = item_id)
+ UNION ALL
+ SELECT df."itemId", df."forecastQuantity" AS qty
+ FROM "demandForecast" df
+ WHERE df."companyId" = company_id AND df."locationId" = location_id
+ AND (item_id IS NULL OR df."itemId" = item_id)
+ ) combined
+ GROUP BY combined."itemId"
+ )
+
+SELECT
+ i."id",
+ i."readableId",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ m."materialSubstanceId",
+ m."materialFormId",
+ m."dimensionId",
+ md."name" AS "dimension",
+ m."finishId",
+ mf."name" AS "finish",
+ m."gradeId",
+ mg."name" AS "grade",
+ mt."name" AS "materialType",
+ m."materialTypeId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."maximumInventoryQuantity",
+ ip."orderMultiple",
+ COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",
+ COALESCE(il."quantityOnHold", 0) AS "quantityOnHold",
+ COALESCE(il."quantityRejected", 0) AS "quantityRejected",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(jo."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(jr."quantityOnProductionDemand", 0) AS "quantityOnProductionDemand",
+ COALESCE(df."demandForecast", 0) AS "demandForecast",
+ COALESCE(il."usageLast30Days", 0) AS "usageLast30Days",
+ COALESCE(il."usageLast90Days", 0) AS "usageLast90Days",
+ CASE
+ WHEN COALESCE(il."usageLast30Days", 0) > 0
+ THEN ROUND(COALESCE(il."quantityOnHand", 0) / il."usageLast30Days", 2)
+ ELSE NULL
+ END AS "daysRemaining",
+ COALESCE(ist."storageTypeIds", ARRAY[]::TEXT[]) AS "storageTypeIds",
+ COALESCE(isu."storageUnitIds", ARRAY[]::TEXT[]) AS "storageUnitIds"
+FROM
+ "item" i
+ LEFT JOIN item_ledgers il ON i."id" = il."itemId"
+ LEFT JOIN item_storage_types ist ON i."id" = ist."itemId"
+ LEFT JOIN item_storage_units isu ON i."id" = isu."itemId"
+ LEFT JOIN open_sales_orders so ON i."id" = so."itemId"
+ LEFT JOIN open_purchase_orders po ON i."id" = po."itemId"
+ LEFT JOIN open_jobs jo ON i."id" = jo."itemId"
+ LEFT JOIN open_job_requirements jr ON i."id" = jr."itemId"
+ LEFT JOIN demand_forecast df ON i."id" = df."itemId"
+ LEFT JOIN material m ON i."readableId" = m."id" AND m."companyId" = company_id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md."id"
+ LEFT JOIN "materialFinish" mf ON m."finishId" = mf."id"
+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg."id"
+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt."id"
+ LEFT JOIN "itemReplenishment" ir ON i."id" = ir."itemId" AND ir."companyId" = company_id
+ LEFT JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id
+WHERE
+ i."itemTrackingType" <> 'Non-Inventory' AND i."companyId" = company_id
+ AND (item_id IS NULL OR i."id" = item_id);
+ END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/database/supabase/migrations/20260713232634_accounting-period-balance.sql b/packages/database/supabase/migrations/20260713232634_accounting-period-balance.sql
new file mode 100644
index 0000000000..675c944a3c
--- /dev/null
+++ b/packages/database/supabase/migrations/20260713232634_accounting-period-balance.sql
@@ -0,0 +1,152 @@
+-- ============================================================
+-- accountingPeriodBalance: per-account GL balance snapshots at period close.
+--
+-- One row per (leaf account, company, closed period) holding the CUMULATIVE
+-- balance through the period's endDate (not the per-period net), so a read
+-- needs exactly one snapshot row. Written by snapshotAccountingPeriodBalances,
+-- which the period-close flow calls inside its transaction. The balance RPCs
+-- (next migration) read "latest snapshot + journal lines after it" and fall
+-- back to the full-history scan when no snapshot exists, so this table is
+-- inert until a close flow starts writing it.
+--
+-- Correctness invariants the period-close flow MUST enforce (and where each is):
+-- 1. No posting with a postingDate inside a closed period (the check must
+-- be on postingDate, not just the assigned accountingPeriodId — the edge
+-- functions' getCurrentAccountingPeriod resolves periods by server time,
+-- so a backdated postingDate could otherwise land behind a snapshot).
+-- Enforced by check_accounting_period_open (period-close-lifecycle), which
+-- also takes the period row FOR SHARE (migration 20260713235930) so a
+-- posting can't race the close and slip behind the snapshot.
+-- 2. Periods close in order: a period cannot close while an earlier period
+-- for the same company is open. Enforced by closeAccountingPeriod.
+-- 3. Reopening period N deletes this company's snapshots with
+-- "endingBalanceDate" >= that period's endDate (they are cumulative, so
+-- later snapshots embed period N's data). Enforced by reopenAccountingPeriod.
+-- ============================================================
+
+CREATE TABLE IF NOT EXISTS "accountingPeriodBalance" (
+ "id" TEXT NOT NULL DEFAULT id('apb'),
+ "companyId" TEXT NOT NULL,
+ "accountingPeriodId" TEXT NOT NULL,
+ "accountId" TEXT NOT NULL REFERENCES "account"("id"),
+ -- cumulative balance through the period's endDate, Draft journals excluded
+ "endingBalance" NUMERIC NOT NULL DEFAULT 0,
+ -- denormalized period endDate so reads don't join accountingPeriod
+ "endingBalanceDate" DATE 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,
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ FOREIGN KEY ("accountingPeriodId") REFERENCES "accountingPeriod"("id") ON DELETE CASCADE
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS "accountingPeriodBalance_account_period_key"
+ ON "accountingPeriodBalance" ("accountId", "accountingPeriodId", "companyId");
+-- the read path's lookup: snapshots for a company at a specific endDate
+CREATE INDEX IF NOT EXISTS "accountingPeriodBalance_companyId_date_idx"
+ ON "accountingPeriodBalance" ("companyId", "endingBalanceDate" DESC, "accountId");
+CREATE INDEX IF NOT EXISTS "accountingPeriodBalance_companyId_idx"
+ ON "accountingPeriodBalance" ("companyId");
+CREATE INDEX IF NOT EXISTS "accountingPeriodBalance_accountingPeriodId_idx"
+ ON "accountingPeriodBalance" ("accountingPeriodId");
+CREATE INDEX IF NOT EXISTS "accountingPeriodBalance_accountId_idx"
+ ON "accountingPeriodBalance" ("accountId");
+CREATE INDEX IF NOT EXISTS "accountingPeriodBalance_createdBy_idx"
+ ON "accountingPeriodBalance" ("createdBy");
+
+ALTER TABLE "public"."accountingPeriodBalance" ENABLE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS "SELECT" ON "public"."accountingPeriodBalance";
+CREATE POLICY "SELECT" ON "public"."accountingPeriodBalance"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_view'))::text[])
+);
+
+DROP POLICY IF EXISTS "INSERT" ON "public"."accountingPeriodBalance";
+CREATE POLICY "INSERT" ON "public"."accountingPeriodBalance"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_create'))::text[])
+);
+
+DROP POLICY IF EXISTS "UPDATE" ON "public"."accountingPeriodBalance";
+CREATE POLICY "UPDATE" ON "public"."accountingPeriodBalance"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])
+);
+
+-- Snapshots are an internal, derived optimization artifact tied to the period
+-- lifecycle. reopenAccountingPeriod clears them through the RLS-enforced request
+-- client, and reopening is an update-tier action (like lock/close), so gate the
+-- DELETE on accounting_update — not accounting_delete — otherwise the reopen
+-- route (which holds accounting_update) would silently no-op the cleanup and
+-- leave stale snapshots behind. Deleting a snapshot only forces a full-scan
+-- recompute, so update-tier access is the right bar.
+DROP POLICY IF EXISTS "DELETE" ON "public"."accountingPeriodBalance";
+CREATE POLICY "DELETE" ON "public"."accountingPeriodBalance"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])
+);
+
+-- Snapshot writer. Runs the last full-history scan a period will ever need —
+-- once, at close time, inside the close transaction. Idempotent via upsert so
+-- a retried close (or a re-close after reopen) refreshes the rows in place.
+CREATE OR REPLACE FUNCTION "snapshotAccountingPeriodBalances" (
+ p_company_id TEXT,
+ p_period_id TEXT,
+ p_user_id TEXT
+) RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path = public
+AS $$
+DECLARE
+ v_end_date DATE;
+ v_close_status "periodCloseStatus";
+BEGIN
+ SELECT "endDate", "closeStatus" INTO v_end_date, v_close_status
+ FROM "accountingPeriod"
+ WHERE "id" = p_period_id AND "companyId" = p_company_id;
+
+ IF v_end_date IS NULL THEN
+ RAISE EXCEPTION 'Accounting period % not found for company %', p_period_id, p_company_id;
+ END IF;
+
+ -- Only Closed periods may hold a snapshot. A Closed period cannot receive new
+ -- postings (the journal_check_period_open trigger from the period-close
+ -- lifecycle blocks any journal whose postingDate lands in a closed period), so
+ -- its cumulative balance is frozen and the snapshot can never go stale.
+ -- closeAccountingPeriod flips the period to Closed inside its transaction
+ -- before calling this, so the check passes for the intended caller; refusing
+ -- anything else is defense-in-depth against writing a snapshot a later posting
+ -- could invalidate.
+ IF v_close_status IS DISTINCT FROM 'Closed' THEN
+ RAISE EXCEPTION 'Cannot snapshot accounting period %: period is not Closed (closeStatus=%)',
+ p_period_id, v_close_status;
+ END IF;
+
+ INSERT INTO "accountingPeriodBalance"
+ ("companyId", "accountingPeriodId", "accountId", "endingBalance", "endingBalanceDate", "createdBy")
+ SELECT
+ p_company_id,
+ p_period_id,
+ a."id",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" <= v_end_date
+ THEN jl."amount" ELSE 0 END), 0),
+ v_end_date,
+ p_user_id
+ FROM "account" a
+ LEFT JOIN "journalLine" jl ON jl."accountId" = a."id" AND jl."companyId" = p_company_id
+ LEFT JOIN "journal" j ON j."id" = jl."journalId"
+ WHERE a."isGroup" = false
+ AND a."active" = true
+ AND a."companyGroupId" = (SELECT "companyGroupId" FROM "company" WHERE "id" = p_company_id)
+ GROUP BY a."id"
+ ON CONFLICT ("accountId", "accountingPeriodId", "companyId")
+ DO UPDATE SET
+ "endingBalance" = EXCLUDED."endingBalance",
+ "endingBalanceDate" = EXCLUDED."endingBalanceDate",
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW();
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260713233919_balance-rpc-snapshot-delta.sql b/packages/database/supabase/migrations/20260713233919_balance-rpc-snapshot-delta.sql
new file mode 100644
index 0000000000..1e5143b7dc
--- /dev/null
+++ b/packages/database/supabase/migrations/20260713233919_balance-rpc-snapshot-delta.sql
@@ -0,0 +1,196 @@
+-- ============================================================
+-- accountTreeBalancesByCompany: snapshot + delta.
+--
+-- Forked from 20260713225803_ledger-balance-posted-filter.sql. Same signature
+-- and return type; trialBalance / translateTrialBalance inherit automatically.
+--
+-- When the company has accountingPeriodBalance snapshots, each balance is
+-- "cumulative snapshot + SUM(journal lines after the snapshot date)", so the
+-- journalLine scan is bounded by the open period(s) instead of all history:
+-- balance = latest snapshot + lines after it
+-- balanceAtDate = latest snapshot <= to_date + lines in (snapshot, to_date]
+-- netChange = balanceAtDate(to_date)
+-- - (latest snapshot < from_date + lines in (snapshot, from_date))
+--
+-- Snapshot dates are per-company scalars (every account snapshots at the same
+-- period endDate), so the delta join prunes on journal(companyId, postingDate)
+-- with two bounded ranges. Companies with no snapshots (or group-wide calls
+-- with p_company_id NULL) take the identical full-scan body as before — no
+-- behavior change until a period-close flow writes snapshots.
+--
+-- accountTreeBalances (group-wide, chart of accounts) intentionally stays on
+-- the full scan: snapshots are per company.
+--
+-- ⚠ KEEP IN SYNC: the two RETURN QUERY branches below (full-scan when there is
+-- no snapshot; snapshot+delta otherwise) share an IDENTICAL "accountTree"
+-- recursive CTE and an IDENTICAL final rollup (SUM by rootId). Only the
+-- "leafBalances" CTE differs — full-scan sums all history, snapshot+delta reads
+-- "snapshot + bounded delta". If you change account-tree construction or the
+-- root aggregation, change BOTH branches or they will disagree. The two branches
+-- MUST return identical results whenever snapshots are present (proven manually
+-- via a seed-both-ways psql diff). Collapsing them into one query with
+-- COALESCE-floored bounds is possible but is deferred until there is an
+-- automated (pgTAP) equivalence gate — do not hand-merge money-path SQL blind.
+-- ============================================================
+
+CREATE OR REPLACE FUNCTION "accountTreeBalancesByCompany" (
+ 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,
+ "balance" NUMERIC,
+ "balanceAtDate" NUMERIC,
+ "netChange" NUMERIC
+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+DECLARE
+ v_latest_date DATE; -- newest snapshot (for `balance`, which is unbounded)
+ v_at_date DATE; -- newest snapshot <= to_date (for balanceAtDate)
+ v_before_from DATE; -- newest snapshot < from_date (for netChange's lower bound)
+BEGIN
+ IF p_company_id IS NOT NULL THEN
+ SELECT MAX("endingBalanceDate") INTO v_latest_date
+ FROM "accountingPeriodBalance"
+ WHERE "companyId" = p_company_id;
+
+ SELECT MAX("endingBalanceDate") INTO v_at_date
+ FROM "accountingPeriodBalance"
+ WHERE "companyId" = p_company_id AND "endingBalanceDate" <= to_date;
+
+ SELECT MAX("endingBalanceDate") INTO v_before_from
+ FROM "accountingPeriodBalance"
+ WHERE "companyId" = p_company_id AND "endingBalanceDate" < from_date;
+ END IF;
+
+ IF v_latest_date IS NULL THEN
+ -- No snapshots for this company (or group-wide call): full-history scan,
+ -- identical to the 20260713225803 definition.
+ RETURN QUERY
+ WITH RECURSIVE "accountTree" AS (
+ SELECT
+ a."id",
+ a."id" AS "rootId",
+ a."isGroup"
+ FROM "account" a
+ WHERE a."companyGroupId" = p_company_group_id AND a."active" = true
+
+ UNION ALL
+
+ SELECT
+ child."id",
+ t."rootId",
+ child."isGroup"
+ FROM "accountTree" t
+ INNER JOIN "account" child ON child."parentId" = t."id"
+ WHERE t."isGroup" = true
+ AND child."companyGroupId" = p_company_group_id
+ AND child."active" = true
+ ),
+ "leafBalances" AS (
+ SELECT
+ a."id" AS "accountId",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' THEN jl."amount" ELSE 0 END), 0) AS "balance",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "balanceAtDate",
+ COALESCE(SUM(CASE WHEN j."status" <> 'Draft' AND j."postingDate" >= from_date AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END), 0) AS "netChange"
+ 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
+ t."rootId" AS "accountId",
+ COALESCE(SUM(lb."balance"), 0)::NUMERIC AS "balance",
+ COALESCE(SUM(lb."balanceAtDate"), 0)::NUMERIC AS "balanceAtDate",
+ COALESCE(SUM(lb."netChange"), 0)::NUMERIC AS "netChange"
+ FROM "accountTree" t
+ LEFT JOIN "leafBalances" lb ON lb."accountId" = t."id" AND t."isGroup" = false
+ GROUP BY t."rootId";
+ RETURN;
+ END IF;
+
+ RETURN QUERY
+ WITH RECURSIVE "accountTree" AS (
+ SELECT
+ a."id",
+ a."id" AS "rootId",
+ a."isGroup"
+ FROM "account" a
+ WHERE a."companyGroupId" = p_company_group_id AND a."active" = true
+
+ UNION ALL
+
+ SELECT
+ child."id",
+ t."rootId",
+ child."isGroup"
+ FROM "accountTree" t
+ INNER JOIN "account" child ON child."parentId" = t."id"
+ WHERE t."isGroup" = true
+ AND child."companyGroupId" = p_company_group_id
+ AND child."active" = true
+ ),
+ -- Only the lines the snapshots don't already cover: after the newest
+ -- snapshot each term uses, plus (for netChange's lower bound) the sliver
+ -- between its snapshot and from_date. Both are bounded postingDate ranges
+ -- served by journal_companyId_postingDate_idx.
+ "deltaLines" AS (
+ SELECT jl."accountId", jl."amount", j."postingDate"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl ON jl."journalId" = j."id"
+ WHERE j."companyId" = p_company_id
+ AND jl."companyId" = p_company_id
+ AND j."status" <> 'Draft'
+ AND (
+ j."postingDate" > LEAST(v_latest_date, COALESCE(v_at_date, DATE '0001-01-01'))
+ OR (j."postingDate" < from_date
+ AND j."postingDate" > COALESCE(v_before_from, DATE '0001-01-01'))
+ )
+ ),
+ "leafBalances" AS (
+ SELECT
+ a."id" AS "accountId",
+ COALESCE(sl."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN dl."postingDate" > v_latest_date
+ THEN dl."amount" ELSE 0 END), 0) AS "balance",
+ COALESCE(sa."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN dl."postingDate" > COALESCE(v_at_date, DATE '0001-01-01')
+ AND dl."postingDate" <= to_date
+ THEN dl."amount" ELSE 0 END), 0) AS "balanceAtDate",
+ (COALESCE(sa."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN dl."postingDate" > COALESCE(v_at_date, DATE '0001-01-01')
+ AND dl."postingDate" <= to_date
+ THEN dl."amount" ELSE 0 END), 0))
+ - (COALESCE(sb."endingBalance", 0)
+ + COALESCE(SUM(CASE WHEN dl."postingDate" > COALESCE(v_before_from, DATE '0001-01-01')
+ AND dl."postingDate" < from_date
+ THEN dl."amount" ELSE 0 END), 0)) AS "netChange"
+ FROM "account" a
+ LEFT JOIN "accountingPeriodBalance" sl ON sl."accountId" = a."id"
+ AND sl."companyId" = p_company_id AND sl."endingBalanceDate" = v_latest_date
+ LEFT JOIN "accountingPeriodBalance" sa ON sa."accountId" = a."id"
+ AND sa."companyId" = p_company_id AND sa."endingBalanceDate" = v_at_date
+ LEFT JOIN "accountingPeriodBalance" sb ON sb."accountId" = a."id"
+ AND sb."companyId" = p_company_id AND sb."endingBalanceDate" = v_before_from
+ LEFT JOIN "deltaLines" dl ON dl."accountId" = a."id"
+ WHERE a."companyGroupId" = p_company_group_id
+ AND a."isGroup" = false
+ AND a."active" = true
+ GROUP BY a."id", sl."endingBalance", sa."endingBalance", sb."endingBalance"
+ )
+ SELECT
+ t."rootId" AS "accountId",
+ COALESCE(SUM(lb."balance"), 0)::NUMERIC AS "balance",
+ COALESCE(SUM(lb."balanceAtDate"), 0)::NUMERIC AS "balanceAtDate",
+ COALESCE(SUM(lb."netChange"), 0)::NUMERIC AS "netChange"
+ FROM "accountTree" t
+ LEFT JOIN "leafBalances" lb ON lb."accountId" = t."id" AND t."isGroup" = false
+ GROUP BY t."rootId";
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260713235406_item-ledger-snapshot.sql b/packages/database/supabase/migrations/20260713235406_item-ledger-snapshot.sql
new file mode 100644
index 0000000000..35338bf5b5
--- /dev/null
+++ b/packages/database/supabase/migrations/20260713235406_item-ledger-snapshot.sql
@@ -0,0 +1,517 @@
+-- ============================================================
+-- itemLedgerSnapshot: snapshot + delta for on-hand quantity reads.
+--
+-- get_inventory_quantities and get_inventory_value_by_location aggregated the
+-- full itemLedger history on every call. This adds a materialized snapshot so
+-- live reads scan only (a) tracked-entity rows and (b) rows newer than the
+-- snapshot cutoff — both small, indexed subsets — while remaining EXACT:
+--
+-- * Only untracked rows ("trackedEntityId" IS NULL) are snapshotted. They
+-- are append-only and immutable. Tracked rows are ALWAYS computed live,
+-- because sync_item_ledger_on_tracked_entity_status_change (20260420112047)
+-- rewrites their "trackedEntityStatus" in place and the status-aware sums
+-- (Rejected / On Hold) must never be stale.
+-- * The snapshot cuts off at now() - 1 hour ("snapshotCutoff" column) rather
+-- than at a max entryNumber. SERIAL values don't respect commit order, so
+-- an entryNumber watermark can permanently miss a row that committed after
+-- the refresh with a lower sequence value. "createdAt" is the transaction
+-- start time, so any row with createdAt older than the cutoff is committed
+-- and visible by refresh time — as long as no write transaction runs
+-- longer than 1 hour (posting transactions run for seconds).
+-- * Readers partition exactly: snapshot rows have createdAt < cutoff, the
+-- live delta takes createdAt >= cutoff. A company with no snapshot rows
+-- (cutoff NULL) falls back to the full live scan — identical behavior.
+--
+-- itemStockQuantities (the UI item-store matview consumed by
+-- RealtimeDataProvider) is intentionally untouched — it remains the
+-- approximate, consumer-facing total. This matview is a private building
+-- block for the SECURITY DEFINER read functions, hence the REVOKEs.
+-- ============================================================
+
+-- Tracked rows are always read live; give those scans their own partial index.
+CREATE INDEX IF NOT EXISTS "itemLedger_tracked_companyId_locationId_itemId_idx"
+ ON "itemLedger" ("companyId", "locationId", "itemId")
+ WHERE "trackedEntityId" IS NOT NULL;
+
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'refresh-item-ledger-snapshot') THEN
+ PERFORM cron.unschedule('refresh-item-ledger-snapshot');
+ END IF;
+END $$;
+
+DROP MATERIALIZED VIEW IF EXISTS "itemLedgerSnapshot";
+
+CREATE MATERIALIZED VIEW "itemLedgerSnapshot" AS
+SELECT
+ "itemId",
+ "companyId",
+ COALESCE("locationId", '') AS "locationId",
+ SUM("quantity") AS "quantity",
+ SUM(CASE
+ WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND "createdAt" >= CURRENT_DATE - INTERVAL '30 days'
+ THEN -"quantity"
+ ELSE 0
+ END) AS "consumed30",
+ SUM(CASE
+ WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND "createdAt" >= CURRENT_DATE - INTERVAL '90 days'
+ THEN -"quantity"
+ ELSE 0
+ END) AS "consumed90",
+ ARRAY_AGG(DISTINCT "storageUnitId") FILTER (WHERE "storageUnitId" IS NOT NULL) AS "storageUnitIds",
+ now() - INTERVAL '1 hour' AS "snapshotCutoff"
+FROM "itemLedger"
+WHERE "trackedEntityId" IS NULL
+ AND "createdAt" < now() - INTERVAL '1 hour'
+GROUP BY "itemId", "companyId", COALESCE("locationId", '');
+
+CREATE UNIQUE INDEX "itemLedgerSnapshot_itemId_companyId_locationId_idx"
+ ON "itemLedgerSnapshot" ("itemId", "companyId", "locationId");
+
+CREATE INDEX "itemLedgerSnapshot_companyId_locationId_idx"
+ ON "itemLedgerSnapshot" ("companyId", "locationId");
+
+-- Matviews don't support RLS; this one is only read inside SECURITY DEFINER
+-- functions, so keep it out of PostgREST entirely.
+REVOKE ALL ON "itemLedgerSnapshot" FROM anon, authenticated;
+
+SELECT
+ cron.schedule(
+ 'refresh-item-ledger-snapshot',
+ '*/30 * * * *',
+ $$
+ REFRESH MATERIALIZED VIEW CONCURRENTLY "itemLedgerSnapshot";
+ $$
+ );
+
+-- ---------------------------------------------------------------------------
+-- get_inventory_quantities: snapshot + delta.
+-- Forked from 20260713231142_inventory-quantities-item-filter.sql. Only the
+-- item_ledgers / item_storage_types / item_storage_units CTEs changed: each
+-- now combines three arms — the snapshot, live tracked rows, and the live
+-- untracked delta past the snapshot cutoff.
+-- ---------------------------------------------------------------------------
+
+DROP FUNCTION IF EXISTS get_inventory_quantities(TEXT, TEXT);
+DROP FUNCTION IF EXISTS get_inventory_quantities(TEXT, TEXT, TEXT);
+
+CREATE OR REPLACE FUNCTION get_inventory_quantities(company_id TEXT, location_id TEXT, item_id TEXT DEFAULT NULL)
+ RETURNS TABLE (
+ "id" TEXT,
+ "readableId" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "active" BOOLEAN,
+ "type" "itemType",
+ "itemTrackingType" "itemTrackingType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "materialSubstanceId" TEXT,
+ "materialFormId" TEXT,
+ "dimensionId" TEXT,
+ "dimension" TEXT,
+ "finishId" TEXT,
+ "finish" TEXT,
+ "gradeId" TEXT,
+ "grade" TEXT,
+ "materialType" TEXT,
+ "materialTypeId" TEXT,
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "leadTime" INTEGER,
+ "lotSize" INTEGER,
+ "reorderingPolicy" "itemReorderingPolicy",
+ "demandAccumulationPeriod" INTEGER,
+ "demandAccumulationSafetyStock" NUMERIC,
+ "reorderPoint" INTEGER,
+ "reorderQuantity" INTEGER,
+ "minimumOrderQuantity" INTEGER,
+ "maximumOrderQuantity" INTEGER,
+ "maximumInventoryQuantity" NUMERIC,
+ "orderMultiple" INTEGER,
+ "quantityOnHand" NUMERIC,
+ "quantityOnHold" NUMERIC,
+ "quantityRejected" NUMERIC,
+ "quantityOnSalesOrder" NUMERIC,
+ "quantityOnPurchaseOrder" NUMERIC,
+ "quantityOnProductionOrder" NUMERIC,
+ "quantityOnProductionDemand" NUMERIC,
+ "demandForecast" NUMERIC,
+ "usageLast30Days" NUMERIC,
+ "usageLast90Days" NUMERIC,
+ "daysRemaining" NUMERIC,
+ "storageTypeIds" TEXT[],
+ "storageUnitIds" TEXT[]
+ ) AS $$
+ DECLARE
+ v_cutoff TIMESTAMPTZ;
+ BEGIN
+ SELECT MAX("snapshotCutoff") INTO v_cutoff
+ FROM "itemLedgerSnapshot"
+ WHERE "companyId" = company_id;
+
+ RETURN QUERY
+
+WITH
+ open_purchase_orders AS (
+ SELECT
+ pol."itemId",
+ SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"
+ FROM
+ "purchaseOrder" po
+ INNER JOIN "purchaseOrderLine" pol
+ ON pol."purchaseOrderId" = po."id"
+ WHERE
+ po."status" IN (
+ 'Planned',
+ 'To Receive',
+ 'To Receive and Invoice'
+ )
+ AND po."companyId" = company_id
+ AND pol."locationId" = location_id
+ AND (item_id IS NULL OR pol."itemId" = item_id)
+ GROUP BY pol."itemId"
+ ),
+ open_sales_orders AS (
+ SELECT
+ sol."itemId",
+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"
+ FROM
+ "salesOrder" so
+ INNER JOIN "salesOrderLine" sol
+ ON sol."salesOrderId" = so."id"
+ WHERE
+ so."status" IN (
+ 'Confirmed',
+ 'To Ship and Invoice',
+ 'To Ship',
+ 'To Invoice',
+ 'In Progress'
+ )
+ AND so."companyId" = company_id
+ AND sol."locationId" = location_id
+ AND (item_id IS NULL OR sol."itemId" = item_id)
+ GROUP BY sol."itemId"
+ ),
+ open_job_requirements AS (
+ SELECT
+ jm."itemId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ AND (item_id IS NULL OR jm."itemId" = item_id)
+ GROUP BY jm."itemId"
+ ),
+ open_jobs AS (
+ SELECT
+ j."itemId",
+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"
+ FROM job j
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ AND (item_id IS NULL OR j."itemId" = item_id)
+ GROUP BY j."itemId"
+ ),
+ -- Snapshot (immutable untracked rows) + live tracked rows + live untracked
+ -- rows past the snapshot cutoff. With no snapshot (v_cutoff NULL) the third
+ -- arm is the full untracked history — the pre-snapshot behavior.
+ item_ledgers AS (
+ SELECT
+ combined."itemId",
+ SUM(combined."quantityOnHand") AS "quantityOnHand",
+ SUM(combined."quantityOnHold") AS "quantityOnHold",
+ SUM(combined."quantityRejected") AS "quantityRejected",
+ SUM(combined."consumed30") / 30 AS "usageLast30Days",
+ SUM(combined."consumed90") / 90 AS "usageLast90Days"
+ FROM (
+ SELECT
+ s."itemId",
+ s."quantity" AS "quantityOnHand",
+ 0::NUMERIC AS "quantityOnHold",
+ 0::NUMERIC AS "quantityRejected",
+ s."consumed30",
+ s."consumed90"
+ FROM "itemLedgerSnapshot" s
+ WHERE s."companyId" = company_id
+ AND s."locationId" = location_id
+ AND (item_id IS NULL OR s."itemId" = item_id)
+
+ UNION ALL
+
+ SELECT
+ il."itemId",
+ CASE WHEN il."trackedEntityStatus" IS NULL
+ OR il."trackedEntityStatus" != 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'On Hold'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '30 days'
+ THEN -il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '90 days'
+ THEN -il."quantity" ELSE 0 END
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NOT NULL
+
+ UNION ALL
+
+ SELECT
+ il."itemId",
+ CASE WHEN il."trackedEntityStatus" IS NULL
+ OR il."trackedEntityStatus" != 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'On Hold'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '30 days'
+ THEN -il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '90 days'
+ THEN -il."quantity" ELSE 0 END
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NULL
+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ ) combined
+ GROUP BY combined."itemId"
+ ),
+ -- Distinct storage units the item is stocked in: snapshot arrays plus the
+ -- same live arms. NULL storageUnitId rows are excluded.
+ item_storage_units AS (
+ SELECT
+ u."itemId",
+ ARRAY_AGG(DISTINCT u."storageUnitId") AS "storageUnitIds"
+ FROM (
+ SELECT s."itemId", su_id AS "storageUnitId"
+ FROM "itemLedgerSnapshot" s
+ CROSS JOIN LATERAL unnest(s."storageUnitIds") AS su_id
+ WHERE s."companyId" = company_id
+ AND s."locationId" = location_id
+ AND (item_id IS NULL OR s."itemId" = item_id)
+
+ UNION ALL
+
+ SELECT il."itemId", il."storageUnitId"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND il."storageUnitId" IS NOT NULL
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NOT NULL
+
+ UNION ALL
+
+ SELECT il."itemId", il."storageUnitId"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND il."storageUnitId" IS NOT NULL
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NULL
+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ ) u
+ GROUP BY u."itemId"
+ ),
+ -- Distinct storage types, derived from the merged storage-unit ids.
+ item_storage_types AS (
+ SELECT
+ isu."itemId",
+ ARRAY_AGG(DISTINCT t) AS "storageTypeIds"
+ FROM item_storage_units isu
+ INNER JOIN "storageUnit" su
+ ON su."id" = ANY(isu."storageUnitIds")
+ AND su."companyId" = company_id
+ CROSS JOIN LATERAL unnest(su."storageTypeIds") AS t
+ GROUP BY isu."itemId"
+ ),
+ demand_forecast AS (
+ SELECT combined."itemId", SUM(qty) AS "demandForecast"
+ FROM (
+ SELECT da."itemId", da."actualQuantity" AS qty
+ FROM "demandActual" da
+ WHERE da."companyId" = company_id AND da."locationId" = location_id
+ AND (item_id IS NULL OR da."itemId" = item_id)
+ UNION ALL
+ SELECT df."itemId", df."forecastQuantity" AS qty
+ FROM "demandForecast" df
+ WHERE df."companyId" = company_id AND df."locationId" = location_id
+ AND (item_id IS NULL OR df."itemId" = item_id)
+ ) combined
+ GROUP BY combined."itemId"
+ )
+
+SELECT
+ i."id",
+ i."readableId",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ m."materialSubstanceId",
+ m."materialFormId",
+ m."dimensionId",
+ md."name" AS "dimension",
+ m."finishId",
+ mf."name" AS "finish",
+ m."gradeId",
+ mg."name" AS "grade",
+ mt."name" AS "materialType",
+ m."materialTypeId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."maximumInventoryQuantity",
+ ip."orderMultiple",
+ COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",
+ COALESCE(il."quantityOnHold", 0) AS "quantityOnHold",
+ COALESCE(il."quantityRejected", 0) AS "quantityRejected",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(jo."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(jr."quantityOnProductionDemand", 0) AS "quantityOnProductionDemand",
+ COALESCE(df."demandForecast", 0) AS "demandForecast",
+ COALESCE(il."usageLast30Days", 0) AS "usageLast30Days",
+ COALESCE(il."usageLast90Days", 0) AS "usageLast90Days",
+ CASE
+ WHEN COALESCE(il."usageLast30Days", 0) > 0
+ THEN ROUND(COALESCE(il."quantityOnHand", 0) / il."usageLast30Days", 2)
+ ELSE NULL
+ END AS "daysRemaining",
+ COALESCE(ist."storageTypeIds", ARRAY[]::TEXT[]) AS "storageTypeIds",
+ COALESCE(isu."storageUnitIds", ARRAY[]::TEXT[]) AS "storageUnitIds"
+FROM
+ "item" i
+ LEFT JOIN item_ledgers il ON i."id" = il."itemId"
+ LEFT JOIN item_storage_types ist ON i."id" = ist."itemId"
+ LEFT JOIN item_storage_units isu ON i."id" = isu."itemId"
+ LEFT JOIN open_sales_orders so ON i."id" = so."itemId"
+ LEFT JOIN open_purchase_orders po ON i."id" = po."itemId"
+ LEFT JOIN open_jobs jo ON i."id" = jo."itemId"
+ LEFT JOIN open_job_requirements jr ON i."id" = jr."itemId"
+ LEFT JOIN demand_forecast df ON i."id" = df."itemId"
+ LEFT JOIN material m ON i."readableId" = m."id" AND m."companyId" = company_id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md."id"
+ LEFT JOIN "materialFinish" mf ON m."finishId" = mf."id"
+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg."id"
+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt."id"
+ LEFT JOIN "itemReplenishment" ir ON i."id" = ir."itemId" AND ir."companyId" = company_id
+ LEFT JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id
+WHERE
+ i."itemTrackingType" <> 'Non-Inventory' AND i."companyId" = company_id
+ AND (item_id IS NULL OR i."id" = item_id);
+ END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- ---------------------------------------------------------------------------
+-- get_inventory_value_by_location: snapshot + delta.
+-- Forked from 20260325031223_inventory-value-report.sql. The original summed
+-- ALL rows regardless of tracked-entity status, so all three arms sum plain
+-- quantity here.
+-- ---------------------------------------------------------------------------
+
+DROP FUNCTION IF EXISTS get_inventory_value_by_location;
+
+CREATE OR REPLACE FUNCTION get_inventory_value_by_location(company_id TEXT)
+RETURNS TABLE (
+ "locationName" TEXT,
+ "itemReadableId" TEXT,
+ "itemName" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "quantityOnHand" NUMERIC,
+ "unitCost" NUMERIC,
+ "totalValue" NUMERIC
+) AS $$
+DECLARE
+ v_cutoff TIMESTAMPTZ;
+BEGIN
+ SELECT MAX("snapshotCutoff") INTO v_cutoff
+ FROM "itemLedgerSnapshot"
+ WHERE "companyId" = company_id;
+
+ RETURN QUERY
+ WITH item_ledgers AS (
+ SELECT
+ combined."itemId",
+ combined."locationId",
+ SUM(combined."quantity") AS "quantityOnHand"
+ FROM (
+ SELECT s."itemId", NULLIF(s."locationId", '') AS "locationId", s."quantity"
+ FROM "itemLedgerSnapshot" s
+ WHERE s."companyId" = company_id
+
+ UNION ALL
+
+ SELECT il."itemId", il."locationId", il."quantity"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."trackedEntityId" IS NOT NULL
+
+ UNION ALL
+
+ SELECT il."itemId", il."locationId", il."quantity"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."trackedEntityId" IS NULL
+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ ) combined
+ GROUP BY combined."itemId", combined."locationId"
+ HAVING SUM(combined."quantity") <> 0
+ )
+ SELECT
+ l."name" AS "locationName",
+ i."readableIdWithRevision" AS "itemReadableId",
+ i."name" AS "itemName",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ il."quantityOnHand",
+ COALESCE(ic."unitCost", 0) AS "unitCost",
+ il."quantityOnHand" * COALESCE(ic."unitCost", 0) AS "totalValue"
+ FROM item_ledgers il
+ INNER JOIN "item" i ON il."itemId" = i."id"
+ INNER JOIN "location" l ON il."locationId" = l."id"
+ LEFT JOIN "itemCost" ic ON i."id" = ic."itemId"
+ WHERE i."companyId" = company_id
+ ORDER BY l."name", i."readableId";
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/database/supabase/migrations/20260713235930_close-snapshot-posting-lock.sql b/packages/database/supabase/migrations/20260713235930_close-snapshot-posting-lock.sql
new file mode 100644
index 0000000000..8480b97316
--- /dev/null
+++ b/packages/database/supabase/migrations/20260713235930_close-snapshot-posting-lock.sql
@@ -0,0 +1,100 @@
+-- ============================================================
+-- Close the concurrency gap between posting and period close introduced by the
+-- accountingPeriodBalance snapshot (20260713232634).
+--
+-- The snapshot is written inside closeAccountingPeriod's transaction, after the
+-- period flips to Closed. A period only becomes Closed on COMMIT, and a Locked
+-- period still accepts postings (that is the point of Locked). So without extra
+-- locking a journal could be inserted into the period in the window between the
+-- close txn's snapshot SELECT and its COMMIT: the posting's BEFORE trigger reads
+-- the period as still-Locked (the close's UPDATE is uncommitted), lets it
+-- through, and it commits a line with postingDate <= endDate that the snapshot
+-- never saw. The read path's delta only picks up postingDate > endDate, so that
+-- line would be silently dropped from the optimized balance until reopen+reclose.
+--
+-- Fix: the posting guard reads the target period FOR SHARE. FOR SHARE conflicts
+-- with the FOR-NO-KEY-UPDATE row lock that closeAccountingPeriod's
+-- `UPDATE ... SET "closeStatus" = 'Closed'` holds until commit, so:
+-- * a posting that starts before the close's UPDATE takes its share lock
+-- first; the close's UPDATE then waits for the posting to commit, and the
+-- snapshot (which runs after the UPDATE) sees that line.
+-- * a posting that starts after the close's UPDATE blocks on the exclusive
+-- lock until the close commits, then re-reads closeStatus = 'Closed' and is
+-- rejected.
+-- Either ordering is now race-free. Concurrent postings do NOT block each other
+-- (FOR SHARE is shared); only an in-flight close serializes them briefly.
+--
+-- Forked from 20260702044133_period-close-lifecycle.sql. Only the final
+-- period-status SELECT (the INSERT / move-into path) gains FOR SHARE — that is
+-- the path a new line lands on. CREATE OR REPLACE keeps the existing
+-- journal_check_period_open trigger binding intact.
+-- ============================================================
+
+CREATE OR REPLACE FUNCTION public.check_accounting_period_open()
+RETURNS trigger
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path TO 'public'
+AS $function$
+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;
+
+ -- FOR SHARE: block behind an in-flight close of this period (see header) so a
+ -- posting can never slip a line into a period after its snapshot was taken.
+ 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
+ FOR SHARE;
+
+ IF v_new_status = 'Closed' THEN
+ RAISE EXCEPTION 'Accounting period is closed for posting date %', NEW."postingDate";
+ END IF;
+
+ RETURN NEW;
+END;
+$function$;