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(production): batch N+1 method-tree queries in get-method and recalculate (#1409)
Naveen Kashyap5aad3581e34b
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 67a45b3158..8192fe76df 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -1023,3 +1023,13 @@ canvas hosting Radix popovers/selects.**Rule:** Programmatic submits inside a `ValidatedForm` must pass a submitter: `form.requestSubmit(form.querySelector('button[type="submit"]'))`, which means the form needs a real submit button (good for accessibility anyway). Never use `form.submit()` in a React Router app. When a form renders errors from `fetcher.data`, verify the submit path actually reaches the fetcher — an unreachable error branch looks identical to "no errors happen".**Applies to:** `packages/form/src/components/InputOTP.tsx`, `packages/form/src/ValidatedForm.tsx`, any auto-submitting form field.++## Batched PostgREST `.in()` with hundreds of ids blows the gateway URL limit — use Kysely for big id-list reads in edge functions++**Context:** Fixing the N+1 traversal in `get-method`'s `itemToJob` by prefetching `itemReplenishment` for a whole method tree (260 item ids) with `client.from(...).in("itemId", ids)` chunked at 200 ids per request.++**Problem:** PostgREST encodes `.in()` filters in the query string. 200 UUID-length ids ≈ 8KB of URL, which exceeded the local gateway's request-line limit — the request failed outright, the prefetch threw, and every job created for a large-BOM item silently landed with an empty BOM (the caller logs the invoke error and continues). A chunk size that works in tests fails on the tenant with the most data.++**Rule:** In edge functions, batch reads keyed by a large id list go through the Kysely `db` handle (bind parameters, no URL cap) whenever no PostgREST embed is needed. If an embed forces PostgREST, chunk conservatively (≤50 ids) and include `res.error.message` in the thrown error so the failure names its cause. Never swallow a prefetch error into a bare string with no detail.++**Applies to:** `packages/database/supabase/functions/**` batch reads; any `.in(...)` over tree-collected or list-collected ids.diff --git a/.ai/runs/2026-08-17-get-method-itemtojob-slow.md b/.ai/runs/2026-08-17-get-method-itemtojob-slow.mdnew file mode 100644index 0000000000..fa7f4b9eba--- /dev/null+++ b/.ai/runs/2026-08-17-get-method-itemtojob-slow.md@@ -0,0 +1,34 @@+# Bugfix run: get-method itemToJob slow on large BOMs++- Date: 2026-08-17+- Mode: fully-autonomous (user directive: "fix only get-method")+- Request: Creating a job for ZA-002-00-000 (Durin Manufacturing) takes ~2.5 min; root cause proven from edge-runtime logs + code. Fix scope limited to the get-method edge function; explicitly excluded: packages/auth fetchWithRetry.+- Phase plan: root-cause [done in-conversation, HIGH] · instrument [skip — cause proven from runtime logs] · fix [run] · test [skip browser — edge function; live timed re-invoke offered to user, blocked on DB-write permission per user rule] · commit [skip — not requested]++## Decisions++- instrument: skip — HIGH confidence, mechanism observed directly in edge-runtime logs (3× stacked get-method invocations at 25s intervals, per-node traversal cadence).+- regression test: no unit-test harness exists for Deno edge functions and the bug is a performance property of a 6,800-line function; red→green proof deferred to a timed live invocation which writes to the dev DB — user's standing rule requires asking before DB mutation, so it is offered, not run.+- scope: itemToJob case only. The itemToJobMakeMethod case (line ~1366) has the same N+1 pattern + debug logs — noted, not fixed.++## Phase log++- root-cause: HIGH. traverseMethod does O(tree) sequential roundtrips: per-node itemReplenishment (line ~604) and methodOperation select (~644); per-material itemReplenishment (~1086) and getStorageUnitId (2 queries, ~1132) — all serialized on the single Kysely transaction connection. For 32 make methods / 44 ops / 259 materials ≈ 600+ roundtrips ≈ 30–60s locally → exceeds the client's 25s per-attempt timeout → fetchWithRetry stacks 3 concurrent delete-and-recreate runs → lock contention + supervisor kills. Debug console.log flooding ([traverseMethod], logTree) adds isolate overhead.+- fix: DONE. In the itemToJob case: (1) collect all tree nodes once after getMethodTree; (2) prefetch itemReplenishment (chunked .in(), 200/chunk, companyId-scoped) and methodOperation+embeds (chunked .in(), 100/chunk) for the whole tree before the transaction; (3) prefetch default storage units (itemLedger grouped aggregate + pickMethod, 2 queries) at transaction start, pickMethod default winning over highest-quantity bin — same precedence as getStorageUnitId; (4) traversal now uses Map lookups: node scrap, per-material scrap (covers supersession-redirected itemIds — targets added to the prefetch set), storage unit; (5) removed [traverseMethod] console.log blocks and the logTree dump. Roundtrips: ~600+ → ~7 fixed queries + inserts. getStorageUnitId import retained (used by other cases at lines ~1833/5002).+- gates: deno check own-file error delta 0→0 (99 pre-existing shared-dep errors unchanged, per lessons.md this is the gate); biome N/A (edge functions outside lint surface, per lessons.md). Unrelated no-op reordering diff in generated types files restored via git checkout.++## Regression + repair (post-fix)++- User created J000006 → empty BOM. Cause: my replenishment prefetch chunked PostgREST `.in()` at 200 UUID ids ≈ 8KB URL → gateway request-line limit → prefetch threw "Failed to get item replenishment"; caller logs and continues, so the job landed with no BOM. Fixed by moving the replenishment read to Kysely `db` (bind params, no URL cap), ops chunk 200→50, error messages now include `res.error.message`. Lesson appended to .ai/lessons.md.+- Repaired + proved: re-invoked get-method itemToJob on J000006 → success in 5.5s (was 25s+ timeouts, never completing); BOM verified 32 jobMakeMethod / 259 jobMaterial / 44 jobOperation. recalculate then run for parity → success.++## Phase 2 (user extended scope): recalculate N+1++- J000007 created by user: get-method now ~4.5s, but recalculate timed out at 25s and retried (logs 14:13:56, 14:14:22). User asked to fix the N+1.+- Rewrote `updateJobQuantities` (recalculate/index.ts): collect tree nodes once; batch-select jobMaterial.itemScrapPercentage + itemReplenishment fallback (2 queries); compute all quantities in memory top-down (identical math); write set-based via `UPDATE … FROM (VALUES …)` for jobMaterial, jobMakeMethod.quantityPerParent, jobOperation target/operation quantities, and trackedEntity (1 batched select + up to 4 statements). ~800 statements → ~7.+- Gates: deno check own-file errors 0→0. Live proof on J000007: 27.5s → **1.086s**, and md5 checksums of (jobMaterial scrap/estimated) and (jobOperation target/operation) are byte-identical before/after — exact behavior parity.++## Outcome++- READY (uncommitted), live-verified end to end: get-method itemToJob ~4.5s (was 3×25s timeout-stacked), recalculate jobRequirements ~1.1s (was 27.5s ×2-3). Job creation for the largest dev BOM should now complete in one attempt, well under the 25s client timeout.+- Known remaining (flagged, not fixed): get-method `itemToJobMakeMethod` case has the same N+1 pattern + [traverseMethod] debug logs; fetchWithRetry retry semantics on non-idempotent invokes (options given to user); recalculate `jobMakeMethodRequirements` case now shares the fixed updateJobQuantities so it benefits too.diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex 047c66db7e..6c97f03e7f 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -484,6 +484,89 @@ serve(async (req: Request) => {const methodTree = methodTrees.data?.[0] as MethodTreeItem;if (!methodTree) throw new Error("Method tree not found");+ // The traversal below runs on a single transaction connection, so any+ // per-node or per-material query is O(tree) sequential roundtrips — on+ // a large BOM that exceeds the caller's invoke timeout. Prefetch each+ // lookup table once for the whole tree instead.+ const treeNodes: MethodTreeItem[] = [];+ const seenTreeNodes = new Set<MethodTreeItem>();+ const collectTreeNodes = (n: MethodTreeItem) => {+ // Corrupt/cyclic tree data must not loop the prefetch walk+ if (seenTreeNodes.has(n)) return;+ seenTreeNodes.add(n);+ treeNodes.push(n);+ n.children.forEach(collectTreeNodes);+ };+ collectTreeNodes(methodTree);++ const treeItemIds = [+ ...new Set([+ ...treeNodes.map((n) => n.data.itemId),+ // Buy/Pick lines can be swapped to their successor item below+ ...[...supersessionRedirect.values()].map((r) => r.to),+ ]),+ ];+ const treeMakeMethodIds = [+ ...new Set(treeNodes.map((n) => n.data.materialMakeMethodId)),+ ];++ const chunk = <T>(arr: T[], size: number): T[][] => {+ const out: T[][] = [];+ for (let i = 0; i < arr.length; i += size) {+ out.push(arr.slice(i, i + size));+ }+ return out;+ };++ // itemReplenishment needs no embeds, so read it over the direct+ // Postgres connection — bind parameters, no PostgREST URL-length cap.+ const [replenishmentRows, operationChunks] = await Promise.all([+ db+ .selectFrom("itemReplenishment")+ .select(["itemId", "scrapPercentage"])+ .where("itemId", "in", treeItemIds)+ .where("companyId", "=", companyId)+ .execute(),+ Promise.all(+ chunk(treeMakeMethodIds, 50).map((ids) =>+ client+ .from("methodOperation")+ .select(+ "*, methodOperationTool(*, methodOperationToolStep(*)), methodOperationParameter(*), methodOperationStep(*)"+ )+ .in("makeMethodId", ids)+ )+ ),+ ]);++ const scrapPercentageByItemId = new Map<string, number>();+ for (const row of replenishmentRows) {+ scrapPercentageByItemId.set(+ row.itemId,+ Number(row.scrapPercentage ?? 0)+ );+ }++ const operationsByMakeMethodId = new Map<+ string,+ NonNullable<(typeof operationChunks)[number]["data"]>+ >();+ for (const res of operationChunks) {+ if (res.error) {+ throw new Error(+ `Failed to get method operations: ${res.error.message}`+ );+ }+ for (const op of res.data ?? []) {+ const list = operationsByMakeMethodId.get(op.makeMethodId);+ if (list) {+ list.push(op);+ } else {+ operationsByMakeMethodId.set(op.makeMethodId, [op]);+ }+ }+ }+const getLaborAndOverheadRates = getRatesFromWorkCenters(workCenters?.data);@@ -544,6 +627,57 @@ serve(async (req: Request) => {.execute(),]);+ // Default storage units for every material at the job's location —+ // two set-based queries instead of up to two per material+ // (getStorageUnitId): pickMethod default wins, else the bin with+ // the highest on-hand quantity.+ const defaultStorageUnitByItemId = new Map<string, string>();+ const jobLocationId = job.data?.locationId;+ if (jobLocationId) {+ const ledgerTotals = await trx+ .selectFrom("itemLedger")+ .where("locationId", "=", jobLocationId)+ .where("itemId", "in", treeItemIds)+ .where("storageUnitId", "is not", null)+ .groupBy(["itemId", "storageUnitId"])+ .select([+ "itemId",+ "storageUnitId",+ (eb) => eb.fn.sum("quantity").as("totalQuantity"),+ ])+ .having((eb) => eb.fn.sum("quantity"), ">", 0)+ .execute();++ const bestQuantityByItemId = new Map<string, number>();+ for (const row of ledgerTotals) {+ const quantity = Number(row.totalQuantity);+ if (+ row.storageUnitId &&+ quantity > (bestQuantityByItemId.get(row.itemId) ?? 0)+ ) {+ bestQuantityByItemId.set(row.itemId, quantity);+ defaultStorageUnitByItemId.set(row.itemId, row.storageUnitId);+ }+ }++ const pickMethods = await trx+ .selectFrom("pickMethod")+ .select(["itemId", "defaultStorageUnitId"])+ .where("locationId", "=", jobLocationId)+ .where("itemId", "in", treeItemIds)+ .where("defaultStorageUnitId", "is not", null)+ .execute();++ for (const pickMethod of pickMethods) {+ if (pickMethod.defaultStorageUnitId) {+ defaultStorageUnitByItemId.set(+ pickMethod.itemId,+ pickMethod.defaultStorageUnitId+ );+ }+ }+ }+async function getConfiguredValue<T>({id,field,@@ -581,19 +715,6 @@ serve(async (req: Request) => {parentJobMakeMethodId: string | null,parentEstimatedQuantity: number) {- console.log("[traverseMethod]", {- isRoot: node.data.isRoot,- itemId: node.data.itemId,- methodType: node.data.methodType,- materialMakeMethodId: node.data.materialMakeMethodId,- childCount: node.children.length,- childMethodTypes: node.children.map(c => ({- itemId: c.data.itemId,- methodType: c.data.methodType,- })),- parentJobMakeMethodId,- });-// For root node, targetQuantity equals the job quantity (parentEstimatedQuantity passed in)// For children, targetQuantity = parentEstimatedQuantity * quantityPerParentconst targetQuantity = node.data.isRoot@@ -601,14 +722,8 @@ serve(async (req: Request) => {: parentEstimatedQuantity * (node.data.quantity ?? 1);// Get scrap percentage for this node's item- const nodeItemReplenishment = await trx- .selectFrom("itemReplenishment")- .select("scrapPercentage")- .where("itemId", "=", node.data.itemId)- .executeTakeFirst();- const nodeScrapPercentage = Number(- nodeItemReplenishment?.scrapPercentage ?? 0- );+ const nodeScrapPercentage =+ scrapPercentageByItemId.get(node.data.itemId) ?? 0;// Calculate quantities:// - For Make parts: estimatedQuantity = targetQuantity (good quantity, NOT including scrap)@@ -641,12 +756,12 @@ serve(async (req: Request) => {// For child nodes, always include operations regardless of parts flagsif (!node.data.isRoot || parts.billOfProcess) {- const relatedOperations = await client- .from("methodOperation")- .select(- "*, methodOperationTool(*, methodOperationToolStep(*)), methodOperationParameter(*), methodOperationStep(*)"- )- .eq("makeMethodId", node.data.materialMakeMethodId);+ const relatedOperations = {+ data:+ operationsByMakeMethodId.get(+ node.data.materialMakeMethodId+ ) ?? [],+ };let jobOperationsInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =[];@@ -1083,14 +1198,8 @@ serve(async (req: Request) => {}// Get scrap percentage for this item- const itemReplenishment = await trx- .selectFrom("itemReplenishment")- .select("scrapPercentage")- .where("itemId", "=", itemId)- .executeTakeFirst();- const itemScrapPercentage = Number(- itemReplenishment?.scrapPercentage ?? 0- );+ const itemScrapPercentage =+ scrapPercentageByItemId.get(itemId) ?? 0;// Calculate scrap quantities for this material// targetQuantity for this child = parent's total (including scrap) * quantity per parent@@ -1129,13 +1238,9 @@ serve(async (req: Request) => {scrapQuantity: childScrapQuantity,estimatedQuantity: childEstimatedQuantity,storageUnitId: locationId- ? await getStorageUnitId(- trx,- child.data.itemId,- locationId,- // @ts-ignore- child.data.storageUnitIds?.[locationId] as string- )+ ? // @ts-ignore+ (child.data.storageUnitIds?.[locationId] as string) ||+ defaultStorageUnitByItemId.get(child.data.itemId): undefined,requiresSerialTracking,requiresBatchTracking,@@ -1202,13 +1307,6 @@ serve(async (req: Request) => {(child) => child.data.methodType === "Make to Order");- console.log("[traverseMethod] materials", {- totalChildren: materialsWithConfiguredFields.length,- madeMaterialsCount: madeMaterials.length,- madeChildrenCount: madeChildren.length,- pickedOrBoughtCount: pickedOrBoughtMaterials.length,- });-if (madeMaterials.length > 0) {const madeMaterialsWithIds = madeMaterials.map((m) => ({...m,@@ -1249,22 +1347,12 @@ serve(async (req: Request) => {const materialId = madeMaterialsWithIds[index].id;const newMakeMethodId = nanoid();- const updateResult = await trx+ await trx.updateTable("jobMakeMethod").set({ id: newMakeMethodId }).where("parentMaterialId", "=", materialId).execute();- console.log("[traverseMethod] processing made child", {- index,- materialId,- newMakeMethodId,- childItemId: child.data.itemId,- parentItemId: itemId,- willRecurse: child.data.itemId !== itemId,- updateResult,- });-// Get the total quantity (estimated + scrap) for this child material// This is what we pass to children for the cascadeconst material = madeMaterials[index];@@ -1338,13 +1426,6 @@ serve(async (req: Request) => {} // end if (parts.billOfMaterial)}- function logTree(node: MethodTreeItem, depth = 0) {- console.log(" ".repeat(depth) + `[tree] ${node.data.itemId} (${node.data.methodType}, isRoot=${node.data.isRoot}, children=${node.children.length})`);- for (const child of node.children) {- logTree(child, depth + 1);- }- }- logTree(methodTree);// Start traversal with job quantity as the root's target/parent estimated quantityawait traverseMethod(diff --git a/packages/database/supabase/functions/lib/job-quantities-engine.test.ts b/packages/database/supabase/functions/lib/job-quantities-engine.test.tsnew file mode 100644index 0000000000..95fb9619d5--- /dev/null+++ b/packages/database/supabase/functions/lib/job-quantities-engine.test.ts@@ -0,0 +1,156 @@+import {+ assert,+ assertEquals,+} from "https://deno.land/[email protected]/testing/asserts.ts";+import {+ computeJobQuantities,+ flattenJobQuantityTree,+ type JobQuantityTreeNode,+} from "./job-quantities-engine.ts";++const node = (+ id: string,+ data: Partial<JobQuantityTreeNode["data"]>,+ children: JobQuantityTreeNode[] = []+): JobQuantityTreeNode => ({+ id,+ data: {+ isRoot: false,+ itemId: `item-${id}`,+ quantity: 1,+ methodType: "Pull from Inventory",+ jobMaterialMakeMethodId: null,+ ...data,+ },+ children,+});++Deno.test("root uses parent quantity directly; children multiply by the parent's total", () => {+ // root (Make, qty 10) -> child (Pick, 2 per parent) -> grandchild (Buy, 3 per parent)+ const tree = node(+ "root",+ { isRoot: true, methodType: "Make to Order" },+ [+ node("child", { quantity: 2, jobMaterialMakeMethodId: "mm-child", methodType: "Make to Order" }, [+ node("grand", { quantity: 3 }),+ ]),+ ]+ );+ const { computed, cycleNodeIds } = computeJobQuantities({+ tree,+ parentEstimatedQuantity: 10,+ storedScrapById: new Map([+ ["child", 0],+ ["grand", 0],+ ]),+ replenishmentScrapByItemId: new Map(),+ });++ assertEquals(cycleNodeIds.size, 0);+ const byId = new Map(computed.map((c) => [c.id, c]));+ assertEquals(byId.get("root")!.targetQuantity, 10);+ // child: parent's totalWithScrap (10) * 2+ assertEquals(byId.get("child")!.targetQuantity, 20);+ // grandchild: child's totalWithScrap (20) * 3+ assertEquals(byId.get("grand")!.targetQuantity, 60);+});++Deno.test("Make estimatedQuantity excludes scrap; Buy/Pick includes it", () => {+ // 10% scrap on 10 units -> whole-unit allowance of 1+ const tree = node("root", { isRoot: true, methodType: "Make to Order" }, [+ node("buy", { quantity: 1 }),+ ]);+ const { computed } = computeJobQuantities({+ tree,+ parentEstimatedQuantity: 10,+ storedScrapById: new Map([["buy", 0.1]]),+ replenishmentScrapByItemId: new Map([["item-root", 0.1]]),+ });+ const byId = new Map(computed.map((c) => [c.id, c]));+ // Make root: estimated = good quantity, total carries the scrap+ assertEquals(byId.get("root")!.estimatedQuantity, 10);+ assertEquals(byId.get("root")!.scrapQuantity, 1);+ assertEquals(byId.get("root")!.totalWithScrap, 11);+ // Buy child (target 11 * 1, 10% scrap -> +2 whole units): estimated includes scrap+ assertEquals(byId.get("buy")!.targetQuantity, 11);+ assertEquals(+ byId.get("buy")!.estimatedQuantity,+ byId.get("buy")!.totalWithScrap+ );+});++Deno.test("a stored 0 scrap is respected; only NULL falls back to replenishment", () => {+ const tree = node("root", { isRoot: true }, [+ node("stored-zero", {}),+ node("null-fallback", {}),+ ]);+ const { computed } = computeJobQuantities({+ tree,+ parentEstimatedQuantity: 10,+ storedScrapById: new Map<string, number | null>([+ ["stored-zero", 0],+ ["null-fallback", null],+ ]),+ replenishmentScrapByItemId: new Map([+ ["item-stored-zero", 0.5],+ ["item-null-fallback", 0.5],+ ]),+ });+ const byId = new Map(computed.map((c) => [c.id, c]));+ assertEquals(byId.get("stored-zero")!.scrapQuantity, 0);+ assert(byId.get("null-fallback")!.scrapQuantity > 0);+});++Deno.test("root has no jobMaterial row: hasJobMaterial false, fallback scrap", () => {+ const tree = node("root", { isRoot: true });+ const { computed } = computeJobQuantities({+ tree,+ parentEstimatedQuantity: 4,+ storedScrapById: new Map(),+ replenishmentScrapByItemId: new Map([["item-root", 0.25]]),+ });+ assertEquals(computed[0]!.hasJobMaterial, false);+ assertEquals(computed[0]!.scrapQuantity, 1); // scrapAllowance(4, 0.25)+});++Deno.test("a cyclic tree is reported and skipped, not recursed forever", () => {+ const a = node("a", { isRoot: true });+ const b = node("b", { quantity: 2 });+ a.children = [b];+ b.children = [a]; // corrupt data: a -> b -> a++ const flat = flattenJobQuantityTree(a);+ assertEquals(flat.nodes.map((n) => n.id), ["a", "b"]);+ assertEquals([...flat.cycleNodeIds], ["a"]);++ const { computed, cycleNodeIds } = computeJobQuantities({+ tree: a,+ parentEstimatedQuantity: 1,+ storedScrapById: new Map([["b", 0]]),+ replenishmentScrapByItemId: new Map(),+ });+ assertEquals(computed.length, 2); // each node computed exactly once+ assertEquals([...cycleNodeIds], ["a"]);+});++Deno.test("a shared (diamond) subtree is computed once per path, matching the historical recursion", () => {+ // Two parents referencing the same child object is not a cycle — the+ // per-node recursion visited it once per path, and so does the engine.+ const shared = node("shared", { quantity: 1 });+ const tree = node("root", { isRoot: true }, [+ node("p1", { quantity: 1 }, [shared]),+ node("p2", { quantity: 1 }, [shared]),+ ]);+ const { computed, cycleNodeIds } = computeJobQuantities({+ tree,+ parentEstimatedQuantity: 1,+ storedScrapById: new Map([+ ["p1", 0],+ ["p2", 0],+ ["shared", 0],+ ]),+ replenishmentScrapByItemId: new Map(),+ });+ assertEquals(cycleNodeIds.size, 0);+ assertEquals(computed.filter((c) => c.id === "shared").length, 2);+});diff --git a/packages/database/supabase/functions/lib/job-quantities-engine.ts b/packages/database/supabase/functions/lib/job-quantities-engine.tsnew file mode 100644index 0000000000..9cf299e376--- /dev/null+++ b/packages/database/supabase/functions/lib/job-quantities-engine.ts@@ -0,0 +1,129 @@+// Pure job-quantity cascade shared by the recalculate edge function.+// Mirrors the mrp-engine pattern: the caller batch-reads its inputs into+// Maps, this module computes the whole tree in memory with no I/O, and the+// caller batch-writes the output. Cycles in the tree data are reported+// (`cycleNodeIds`) instead of recursing forever — the same contract as+// mrp-engine's `cycleItemIds`.++import { scrapAllowance } from "../shared/precision.ts";++export type JobQuantityTreeNode = {+ id: string;+ data: {+ isRoot: boolean;+ itemId: string;+ quantity: number;+ methodType: string;+ jobMaterialMakeMethodId?: string | null;+ };+ children?: JobQuantityTreeNode[] | null;+};++export type ComputedJobQuantityNode = {+ id: string;+ hasJobMaterial: boolean;+ jobMaterialMakeMethodId: string | null;+ quantityPerParent: number;+ targetQuantity: number;+ scrapQuantity: number;+ estimatedQuantity: number;+ totalWithScrap: number;+};++export type JobQuantitiesInput = {+ tree: JobQuantityTreeNode;+ parentEstimatedQuantity: number;+ // jobMaterial.itemScrapPercentage keyed by jobMaterial id. A stored 0 is+ // intentional (locked at job creation) — only a NULL falls back to the+ // item's current replenishment scrap percentage. The root node has no+ // jobMaterial row and always uses the fallback.+ storedScrapById: Map<string, number | null>;+ replenishmentScrapByItemId: Map<string, number>;+};++export type JobQuantitiesOutput = {+ computed: ComputedJobQuantityNode[];+ cycleNodeIds: Set<string>;+};++// Flatten the tree once so the caller can batch its reads (jobMaterial ids,+// item ids). A node re-entered on the current path is a cycle in the tree+// data — it is skipped and reported rather than looped on.+export function flattenJobQuantityTree(root: JobQuantityTreeNode): {+ nodes: JobQuantityTreeNode[];+ cycleNodeIds: Set<string>;+} {+ const nodes: JobQuantityTreeNode[] = [];+ const cycleNodeIds = new Set<string>();+ const walk = (node: JobQuantityTreeNode, path: Set<string>) => {+ if (path.has(node.id)) {+ cycleNodeIds.add(node.id);+ return;+ }+ path.add(node.id);+ nodes.push(node);+ for (const child of node.children ?? []) {+ walk(child, path);+ }+ path.delete(node.id);+ };+ walk(root, new Set());+ return { nodes, cycleNodeIds };+}++// Same math as the historical per-node recursion, walked top-down:+// - For root: targetQuantity = parentEstimatedQuantity+// - For children: targetQuantity = parent's totalWithScrap * quantity per parent+// - scrapQuantity = whole-unit scrap allowance; fractional targets flow through+// - estimatedQuantity: For Make = good quantity (without scrap), For Buy/Pick = total+export function computeJobQuantities(+ input: JobQuantitiesInput+): JobQuantitiesOutput {+ const { tree, parentEstimatedQuantity, storedScrapById } = input;+ const computed: ComputedJobQuantityNode[] = [];+ const cycleNodeIds = new Set<string>();++ const walk = (+ node: JobQuantityTreeNode,+ parentQuantity: number,+ path: Set<string>+ ) => {+ if (path.has(node.id)) {+ cycleNodeIds.add(node.id);+ return;+ }+ path.add(node.id);++ const targetQuantity = node.data.isRoot+ ? parentQuantity+ : node.data.quantity * parentQuantity;+ const stored = storedScrapById.get(node.id);+ const scrapPercentage =+ stored != null+ ? Number(stored)+ : input.replenishmentScrapByItemId.get(node.data.itemId) ?? 0;+ const scrapQuantity = scrapAllowance(targetQuantity, scrapPercentage);+ const totalWithScrap = targetQuantity + scrapQuantity;+ const estimatedQuantity =+ node.data.methodType === "Make to Order" ? targetQuantity : totalWithScrap;++ computed.push({+ id: node.id,+ hasJobMaterial: storedScrapById.has(node.id),+ jobMaterialMakeMethodId: node.data.jobMaterialMakeMethodId ?? null,+ quantityPerParent: node.data.quantity,+ targetQuantity,+ scrapQuantity,+ estimatedQuantity,+ totalWithScrap,+ });++ for (const child of node.children ?? []) {+ walk(child, totalWithScrap, path);+ }+ path.delete(node.id);+ };++ walk(tree, parentEstimatedQuantity, new Set());+ return { computed, cycleNodeIds };+}diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.tsindex abe4d93478..ddd0fa56b7 100644--- a/packages/database/supabase/functions/recalculate/index.ts+++ b/packages/database/supabase/functions/recalculate/index.ts@@ -3,11 +3,15 @@ import { z } from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";-import { Transaction } from "kysely";+import { sql, Transaction } from "kysely";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";+import {+ computeJobQuantities,+ type ComputedJobQuantityNode,+ flattenJobQuantityTree,+} from "../lib/job-quantities-engine.ts";import { getJobMethodTree, JobMethodTreeItem } from "../lib/methods.ts";import { requirePermissions } from "../lib/supabase.ts";-import { scrapAllowance } from "../shared/precision.ts";const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);@@ -187,102 +191,139 @@ const updateJobQuantities = async (tree: JobMethodTreeItem,parentEstimatedQuantity: number = 1) => {- // Target quantity for this node:- // - For root: targetQuantity = parentEstimatedQuantity (which is productionQuantity from job)- // - For children: targetQuantity = parentEstimatedQuantity * quantity (quantity per parent)- const targetQuantity = tree.data.isRoot- ? parentEstimatedQuantity- : tree.data.quantity * parentEstimatedQuantity;-- // Get scrap percentage from jobMaterial (stored at job creation time)- // Fall back to itemReplenishment if not stored- // Scrap applies to every method type (get-method stamps itemScrapPercentage- // on every material row and applies scrap unconditionally at creation)- let scrapPercentage = 0;- const jobMaterial = await trx+ // The tree is already fully loaded, so compute every node's quantities in+ // memory (lib/job-quantities-engine.ts, mirroring the mrp-engine pattern)+ // and write them set-based. The previous per-node recursion issued 2–4+ // statements per node on one transaction connection — O(tree) sequential+ // roundtrips, which on a large BOM exceeded the caller's invoke timeout.+ const { nodes, cycleNodeIds: flattenCycles } = flattenJobQuantityTree(tree);++ const jobMaterials = await trx.selectFrom("jobMaterial")- .select("itemScrapPercentage")- .where("id", "=", tree.id)- .executeTakeFirst();-- // A stored 0 is intentional (locked at job creation) — only a NULL falls- // back to the item's current replenishment scrap percentage.- if (jobMaterial?.itemScrapPercentage != null) {- scrapPercentage = Number(jobMaterial.itemScrapPercentage);- } else {- // Fall back to itemReplenishment- const itemReplenishment = await trx+ .select(["id", "itemScrapPercentage"])+ .where(+ "id",+ "in",+ nodes.map((n) => n.id)+ )+ .execute();+ const storedScrapById = new Map(+ jobMaterials.map((m) => [m.id, m.itemScrapPercentage])+ );++ const fallbackItemIds = [+ ...new Set(+ nodes+ .filter((n) => storedScrapById.get(n.id) == null)+ .map((n) => n.data.itemId)+ ),+ ];+ const replenishmentScrapByItemId = new Map<string, number>();+ if (fallbackItemIds.length > 0) {+ const replenishments = await trx.selectFrom("itemReplenishment")- .select("scrapPercentage")- .where("itemId", "=", tree.data.itemId)- .executeTakeFirst();- scrapPercentage = Number(itemReplenishment?.scrapPercentage ?? 0);+ .select(["itemId", "scrapPercentage"])+ .where("itemId", "in", fallbackItemIds)+ .execute();+ for (const row of replenishments) {+ replenishmentScrapByItemId.set(+ row.itemId,+ Number(row.scrapPercentage ?? 0)+ );+ }}- // Calculate scrap and estimated quantities- // scrapQuantity = portion attributable to scrap- // totalWithScrap = target + scrap allowance (what we need to make/procure)- // estimatedQuantity: For Make = good quantity (without scrap), For Buy/Pick = total- // Whole-unit scrap allowance; the fractional target itself is never rounded- const scrapQuantity = scrapAllowance(targetQuantity, scrapPercentage);- const totalWithScrap = targetQuantity + scrapQuantity;- // For Make: estimatedQuantity is good quantity (without scrap)- // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure- const estimatedQuantity =- tree.data.methodType === "Make to Order" ? targetQuantity : totalWithScrap;-- // Update jobMaterial with scrap and estimated quantities- await trx- .updateTable("jobMaterial")- .set({- scrapQuantity: scrapQuantity,- estimatedQuantity: estimatedQuantity,- })- .where("id", "=", tree.id)- .execute();+ const { computed, cycleNodeIds } = computeJobQuantities({+ tree,+ parentEstimatedQuantity,+ storedScrapById,+ replenishmentScrapByItemId,+ });+ const allCycleNodeIds = new Set([...flattenCycles, ...cycleNodeIds]);+ if (allCycleNodeIds.size > 0) {+ // Corrupt tree data — the nodes were skipped rather than looped on.+ console.error(+ "recalculate: cyclic job method tree; skipped node ids:",+ [...allCycleNodeIds]+ );+ }- if (tree.data.jobMaterialMakeMethodId) {- const [jobMakeMethod] = await Promise.all([- trx- .selectFrom("jobMakeMethod")- .select(["trackedEntityId", "requiresSerialTracking"])- .where("id", "=", tree.data.jobMaterialMakeMethodId)- .executeTakeFirst(),- trx- .updateTable("jobMakeMethod")- .set({ quantityPerParent: tree.data.quantity })- .where("id", "=", tree.data.jobMaterialMakeMethodId)- .execute(),- trx- .updateTable("jobOperation")- .set({- targetQuantity: targetQuantity,- // Fractional targets flow through; the scrap allowance is already whole- operationQuantity: totalWithScrap,- })- .where("jobMakeMethodId", "=", tree.data.jobMaterialMakeMethodId)- .where("reworkId", "is", null)- .execute(),- ]);-- if (jobMakeMethod?.trackedEntityId) {- await trx- .updateTable("trackedEntity")- .set({- quantity: jobMakeMethod.requiresSerialTracking- ? 1- : totalWithScrap,- })- .where("id", "=", jobMakeMethod.trackedEntityId)- .execute();- }+ // jobMaterial scrap/estimated — one VALUES-join update for the whole tree+ const materialRows = computed.filter((c) => c.hasJobMaterial);+ if (materialRows.length > 0) {+ await sql`+ UPDATE "jobMaterial" AS m+ SET "scrapQuantity" = v.scrap::numeric,+ "estimatedQuantity" = v.estimated::numeric+ FROM (VALUES ${sql.join(+ materialRows.map(+ (c) => sql`(${c.id}, ${c.scrapQuantity}, ${c.estimatedQuantity})`+ )+ )}) AS v(id, scrap, estimated)+ WHERE m.id = v.id+ `.execute(trx);}- // Recursively update children with this node's total (estimated + scrap)- // Children use the total for their target calculation to properly cascade scrap- if (tree.children) {- for (const child of tree.children) {- await updateJobQuantities(trx, child, totalWithScrap);+ const makeNodes = computed.filter(+ (c): c is ComputedJobQuantityNode & { jobMaterialMakeMethodId: string } =>+ c.jobMaterialMakeMethodId !== null+ );+ if (makeNodes.length > 0) {+ await sql`+ UPDATE "jobMakeMethod" AS jmm+ SET "quantityPerParent" = v.qpp::numeric+ FROM (VALUES ${sql.join(+ makeNodes.map(+ (c) => sql`(${c.jobMaterialMakeMethodId}, ${c.quantityPerParent})`+ )+ )}) AS v(id, qpp)+ WHERE jmm.id = v.id+ `.execute(trx);++ await sql`+ UPDATE "jobOperation" AS op+ SET "targetQuantity" = v.target::numeric,+ "operationQuantity" = v.total::numeric+ FROM (VALUES ${sql.join(+ makeNodes.map(+ (c) =>+ sql`(${c.jobMaterialMakeMethodId}, ${c.targetQuantity}, ${c.totalWithScrap})`+ )+ )}) AS v(id, target, total)+ WHERE op."jobMakeMethodId" = v.id+ AND op."reworkId" IS NULL+ `.execute(trx);++ const trackedMakeMethods = await trx+ .selectFrom("jobMakeMethod")+ .select(["id", "trackedEntityId", "requiresSerialTracking"])+ .where(+ "id",+ "in",+ makeNodes.map((c) => c.jobMaterialMakeMethodId)+ )+ .where("trackedEntityId", "is not", null)+ .execute();++ if (trackedMakeMethods.length > 0) {+ const totalByMakeMethodId = new Map(+ makeNodes.map((c) => [c.jobMaterialMakeMethodId, c.totalWithScrap])+ );+ await sql`+ UPDATE "trackedEntity" AS te+ SET "quantity" = v.quantity::numeric+ FROM (VALUES ${sql.join(+ trackedMakeMethods.map(+ (m) =>+ sql`(${m.trackedEntityId}, ${+ m.requiresSerialTracking+ ? 1+ : totalByMakeMethodId.get(m.id) ?? 1+ })`+ )+ )}) AS v(id, quantity)+ WHERE te.id = v.id+ `.execute(trx);}}};