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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(inventory): real-time item quantities + MRP correctness fixes (#1373)
Sid228b336923aa
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex f518163e2c..607ed6a8d2 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -923,3 +923,33 @@ canvas hosting Radix popovers/selects.**Rule:** When porting a query from supabase-js to Kysely, treat every `NUMERIC`/`DECIMAL`/`BIGINT` read as a **string** regardless of what the generated type claims. Normalize with `Number(...)` only where the value has to be a number — an object/`Map` key, a `===` comparison, arithmetic — and only for bounded fields like a quantity or a precision. Do **not** normalize a whole row for tidiness: `Number()` on a `BIGINT` or a wide `NUMERIC` silently loses precision past `Number.MAX_SAFE_INTEGER`, and money is exactly where that matters. Writing values back untouched is both safe and preferable — pg accepts the canonical string for a numeric param, and passing it straight through preserves the stored value exactly. More generally: a client swap can change runtime value types without changing a single TypeScript type, so a typecheck is not evidence that a port behaves identically — exercise it against a real database.**Applies to:** `apps/erp/app/modules/sales/sales.service.ts` (`upsertQuoteLinePrices`), any `Kysely<KyselyDatabase>` service in `apps/erp/app/modules/**` or `packages/database/supabase/functions/**`, and the `getPostgresClient` pool in `packages/database/supabase/functions/lib/postgres/index.ts`.++## Postgres transition tables are visible ONLY to the function the trigger invokes directly++**Context:** The `itemStockQuantities` aggregate needed a statement-level handler on `itemLedger` so a bulk posting is one upsert instead of N. The event system already builds statement-level triggers (`trg_event_async_*` with `REFERENCING NEW TABLE AS batched_new`), so the obvious move was to have `dispatch_event_batch()` forward to a custom function.++**Problem:** A nested call cannot see the transition tables. A plain function called from the trigger function fails with `relation "batched_new" does not exist` — and this holds for dynamic SQL too (`EXECUTE 'SELECT count(*) FROM batched_new'` fails identically), because the ephemeral named relation lives in the trigger function's own query environment and is not propagated. The only ways to hand a batch onward are materializing it into a temp table per statement (real cost on a hot write path) or not nesting at all. Separately, `dispatch_event_batch()` early-returns when a table has no active subscription and when `app.sync_in_progress` is set — both correct for queueing, fatal for an aggregate that must always be maintained.++**Rule:** A function that needs `batched_new`/`batched_old` must be attached as the trigger's own function. Use `attach_statement_handler(table, functions[])` (`20260812002453`), the statement-level sibling of the row-level interceptors; it does not enqueue to PGMQ. Handlers are attached for INSERT/UPDATE/DELETE and must branch on `TG_OP` — only `batched_new` exists on INSERT, only `batched_old` on DELETE (PL/pgSQL plans lazily, so an unexecuted branch never resolves its missing table). Note also that adding a defaulted parameter to `attach_event_trigger` is a trap: two overloads are live, and a third with defaults makes existing 2-arg calls ambiguous.++**Applies to:** `packages/database/supabase/migrations/20260812002453_event-system-statement-handlers.sql`, `.claude/rules/event-system.md`, any statement-level trigger work under `packages/database/supabase/migrations/`.++## Enumerate the full ON DELETE graph before writing a data-deleting migration++**Context:** A migration deleted 50 `jobMaterial` rows where a job listed its own output item as a material. A dry run "passed": it completed, and `productionQuantity` was verified unchanged at 4,566 rows.++**Problem:** The verification only covered the one child table that happens to be `NO ACTION`. `jobMaterial → jobMakeMethod → jobOperation` cascades into **six** further tables — `productionEvent` (labor/time), `jobOperationTool`, `jobOperationStep`, `jobOperationParameter`, `rework`, `nonConformanceJobOperation` — all `CASCADE`, all silent. `productionQuantity` was noticed precisely because `NO ACTION` raises an error; the destructive edges said nothing. Comparing the restored database against the untouched backup showed `productionEvent` had gone 3,159 → 3,158: one real customer labor record destroyed by a migration that appeared to succeed.++**Rule:** Before any `DELETE` in a migration, query `pg_constraint` for `confrelid` of every table the delete can reach and read `confdeltype` for each edge (`c` = CASCADE, `r`/`a` = RESTRICT/NO ACTION, `n` = SET NULL). The `RESTRICT` edges are the ones that will teach you by failing; the `CASCADE` edges are where the data actually goes. Design the cleanup so the cascade cannot reach anything historical — here, detaching (`parentMaterialId = NULL`) every subtree containing ANY `jobOperation`, so only empty method copies are collected. Verify with a probe that builds the exact structure, runs the real delete statement, and asserts the child rows survive — and where a snapshot exists, diff the affected table's count against the backup rather than trusting that the statement completed.++**Applies to:** `packages/database/supabase/migrations/20260812032423_job-material-self-reference-guard.sql`, any migration under `packages/database/supabase/migrations/` containing `DELETE FROM`.++## `max_rows` is enforced in production but not by the local dev stack++**Context:** MRP's Phase-1 loads used bare `.select("*")` with no pagination, and had done so since the function was written. Every local test passed.++**Problem:** `packages/database/supabase/config.toml` sets `max_rows = 1000`, so PostgREST truncates responses in production. The crbn dev stack runs its own `postgrest` container without `PGRST_DB_MAX_ROWS`, so locally the same query returns everything — verified: a view with 2,497 rows returned all 2,497 locally. Two production tenants exceeded the cap on `openJobMaterialLines` (2,497 and 1,495 rows) and a third on `demandActual` (9,391), so MRP silently planned on truncated demand and its zeroing pass missed stale actuals. The bug is structurally invisible to local testing.++**Rule:** Any PostgREST read that can exceed 1000 rows must paginate — `fetchAllFromTable`/`fetchAllRecords` from `@carbon/database` in app code, `fetchAll` from `supabase/functions/lib/fetch-all.ts` in edge functions — and must carry a stable `.order()` so pages don't shift between requests. Do not conclude "it returns everything" from a local run; check the row count against `max_rows` in `config.toml` instead.++**Applies to:** `packages/database/supabase/functions/mrp/index.ts`, `packages/database/supabase/functions/lib/fetch-all.ts`, `packages/database/supabase/config.toml`, any `.select()` in `packages/database/supabase/functions/**` or `apps/erp/app/modules/**`.diff --git a/.ai/research/2026-08-12-mrp-findings.md b/.ai/research/2026-08-12-mrp-findings.mdnew file mode 100644index 0000000000..51dea64f09--- /dev/null+++ b/.ai/research/2026-08-12-mrp-findings.md@@ -0,0 +1,241 @@+# MRP: measured findings from the production snapshot++Measured 2026-08-12 against a restored production cluster dump+(`<production cluster dump>`, 1,634 companies, 18,542 items, 15,095 make+methods, 12,534 method materials, 24,310 `itemLedger` rows — amplified to 8M+ledger rows for one tenant during the `itemStockQuantities` benchmark). All+numbers are from real runs, not estimates. Companion work: the incremental+`itemStockQuantities` table (branch `sid/item-dropdown-inventory-refresh`,+commit `54416a34bb`).++## Bugs found (ranked)++### 1. CRITICAL — MRP hard-fails for tenants with hyphenated (imported) item ids — **FIXED 2026-08-12**++Fixed on `sid/item-dropdown-inventory-refresh`: composite keys now join on a+control character (`KEY_SEP = "\x1f"` in `lib/mrp-engine.ts`), every inline key+construction in `mrp/index.ts` goes through `makeKey` / `makeLocationItemKey` /+`makeActualKey`, and Deno regression tests cover hyphenated ids in every key+position (`lib/mrp-engine.test.ts`). Verified live: the failing tenant returns+201 with 256 demandActual + 29 supplyActual rows, all full UUIDs, zero orphan+refs; the giant tenant's output is byte-identical pre/post fix.++`mrp/index.ts` Phase 6 rebuilds composite map keys with naive splits:++```ts+// key layout: `${itemId}-${locationId}-${periodId}-Sales Order`+itemId: key.split("-")[0], locationId: key.split("-")[1], periodId: key.split("-")[2]+// and for supply: const [locationId, periodId, itemId] = key.split("-")+```++`item.id` is TEXT and the import pipeline accepts caller-supplied ids, so+migrated data can carry any id shape. In the snapshot, 330 items across 3+tenants have **UUID v5** ids (deterministic name-based — the fingerprint of a+bulk import minting idempotent ids; all created in single-day batches per+tenant). A hyphenated itemId is truncated to its first segment by the split,+distinct (item, period) pairs collapse to the same tuple, and the batched+insert dies with Postgres error 21000 (`ON CONFLICT DO UPDATE command cannot+affect row a second time`). Reproduced: tenant `tenant-B` (all+229 open-line item ids are UUIDs) → HTTP 500 every run. Because ids arrive via+onboarding imports, the affected population is *recently migrated customers*,+and it grows with every data migration — not a frozen legacy set.++- **Silent in production.** The 3-hourly scheduler (`scheduled/mrp.ts:34-43`)+ logs `result.error` and continues. Production evidence: that tenant has+ **zero `demandActual` rows** in the snapshot — MRP has never completed for+ them.+- **Partial-write corruption on every failure — FIXED 2026-08-12.** The run+ deleted and rewrote `demandForecast` (+source) successfully, then crashed at+ `demandActual` — affected tenants carried fresh forecasts and permanently+ empty actuals. Phase 7 is now one Kysely transaction. Proven by fault+ injection: with a poisoned trigger on the LAST table written, the run 500s+ and `demandForecast` is untouched to the microsecond (previously it was+ wiped and rewritten before the crash).+- Blast radius in the snapshot: ≥4 tenants with hyphenated item ids in open job+ demand.+- Fix shape: stop round-tripping through string keys — carry structured+ `{itemId, locationId, periodId}` values in the maps (or reuse `splitKey`,+ which already handles hyphenated ids by position). Small, mechanical.++### 2. HIGH — input truncation at PostgREST `max_rows` (prod-only) — **FIXED 2026-08-12**++Fixed: all PostgREST reads in `mrp/index.ts` paginate via `lib/fetch-all.ts`+(1000-row pages, stable `.order()`), including the Phase-6 `demandActual` /+`supplyActual` reads, which also exceeded the cap (9,391 rows observed — in+prod their zeroing pass was truncated too). Verified: the tenant whose inputs+span multiple pages (2,497 job lines, 9,391 actuals) produces byte-identical+output to the unpaginated baseline.++Phase-1 loads use bare `.select("*")` with no pagination. Production+`config.toml` sets `max_rows = 1000`; the crbn dev stack does **not** enforce it+(verified empirically: 2,497 rows returned locally), which is why this is+invisible in dev. Snapshot tenants over the limit: `tenant-A`+(2,497 open job material lines) and `tenant-B` (1,495). In prod+those tenants plan on a silently truncated demand picture. Fix:+`fetchAllFromTable`-style pagination for the five Phase-1 reads.++### 3. MEDIUM — self-referencing BOMs exist in production data — **BOM layer FIXED 2026-08-12**++Fixed in `20260812030545_bom-self-reference-guard.sql`: the 6 `methodMaterial`+self-references deleted (all confirmed accidental: 4× tenant-E purchased+hardware, 1× tenant-F mis-pick, 1× test-tenant junk), and a **sync+interceptor** (`sync_check_method_material_self_reference`, wired via+`attach_event_trigger`) now vetoes both shapes on write — item on its own BOM,+and `materialMakeMethodId = makeMethodId`. Verified: both vetoes fire with+`check_violation`, legitimate BOM lines still insert.++**Job layer also FIXED 2026-08-12** (`20260812032423_job-material-self-reference-guard.sql`),+by product decision: self-consumption benefits no one and should have been+prevented from the start. `jobMaterial` rows where the job consumes its own+output item numbered **50 across ~20 tenants** — most added directly on jobs,+not copied from BOMs. All 50 deleted; a sync interceptor+(`sync_check_job_material_self_reference`, PREPENDED to jobMaterial's existing+interceptor chain) now vetoes the class on every write path. Deletion nuance+that mattered, and that a first pass got WRONG: the cascade chain+(`jobMaterial → jobMakeMethod → jobOperation`) reaches SIX child tables —+`productionEvent` (labor/time), `jobOperationTool`, `jobOperationStep`,+`jobOperationParameter`, `rework`, `nonConformanceJobOperation`. Only+`productionQuantity` is `NO ACTION`; it raises, which is the only reason the+problem was noticed at all. The others delete silently. A first version of this+migration detached only subtrees containing `productionQuantity` and did+destroy a labor record on the restored snapshot (`productionEvent` 3,159 in the+backup → 3,158 after). The shipped version detaches every subtree containing+ANY `jobOperation`, so the cascade can never reach an operation; only empty+method copies are collected. Re-proven by probe: labor 1→1, operation kept,+self-consuming line deleted. Verified: 0 self-rows remain, veto fires,+legitimate materials insert, existing interceptor chain intact.++**Lesson worth generalizing:** before writing any data-deleting migration,+enumerate the full `ON DELETE` graph (`pg_constraint.confdeltype`) — a+`RESTRICT`/`NO ACTION` edge fails loudly and teaches you; every `CASCADE` edge+is silent and is where the data actually goes.++6 `methodMaterial` rows across 3 tenants list an item as a component of itself+(one at quantity **100**): 4 purchased-hardware parts in `tenant-E`, 1 in+`tenant-F`, and 1 junk row in a test tenant.+`computeLowLevelCodes` survives via its `visited`+guard (silently truncating the cycle); `explodeBom` does not loop but generates+self-demand that is never netted — inflated, wrong requirements for those items.+Two-part fix: a DB guard (`CHECK`/trigger rejecting `mm."itemId" =+makeMethod."itemId"`, plus data cleanup) and explicit cycle detection in the+engine (comes free with the Kahn rewrite below).++## Before/after benchmark (same DB, same 8M-row ledger, 2026-08-12)++End-to-end MRP, 5 runs per tenant, best-of reported (edge function via HTTP):++| Tenant | Shape | Before | After | Change |+|---|---|---|---|---|+| `tenant-C` | mid-size, 1,739 BOM edges | 0.52 s | **0.084 s** | 6× faster |+| `tenant-A` | giant, 8M ledger rows | 17.5–20.4 s | **0.226 s** | **~85× faster** |+| `tenant-B` | imported UUID item ids | **HTTP 500** (every run, since onboarding) | **0.207 s** | now works at all |+| `tenant-D` (tenant-D) | contains a BOM cycle | silently mis-planned | **0.036 s** + logged warning | now correct + visible |++Component: the on-hand input, both queries measured back-to-back on the same+data —++| On-hand input | Time |+|---|---|+| OLD: `SELECT itemId, locationId, SUM(quantity) FROM itemLedger WHERE companyId=… GROUP BY` | **19.8–20.3 s** |+| NEW: `SELECT … FROM itemStockQuantities WHERE companyId=…` | **0.27–5.6 ms** |++The old query's plan explains the whole run: `Buffers: shared hit=840+read=399986` — ~3 GB read from disk per run, I/O-bound, and it does not warm up+across repeats (the table is 6 GB against a much smaller `shared_buffers`).+NOTE: an earlier probe in this document measured 0.8–1.7 s for "the same"+query; that was a `count(*)` wrapper measured immediately after the amplifying+writes, i.e. a different plan against warm page cache. The ~20 s figure is the+honest steady state, and it matches the observed 17.5–20.4 s end-to-end run.++### Low-level codes: Kahn vs path enumeration++On real customer BOMs the two are equivalent (worst real case 2.03 ms → 0.49 ms,+4.1×) — the exponential blowup is NOT triggered by current data, as first+measured. But the risk is real and cheap to demonstrate on a *tiny* graph+whose node count grows linearly while root-to-node paths grow exponentially:++| Layers | Nodes | Edges | Old | Kahn | Speedup |+|---|---|---|---|---|---|+| 8 | 18 | 32 | 0.59 ms | 0.106 ms | 6× |+| 12 | 26 | 48 | 4.19 ms | 0.023 ms | 181× |+| 16 | 34 | 64 | 59.0 ms | 0.031 ms | 1,927× |+| 18 | 38 | 72 | 211.5 ms | 0.034 ms | 6,283× |+| 20 | 42 | 80 | **851.8 ms** | 0.038 ms | **22,639×** |++A **42-node** BOM — trivially small — took the old implementation 0.85 s, and+each added layer roughly quadruples it. Reuse-heavy nesting like this is normal+in electronics and aerospace assemblies, so this was a live landmine for the+next customer with a deep BOM, not a theoretical one.++## Performance baselines (measured)++| Scenario | Wall time |+|---|---|+| Full company MRP, mid-size tenant (`tenant-C`, 1,739 BOM edges, 199 methods) | **0.52 s** |+| Full company MRP, giant tenant (`tenant-A`, 3,330 BOM edges, 8M-row amplified ledger) | **17.5–20.4 s** |++Attribution for the giant (sampled `pg_stat_activity` during the run + direct+query timing):++| Component | Cost |+|---|---|+| `itemLedger` GROUP BY on-hand input (8M rows) | ~6–8 s from the function's connection (0.8–1.7 s via psql — plan/streaming difference) |+| The four open-demand/supply view reads | < 50 ms total server-side |+| `activeMakeMethods` + `methodMaterial` | < 35 ms |+| Output writes (~19k rows, sequential 500-row batches) + PostgREST round-trips + Deno CPU | the remaining ~10 s, unattributed at finer grain (needs in-function instrumentation) |++**Lever confirmed:** the on-hand input read from the new `itemStockQuantities`+table is **0.15 ms** vs 812 ms–1.7 s for the raw GROUP BY at 8M rows — but note+the semantic difference: MRP currently sums raw quantity (Rejected included),+the table excludes Rejected. Adopting it is a deliberate correctness decision,+not a drop-in.++## Low-level-code verdict: no real-world blowup (hypothesis falsified)++`computeLowLevelCodes` **used to** enumerate root-to-node paths with a copied+`visited` Set per child — worst-case exponential on diamond-heavy BOMs.+Measured against every company's real BOM: worst case **1.62 ms** (`tenant-A`,+1,133 items / 3,330 edges); the Kahn longest-path implementation agreed on+every acyclic input and was at best 2.4× faster. Current customer BOMs are too+shallow/narrow to trigger the explosion, so the hypothesis was falsified on+real data. Kahn **shipped anyway** and is now the implementation — not for+speed on today's data, but because it *detects* the real cycles above instead+of silently truncating them, and because the exponential case is trivially+reachable (a 42-node synthetic BOM took the old code 852 ms; see the table+above).++## Recommended order (updated by evidence)++1. **Fix the key-parsing bug** (structured keys / `splitKey`) — restores MRP for+ UUID-id tenants. Trivial diff, big blast radius.+2. **Make the output write transactional** — **DONE 2026-08-12** (Phase 7 in one+ Kysely transaction; rollback proven by fault injection).+3. **Paginate the inputs** — **DONE 2026-08-12** (`lib/fetch-all.ts`; Phase 1+ AND the Phase-6 actuals reads; multi-page output byte-identical).+4. **BOM cycle guard + Kahn rewrite** — **DONE 2026-08-12.**+ - `computeLowLevelCodes` is now Kahn's longest-path (O(items + edges),+ replacing worst-case-exponential path enumeration) and returns+ `cycleItemIds`. `explodeBom` plans cycle members as LEAF items (their own+ demand still nets; nothing explodes through them) and the run logs a+ warning via `getFunctionLogger` naming company + items — no longer+ silently wrong, and one corrupt loop no longer fails a whole company.+ - The `methodMaterial` interceptor gained a recursive-CTE reachability walk+ (active methods, per company, UNION-deduped so it terminates over+ existing cyclic data, depth-capped): writes that would close a+ multi-node cycle (A→B→A) are vetoed at the door.+ - A real multi-node cycle was found in prod: tenant-D,+ A → B → C → A (1 active job on those items).+ Grandfathered data — their MRP now runs green with the warning logged;+ editing inside the loop will veto until they break it.+5. **Read on-hand from `itemStockQuantities`** — **DONE 2026-08-12.** Semantics+ decided: Rejected stock excluded (matches `get_inventory_quantities`; exactly+ one tenant / 10 units were affected by the change). Measured effect: the+ 8M-row tenant's full MRP run dropped from ~20 s to **~0.3 s** with+ byte-identical output (7,953 demandActual rows, same quantity sum) — the+ entire history-scaling cost was the ledger scan.+6. Net-change/dirty-skip scheduling and per-company fan-out — the big+ architectural wins, justified once 1–5 land; a full run for a normal tenant+ is already ~0.5 s, so event-driven near-realtime MRP is viable after the+ correctness fixes.++Items 1–3 are correctness bugs and jump the queue over every optimization.diff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.mdindex 3e76045a95..990fee51af 100644--- a/.claude/rules/event-system.md+++ b/.claude/rules/event-system.md@@ -45,7 +45,11 @@ The wake path (`20260721184852_event-queue-wake.sql`) — both helpers live in t- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`).- `dispatch_event_interceptors()` — BEFORE ROW. Runs named sync interceptor functions inline (data-integrity, not async).- `dispatch_event_after_interceptors()` — AFTER ROW. Same but post-commit-of-row, safe for FK refs (added `20260410030406`).-- `attach_event_trigger(table, sync_functions[], after_sync_functions[])` — helper that wires the BEFORE SYNC / AFTER SYNC / ASYNC STATEMENT triggers on a table (3rd arg added `20260410030406`).+- `attach_event_trigger(table, sync_functions[], after_sync_functions[])` — helper that wires the BEFORE SYNC / AFTER SYNC / ASYNC STATEMENT triggers on a table (3rd arg added `20260410030406`). **Two overloads are live** — `(TEXT,TEXT[])` and `(TEXT,TEXT[],TEXT[])` — because `CREATE OR REPLACE` with an added parameter creates a sibling rather than replacing. Adding a *defaulted* parameter to this function is therefore a trap: a 2-arg call then matches more than one candidate and fails with `function attach_event_trigger(unknown, text[]) is not unique`, breaking 62 call sites. Adding an argument means dropping both overloads first.+- `attach_statement_handler(table, handler_functions[])` (`20260812002453`) — the STATEMENT-level counterpart to the row-level interceptors. Attaches each function as `trg_event_statement_<fn>_{ins,upd,del}` with transition tables `batched_new` / `batched_old`; an empty array detaches. Does **not** register the table for PGMQ dispatch. Used by `itemLedger` to maintain the `itemStockQuantities` aggregate.+ - Handlers are attached for all three operations, so each **must branch on `TG_OP`**: only `batched_new` exists on INSERT, only `batched_old` on DELETE. PL/pgSQL plans lazily, so a branch that doesn't run never resolves its missing transition table.+ - **Why handlers can't live inside `dispatch_event_batch()`:** (1) transition tables are visible ONLY to the function the trigger invokes directly — a nested call fails with `relation "batched_new" does not exist`, for static *and* dynamic SQL, so hosting handlers there would force materializing every batch into a temp table per statement; (2) `dispatch_event_batch()` returns early when the table has no active subscription and again when `app.sync_in_progress` is set — both correct for queueing, fatal for an aggregate (`itemLedger` has no subscriptions, so the handler would never run).+ - **Why not just `attach_event_trigger`:** it always attaches `dispatch_event_batch()`, which resolves primary-key columns from the catalog *before* its no-subscription early return — measured ~0.2–0.4 ms per statement on a table nothing subscribes to, vs ~0.05 ms for the bare INSERT.- `get_primary_key_column(table)` — dynamic PK lookup (`20260212165827`).### RPC (callable from app)diff --git a/.claude/rules/inventory-system.md b/.claude/rules/inventory-system.mdindex e1654477b0..afa48650b4 100644--- a/.claude/rules/inventory-system.md+++ b/.claude/rules/inventory-system.md@@ -107,7 +107,13 @@ Validators in `inventory.models.ts`: `inventoryAdjustmentValidator`, `receiptVal`quantity`, `consumed30/90`, `storageUnitIds`, `snapshotCutoff`. pg_cron refresh every 30 min.Read only inside the SECURITY DEFINER quantity functions (REVOKEd from PostgREST roles); livereads add rows past `snapshotCutoff` plus ALL tracked rows, so results stay exact. Distinct- from `itemStockQuantities` (the approximate UI item-store matview used by RealtimeDataProvider).+ from `itemStockQuantities` — since `20260812002454` a real TABLE maintained+ transactionally by a statement-level handler on `itemLedger`+ (`apply_item_stock_quantities`, attached via `attach_statement_handler`), no+ longer an approximate matview. Excludes `Rejected` tracked stock; exact, with a+ nightly `reconcile-item-stock-quantities` cron as drift backstop. Read by+ RealtimeDataProvider (with realtime push), the workflow engine's+ `item.quantityOnHand` operation, and the MRP edge function's on-hand input.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 viadiff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.mdindex 2efd5ebe14..98e3348a04 100644--- a/.claude/rules/mrp-system.md+++ b/.claude/rules/mrp-system.md@@ -44,6 +44,24 @@ Deno edge function** — NOT Trigger.dev, and not inline in the app server.with the output: MRP **consumes `demandProjection`** (user-entered) and **writes`demandForecast`** (rebuilt each run — see Outputs below).- **Inputs (supply)**: views `openProductionOrders`, `openPurchaseOrderLines`.+ - **Inputs (on-hand)**: the `itemStockQuantities` table (trigger-maintained,+ `20260812002454`) — an indexed per-company read, replacing the old full+ `itemLedger` GROUP BY that grew with total history. Excludes `Rejected`+ tracked stock (matching `get_inventory_quantities`); the raw scan counted it.+ - **Reads paginate**: every PostgREST read goes through `lib/fetch-all.ts`+ (1000-row pages + stable `.order()`) — production `max_rows = 1000`+ truncates bare `.select("*")` reads, and the dev stack does NOT enforce+ the cap, so truncation is invisible locally.+ - **Writes are atomic**: the Phase-7 delete-and-rewrite of+ `demandForecast`/`demandForecastSource`/`supplyForecast` + actual inserts+ runs in ONE Kysely transaction — a failed run leaves prior planning data+ intact.+ - **Key encoding**: every composite map key goes through `makeKey` /+ `makeLocationItemKey` / `makeActualKey` in `lib/mrp-engine.ts` (joined on+ `KEY_SEP = "\x1f"`). Never build `${a}-${b}` keys — ids are caller-supplied+ TEXT (imports mint hyphenated UUIDs); "-"-joined keys truncated them on+ parse and MRP 500'd for those tenants (Postgres 21000). Regression tests:+ `lib/mrp-engine.test.ts` (deno test).- **BOM explosion**: for `Make` items, explodes the active make method toderive child demand with low-level-code ordering, per-period inventorynetting, and lead-time offsetting.diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsxindex 834ddd8aed..415c84ee3f 100644--- a/apps/erp/app/components/RealtimeDataProvider.tsx+++ b/apps/erp/app/components/RealtimeDataProvider.tsx@@ -4,7 +4,7 @@ import { useCarbon } from "@carbon/auth";import { type Database, fetchAllFromTable } from "@carbon/database";import { getLogger } from "@carbon/logger";import { useInterval, useRealtimeChannel } from "@carbon/react";-import { useEffect } from "react";+import { useEffect, useRef } from "react";import { useUser } from "~/hooks";import {upsertIntoListStore,@@ -51,6 +51,10 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {const fetchQuantities = async () => {if (!carbon || !companyId) return;+ // A company switch (including A -> B -> A) bumps this. Comparing ids alone+ // would let a request from the FIRST visit to A land after returning to A+ // and overwrite newer quantities.+ const requestedGeneration = quantitiesGeneration.current;const { data, error } = await fetchAllFromTable<{itemId: string;@@ -58,13 +62,17 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {quantityOnHand: number;}>(carbon,- // @ts-ignore -- itemStockQuantities is a materialized view"itemStockQuantities","itemId, locationId, quantityOnHand",- (query) => query.eq("companyId", companyId)+ // Ordered by the rest of the table's key: fetchAllFromTable pages, and+ // without a stable sort a concurrent write can shift rows across a page+ // boundary, dropping or duplicating one in `totalMap`.+ (query) =>+ query.eq("companyId", companyId).order("itemId").order("locationId"));if (error || !data) return;+ if (quantitiesGeneration.current !== requestedGeneration) return;const totalMap = new Map<string, number>();const locationMap = new Map<string, Record<string, number>>();@@ -89,6 +97,38 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {);};+ // A posting writes one itemStockQuantities row per (item, location) it+ // touched, so a single receipt can emit a burst. Coalesce them into one+ // refetch — the same 1.5s quiet window `useDebouncedRealtime` uses.+ const quantitiesRefresh = useRef<ReturnType<typeof setTimeout> | null>(null);+ const quantitiesGeneration = useRef(0);++ // Bumped on every company change so in-flight reads and pending timers from+ // the previous company are discarded rather than applied to the new one.+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on companyId by design+ useEffect(() => {+ quantitiesGeneration.current += 1;+ if (quantitiesRefresh.current) {+ clearTimeout(quantitiesRefresh.current);+ quantitiesRefresh.current = null;+ }+ }, [companyId]);++ const scheduleQuantitiesRefresh = () => {+ if (quantitiesRefresh.current) clearTimeout(quantitiesRefresh.current);+ quantitiesRefresh.current = setTimeout(() => {+ quantitiesRefresh.current = null;+ fetchQuantities();+ }, 1500);+ };++ useEffect(+ () => () => {+ if (quantitiesRefresh.current) clearTimeout(quantitiesRefresh.current);+ },+ []+ );+const hydrate = async () => {const idb = (await import("localforage")).default;const requestedCompanyId = companyId;@@ -319,6 +359,29 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {}})+ .on(+ "postgres_changes",+ {+ event: "*",+ schema: "public",+ // Quantities are maintained incrementally by triggers on itemLedger,+ // so this fires on the posting itself rather than up to 40 min later+ // (the old 30 min matview refresh + the 10 min poll below).+ // Server-side filter: with ~1600 tenants an unfiltered subscription+ // would fan every company's postings out to every client.+ table: "itemStockQuantities",+ filter: `companyId=eq.${companyId}`+ },+ (payload) => {+ // companyId is part of the primary key, so it is present even on a+ // DELETE payload (which otherwise carries only key columns).+ const row =+ payload.eventType === "DELETE" ? payload.old : payload.new;+ if (row && "companyId" in row && row.companyId !== companyId)+ return;+ scheduleQuantitiesRefresh();+ }+ ).on("postgres_changes",{diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.mdindex 3cd77ba3bf..90110bb25c 100644--- a/apps/erp/app/modules/inventory/AGENTS.md+++ b/apps/erp/app/modules/inventory/AGENTS.md@@ -44,6 +44,7 @@ pnpm exec turbo run typecheck --filter=erp # the app's package name is "erp",| Table / View | Purpose ||---|---|| `itemLedger` / `itemLedgers` (view) | Append-only movement log: item, location, quantity, document ref, trackedEntityId |+| `itemStockQuantities` | On-hand per (item, company, location) — a real TABLE maintained transactionally by a statement-level event handler on `itemLedger` (`apply_item_stock_quantities`, attached via `attach_statement_handler`; was a 30-min-refresh matview until `20260812002454`). Excludes `Rejected` tracked stock. Never write to it directly — it is derived state; the nightly `reconcile-item-stock-quantities` cron repairs any drift. Read by the item-dropdown store (with realtime push), the workflow engine's `item.quantityOnHand`, and MRP's on-hand input || `storageUnit` | Hierarchical bins/shelves via `parentId`; scoped to location || `storageType` | Storage unit type definitions (capacity, constraints) || `trackedEntity` | Serial/batch/lot instances with readableId, status, quantity, expirationDate |diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex b0bb0c3b01..4ef1350413 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -20758,6 +20758,27 @@ export type Database = {},]}+ itemStockQuantities: {+ Row: {+ companyId: string+ itemId: string+ locationId: string+ quantityOnHand: number+ }+ Insert: {+ companyId: string+ itemId: string+ locationId?: string+ quantityOnHand?: number+ }+ Update: {+ companyId?: string+ itemId?: string+ locationId?: string+ quantityOnHand?: number+ }+ Relationships: []+ }itemSupersession: {Row: {companyId: string@@ -61180,20 +61201,6 @@ export type Database = {tableName: string | nulltype: string | null}- Insert: {- attachedFunctions?: never- status?: never- systemTriggerName?: unknown- tableName?: never- type?: never- }- Update: {- attachedFunctions?: never- status?: never- systemTriggerName?: unknown- tableName?: never- type?: never- }Relationships: []}gaugeCalibrationRecords: {@@ -62940,86 +62947,6 @@ export type Database = {},]}- itemStockQuantities: {- Row: {- companyId: string | null- itemId: string | null- locationId: string | null- quantityOnHand: number | 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"]- },- ]- }jobMaterialWithMakeMethodId: {Row: {companyId: string | null@@ -67761,14 +67688,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -71147,7 +71074,7 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -71161,7 +71088,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -75075,19 +75002,18 @@ export type Database = {netChange: number}[]}- attach_event_trigger:- | {- Args: { sync_functions?: string[]; table_name_text: string }- Returns: undefined- }- | {- Args: {- after_sync_functions?: string[]- sync_functions?: string[]- table_name_text: string- }- Returns: undefined- }+ attach_event_trigger: {+ Args: {+ after_sync_functions?: string[]+ sync_functions?: string[]+ table_name_text: string+ }+ Returns: undefined+ }+ attach_statement_handler: {+ Args: { handler_functions?: string[]; table_name_text: string }+ Returns: undefined+ }backflush_job_materials: {Args: {p_company_id: string@@ -77099,6 +77025,13 @@ export type Database = {Returns: boolean}is_valid_timezone: { Args: { tz: string }; Returns: boolean }+ item_ledger_on_hand_contribution: {+ Args: {+ quantity: number+ tracked_entity_status: Database["public"]["Enums"]["trackedEntityStatus"]+ }+ Returns: number+ }items_search: {Args: {match_count: number@@ -77286,6 +77219,7 @@ export type Database = {}Returns: undefined}+ reconcile_item_stock_quantities: { Args: never; Returns: undefined }resolve_shelf_life_start_for_receipt: {Args: { p_item_id: string; p_receipt_id: string }Returns: string@@ -77397,6 +77331,14 @@ export type Database = {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined}+ sync_check_job_material_self_reference: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }+ sync_check_method_material_self_reference: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }sync_contact_to_parent: {Args: {new_data: Jsondiff --git a/packages/database/supabase/functions/lib/fetch-all.ts b/packages/database/supabase/functions/lib/fetch-all.tsnew file mode 100644index 0000000000..03a3b66ad2--- /dev/null+++ b/packages/database/supabase/functions/lib/fetch-all.ts@@ -0,0 +1,48 @@+// Deno mirror of @carbon/database's fetchAllFromTable: pages through PostgREST+// in 1000-row batches so reads are complete past the production `max_rows`+// cap. The local dev stack does not enforce the cap, which is exactly why+// truncated reads ship unnoticed — always use this for a read that can exceed+// 1000 rows.++// deno-lint-ignore-file no-explicit-any++const BATCH_SIZE = 1000;+// Backstop only: a server that ignored `Range` would otherwise loop forever+// inside an edge function. 1000 pages = 1M rows, far past any real input.+const MAX_PAGES = 1000;++type PageResult<T> = {+ data: T[] | null;+ // Carries PostgREST's error through unchanged (code/details/hint included) —+ // narrowing it to a message would discard the diagnostics.+ error: { message: string; [key: string]: unknown } | null;+};++export async function fetchAll<T>(+ buildQuery: () => any+): Promise<PageResult<T>> {+ const allData: T[] = [];++ for (let page = 0; page < MAX_PAGES; page++) {+ const offset = page * BATCH_SIZE;+ const result = await buildQuery().range(offset, offset + BATCH_SIZE - 1);++ if (result.error) {+ return { data: null, error: result.error };+ }++ const rows: T[] = result.data ?? [];+ allData.push(...rows);++ if (rows.length < BATCH_SIZE) {+ return { data: allData, error: null };+ }+ }++ return {+ data: null,+ error: {+ message: `fetchAll exceeded ${MAX_PAGES} pages — refusing to plan on a partial read`,+ },+ };+}diff --git a/packages/database/supabase/functions/lib/mrp-engine.test.ts b/packages/database/supabase/functions/lib/mrp-engine.test.tsnew file mode 100644index 0000000000..a480153f13--- /dev/null+++ b/packages/database/supabase/functions/lib/mrp-engine.test.ts@@ -0,0 +1,195 @@+import {+ assert,+ assertEquals,+} from "https://deno.land/[email protected]/testing/asserts.ts";+import {+ computeLowLevelCodes,+ explodeBom,+ makeActualKey,+ makeKey,+ makeLocationItemKey,+ splitActualKey,+ splitKey,+ type BomChild,+} from "./mrp-engine.ts";++// Ids are caller-supplied TEXT: bulk imports mint UUIDs, so every id position+// must survive hyphens. The old "-"-joined keys truncated a UUID itemId to its+// first segment on parse, collapsing distinct (item, period) pairs into+// duplicate upsert rows (Postgres 21000) — MRP failed outright for those+// tenants.+const UUID_ITEM = "0107b4c3-a1ce-5c84-ae99-6d3c505f4a48";+const UUID_ITEM_2 = "0107b4c3-a1ce-9999-bb00-000000000000"; // same first segments+const UUID_LOCATION = "b81f0b70-9d05-4c1e-8339-000000000001";++Deno.test("makeKey/splitKey round-trip hyphenated ids in every position", () => {+ const key = makeKey(UUID_LOCATION, "period-1", UUID_ITEM);+ assertEquals(splitKey(key), [UUID_LOCATION, "period-1", UUID_ITEM]);+});++Deno.test("keys for distinct items never collide on shared id prefixes", () => {+ const a = makeKey(UUID_LOCATION, "p1", UUID_ITEM);+ const b = makeKey(UUID_LOCATION, "p1", UUID_ITEM_2);+ assert(a !== b);+});++Deno.test("makeActualKey/splitActualKey round-trip with source types containing spaces", () => {+ const key = makeActualKey(UUID_ITEM, UUID_LOCATION, "p1", "Sales Order");+ assertEquals(splitActualKey(key), [+ UUID_ITEM,+ UUID_LOCATION,+ "p1",+ "Sales Order",+ ]);+});++Deno.test("makeLocationItemKey is unambiguous for hyphenated pairs", () => {+ // "-"-joined keys could not distinguish (a-b, c) from (a, b-c).+ assert(+ makeLocationItemKey("a-b", "c") !== makeLocationItemKey("a", "b-c")+ );+});++Deno.test("explodeBom nets and explodes demand for UUID-id items", () => {+ const parent = UUID_ITEM;+ const child = UUID_LOCATION.replace("b81f", "c81f"); // another hyphenated id+ const location = UUID_LOCATION;+ const periods = [{ id: "p1" }, { id: "p2" }];++ const bomByItem = new Map<string, BomChild[]>([+ [parent, [{ itemId: child, quantity: 2, methodType: "Pull from Inventory" }]],+ ]);++ const { bomDerivedDemand } = explodeBom({+ grossDemand: new Map([[makeKey(location, "p2", parent), 10]]),+ bomByItem,+ replenishmentSystemByItem: new Map([+ [parent, "Make"],+ [child, "Buy"],+ ]),+ leadTimeByItem: new Map([[child, 7]]),+ periods,+ onHandByLocationItem: new Map([[makeLocationItemKey(location, parent), 4]]),+ jobSupplyByLocationPeriodItem: new Map(),+ topLevelContributors: new Map(),+ });++ // 10 demanded - 4 on hand = 6 to make; child qty 2 => 12, pulled one week+ // earlier by the 7-day lead time.+ const childKey = makeKey(location, "p1", child);+ assertEquals(bomDerivedDemand.get(childKey), 12);+ // The key parses back to the full hyphenated ids, not truncated segments.+ assertEquals(splitKey(childKey), [location, "p1", child]);+});++Deno.test("computeLowLevelCodes handles hyphenated ids and shared subassemblies", () => {+ const bomByItem = new Map<string, BomChild[]>([+ ["top", [+ { itemId: UUID_ITEM, quantity: 1, methodType: "Make to Order" },+ { itemId: "mid", quantity: 1, methodType: "Make to Order" },+ ]],+ ["mid", [{ itemId: UUID_ITEM, quantity: 1, methodType: "Pull from Inventory" }]],+ ]);+ const { llc, cycleItemIds } = computeLowLevelCodes(bomByItem);+ assertEquals(llc.get("top"), 0);+ assertEquals(llc.get("mid"), 1);+ // Deepest occurrence wins: UUID item appears at level 1 (under top) and+ // level 2 (under mid).+ assertEquals(llc.get(UUID_ITEM), 2);+ assertEquals(cycleItemIds.size, 0);+});++Deno.test("computeLowLevelCodes reports cycles instead of silently truncating", () => {+ // Real production shape (tenant "Farm it"): seeds -> flower -> bouquet -> seeds.+ const bomByItem = new Map<string, BomChild[]>([+ ["seeds", [{ itemId: "flower", quantity: 1, methodType: "Make to Order" }]],+ ["flower", [{ itemId: "bouquet", quantity: 1, methodType: "Make to Order" }]],+ ["bouquet", [{ itemId: "seeds", quantity: 1, methodType: "Make to Order" }]],+ // an untangled item alongside the cycle still levels normally+ ["clean", [{ itemId: "leaf", quantity: 1, methodType: "Pull from Inventory" }]],+ ]);+ const { llc, cycleItemIds } = computeLowLevelCodes(bomByItem);+ assertEquals([...cycleItemIds].sort(), ["bouquet", "flower", "seeds"]);+ assertEquals(llc.get("clean"), 0);+ assertEquals(llc.get("leaf"), 1);+});++Deno.test("explodeBom plans around a cycle instead of hanging or failing", () => {+ const location = "loc-1";+ const bomByItem = new Map<string, BomChild[]>([+ ["seeds", [{ itemId: "flower", quantity: 1, methodType: "Make to Order" }]],+ ["flower", [{ itemId: "seeds", quantity: 2, methodType: "Make to Order" }]],+ ]);++ const { bomDerivedDemand, cycleItemIds } = explodeBom({+ grossDemand: new Map([[makeKey(location, "p1", "flower"), 5]]),+ bomByItem,+ replenishmentSystemByItem: new Map([+ ["seeds", "Make"],+ ["flower", "Make"],+ ]),+ leadTimeByItem: new Map(),+ periods: [{ id: "p1" }],+ onHandByLocationItem: new Map(),+ jobSupplyByLocationPeriodItem: new Map(),+ topLevelContributors: new Map(),+ });++ assertEquals([...cycleItemIds].sort(), ["flower", "seeds"]);+ // Cycle members are treated as leaves: no demand explodes through them.+ assertEquals(bomDerivedDemand.size, 0);+});++Deno.test("explodeBom does not mutate the caller's bomByItem", () => {+ const bomByItem = new Map<string, BomChild[]>([+ ["a", [{ itemId: "b", quantity: 1, methodType: "Make to Order" }]],+ ["b", [{ itemId: "a", quantity: 1, methodType: "Make to Order" }]],+ ]);+ const sizeBefore = bomByItem.size;++ explodeBom({+ grossDemand: new Map([[makeKey("loc", "p1", "a"), 1]]),+ bomByItem,+ replenishmentSystemByItem: new Map([["a", "Make"], ["b", "Make"]]),+ leadTimeByItem: new Map(),+ periods: [{ id: "p1" }],+ onHandByLocationItem: new Map(),+ jobSupplyByLocationPeriodItem: new Map(),+ topLevelContributors: new Map(),+ });++ assertEquals(bomByItem.size, sizeBefore);+ assert(bomByItem.has("a") && bomByItem.has("b"));+});++Deno.test("a clean parent still explodes onto a cycle item, but nothing explodes onward", () => {+ const loc = "loc";+ // clean -> cyc1; cyc1 <-> cyc2 form a cycle. The corrupt loop must not cost+ // the clean part of the graph its planning.+ const bomByItem = new Map<string, BomChild[]>([+ ["clean", [{ itemId: "cyc1", quantity: 1, methodType: "Pull from Inventory" }]],+ ["cyc1", [{ itemId: "cyc2", quantity: 1, methodType: "Make to Order" }]],+ ["cyc2", [{ itemId: "cyc1", quantity: 1, methodType: "Make to Order" }]],+ ]);++ const { bomDerivedDemand, cycleItemIds } = explodeBom({+ grossDemand: new Map([[makeKey(loc, "p1", "clean"), 10]]),+ bomByItem,+ replenishmentSystemByItem: new Map([+ ["clean", "Make"],+ ["cyc1", "Make"],+ ["cyc2", "Make"],+ ]),+ leadTimeByItem: new Map(),+ periods: [{ id: "p1" }],+ onHandByLocationItem: new Map(),+ jobSupplyByLocationPeriodItem: new Map(),+ topLevelContributors: new Map(),+ });++ assert(cycleItemIds.has("cyc1") && cycleItemIds.has("cyc2"));+ // The clean parent plans normally: its demand reaches cyc1.+ assertEquals(bomDerivedDemand.get(makeKey(loc, "p1", "cyc1")), 10);+ // cyc1 is a leaf, so no phantom demand is manufactured around the loop.+ assertEquals(bomDerivedDemand.get(makeKey(loc, "p1", "cyc2")), undefined);+});diff --git a/packages/database/supabase/functions/lib/mrp-engine.ts b/packages/database/supabase/functions/lib/mrp-engine.tsindex 91f037324f..44fe43bc5a 100644--- a/packages/database/supabase/functions/lib/mrp-engine.ts+++ b/packages/database/supabase/functions/lib/mrp-engine.ts@@ -51,11 +51,21 @@ export type BomExplosionOutput = {grossDemand: Map<string, number>;bomDerivedDemand: Map<string, number>;demandContributors: Map<string, DemandContributor[]>;+ // Items on (or strictly downstream of) a BOM cycle. They are planned as leaf+ // items — no demand explodes through them — and the caller should log them.+ cycleItemIds: Set<string>;};+// Composite map keys join their parts with a control character. Ids are+// caller-supplied TEXT — bulk imports mint UUIDs with hyphens — so no printable+// delimiter is collision-safe. Joining on "-" truncated hyphenated item ids on+// parse and collapsed distinct (item, period) pairs into duplicate rows+// (Postgres 21000 on the batched upsert).+export const KEY_SEP = "\x1f";+export function splitKey(key: string): [string, string, string] {- const parts = key.split("-");- return [parts[0]!, parts[1]!, parts.slice(2).join("-")];+ const parts = key.split(KEY_SEP);+ return [parts[0]!, parts[1]!, parts[2]!];}export function makeKey(@@ -63,7 +73,32 @@ export function makeKey(periodId: string,itemId: string): string {- return `${locationId}-${periodId}-${itemId}`;+ return locationId + KEY_SEP + periodId + KEY_SEP + itemId;+}++export function makeLocationItemKey(+ locationId: string,+ itemId: string+): string {+ return locationId + KEY_SEP + itemId;+}++export function makeActualKey(+ itemId: string,+ locationId: string,+ periodId: string,+ sourceType: string+): string {+ return (+ itemId + KEY_SEP + locationId + KEY_SEP + periodId + KEY_SEP + sourceType+ );+}++export function splitActualKey(+ key: string+): [string, string, string, string] {+ const parts = key.split(KEY_SEP);+ return [parts[0]!, parts[1]!, parts[2]!, parts[3]!];}function effectiveReplenishment(@@ -74,35 +109,60 @@ function effectiveReplenishment(: (repSys as "Buy" | "Make" | undefined);}+// Low-level code = the deepest level at which an item appears in any BOM,+// i.e. the longest root-to-item path. Computed as longest-path-in-a-DAG via+// Kahn's topological order: each BOM edge is relaxed exactly once, O(items ++// edges). The previous implementation enumerated every root-to-item PATH with+// a copied visited-set per child — worst-case exponential on shared+// subassemblies, and it silently truncated cycles, so a corrupt BOM planned+// quietly wrong instead of being reported.export function computeLowLevelCodes(bomByItem: Map<string, BomChild[]>-): Map<string, number> {- const llc = new Map<string, number>();+): { llc: Map<string, number>; cycleItemIds: Set<string> } {+ const indegree = new Map<string, number>();+ const nodes = new Set<string>();- function assignLevel(- itemId: string,- level: number,- visited: Set<string>- ): void {- if (visited.has(itemId)) return;- visited.add(itemId);-- const currentLLC = llc.get(itemId) ?? -1;- if (level > currentLLC) {- llc.set(itemId, level);+ for (const [parent, children] of bomByItem) {+ nodes.add(parent);+ if (!indegree.has(parent)) indegree.set(parent, 0);+ for (const child of children) {+ nodes.add(child.itemId);+ indegree.set(child.itemId, (indegree.get(child.itemId) ?? 0) + 1);}+ }- const children = bomByItem.get(itemId) ?? [];- for (const child of children) {- assignLevel(child.itemId, level + 1, new Set(visited));+ const llc = new Map<string, number>();+ const queue: string[] = [];+ for (const n of nodes) {+ if ((indegree.get(n) ?? 0) === 0) {+ llc.set(n, 0);+ queue.push(n);}}- for (const itemId of bomByItem.keys()) {- assignLevel(itemId, 0, new Set());+ let head = 0;+ while (head < queue.length) {+ const item = queue[head++];+ const level = llc.get(item) ?? 0;+ for (const child of bomByItem.get(item) ?? []) {+ const next = level + 1;+ if (next > (llc.get(child.itemId) ?? -1)) llc.set(child.itemId, next);+ const remaining = (indegree.get(child.itemId) ?? 0) - 1;+ indegree.set(child.itemId, remaining);+ if (remaining === 0) queue.push(child.itemId);+ }+ }++ // Nodes never dequeued sit on (or strictly downstream of) a cycle — the+ // topological order cannot reach them. They get no level.+ const cycleItemIds = new Set<string>();+ if (queue.length < nodes.size) {+ for (const n of nodes) {+ if (!llc.has(n) || (indegree.get(n) ?? 0) > 0) cycleItemIds.add(n);+ }}- return llc;+ return { llc, cycleItemIds };}export function explodeBom(input: BomExplosionInput): BomExplosionOutput {@@ -121,8 +181,33 @@ export function explodeBom(input: BomExplosionInput): BomExplosionOutput {const bomDerivedDemand = new Map<string, number>();const demandContributors = new Map<string, DemandContributor[]>();- const llc = computeLowLevelCodes(bomByItem);- const maxLevel = llc.size > 0 ? Math.max(...llc.values()) : 0;+ const { llc, cycleItemIds } = computeLowLevelCodes(bomByItem);++ // A cycle cannot be leveled (rose seeds -> rose -> bouquet -> rose seeds is+ // real production data). Failing the whole company's run for one corrupt+ // loop is worse than planning around it: treat cycle members as leaf items —+ // their own demand still nets and outputs, but nothing explodes THROUGH+ // them — and report them so the caller can log instead of planning quietly+ // wrong.+ //+ // Copy rather than mutate: bomByItem belongs to the caller, which built it+ // and may still read it.+ const explodableBom =+ cycleItemIds.size > 0+ ? new Map([...bomByItem].filter(([itemId]) => !cycleItemIds.has(itemId)))+ : bomByItem;++ // Cycle members get no level from the topological pass. Leaving them+ // unleveled would default them to level 0 (`llc.get(id) ?? 0`), so demand a+ // clean parent explodes onto them at a later level would never be netted+ // against on-hand — an overstated requirement. Plan them LAST instead.+ const maxCleanLevel = llc.size > 0 ? Math.max(...llc.values()) : 0;+ const cycleLevel = cycleItemIds.size > 0 ? maxCleanLevel + 1 : maxCleanLevel;+ for (const itemId of cycleItemIds) {+ llc.set(itemId, cycleLevel);+ }++ const maxLevel = cycleLevel;const periodIndexById = new Map(periods.map((p, i) => [p.id, i]));@@ -134,19 +219,19 @@ export function explodeBom(input: BomExplosionInput): BomExplosionOutput {if (qty <= 0) continue;const [locationId, , itemId] = splitKey(key);if ((llc.get(itemId) ?? 0) === level) {- locItemsAtLevel.add(`${locationId}|${itemId}`);+ locItemsAtLevel.add(makeLocationItemKey(locationId, itemId));}}for (const locItem of locItemsAtLevel) {- const sepIdx = locItem.indexOf("|");+ const sepIdx = locItem.indexOf(KEY_SEP);const locationId = locItem.slice(0, sepIdx);const itemId = locItem.slice(sepIdx + 1);const effRepSys = effectiveReplenishment(replenishmentSystemByItem.get(itemId));- const invKey = `${locationId}-${itemId}`;+ const invKey = makeLocationItemKey(locationId, itemId);// Running balance for this (location, item) across the planning// horizon: starts at on-hand, +supply as each period passes,// −demand as we hit it. Floored at 0 because any shortfall is@@ -167,7 +252,7 @@ export function explodeBom(input: BomExplosionInput): BomExplosionOutput {// demandForecast / quantityToOrder via the caller.if (netRequirement <= 0 || effRepSys !== "Make") continue;- const children = bomByItem.get(itemId) ?? [];+ const children = explodableBom.get(itemId) ?? [];for (const child of children) {const childEffRepSys = effectiveReplenishment(replenishmentSystemByItem.get(child.itemId)@@ -231,5 +316,5 @@ export function explodeBom(input: BomExplosionInput): BomExplosionOutput {}}- return { grossDemand, bomDerivedDemand, demandContributors };+ return { grossDemand, bomDerivedDemand, demandContributors, cycleItemIds };}diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex b0bb0c3b01..4ef1350413 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -20758,6 +20758,27 @@ export type Database = {},]}+ itemStockQuantities: {+ Row: {+ companyId: string+ itemId: string+ locationId: string+ quantityOnHand: number+ }+ Insert: {+ companyId: string+ itemId: string+ locationId?: string+ quantityOnHand?: number+ }+ Update: {+ companyId?: string+ itemId?: string+ locationId?: string+ quantityOnHand?: number+ }+ Relationships: []+ }itemSupersession: {Row: {companyId: string@@ -61180,20 +61201,6 @@ export type Database = {tableName: string | nulltype: string | null}- Insert: {- attachedFunctions?: never- status?: never- systemTriggerName?: unknown- tableName?: never- type?: never- }- Update: {- attachedFunctions?: never- status?: never- systemTriggerName?: unknown- tableName?: never- type?: never- }Relationships: []}gaugeCalibrationRecords: {@@ -62940,86 +62947,6 @@ export type Database = {},]}- itemStockQuantities: {- Row: {- companyId: string | null- itemId: string | null- locationId: string | null- quantityOnHand: number | 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"]- },- ]- }jobMaterialWithMakeMethodId: {Row: {companyId: string | null@@ -67761,14 +67688,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -71147,7 +71074,7 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -71161,7 +71088,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -75075,19 +75002,18 @@ export type Database = {netChange: number}[]}- attach_event_trigger:- | {- Args: { sync_functions?: string[]; table_name_text: string }- Returns: undefined- }- | {- Args: {- after_sync_functions?: string[]- sync_functions?: string[]- table_name_text: string- }- Returns: undefined- }+ attach_event_trigger: {+ Args: {+ after_sync_functions?: string[]+ sync_functions?: string[]+ table_name_text: string+ }+ Returns: undefined+ }+ attach_statement_handler: {+ Args: { handler_functions?: string[]; table_name_text: string }+ Returns: undefined+ }backflush_job_materials: {Args: {p_company_id: string@@ -77099,6 +77025,13 @@ export type Database = {Returns: boolean}is_valid_timezone: { Args: { tz: string }; Returns: boolean }+ item_ledger_on_hand_contribution: {+ Args: {+ quantity: number+ tracked_entity_status: Database["public"]["Enums"]["trackedEntityStatus"]+ }+ Returns: number+ }items_search: {Args: {match_count: number@@ -77286,6 +77219,7 @@ export type Database = {}Returns: undefined}+ reconcile_item_stock_quantities: { Args: never; Returns: undefined }resolve_shelf_life_start_for_receipt: {Args: { p_item_id: string; p_receipt_id: string }Returns: string@@ -77397,6 +77331,14 @@ export type Database = {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined}+ sync_check_job_material_self_reference: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }+ sync_check_method_material_self_reference: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }sync_contact_to_parent: {Args: {new_data: Jsondiff --git a/packages/database/supabase/functions/mrp/index.ts b/packages/database/supabase/functions/mrp/index.tsindex f9ff5331a3..f4c06e427f 100644--- a/packages/database/supabase/functions/mrp/index.ts+++ b/packages/database/supabase/functions/mrp/index.ts@@ -8,6 +8,10 @@ import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";import {explodeBom,+ makeActualKey,+ makeKey,+ makeLocationItemKey,+ splitActualKey,splitKey,type BomChild,type DemandContributor,@@ -15,8 +19,10 @@ import {type ReplenishmentSystem,} from "../lib/mrp-engine.ts";-import { Kysely, sql } from "npm:kysely";+import { Kysely } from "npm:kysely";import z from "npm:zod@^3.24.1";+import { fetchAll } from "../lib/fetch-all.ts";+import { getFunctionLogger } from "../lib/logging.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import { requirePermissions } from "../lib/supabase.ts";import { Database } from "../lib/types.ts";@@ -24,6 +30,7 @@ import { buildSupersessionRedirectMap } from "../lib/supersession-pick.ts";const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);+const logger = getFunctionLogger("mrp");const WEEKS_TO_FORECAST = 18 * 4;@@ -78,7 +85,7 @@ serve(async (req: Request) => {const parsedPayload = payloadValidator.parse(payload);const { type, companyId, userId } = parsedPayload;- console.log({ function: "mrp", type, companyId, userId });+ logger.info("run started", { type, companyId, userId });const today = datetime.today(await getCompanyTimeZone(db, companyId));const ranges = getStartAndEndDates(today, "Week");@@ -95,6 +102,11 @@ serve(async (req: Request) => {try {// ──────────────────────────────────────────────────────────────// PHASE 1: Bulk data pre-loading+ //+ // Every PostgREST read is paginated via fetchAll: production caps+ // responses at max_rows = 1000, and tenants exceed that on these views+ // (2,497 open job material lines observed) — an uncapped read plans on+ // silently truncated demand. The `.order("id")` keeps pages stable.// ──────────────────────────────────────────────────────────────const [@@ -104,27 +116,46 @@ serve(async (req: Request) => {purchaseOrderLines,demandProjections,] = await Promise.all([- client.from("openSalesOrderLines").select("*").eq("companyId", companyId),- client- .from("openJobMaterialLines")- .select("*")- .eq("companyId", companyId),- client- .from("openProductionOrders")- .select("*")- .eq("companyId", companyId),- client- .from("openPurchaseOrderLines")- .select("*")- .eq("companyId", companyId),- client- .from("demandProjection")- .select("*")- .eq("companyId", companyId)- .in(- "periodId",- periods.map((p: DemandPeriod) => p.id ?? "").filter(Boolean)- ),+ fetchAll<Database["public"]["Views"]["openSalesOrderLines"]["Row"]>(() =>+ client+ .from("openSalesOrderLines")+ .select("*")+ .eq("companyId", companyId)+ .order("id")+ ),+ fetchAll<Database["public"]["Views"]["openJobMaterialLines"]["Row"]>(() =>+ client+ .from("openJobMaterialLines")+ .select("*")+ .eq("companyId", companyId)+ .order("id")+ ),+ fetchAll<Database["public"]["Views"]["openProductionOrders"]["Row"]>(() =>+ client+ .from("openProductionOrders")+ .select("*")+ .eq("companyId", companyId)+ .order("id")+ ),+ fetchAll<Database["public"]["Views"]["openPurchaseOrderLines"]["Row"]>(+ () =>+ client+ .from("openPurchaseOrderLines")+ .select("*")+ .eq("companyId", companyId)+ .order("id")+ ),+ fetchAll<Database["public"]["Tables"]["demandProjection"]["Row"]>(() =>+ client+ .from("demandProjection")+ .select("*")+ .eq("companyId", companyId)+ .in(+ "periodId",+ periods.map((p: DemandPeriod) => p.id ?? "").filter(Boolean)+ )+ .order("id")+ ),]);if (salesOrderLines.error) throw new Error("Failed to load sales order lines");@@ -164,12 +195,21 @@ serve(async (req: Request) => {// Loaded via the supabase client (like the other demand inputs) so DATE// columns come back as "YYYY-MM-DD" strings — Kysely/node-pg would hand back// JS Date objects, which parseDate() can't take.- const supersessions = await client- .from("itemSupersession")- .select(- "itemId, supersessionMode, successorItemId, successorEffectivityDate, conversionFactor"- )- .eq("companyId", companyId);+ const supersessions = await fetchAll<{+ itemId: string;+ supersessionMode: string;+ successorItemId: string | null;+ successorEffectivityDate: string | null;+ conversionFactor: number | null;+ }>(() =>+ client+ .from("itemSupersession")+ .select(+ "itemId, supersessionMode, successorItemId, successorEffectivityDate, conversionFactor"+ )+ .eq("companyId", companyId)+ .order("itemId")+ );if (supersessions.error) throw new Error("Failed to load supersessions");const supersessionByItem = new Map<string,@@ -180,7 +220,7 @@ serve(async (req: Request) => {conversionFactor: number;}>();- for (const s of supersessions.data) {+ for (const s of supersessions.data ?? []) {supersessionByItem.set(s.itemId, {supersessionMode: s.supersessionMode,successorItemId: s.successorItemId,@@ -200,20 +240,23 @@ serve(async (req: Request) => {today.toString());- // Bulk-load inventory by location+item+ // Bulk-load inventory by location+item from the trigger-maintained+ // aggregate: transactionally current and an indexed read of a few hundred+ // rows, where the previous full-ledger GROUP BY grew with total history+ // (~6-8s of an 8M-row tenant's run). Semantics deliberately follow the+ // aggregate: Rejected tracked stock is NOT available to plan against,+ // matching get_inventory_quantities — the raw ledger sum counted it.const inventoryRows = await db- .selectFrom("itemLedger")- .select(["itemId", "locationId"])- .select(sql<number>`SUM("quantity")`.as("quantityOnHand"))+ .selectFrom("itemStockQuantities")+ .select(["itemId", "locationId", "quantityOnHand"]).where("companyId", "=", companyId)- .groupBy(["itemId", "locationId"]).execute();const baseInventoryByLocationItem = new Map<string, number>();for (const row of inventoryRows) {if (row.itemId && row.locationId) {baseInventoryByLocationItem.set(- `${row.locationId}-${row.itemId}`,+ makeLocationItemKey(row.locationId, row.itemId),Number(row.quantityOnHand) || 0);}@@ -221,14 +264,20 @@ serve(async (req: Request) => {// Bulk-load all BOMs: use activeMakeMethods view (returns one method per item,// prioritizing 'Active' status then highest version — same logic as get_method_tree)- const activeMethodsResult = await client- .from("activeMakeMethods")- .select("id, itemId")- .eq("companyId", companyId);+ const activeMethodsResult = await fetchAll<{+ id: string | null;+ itemId: string | null;+ }>(() =>+ client+ .from("activeMakeMethods")+ .select("id, itemId")+ .eq("companyId", companyId)+ .order("id")+ );if (activeMethodsResult.error) throw activeMethodsResult.error;const methodIdByItem = new Map<string, string>();- for (const m of activeMethodsResult.data) {+ for (const m of activeMethodsResult.data ?? []) {if (m.id && m.itemId) {methodIdByItem.set(m.itemId, m.id);}@@ -293,7 +342,7 @@ serve(async (req: Request) => {// Supply bucketed by location+period+item (for demand projection netting + supplyActual output)const jobSupplyByLocationPeriodItem = new Map<string, number>();- for (const line of productionLines.data) {+ for (const line of productionLines.data ?? []) {if (!line.itemId || !line.quantityToReceive) continue;const dueDate = line.dueDate@@ -305,7 +354,11 @@ serve(async (req: Request) => {const period = findPeriod(dueDate, today, periods);if (!period) continue;- const periodKey = `${line.locationId ?? ""}-${period.id ?? ""}-${line.itemId}`;+ const periodKey = makeKey(+ line.locationId ?? "",+ period.id ?? "",+ line.itemId+ );jobSupplyByLocationPeriodItem.set(periodKey,(jobSupplyByLocationPeriodItem.get(periodKey) ?? 0) + line.quantityToReceive@@ -314,7 +367,7 @@ serve(async (req: Request) => {const poSupplyByLocationPeriodItem = new Map<string, number>();- for (const line of purchaseOrderLines.data) {+ for (const line of purchaseOrderLines.data ?? []) {if (!line.itemId || !line.quantityToReceive) continue;const dueDate = line.promisedDate@@ -326,7 +379,11 @@ serve(async (req: Request) => {const period = findPeriod(dueDate, today, periods);if (!period) continue;- const periodKey = `${line.locationId ?? ""}-${period.id ?? ""}-${line.itemId}`;+ const periodKey = makeKey(+ line.locationId ?? "",+ period.id ?? "",+ line.itemId+ );poSupplyByLocationPeriodItem.set(periodKey,(poSupplyByLocationPeriodItem.get(periodKey) ?? 0) + line.quantityToReceive@@ -356,13 +413,17 @@ serve(async (req: Request) => {// credited exactly once by explodeBom's running balance (which receives// jobAndPoSupplyByLocationPeriodItem below). Netting here as well would// double-count supply and under-drive child demand.- for (const projection of demandProjections.data) {+ for (const projection of demandProjections.data ?? []) {if (!projection.itemId || !projection.forecastQuantity) continue;const netDemand = projection.forecastQuantity;if (netDemand > 0) {- const key = `${projection.locationId ?? ""}-${projection.periodId}-${projection.itemId}`;+ const key = makeKey(+ projection.locationId ?? "",+ projection.periodId,+ projection.itemId+ );grossDemand.set(key, (grossDemand.get(key) ?? 0) + netDemand);// Seed top-level contributor for this projection. Use the projection's@@ -382,7 +443,7 @@ serve(async (req: Request) => {}// Sales order lines- for (const line of salesOrderLines.data) {+ for (const line of salesOrderLines.data ?? []) {if (!line.itemId || !line.quantityToSend) continue;const promiseDate = line.promisedDate@@ -391,10 +452,15 @@ serve(async (req: Request) => {const period = findPeriod(promiseDate, today, periods);if (!period) continue;- const key = `${line.locationId ?? ""}-${period.id ?? ""}-${line.itemId}`;+ const key = makeKey(line.locationId ?? "", period.id ?? "", line.itemId);grossDemand.set(key, (grossDemand.get(key) ?? 0) + line.quantityToSend);- const actualKey = `${line.itemId}-${line.locationId ?? ""}-${period.id ?? ""}-Sales Order`;+ const actualKey = makeActualKey(+ line.itemId,+ line.locationId ?? "",+ period.id ?? "",+ "Sales Order"+ );salesDemandByKey.set(actualKey,(salesDemandByKey.get(actualKey) ?? 0) + line.quantityToSend@@ -413,7 +479,7 @@ serve(async (req: Request) => {}// Job material lines- for (const line of jobMaterialLines.data) {+ for (const line of jobMaterialLines.data ?? []) {if (!line.itemId || !line.quantityToIssue) continue;const dueDate = line.dueDate ? parseDate(line.dueDate) : today;@@ -421,10 +487,15 @@ serve(async (req: Request) => {const period = findPeriod(requiredDate, today, periods);if (!period) continue;- const key = `${line.locationId ?? ""}-${period.id ?? ""}-${line.itemId}`;+ const key = makeKey(line.locationId ?? "", period.id ?? "", line.itemId);grossDemand.set(key, (grossDemand.get(key) ?? 0) + line.quantityToIssue);- const actualKey = `${line.itemId}-${line.locationId ?? ""}-${period.id ?? ""}-Job Material`;+ const actualKey = makeActualKey(+ line.itemId,+ line.locationId ?? "",+ period.id ?? "",+ "Job Material"+ );jobMaterialDemandByKey.set(actualKey,(jobMaterialDemandByKey.get(actualKey) ?? 0) + line.quantityToIssue@@ -458,11 +529,13 @@ serve(async (req: Request) => {for (const location of locations.data) {// Consume First draws down the old item's on-hand before redirecting.let oldOnHand = consumeOnHand- ? (baseInventoryByLocationItem.get(`${location.id}-${oldItemId}`) ?? 0)+ ? (baseInventoryByLocationItem.get(+ makeLocationItemKey(location.id, oldItemId)+ ) ?? 0): 0;for (const period of periods) {- const oldKey = `${location.id}-${period.id ?? ""}-${oldItemId}`;+ const oldKey = makeKey(location.id, period.id ?? "", oldItemId);const demand = grossDemand.get(oldKey);if (!demand) continue;@@ -476,7 +549,7 @@ serve(async (req: Request) => {topLevelContributors.delete(oldKey);if (redirect > 0) {- const newKey = `${location.id}-${period.id ?? ""}-${successorId}`;+ const newKey = makeKey(location.id, period.id ?? "", successorId);grossDemand.set(newKey, (grossDemand.get(newKey) ?? 0) + redirect);if (contributors) {// Mark the moved demand so it can be shown as redirected from the@@ -532,7 +605,7 @@ serve(async (req: Request) => {}}- const { bomDerivedDemand, demandContributors } = explodeBom({+ const { bomDerivedDemand, demandContributors, cycleItemIds } = explodeBom({grossDemand,bomByItem,replenishmentSystemByItem,@@ -543,6 +616,13 @@ serve(async (req: Request) => {topLevelContributors,});+ if (cycleItemIds.size > 0) {+ logger.warn(+ "BOM cycle detected — cycle items were planned as leaf items (no explosion through them)",+ { companyId, itemIds: [...cycleItemIds] }+ );+ }+// demandForecast output: Map<"itemId-locationId-periodId", record>const demandForecastMap = new Map<string,@@ -557,7 +637,7 @@ serve(async (req: Request) => {if (qty <= 0) continue;const [locationId, periodId, itemId] = splitKey(key);- const forecastKey = `${itemId}-${locationId}-${periodId}`;+ const forecastKey = makeKey(locationId, periodId, itemId);const existing = demandForecastMap.get(forecastKey);if (existing) {existing.forecastQuantity = Number(existing.forecastQuantity) + qty;@@ -637,26 +717,41 @@ serve(async (req: Request) => {Database["public"]["Tables"]["supplyActual"]["Insert"]>();+ // Paginated: a single tenant's actuals exceed the production max_rows cap+ // (9,391 rows observed), and a truncated read here leaves stale actuals+ // un-zeroed. Ordering by the primary key keeps pages stable.const [{ data: existingDemandActuals, error: demandActualsError },{ data: existingSupplyActuals, error: supplyActualsError },] = await Promise.all([- client- .from("demandActual")- .select("*")- .eq("companyId", companyId)- .in(- "periodId",- periods.map((p) => p.id ?? "")- ),- client- .from("supplyActual")- .select("*")- .eq("companyId", companyId)- .in(- "periodId",- periods.map((p: DemandPeriod) => p.id ?? "").filter(Boolean)- ),+ fetchAll<Database["public"]["Tables"]["demandActual"]["Row"]>(() =>+ client+ .from("demandActual")+ .select("*")+ .eq("companyId", companyId)+ .in(+ "periodId",+ periods.map((p) => p.id ?? "")+ )+ .order("itemId")+ .order("locationId")+ .order("periodId")+ .order("sourceType")+ ),+ fetchAll<Database["public"]["Tables"]["supplyActual"]["Row"]>(() =>+ client+ .from("supplyActual")+ .select("*")+ .eq("companyId", companyId)+ .in(+ "periodId",+ periods.map((p: DemandPeriod) => p.id ?? "").filter(Boolean)+ )+ .order("itemId")+ .order("locationId")+ .order("periodId")+ .order("sourceType")+ ),]);if (demandActualsError) throw demandActualsError;@@ -665,7 +760,12 @@ serve(async (req: Request) => {// Zero out existing demand actuals (they'll be overwritten if still relevant)if (existingDemandActuals) {for (const existing of existingDemandActuals) {- const key = `${existing.itemId}-${existing.locationId}-${existing.periodId}-${existing.sourceType}`;+ const key = makeActualKey(+ existing.itemId,+ existing.locationId ?? "",+ existing.periodId,+ existing.sourceType+ );demandActualsMap.set(key, {itemId: existing.itemId,locationId: existing.locationId,@@ -682,10 +782,11 @@ serve(async (req: Request) => {// Sales order demand actualsfor (const [key, quantity] of salesDemandByKey) {if (quantity > 0) {+ const [itemId, locationId, periodId] = splitActualKey(key);demandActualsMap.set(key, {- itemId: key.split("-")[0],- locationId: key.split("-")[1],- periodId: key.split("-")[2],+ itemId,+ locationId,+ periodId,actualQuantity: quantity,sourceType: "Sales Order",companyId,@@ -698,10 +799,11 @@ serve(async (req: Request) => {// Job material demand actualsfor (const [key, quantity] of jobMaterialDemandByKey) {if (quantity > 0) {+ const [itemId, locationId, periodId] = splitActualKey(key);demandActualsMap.set(key, {- itemId: key.split("-")[0],- locationId: key.split("-")[1],- periodId: key.split("-")[2],+ itemId,+ locationId,+ periodId,actualQuantity: quantity,sourceType: "Job Material",companyId,@@ -714,7 +816,12 @@ serve(async (req: Request) => {// Zero out existing supply actualsif (existingSupplyActuals) {for (const existing of existingSupplyActuals) {- const key = `${existing.itemId}-${existing.locationId}-${existing.periodId}-${existing.sourceType}`;+ const key = makeActualKey(+ existing.itemId,+ existing.locationId ?? "",+ existing.periodId,+ existing.sourceType+ );supplyActualsMap.set(key, {itemId: existing.itemId,locationId: existing.locationId,@@ -731,8 +838,13 @@ serve(async (req: Request) => {// Production order supply actualsfor (const [key, quantity] of jobSupplyByLocationPeriodItem) {if (quantity > 0) {- const [locationId, periodId, itemId] = key.split("-");- const actualKey = `${itemId}-${locationId}-${periodId}-Production Order`;+ const [locationId, periodId, itemId] = splitKey(key);+ const actualKey = makeActualKey(+ itemId,+ locationId,+ periodId,+ "Production Order"+ );supplyActualsMap.set(actualKey, {itemId,locationId,@@ -749,8 +861,13 @@ serve(async (req: Request) => {// Purchase order supply actualsfor (const [key, quantity] of poSupplyByLocationPeriodItem) {if (quantity > 0) {- const [locationId, periodId, itemId] = key.split("-");- const actualKey = `${itemId}-${locationId}-${periodId}-Purchase Order`;+ const [locationId, periodId, itemId] = splitKey(key);+ const actualKey = makeActualKey(+ itemId,+ locationId,+ periodId,+ "Purchase Order"+ );supplyActualsMap.set(actualKey, {itemId,locationId,@@ -775,93 +892,105 @@ serve(async (req: Request) => {const BATCH_SIZE = 500;try {- // Delete existing MRP forecasts- await db- .deleteFrom("demandForecast")- .where("companyId", "=", companyId)- .where("forecastMethod", "=", "mrp")- .execute();-- // Delete existing MRP forecast source rows. The demandForecast delete- // above removes the parent rows; this removes their attribution rows.- // demandForecastSource only ever holds MRP-derived rows.- await db- .deleteFrom("demandForecastSource")- .where("companyId", "=", companyId)- .execute();-- await db- .deleteFrom("supplyForecast")- .where(- "locationId",- "in",- locations.data.map((l) => l.id)- )- .where("companyId", "=", companyId)- .execute();-- // Insert demand forecasts in batches- for (let i = 0; i < demandForecastUpserts.length; i += BATCH_SIZE) {- const batch = demandForecastUpserts.slice(i, i + BATCH_SIZE);- await db- .insertInto("demandForecast")- .values(batch)- .onConflict((oc) =>- oc.columns(["itemId", "locationId", "periodId"]).doUpdateSet({- forecastQuantity: (eb) => eb.ref("excluded.forecastQuantity"),- forecastMethod: (eb) => eb.ref("excluded.forecastMethod"),- updatedAt: new Date().toISOString(),- updatedBy: userId,- })- )+ // One transaction for the whole delete-and-rewrite: these statements+ // previously ran independently, so a crash mid-sequence (or a reader+ // between the delete and the inserts) saw planning data half-written —+ // fresh forecasts with empty actuals. All-or-nothing now; Kysely rolls+ // everything back on any throw.+ await db.transaction().execute(async (trx) => {+ // Delete existing MRP forecasts+ await trx+ .deleteFrom("demandForecast")+ .where("companyId", "=", companyId)+ .where("forecastMethod", "=", "mrp").execute();- }- // Insert demand forecast source rows in batches. No onConflict — the- // upstream delete guarantees no key collisions.- for (let i = 0; i < demandForecastSourceInserts.length; i += BATCH_SIZE) {- const batch = demandForecastSourceInserts.slice(i, i + BATCH_SIZE);- await db- .insertInto("demandForecastSource")- .values(batch)+ // Delete existing MRP forecast source rows. The demandForecast delete+ // above removes the parent rows; this removes their attribution rows.+ // demandForecastSource only ever holds MRP-derived rows.+ await trx+ .deleteFrom("demandForecastSource")+ .where("companyId", "=", companyId).execute();- }- // Insert demand actuals in batches- for (let i = 0; i < demandActualUpserts.length; i += BATCH_SIZE) {- const batch = demandActualUpserts.slice(i, i + BATCH_SIZE);- await db- .insertInto("demandActual")- .values(batch)- .onConflict((oc) =>- oc- .columns(["itemId", "locationId", "periodId", "sourceType"])- .doUpdateSet({- actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),- updatedAt: new Date().toISOString(),- updatedBy: userId,- })- )- .execute();- }+ // Guarded: an empty array renders as `IN ()`, which is a syntax error+ // (42601), so a company with no locations configured crashed the whole+ // run. Nothing to clear in that case anyway.+ if (locations.data.length > 0) {+ await trx+ .deleteFrom("supplyForecast")+ .where(+ "locationId",+ "in",+ locations.data.map((l) => l.id)+ )+ .where("companyId", "=", companyId)+ .execute();+ }- // Insert supply actuals in batches- for (let i = 0; i < supplyActualUpserts.length; i += BATCH_SIZE) {- const batch = supplyActualUpserts.slice(i, i + BATCH_SIZE);- await db- .insertInto("supplyActual")- .values(batch)- .onConflict((oc) =>- oc- .columns(["itemId", "locationId", "periodId", "sourceType"])- .doUpdateSet({- actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),- updatedAt: new Date().toISOString(),+ // Insert demand forecasts in batches+ for (let i = 0; i < demandForecastUpserts.length; i += BATCH_SIZE) {+ const batch = demandForecastUpserts.slice(i, i + BATCH_SIZE);+ await trx+ .insertInto("demandForecast")+ .values(batch)+ .onConflict((oc) =>+ oc.columns(["itemId", "locationId", "periodId"]).doUpdateSet({+ forecastQuantity: (eb) => eb.ref("excluded.forecastQuantity"),+ forecastMethod: (eb) => eb.ref("excluded.forecastMethod"),+ updatedAt: datetime.timestamp(),updatedBy: userId,})- )- .execute();- }+ )+ .execute();+ }++ // Insert demand forecast source rows in batches. No onConflict — the+ // upstream delete guarantees no key collisions.+ for (let i = 0; i < demandForecastSourceInserts.length; i += BATCH_SIZE) {+ const batch = demandForecastSourceInserts.slice(i, i + BATCH_SIZE);+ await trx+ .insertInto("demandForecastSource")+ .values(batch)+ .execute();+ }++ // Insert demand actuals in batches+ for (let i = 0; i < demandActualUpserts.length; i += BATCH_SIZE) {+ const batch = demandActualUpserts.slice(i, i + BATCH_SIZE);+ await trx+ .insertInto("demandActual")+ .values(batch)+ .onConflict((oc) =>+ oc+ .columns(["itemId", "locationId", "periodId", "sourceType"])+ .doUpdateSet({+ actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),+ updatedAt: datetime.timestamp(),+ updatedBy: userId,+ })+ )+ .execute();+ }++ // Insert supply actuals in batches+ for (let i = 0; i < supplyActualUpserts.length; i += BATCH_SIZE) {+ const batch = supplyActualUpserts.slice(i, i + BATCH_SIZE);+ await trx+ .insertInto("supplyActual")+ .values(batch)+ .onConflict((oc) =>+ oc+ .columns(["itemId", "locationId", "periodId", "sourceType"])+ .doUpdateSet({+ actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),+ updatedAt: datetime.timestamp(),+ updatedBy: userId,+ })+ )+ .execute();+ }+ });return jsonResponse({ success: true }, 201);} catch (err) {@@ -964,7 +1093,7 @@ async function getOrCreateDemandPeriods(startDate: period.startDate,endDate: period.endDate,periodType,- createdAt: new Date().toISOString(),+ createdAt: datetime.timestamp(),}))).returningAll()diff --git a/packages/database/supabase/migrations/20260812002453_event-system-statement-handlers.sql b/packages/database/supabase/migrations/20260812002453_event-system-statement-handlers.sqlnew file mode 100644index 0000000000..18634ef12d--- /dev/null+++ b/packages/database/supabase/migrations/20260812002453_event-system-statement-handlers.sql@@ -0,0 +1,119 @@+-- Event system: attach_statement_handler — a table can register its own+-- STATEMENT-level handler, run with the transition tables batched_new /+-- batched_old. The statement-level sibling of attach_event_trigger's row-level+-- interceptors; does not enqueue to PGMQ.+--+-- This cannot live inside dispatch_event_batch(): transition tables are visible+-- only to the function a trigger invokes directly (a nested call fails with+-- `relation "batched_new" does not exist`), and dispatch_event_batch returns+-- early for tables with no active subscription. It is also not an extra+-- parameter on attach_event_trigger: adding a defaulted parameter alongside the+-- two live overloads makes existing calls ambiguous, and the dispatcher costs+-- ~0.3 ms per statement even with no subscribers — wrong default for a+-- high-volume table like itemLedger that only wants a local aggregate.++-- 20260410030406 added attach_event_trigger's 3rd parameter via CREATE OR+-- REPLACE, which created a SIBLING overload rather than replacing. A 2-argument+-- call has been ambiguous ("is not unique") ever since — unnoticed only because+-- no migration since uses that form. The old overload is redundant (the newer+-- one defaults its 3rd arg), so drop it.+DROP FUNCTION IF EXISTS public.attach_event_trigger(TEXT, TEXT[]);++CREATE OR REPLACE FUNCTION public.attach_statement_handler(+ table_name_text TEXT,+ handler_functions TEXT[] DEFAULT ARRAY[]::TEXT[]+)+RETURNS VOID AS $$+DECLARE+ fn TEXT;+ existing TEXT;+BEGIN+ -- Drop-then-attach, like attach_event_trigger's sync sections: re-running is+ -- idempotent and an empty array detaches.+ FOR existing IN+ SELECT t.tgname+ FROM pg_trigger t+ WHERE t.tgrelid = format('%I', table_name_text)::regclass+ AND NOT t.tgisinternal+ AND t.tgname LIKE 'trg\_event\_statement\_%'+ LOOP+ EXECUTE format('DROP TRIGGER IF EXISTS %2$I ON %1$I;', table_name_text, existing);+ END LOOP;++ -- One function serves all three operations, so it must branch on TG_OP: only+ -- batched_new exists on INSERT and only batched_old on DELETE. PL/pgSQL plans+ -- lazily, so a branch that does not run never resolves its missing table.+ FOREACH fn IN ARRAY handler_functions LOOP+ EXECUTE format('+ CREATE TRIGGER %2$I AFTER INSERT ON %1$I+ REFERENCING NEW TABLE AS batched_new+ FOR EACH STATEMENT EXECUTE FUNCTION %3$I();+ ', table_name_text, format('trg_event_statement_%s_ins', fn), fn);++ EXECUTE format('+ CREATE TRIGGER %2$I AFTER UPDATE ON %1$I+ REFERENCING NEW TABLE AS batched_new OLD TABLE AS batched_old+ FOR EACH STATEMENT EXECUTE FUNCTION %3$I();+ ', table_name_text, format('trg_event_statement_%s_upd', fn), fn);++ EXECUTE format('+ CREATE TRIGGER %2$I AFTER DELETE ON %1$I+ REFERENCING OLD TABLE AS batched_old+ FOR EACH STATEMENT EXECUTE FUNCTION %3$I();+ ', table_name_text, format('trg_event_statement_%s_del', fn), fn);+ END LOOP;+END;+$$ LANGUAGE plpgsql;++COMMENT ON FUNCTION public.attach_statement_handler(TEXT, TEXT[]) IS+ 'Attaches statement-level handler functions to a table, run with the transition tables batched_new / batched_old. The statement-level sibling of attach_event_trigger''s row-level interceptors; does not register the table for PGMQ dispatch. Handlers must branch on TG_OP.';++-- Same columns as before; the CASE expressions gain a HANDLER (STATEMENT) branch.+DROP VIEW IF EXISTS "eventSystemTrigger";++CREATE VIEW "eventSystemTrigger" AS+SELECT+ t.tgrelid::regclass::text AS "tableName",++ CASE+ WHEN t.tgname LIKE 'trg_event_statement_%' THEN 'HANDLER (STATEMENT)'+ WHEN t.tgname LIKE 'trg_event_after_sync_%' THEN 'AFTER SYNC (ROW)'+ WHEN t.tgname LIKE 'trg_event_sync_%' THEN 'BEFORE SYNC (ROW)'+ WHEN t.tgname LIKE 'trg_event_async_%' THEN 'ASYNC (STATEMENT)'+ ELSE 'UNKNOWN'+ END AS "type",++ CASE+ -- ::text so the generated column type stays string, not `name`+ WHEN t.tgname LIKE 'trg_event_statement_%' THEN p.proname::text+ WHEN t.tgname LIKE 'trg_event_after_sync_%' THEN+ REPLACE(+ REPLACE(+ substring(pg_get_triggerdef(t.oid) FROM 'dispatch_event_after_interceptors\((.*)\)'),+ '''', ''+ ),+ ', ', ' -> '+ )+ WHEN t.tgname LIKE 'trg_event_sync_%' THEN+ REPLACE(+ REPLACE(+ substring(pg_get_triggerdef(t.oid) FROM 'dispatch_event_interceptors\((.*)\)'),+ '''', ''+ ),+ ', ', ' -> '+ )+ ELSE 'PGMQ Batch'+ END AS "attachedFunctions",++ CASE+ WHEN t.tgenabled = 'O' THEN 'Active'+ WHEN t.tgenabled = 'D' THEN 'Disabled'+ ELSE 'Replica Only'+ END AS "status",++ t.tgname AS "systemTriggerName"+FROM pg_trigger t+JOIN pg_proc p ON p.oid = t.tgfoid+WHERE t.tgname LIKE 'trg_event_%'+ AND NOT t.tgisinternal+ORDER BY "tableName", "type" DESC;diff --git a/packages/database/supabase/migrations/20260812002454_item-stock-quantities-incremental.sql b/packages/database/supabase/migrations/20260812002454_item-stock-quantities-incremental.sqlnew file mode 100644index 0000000000..96ae31b024--- /dev/null+++ b/packages/database/supabase/migrations/20260812002454_item-stock-quantities-incremental.sql@@ -0,0 +1,263 @@+-- itemStockQuantities: materialized view -> incrementally maintained table.+--+-- The matview was a full scan of itemLedger refreshed by pg_cron every 30 min,+-- so the item-dropdown badge could be ~40 min stale (30 min cron + the client's+-- 10 min poll). Scan cost also grew with total ledger history, for every tenant+-- at once, 48 times a day.+--+-- itemLedger is effectively append-only -- the only in-place UPDATE is the+-- denormalized "trackedEntityStatus" column, itself maintained by+-- sync_item_ledger_on_tracked_entity_status_change (20260420112047) -- so the+-- aggregate can be maintained by signed deltas at O(rows written) instead of+-- recomputed at O(all history).+--+-- Relation name and columns are unchanged: RealtimeDataProvider.tsx and the+-- workflow engine's item.quantityOnHand operation read it by name.++-- ---------------------------------------------------------------------------+-- 1. Stop the periodic refresh+-- ---------------------------------------------------------------------------++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'refresh-item-stock-quantities') THEN+ PERFORM cron.unschedule('refresh-item-stock-quantities');+ END IF;+END $$;++-- ---------------------------------------------------------------------------+-- 2. The on-hand filter, defined exactly once+--+-- Every delta the triggers apply and the reconciliation recompute go through+-- this, so the incremental path cannot drift from the batch path. Mirrors the+-- matview's `SUM(quantity) FILTER (WHERE status IS NULL OR status <> 'Rejected')`.+-- ---------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION item_ledger_on_hand_contribution(+ quantity NUMERIC,+ tracked_entity_status "trackedEntityStatus"+)+RETURNS NUMERIC+LANGUAGE sql+IMMUTABLE+AS $$+ SELECT CASE+ WHEN tracked_entity_status IS NULL OR tracked_entity_status <> 'Rejected'+ THEN COALESCE(quantity, 0)+ ELSE 0+ END;+$$;++-- ---------------------------------------------------------------------------+-- 3. Replace the matview with a real table+--+-- quantityOnHand is NOT NULL DEFAULT 0 where the matview's SUM(...) FILTER+-- could yield NULL (a group whose rows are all Rejected). Both consumers+-- already coerce null -> 0, so this normalizes rather than changes behaviour.+-- ---------------------------------------------------------------------------++DROP MATERIALIZED VIEW IF EXISTS "itemStockQuantities";++-- Convention exceptions, deliberate: this is DERIVED state, not an entity.+-- The natural key (itemId, companyId, locationId) IS the identity — a surrogate+-- id() would add no meaning and would break the ON CONFLICT upserts the trigger+-- depends on. Audit columns are omitted for the same reason: every row is+-- written by a trigger or the reconciliation job, never by a user, so+-- createdBy/updatedBy would record 'system' forever on a hot-path table. The+-- matview this replaces had neither.+CREATE TABLE "itemStockQuantities" (+ "itemId" TEXT NOT NULL,+ "companyId" TEXT NOT NULL,+ -- '' is the bucket for ledger rows with no location, matching the matview's+ -- COALESCE("locationId", ''). Part of the key, so it cannot be NULL.+ "locationId" TEXT NOT NULL DEFAULT '',+ "quantityOnHand" NUMERIC NOT NULL DEFAULT 0,++ PRIMARY KEY ("itemId", "companyId", "locationId")+);++CREATE INDEX "itemStockQuantities_companyId_idx"+ ON "itemStockQuantities" ("companyId");++-- ---------------------------------------------------------------------------+-- 4. Backfill from the ledger (same statement the matview used)+-- ---------------------------------------------------------------------------++INSERT INTO "itemStockQuantities" ("itemId", "companyId", "locationId", "quantityOnHand")+SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ COALESCE(SUM(item_ledger_on_hand_contribution("quantity", "trackedEntityStatus")), 0)+FROM "itemLedger"+GROUP BY "itemId", "companyId", COALESCE("locationId", '');++-- ---------------------------------------------------------------------------+-- 5. Incremental maintenance -- a statement-level event handler+--+-- Statement-level so a bulk posting is one upsert rather than N (this includes+-- the multi-row UPDATE the trackedEntity status sync issues). SECURITY DEFINER+-- because itemLedger has no UPDATE RLS policy and writers hold no grants on the+-- aggregate. ORDER BY on the key so concurrent statements take row locks in a+-- consistent order (deadlock avoidance).+-- ---------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION apply_item_stock_quantities()+RETURNS TRIGGER AS $$+BEGIN+ IF TG_OP = 'INSERT' THEN+ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ SUM(item_ledger_on_hand_contribution("quantity", "trackedEntityStatus"))+ FROM batched_new+ GROUP BY "itemId", "companyId", COALESCE("locationId", '')+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = isq."quantityOnHand" + EXCLUDED."quantityOnHand";++ ELSIF TG_OP = 'UPDATE' THEN+ -- Generic old-vs-new: subtract every old row's contribution at its old key+ -- and add every new row's at its new key. Covers the real case (a+ -- trackedEntityStatus flip) and any future quantity/location/item edit+ -- without special-casing.+ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT "itemId", "companyId", "locationId", SUM(delta)+ FROM (+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", '') AS "locationId",+ -item_ledger_on_hand_contribution("quantity", "trackedEntityStatus") AS delta+ FROM batched_old+ UNION ALL+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ item_ledger_on_hand_contribution("quantity", "trackedEntityStatus")+ FROM batched_new+ ) d+ GROUP BY "itemId", "companyId", "locationId"+ -- A key whose net delta is zero already holds the right number; skipping it+ -- avoids taking a lock on every row a wide UPDATE happened to touch.+ HAVING SUM(delta) <> 0+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = isq."quantityOnHand" + EXCLUDED."quantityOnHand";++ ELSIF TG_OP = 'DELETE' THEN+ -- Defensive: no application path deletes itemLedger rows today. A key left+ -- at zero with no backing ledger rows is removed by the nightly+ -- reconciliation.+ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ -SUM(item_ledger_on_hand_contribution("quantity", "trackedEntityStatus"))+ FROM batched_old+ GROUP BY "itemId", "companyId", COALESCE("locationId", '')+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = isq."quantityOnHand" + EXCLUDED."quantityOnHand";+ END IF;++ RETURN NULL;+END;+$$ LANGUAGE plpgsql+SECURITY DEFINER+-- Pinned: this runs on every itemLedger write, so the caller is an ordinary+-- application role. Without it, unqualified names resolve through a+-- caller-controlled search_path.+SET search_path = public, pg_temp;++SELECT attach_statement_handler('itemLedger', ARRAY['apply_item_stock_quantities']);++-- ---------------------------------------------------------------------------+-- 6. RLS+--+-- The matview could not carry RLS at all -- tenant isolation depended on every+-- caller remembering .eq("companyId", ...). A real table closes that.+--+-- Reads only: the triggers and reconciliation are SECURITY DEFINER, so no+-- INSERT/UPDATE/DELETE policy exists and PostgREST clients cannot write.+-- get_companies_with_employee_role() is wrapped in a SELECT so it is evaluated+-- once per query rather than once per row.+-- ---------------------------------------------------------------------------++ALTER TABLE "public"."itemStockQuantities" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."itemStockQuantities"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);++GRANT SELECT ON "public"."itemStockQuantities" TO authenticated;++-- ---------------------------------------------------------------------------+-- 7. Realtime: let the client patch the badge instead of waiting for its poll+-- ---------------------------------------------------------------------------++ALTER PUBLICATION supabase_realtime ADD TABLE "itemStockQuantities";++-- ---------------------------------------------------------------------------+-- 8. Nightly reconciliation+--+-- The triggers are the source of truth; this is the backstop that converges any+-- drift (a write path that bypassed the triggers, a hand-run SQL fix) and drops+-- keys whose ledger rows are gone. One pass a night costs about the same as a+-- single one of the 48 daily refreshes this migration removes.+-- ---------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION reconcile_item_stock_quantities()+RETURNS void+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public, pg_temp+AS $$+BEGIN+ -- The triggers apply RELATIVE deltas, which is safe under concurrency. This+ -- function writes an ABSOLUTE recompute, which is not: at READ COMMITTED a+ -- ledger write committing between this statement's snapshot and its row lock+ -- would have its delta overwritten — the drift repair would itself create+ -- drift. Hold a SHARE lock so no ledger write can interleave. SHARE conflicts+ -- with ROW EXCLUSIVE (INSERT/UPDATE/DELETE) but not with other readers, and+ -- this runs once nightly.+ LOCK TABLE "itemLedger" IN SHARE MODE;++ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ COALESCE(SUM(item_ledger_on_hand_contribution("quantity", "trackedEntityStatus")), 0)+ FROM "itemLedger"+ GROUP BY "itemId", "companyId", COALESCE("locationId", '')+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = EXCLUDED."quantityOnHand"+ WHERE isq."quantityOnHand" IS DISTINCT FROM EXCLUDED."quantityOnHand";++ DELETE FROM "itemStockQuantities" isq+ WHERE NOT EXISTS (+ SELECT 1+ FROM "itemLedger" il+ WHERE il."itemId" = isq."itemId"+ AND il."companyId" = isq."companyId"+ AND COALESCE(il."locationId", '') = isq."locationId"+ );+END;+$$;++SELECT cron.schedule(+ 'reconcile-item-stock-quantities',+ '15 3 * * *',+ $$SELECT reconcile_item_stock_quantities();$$+);diff --git a/packages/database/supabase/migrations/20260812030545_bom-self-reference-guard.sql b/packages/database/supabase/migrations/20260812030545_bom-self-reference-guard.sqlnew file mode 100644index 0000000000..5e8ec0ea12--- /dev/null+++ b/packages/database/supabase/migrations/20260812030545_bom-self-reference-guard.sql@@ -0,0 +1,103 @@+-- BOM self-reference guard: an item can never be a material on its own make+-- method.+--+-- Six production rows said "to make one X, consume Q of X", each with+-- materialMakeMethodId pointing back at its own makeMethodId — a one-node+-- cycle in the method graph. Nothing validated against it: the BOM editor+-- accepts any item as a material, and upsertMethodMaterial resolves+-- materialMakeMethodId from the child item's active method, so picking the+-- parent item assembles the loop automatically. Downstream: MRP emits phantom+-- self-demand (demand inflated by (1 + qty)), jobs copy the row and require+-- their own output item as a picked/purchased input, and every recursive+-- method-tree walker terminates only via incidental cycle guards.++-- ---------------------------------------------------------------------------+-- 1. Delete the existing self-references (6 rows across 3 tenants, all+-- verified accidental: purchased hardware and mis-picks, plus one junk row+-- in a test tenant; across ALL make method versions, not just active ones).+-- ---------------------------------------------------------------------------++DELETE FROM "methodMaterial" mm+USING "makeMethod" m+WHERE m."id" = mm."makeMethodId"+ AND m."companyId" = mm."companyId"+ AND m."itemId" = mm."itemId";++-- ---------------------------------------------------------------------------+-- 2. Sync interceptor: veto the write inline, for every write path+-- (PostgREST, Kysely, SQL). BEFORE ROW via dispatch_event_interceptors;+-- RAISE aborts the statement.+-- ---------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_check_method_material_self_reference(+ p_table TEXT,+ p_operation TEXT,+ p_new JSONB,+ p_old JSONB+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+-- Pinned: runs on every write to this table, so the caller is an ordinary+-- application role and must not control name resolution.+SET search_path = public, pg_temp+AS $$+DECLARE+ parent_item_id TEXT;+ cycle_found BOOLEAN;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN RETURN; END IF;++ -- A make method belongs to exactly one item, so a materialMakeMethodId equal+ -- to the row's own makeMethodId is always a self-loop regardless of itemId.+ IF p_new->>'materialMakeMethodId' = p_new->>'makeMethodId' THEN+ RAISE EXCEPTION 'An item cannot use its own make method as a material sub-method'+ USING ERRCODE = 'check_violation';+ END IF;++ SELECT "itemId" INTO parent_item_id+ FROM "makeMethod"+ WHERE "id" = p_new->>'makeMethodId'+ AND "companyId" = p_new->>'companyId';++ IF parent_item_id = p_new->>'itemId' THEN+ RAISE EXCEPTION 'An item cannot be a material on its own bill of materials'+ USING ERRCODE = 'check_violation';+ END IF;++ -- Multi-node cycles (A needs B, B needs A): would the new material's own+ -- active-method BOM graph reach back to this method's item? Bounded walk+ -- over active methods only — the graph MRP plans against. UNION (not UNION+ -- ALL) dedupes, so the walk terminates even over pre-existing cycles; the+ -- depth cap is a backstop. BOM edits are UI-volume, so the walk is cheap.+ WITH RECURSIVE reachable AS (+ SELECT p_new->>'itemId' AS item_id, 0 AS depth+ UNION+ SELECT mm."itemId", r.depth + 1+ FROM reachable r+ JOIN "activeMakeMethods" amm+ ON amm."itemId" = r.item_id+ AND amm."companyId" = p_new->>'companyId'+ JOIN "methodMaterial" mm+ ON mm."makeMethodId" = amm."id"+ AND mm."companyId" = amm."companyId"+ WHERE r.depth < 100+ )+ SELECT EXISTS (SELECT 1 FROM reachable WHERE item_id = parent_item_id)+ INTO cycle_found;++ IF cycle_found THEN+ RAISE EXCEPTION 'Adding this material would create a loop in the bill of materials: its own BOM already contains this item'+ USING ERRCODE = 'check_violation';+ END IF;+END;+$$;++-- Explicit 3-argument form. The 2-argument overload is dropped by+-- 20260812002453, which runs first, but naming every argument keeps this call+-- unambiguous no matter which overloads exist when it runs.+SELECT attach_event_trigger(+ 'methodMaterial',+ ARRAY['sync_check_method_material_self_reference']::TEXT[],+ ARRAY[]::TEXT[]+);diff --git a/packages/database/supabase/migrations/20260812032423_job-material-self-reference-guard.sql b/packages/database/supabase/migrations/20260812032423_job-material-self-reference-guard.sqlnew file mode 100644index 0000000000..559ddff829--- /dev/null+++ b/packages/database/supabase/migrations/20260812032423_job-material-self-reference-guard.sql@@ -0,0 +1,108 @@+-- Job-level self-consumption guard: a job can never list its own output item+-- as a material.+--+-- Companion to 20260812030545 (the same guard on methodMaterial). 50 jobMaterial+-- rows across ~20 tenants had jm."itemId" = job."itemId" — a job requiring its+-- own output to be picked or purchased before it can produce it. Most were+-- added directly on jobs, not copied from the (now guarded) BOMs, so the job+-- table needs its own gate.++-- ---------------------------------------------------------------------------+-- 1. Cleanup.+--+-- Deleting a material line cascades jobMaterial -> jobMakeMethod ->+-- jobOperation, and SIX tables cascade off jobOperation: productionEvent+-- (labor/time), jobOperationTool, jobOperationStep, jobOperationParameter,+-- rework and nonConformanceJobOperation. Only productionQuantity is+-- NO ACTION — i.e. it raises — so it is the ONLY one a failed delete would+-- reveal; the rest disappear silently.+--+-- So the rule here is not "detach what would error", it is "never let the+-- cascade reach an operation at all": detach every subtree containing ANY+-- jobOperation. Detached methods stay on the job as root-level methods with+-- their operations, labor and production intact. Only genuinely empty+-- method copies are allowed to cascade away.+--+-- Verified against the prod snapshot: 0 itemLedger / pickingListLine+-- references to any of the self-consuming lines.+-- ---------------------------------------------------------------------------++WITH RECURSIVE bad AS (+ SELECT jm.id, jm."companyId"+ FROM "jobMaterial" jm+ JOIN job j ON j.id = jm."jobId" AND j."companyId" = jm."companyId"+ WHERE jm."itemId" = j."itemId"+),+subtree AS (+ SELECT b.id AS bad_id, m.id AS method_id, b."companyId"+ FROM bad b+ JOIN "jobMakeMethod" m+ ON m."parentMaterialId" = b.id AND m."companyId" = b."companyId"+ UNION+ SELECT s.bad_id, m2.id, s."companyId"+ FROM subtree s+ JOIN "jobMaterial" jm2+ ON jm2."jobMakeMethodId" = s.method_id AND jm2."companyId" = s."companyId"+ JOIN "jobMakeMethod" m2+ ON m2."parentMaterialId" = jm2.id AND m2."companyId" = jm2."companyId"+),+dirty AS (+ SELECT DISTINCT s.bad_id+ FROM subtree s+ JOIN "jobOperation" jo+ ON jo."jobMakeMethodId" = s.method_id AND jo."companyId" = s."companyId"+)+UPDATE "jobMakeMethod" m+SET "parentMaterialId" = NULL+WHERE m."parentMaterialId" IN (SELECT bad_id FROM dirty);++DELETE FROM "jobMaterial" jm+USING job j+WHERE j.id = jm."jobId"+ AND j."companyId" = jm."companyId"+ AND jm."itemId" = j."itemId";++-- ---------------------------------------------------------------------------+-- 2. Sync interceptor: veto on write, every path (UI, MES, API, Kysely).+-- ---------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION sync_check_job_material_self_reference(+ p_table TEXT,+ p_operation TEXT,+ p_new JSONB,+ p_old JSONB+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+-- Pinned: runs on every write to this table, so the caller is an ordinary+-- application role and must not control name resolution.+SET search_path = public, pg_temp+AS $$+DECLARE+ job_item_id TEXT;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN RETURN; END IF;++ SELECT "itemId" INTO job_item_id+ FROM job+ WHERE "id" = p_new->>'jobId'+ AND "companyId" = p_new->>'companyId';++ IF job_item_id = p_new->>'itemId' THEN+ RAISE EXCEPTION 'A job cannot consume the item it produces as a material'+ USING ERRCODE = 'check_violation';+ END IF;+END;+$$;++-- jobMaterial is already event-wired (20260410031810); re-attach with the+-- check PREPENDED to the existing interceptor lists so nothing is clobbered.+SELECT attach_event_trigger(+ 'jobMaterial',+ ARRAY[+ 'sync_check_job_material_self_reference',+ 'sync_update_job_material_make_method_item_id'+ ]::TEXT[],+ ARRAY['sync_insert_job_material_make_method']::TEXT[]+);