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): job completion draws every lineside bin a material was picked to
naveenkash0b26b69471d9
diff --git a/.ai/specs/2026-10-14-strict-backflush.md b/.ai/specs/2026-10-14-strict-backflush.mdindex b476297bb9..0655a8c2bd 100644--- a/.ai/specs/2026-10-14-strict-backflush.md+++ b/.ai/specs/2026-10-14-strict-backflush.md@@ -55,7 +55,7 @@ Example: the BoM says "pull 10 × PART-123 from Shelf A-4". Shelf A-4 has 6 and| 2 | Which lines need a Pull From | A method material line needs a Pull From when its `methodType` is not `Make to Order`, its `itemType` is Material, Part or Consumable, and its item's `itemTrackingType` is not `Non-Inventory`. | The backflush reads exactly these lines (`issueJobOperationMaterials`, `backflush_job_materials`). A Make to Order line is built, not pulled. A Purchase to Order line is consumed from a bin, and the BoM editor labels it "Pull From". || 3 | Which locations need a Pull From | Each location that has at least one active work center and at least one active storage unit. | Pull From is stored per location (`methodMaterial.storageUnitIds`). A location with no work center builds nothing. A location with no storage unit has no bin a line could name, so a Pull From there can never be set. || 4 | Draft methods | Release refuses a job whose pulled line has no `storageUnitId`. | A job can come from a Draft method, so the activation check alone has a gap. |-| 5 | Picked stock | The material's picks and unclaimed lineside stock are consumed first, as today. The strict rule applies to the remainder, against the line's Pull From. After a pick, the Pull From is the source bin of the line's oldest pick line into its current bin (`pullFromStorageUnit`). Job completion (SQL) draws a picked line from its lineside bin first, up to what the bin holds, then the rest from the Pull From. | A pick moves stock out of the Pull From bin with a transfer, so the records stay correct. Picking also moves `jobMaterial.storageUnitId` to the lineside bin, so that column no longer names the Pull From. The pick line keeps it. A later picking list takes the fullest bin, so only the oldest pick line names the Pull From. |+| 5 | Picked stock | The material's picks and unclaimed lineside stock are consumed first, as today. The strict rule applies to the remainder, against the line's Pull From. After a pick, the Pull From is the source bin of the line's oldest pick line into its current bin (`pullFromStorageUnit`). Job completion (SQL) draws a picked line from every lineside bin its live picks went to first (most staged first), up to what each bin holds, then the rest from the Pull From. | A pick moves stock out of the Pull From bin with a transfer, so the records stay correct. Picking also moves `jobMaterial.storageUnitId` to the lineside bin, so that column no longer names the Pull From. The pick line keeps it. A later picking list takes the fullest bin, so only the oldest pick line names the Pull From. || 4a | Every path to Ready | Each path that sets a job to Ready runs the release checks: `releaseJobs` (the Release dialog, bulk release, planning, the API), batch release, and a kanban scan with auto-release. `updateJobStatus` is not published. A kanban job that fails them stays Draft and stays linked; the scan lands on the job with the reason. A kanban job whose method could not be copied is not released either, and the scan says so. | A check on some paths only is a check a user can step around. The kanban scan and the API wrote the status directly. || 4b | Job creation under strict backflush | A job line gets the BoM's Pull From, else the item's default storage unit. It never takes the fullest bin. A line with neither has no storage unit, and release refuses the job. | The fullest bin is a guess that depends on where the stock is. It let a job built from a BoM with no Pull From pass release. || 5a | Locations without a pull-from bin | Strict backflush applies only at a location from decision 3. Elsewhere the backflush, release and the badges behave as with the setting off. | Activation asks for no Pull From there, so a refusal there could never be fixed. |@@ -169,6 +169,7 @@ No new table. No RLS change.- 2026-10-19: Review fixes: the dry run is its own posting type (`jobOperationDryRun`); batch completion checks every member in one dry run; Consume First swaps never take the fullest bin under strict backflush; a completion dry-run refusal keeps its status category.- 2026-10-19: Merged main, which moved the server functions into the ERP modules and unpublished `updateJobStatus`. The strict backflush code moved with them (see the API table). Every path to Ready now runs `jobReleaseProblems`, then `releaseCheckedJobs`. The `updateJobStatus` guard and `jobReleaseBlockers` are gone: main's `releaseJobs` is the published release, and its readiness already covers "nothing to make".- 2026-10-19: Browser test of every path to Ready. A kanban release reuses the supplier's newest Draft PO for outside operations (no one at a scan can choose one), and a refused scan shows its reason on the job page.+- 2026-10-19: Job completion (SQL) draws from every lineside bin a material was picked to, not only the line's latest one. Before, a material picked to two lineside bins was refused under Prevent negative stock while its stock sat at the earlier bin (CodeRabbit review).- 2026-10-19: A kanban scan whose Get Method fails names the failure instead of leaving a silent Draft job (decision 4a). The kanban release runs on the scan's own handles. `apps/erp/test/database/kanban-scan.test.ts` covers the refused, released and method-failure scans. Removed the stale out-of-scope and risk rows that said kanban and MCP skip the release checks.- 2026-10-17: Every path to Ready now runs the release checks: the kanban scan with auto-release (through `releaseJobs`) and the API tool `updateJobStatus` were missed (decision 4a). Job creation under strict backflush no longer takes the fullest bin (decision 4b).- 2026-10-16: Self-review fixes: after a partial pick, the rest now comes from the Pull From, not lineside (decision 5, TypeScript and SQL); strict backflush skips a location with no pull-from bin (decision 5a); both paths lock every (bin, item) pair in one order before the first draw; SQL compares rounded quantities and counts a refused need; the dry run stops at the strict check; the inspection lot is checked before it closes; the New Version route checks activation; every release path checks storage units; the card counts with SQL and the jobs list holds only lines a backflush would refuse (decision 8); the BoM badges use the pull-from locations.diff --git a/apps/erp/test/database/strict-backflush.test.ts b/apps/erp/test/database/strict-backflush.test.tsindex 6457c0667d..b7673153c1 100644--- a/apps/erp/test/database/strict-backflush.test.ts+++ b/apps/erp/test/database/strict-backflush.test.ts@@ -63,13 +63,14 @@ async function pick(job: { jobId: string; materialId: string },from: string,to: string,- quantity: number+ quantity: number,+ listKey = "PL") {await seed(f, async (trx) => {const list = await trx.insertInto("pickingList").values({- pickingListId: `${job.jobId}-PL`,+ pickingListId: `${job.jobId}-${listKey}`,locationId: f.locationId,companyId: f.companyId,createdBy: USER@@ -587,6 +588,36 @@ databaseTest(});+databaseTest(+ "the SQL job-completion backflush draws every lineside bin the material was picked to",+ async () => {+ const f = await alwaysPostFixture();+ try {+ const shelfA = await storageUnit(f, "Shelf A");+ const linesideOne = await storageUnit(f, "Lineside 1");+ const linesideTwo = await storageUnit(f, "Lineside 2");+ await stockBin(f, shelfA, 2);+ await setStrict(f, true);++ const job = await jobFixture(f);+ await setMaterialBin(f, job.materialId, shelfA);+ await pick(f, job, shelfA, linesideOne, 1, "PL-1");+ await pick(f, job, shelfA, linesideTwo, 1, "PL-2");+ await sql`SELECT backflush_job_materials(${job.jobId}, 1, ${f.companyId}, ${USER})`.execute(+ f.db+ );+ expect(byBin(await consumption(f, job.jobId))).toEqual(+ byBin([+ { storageUnitId: linesideOne, quantity: -1 },+ { storageUnitId: linesideTwo, quantity: -1 }+ ])+ );+ } finally {+ await f.cleanup();+ }+ }+);+databaseTest("strict backflush skips a location with no active work center",async () => {diff --git a/packages/database/supabase/migrations/20261015163040_strict-backflush.sql b/packages/database/supabase/migrations/20261015163040_strict-backflush.sqlindex 93d1abfb77..f881015fe6 100644--- a/packages/database/supabase/migrations/20261015163040_strict-backflush.sql+++ b/packages/database/supabase/migrations/20261015163040_strict-backflush.sql@@ -31,6 +31,7 @@ DECLAREv_storage_unit_name TEXT;v_strict_problems TEXT[] := '{}';v_pull_from TEXT;+ v_lineside RECORD;v_lineside_take NUMERIC;v_issue_total NUMERIC;v_lock_key BIGINT;@@ -193,11 +194,34 @@ BEGINLIMIT 1), v_material."storageUnitId");- IF v_pull_from <> v_material."storageUnitId" THEN+ -- Every storage unit this material's live picks went to, most staged+ -- first (getPickedBudgets), not only the line's latest one.+ FOR v_lineside IN+ SELECT dest.id+ FROM (+ SELECT pll."toStorageUnitId" AS id,+ SUM(GREATEST(COALESCE(pll."quantityPicked", 0) - COALESCE(pll."quantityReturned", 0), 0)) AS staged+ FROM "pickingListLine" pll+ JOIN "pickingList" pl ON pl.id = pll."pickingListId"+ WHERE pll."jobMaterialId" = v_material.id+ AND pll."companyId" = p_company_id+ AND pll.status <> 'Cancelled'+ AND pl.status <> 'Cancelled'+ AND pll."toStorageUnitId" IS NOT NULL+ GROUP BY pll."toStorageUnitId"+ UNION ALL+ SELECT v_material."storageUnitId", 0+ ) dest+ WHERE dest.id <> v_pull_from+ GROUP BY dest.id+ ORDER BY SUM(dest.staged) DESC, dest.id+ LOOP+ EXIT WHEN v_material_qty_to_issue <= 0;+SELECT COALESCE(SUM(quantity), 0) INTO v_bin_on_handFROM "itemLedger"WHERE "itemId" = v_material."itemId"- AND "storageUnitId" = v_material."storageUnitId"+ AND "storageUnitId" = v_lineside.idAND "locationId" = v_job_location_idAND "companyId" = p_company_idAND "trackedEntityId" IS NULL;@@ -211,16 +235,16 @@ BEGIN) VALUES ('Consumption', 'Job Consumption', p_job_id, p_company_id,v_material."itemId", -v_lineside_take,- v_job_location_id, v_material."storageUnitId", p_user_id+ v_job_location_id, v_lineside.id, p_user_id);v_bf_item_ids := v_bf_item_ids || v_material."itemId";v_bf_quantities := v_bf_quantities || v_lineside_take;- v_bf_storage_unit_ids := v_bf_storage_unit_ids || v_material."storageUnitId";+ v_bf_storage_unit_ids := v_bf_storage_unit_ids || v_lineside.id;v_material_qty_to_issue := v_material_qty_to_issue - v_lineside_take;END IF;- END IF;+ END LOOP;-- A refused material still writes its row (the function raises before-- commit), so a later material on the bin counts this need.diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex 2e7f55444e..b52d6cca6a 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -5,7 +5,7 @@"sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-19T13:03:48.932Z",+ "exportedAt": "2026-10-19T17:36:36.902Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",