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(database): count parallel final operations once at job completion (#1900)
Naveen Kashyap68cc2db7b742
diff --git a/packages/database/src/event-system/handlers/sync_finish_job_operation.sql b/packages/database/src/event-system/handlers/sync_finish_job_operation.sqlindex 3ed5344dac..793cc7fef1 100644--- a/packages/database/src/event-system/handlers/sync_finish_job_operation.sql+++ b/packages/database/src/event-system/handlers/sync_finish_job_operation.sql@@ -60,12 +60,28 @@ BEGINFROM "job"WHERE id = p_new->>'jobId';+ -- The units out of the routing's final operations. Two kinds of final+ -- operation report differently:+ -- * the routing's own (parallel "With Previous" operations at the end)+ -- each see EVERY unit, so a unit is finished once it has come through+ -- all of them: the smallest count. Summing them completed a 3-unit job+ -- at 6, which a serial job then refused for want of units. One closed+ -- with Finish and no quantity reports nothing, so it is left out.+ -- * a rework branch triggered at the final operation (trigger-rework)+ -- carries only the reworked units, which the operation it came from+ -- reports as reworked, not complete: those add on top.v_quantity_complete := (- SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)+ SELECT COALESCE(MIN(terminal_jo."quantityComplete") FILTER (+ WHERE terminal_jo."reworkId" IS NULL AND terminal_jo."quantityComplete" > 0+ ), 0)+ + COALESCE(SUM(terminal_jo."quantityComplete") FILTER (+ WHERE terminal_jo."reworkId" IS NOT NULL+ ), 0)FROM "jobOperation" terminal_joINNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"WHERE terminal_jo."jobId" = p_new->>'jobId'AND terminal_jmm."parentMaterialId" IS NULL+ AND terminal_jo.status <> 'Canceled'AND NOT EXISTS (SELECT 1FROM "jobOperationDependency" depdiff --git a/packages/database/src/event-system/handlers/sync_update_job_operation_quantities.sql b/packages/database/src/event-system/handlers/sync_update_job_operation_quantities.sqlindex e198a490ff..245a0d9fc0 100644--- a/packages/database/src/event-system/handlers/sync_update_job_operation_quantities.sql+++ b/packages/database/src/event-system/handlers/sync_update_job_operation_quantities.sql@@ -88,12 +88,21 @@ BEGINIF v_job_id IS NOT NULL AND v_is_last_top_level_operation THENUPDATE "job"+ -- Counted as sync_finish_job_operation counts the receipt: the smallest of+ -- the routing's own final operations (parallel ones each see every unit)+ -- plus what rework branches completed.SET "quantityComplete" = (- SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)+ SELECT COALESCE(MIN(terminal_jo."quantityComplete") FILTER (+ WHERE terminal_jo."reworkId" IS NULL AND terminal_jo."quantityComplete" > 0+ ), 0)+ + COALESCE(SUM(terminal_jo."quantityComplete") FILTER (+ WHERE terminal_jo."reworkId" IS NOT NULL+ ), 0)FROM "jobOperation" terminal_joINNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"WHERE terminal_jo."jobId" = v_job_idAND terminal_jmm."parentMaterialId" IS NULL+ AND terminal_jo.status <> 'Canceled'AND NOT EXISTS (SELECT 1FROM "jobOperationDependency" depdiff --git a/packages/database/supabase/migrations/20261012111443_job-completion-parallel-terminal-operations.sql b/packages/database/supabase/migrations/20261012111443_job-completion-parallel-terminal-operations.sqlnew file mode 100644index 0000000000..0d90e9b803--- /dev/null+++ b/packages/database/supabase/migrations/20261012111443_job-completion-parallel-terminal-operations.sql@@ -0,0 +1,261 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++CREATE OR REPLACE FUNCTION public.sync_finish_job_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_job_location_id TEXT;+ v_job_storage_unit_id TEXT;+ v_job_quantity NUMERIC;+ v_sales_order_id TEXT;+ v_quantity_complete NUMERIC;+ v_quantity_lost NUMERIC;+ v_quantity_received NUMERIC;+ v_job_status TEXT;+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;++ UPDATE "productionEvent"+ SET "endTime" = NOW()+ WHERE "jobOperationId" = p_new->>'id'+ AND "endTime" IS NULL;++ UPDATE "jobOperation" op+ SET status = 'Ready'+ WHERE EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ WHERE dep."operationId" = op.id+ AND dep."dependsOnId" = p_new->>'id'+ AND op.status = 'Waiting'+ )+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep2+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"+ WHERE dep2."operationId" = op.id+ AND jo2.status != 'Done'+ AND jo2.id != p_new->>'id'+ );++ SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';+ -- A Draft/Planned job's operation can only reach Done through a released+ -- BATCH (batch release outranks job release for floor visibility), so the+ -- run genuinely happened. Completing the batch must complete those jobs+ -- too: otherwise their output lots exist while their receipts never post,+ -- and a merged output lot carries only the received fraction of its+ -- quantity.+ IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused')+ AND NOT (+ (p_new->>'jobOperationBatchId') IS NOT NULL+ AND v_job_status IN ('Draft', 'Planned')+ ) THEN+ RETURN;+ END IF;++ IF is_last_job_operation(p_new->>'id') THEN+ SELECT "locationId", "storageUnitId", quantity, "salesOrderId", "quantityReceivedToInventory"+ INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id, v_quantity_received+ FROM "job"+ WHERE id = p_new->>'jobId';++ -- The units out of the routing's final operations. Two kinds of final+ -- operation report differently:+ -- * the routing's own (parallel "With Previous" operations at the end)+ -- each see EVERY unit, so a unit is finished once it has come through+ -- all of them: the smallest count. Summing them completed a 3-unit job+ -- at 6, which a serial job then refused for want of units. One closed+ -- with Finish and no quantity reports nothing, so it is left out.+ -- * a rework branch triggered at the final operation (trigger-rework)+ -- carries only the reworked units, which the operation it came from+ -- reports as reworked, not complete: those add on top.+ v_quantity_complete := (+ SELECT COALESCE(MIN(terminal_jo."quantityComplete") FILTER (+ WHERE terminal_jo."reworkId" IS NULL AND terminal_jo."quantityComplete" > 0+ ), 0)+ + COALESCE(SUM(terminal_jo."quantityComplete") FILTER (+ WHERE terminal_jo."reworkId" IS NOT NULL+ ), 0)+ FROM "jobOperation" terminal_jo+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"+ WHERE terminal_jo."jobId" = p_new->>'jobId'+ AND terminal_jmm."parentMaterialId" IS NULL+ AND terminal_jo.status <> 'Canceled'+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = terminal_jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ );++ IF COALESCE(v_quantity_complete, 0) = 0 THEN+ -- The zero fallback exists for the quantity-less Finish flow (no+ -- productionQuantity ever recorded). When the job DID record scrap or+ -- rework, zero completions is a real outcome (e.g. a fully-scrapped+ -- lot) — falling back would receive scrapped units into stock.+ SELECT COALESCE(SUM(COALESCE("quantityScrapped", 0) + COALESCE("quantityReworked", 0)), 0)+ INTO v_quantity_lost+ FROM "jobOperation"+ WHERE "jobId" = p_new->>'jobId';++ IF v_quantity_lost = 0 THEN+ v_quantity_complete := v_job_quantity;+ ELSE+ -- Nothing to receive: close the job without posting Assembly Output.+ -- Materials were already consumed by the scrap/complete flows; WIP+ -- cost disposition for fully-scrapped jobs is a costing follow-up.+ UPDATE "job"+ SET status = 'Completed',+ "completedDate" = NOW(),+ "quantityComplete" = 0,+ "updatedBy" = COALESCE(p_new->>'updatedBy', p_new->>'createdBy'),+ "updatedAt" = NOW()+ WHERE id = p_new->>'jobId';+ RETURN;+ END IF;+ END IF;++ -- A reopened job may already have received more than its operations now+ -- report. complete_job_to_inventory refuses a quantity below what was+ -- received, and refusing here would block the Done update itself.+ v_quantity_complete := GREATEST(v_quantity_complete, COALESCE(v_quantity_received, 0));++ PERFORM complete_job_to_inventory(+ p_job_id := p_new->>'jobId',+ p_quantity_complete := v_quantity_complete,+ p_storage_unit_id := v_job_storage_unit_id,+ p_location_id := v_job_location_id,+ p_company_id := p_new->>'companyId',+ p_user_id := COALESCE(p_new->>'updatedBy', p_new->>'createdBy')+ );+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_job_operation_quantities(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_job_operation_id TEXT;+ v_job_id TEXT;+ v_user_id TEXT;+ v_is_last_top_level_operation BOOLEAN := FALSE;+BEGIN+ v_user_id := COALESCE(+ p_new->>'updatedBy', p_new->>'createdBy',+ p_old->>'updatedBy', p_old->>'createdBy'+ );++ IF p_operation = 'INSERT' THEN+ v_job_operation_id := p_new->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete" ++ CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked" ++ CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped" ++ CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;++ ELSIF p_operation = 'UPDATE' THEN+ v_job_operation_id := p_new->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete"+ - CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked"+ - CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped"+ - CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;++ ELSIF p_operation = 'DELETE' THEN+ v_job_operation_id := p_old->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete" -+ CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked" -+ CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped" -+ CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;+ END IF;++ UPDATE "jobOperation"+ SET "status" = 'Done',+ "updatedBy" = COALESCE(v_user_id, "updatedBy", "createdBy"),+ "updatedAt" = NOW()+ WHERE id = v_job_operation_id+ AND "status" NOT IN ('Done', 'Canceled')+ AND "targetQuantity" > 0+ AND ("quantityComplete" + "quantityReworked") >= "targetQuantity";++ SELECT jo."jobId" INTO v_job_id+ FROM "jobOperation" jo+ WHERE jo.id = v_job_operation_id;++ SELECT EXISTS (+ SELECT 1+ FROM "jobOperation" jo+ INNER JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"+ WHERE jo.id = v_job_operation_id+ AND jmm."parentMaterialId" IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ ) INTO v_is_last_top_level_operation;++ IF v_job_id IS NOT NULL AND v_is_last_top_level_operation THEN+ UPDATE "job"+ -- Counted as sync_finish_job_operation counts the receipt: the smallest of+ -- the routing's own final operations (parallel ones each see every unit)+ -- plus what rework branches completed.+ SET "quantityComplete" = (+ SELECT COALESCE(MIN(terminal_jo."quantityComplete") FILTER (+ WHERE terminal_jo."reworkId" IS NULL AND terminal_jo."quantityComplete" > 0+ ), 0)+ + COALESCE(SUM(terminal_jo."quantityComplete") FILTER (+ WHERE terminal_jo."reworkId" IS NOT NULL+ ), 0)+ FROM "jobOperation" terminal_jo+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"+ WHERE terminal_jo."jobId" = v_job_id+ AND terminal_jmm."parentMaterialId" IS NULL+ AND terminal_jo.status <> 'Canceled'+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = terminal_jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ )+ WHERE id = v_job_id+ AND status NOT IN ('Completed', 'Cancelled');+ END IF;+END;+$function$;diff --git a/packages/database/supabase/tests/job-completion-terminal-operations.test.sql b/packages/database/supabase/tests/job-completion-terminal-operations.test.sqlnew file mode 100644index 0000000000..01e45edf6c--- /dev/null+++ b/packages/database/supabase/tests/job-completion-terminal-operations.test.sql@@ -0,0 +1,230 @@+-- Finishing the last operation on the floor receives the units that came out of+-- the routing's final operations (sync_finish_job_operation) — once, however the+-- routing ends.+-- Isolated fixture company; no existing business data is read or edited. Always rolls back.+-- Run: pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -f packages/database/supabase/tests/job-completion-terminal-operations.test.sql+\set ON_ERROR_STOP on+BEGIN;+SET LOCAL statement_timeout = '60s';++-- A released job for p_item_id with p_quantity units. Serial items keep their+-- placeholder split into numbered single units, as the item serial sequence+-- does at job creation.+CREATE FUNCTION pg_temp.make_job(+ p_company_id text, p_location_id text, p_item_id text, p_readable_id text, p_quantity numeric+) RETURNS text LANGUAGE plpgsql AS $fn$+DECLARE+ v_job_id text;+ v_make_method_id text;+ v_seed record;+BEGIN+ INSERT INTO job ("jobId", "itemId", quantity, "locationId", "companyId", "createdBy", "unitOfMeasureCode")+ VALUES (p_readable_id, p_item_id, p_quantity, p_location_id, p_company_id, 'system', 'EA')+ RETURNING id INTO v_job_id;++ SELECT id INTO STRICT v_make_method_id+ FROM "jobMakeMethod" WHERE "jobId" = v_job_id AND "parentMaterialId" IS NULL;++ SELECT * INTO v_seed FROM "trackedEntity" WHERE attributes->>'Job Make Method' = v_make_method_id;+ IF v_seed.id IS NOT NULL THEN+ UPDATE "trackedEntity" SET quantity = 1, "readableId" = p_readable_id || '-01' WHERE id = v_seed.id;+ FOR n IN 2..p_quantity::int LOOP+ INSERT INTO "trackedEntity" ("sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ quantity, status, "companyId", "createdBy", attributes, "itemId", "readableId")+ VALUES (v_seed."sourceDocument", v_seed."sourceDocumentId", v_seed."sourceDocumentReadableId",+ 1, 'Reserved', p_company_id, 'system', v_seed.attributes, v_seed."itemId",+ p_readable_id || '-' || lpad(n::text, 2, '0'));+ END LOOP;+ END IF;++ UPDATE job SET status = 'In Progress' WHERE id = v_job_id;+ RETURN v_job_id;+END;+$fn$;++-- An operation on the job's top-level make method that runs after p_depends_on.+CREATE FUNCTION pg_temp.add_operation(+ p_job_id text, p_company_id text, p_process_id text, p_work_center_id text,+ p_quantity numeric, p_order numeric, p_depends_on text DEFAULT NULL, p_rework_id text DEFAULT NULL+) RETURNS text LANGUAGE plpgsql AS $fn$+DECLARE v_operation text;+BEGIN+ INSERT INTO "jobOperation" ("jobId", "jobMakeMethodId", "processId", "workCenterId",+ "operationQuantity", "targetQuantity", "order", status, "reworkId", "companyId", "createdBy")+ SELECT p_job_id, m.id, p_process_id, p_work_center_id,+ p_quantity, p_quantity, p_order, 'Ready', p_rework_id, p_company_id, 'system'+ FROM "jobMakeMethod" m WHERE m."jobId" = p_job_id AND m."parentMaterialId" IS NULL+ RETURNING id INTO v_operation;++ IF p_depends_on IS NOT NULL THEN+ INSERT INTO "jobOperationDependency" ("operationId", "dependsOnId", "jobId", "companyId")+ VALUES (v_operation, p_depends_on, p_job_id, p_company_id);+ END IF;++ RETURN v_operation;+END;+$fn$;++-- What the MES writes when an operator reports units on an operation.+CREATE FUNCTION pg_temp.try_report(p_operation_id text, p_type text, p_quantity numeric) RETURNS text+LANGUAGE plpgsql AS $fn$+BEGIN+ INSERT INTO "productionQuantity" ("jobOperationId", type, quantity, "companyId", "createdBy")+ SELECT p_operation_id, p_type::"productionQuantityType", p_quantity, "companyId", 'system'+ FROM "jobOperation" WHERE id = p_operation_id;+ RETURN NULL;+EXCEPTION WHEN OTHERS THEN+ RETURN SQLERRM;+END;+$fn$;++-- The MES Finish button: Done with no quantity reported.+CREATE FUNCTION pg_temp.try_finish(p_operation_id text) RETURNS text+LANGUAGE plpgsql AS $fn$+BEGIN+ UPDATE "jobOperation" SET status = 'Done', "updatedBy" = 'system' WHERE id = p_operation_id;+ RETURN NULL;+EXCEPTION WHEN OTHERS THEN+ RETURN SQLERRM;+END;+$fn$;++CREATE FUNCTION pg_temp.receipts(p_job_id text) RETURNS text LANGUAGE sql AS $fn$+ SELECT count(*)::text || ':' || COALESCE(sum(quantity), 0)::numeric::text+ FROM "itemLedger"+ WHERE "documentId" = p_job_id AND "documentType" = 'Job Receipt';+$fn$;++CREATE FUNCTION pg_temp.header(p_job_id text) RETURNS text LANGUAGE sql AS $fn$+ SELECT status || '@' || "quantityComplete"::numeric::text FROM job WHERE id = p_job_id;+$fn$;++DO $cases$+DECLARE+ v_group_id text; v_company_id text; v_location_id text;+ v_serial_item text; v_stocked_item text;+ v_process text; v_work_center text;+ v_job text; v_error text; v_rework text; v_account text; v_defaults jsonb;+ v_first text; v_left text; v_right text; v_last text;+BEGIN+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Terminal ops test', 'system') RETURNING id INTO v_group_id;+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)+ VALUES ('Terminal ops test', v_group_id, 'USD', 'UTC') RETURNING id INTO v_company_id;+ INSERT INTO location (name, "addressLine1", city, "postalCode", "companyId", "createdBy", timezone)+ VALUES ('Plant', '1 Test Way', 'Testville', '00000', v_company_id, 'system', 'UTC') RETURNING id INTO v_location_id;+ INSERT INTO "unitOfMeasure" (code, name, "companyId", "createdBy")+ VALUES ('EA', 'Each', v_company_id, 'system') ON CONFLICT DO NOTHING;+ -- Every completion journals (Provisional before a cutover): the settings row+ -- the posting reads, the journal sequence, an account and the defaults.+ INSERT INTO "companySettings" (id) VALUES (v_company_id) ON CONFLICT (id) DO NOTHING;+ INSERT INTO "sequence" ("table", name, prefix, "companyId", "updatedBy")+ VALUES ('journalEntry', 'Journal entries', 'JE-', v_company_id, 'system') ON CONFLICT DO NOTHING;+ INSERT INTO account (name, class, "accountType", "incomeBalance", "companyGroupId", "createdBy")+ VALUES ('Any', 'Asset', 'Bank', 'Balance Sheet', v_group_id, 'system') RETURNING id INTO v_account;+ SELECT jsonb_object_agg(attname, to_jsonb(v_account)) INTO v_defaults+ FROM pg_attribute WHERE attrelid = '"accountDefault"'::regclass AND attnum > 0 AND NOT attisdropped AND attnotnull AND attname <> 'companyId';+ INSERT INTO "accountDefault"+ SELECT (jsonb_populate_record(NULL::"accountDefault", v_defaults || jsonb_build_object('companyId', v_company_id))).*;+ INSERT INTO item ("readableId", name, type, "replenishmentSystem", "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")+ VALUES ('T-STOCKED', 'Stocked assembly', 'Part', 'Make', 'Inventory', 'EA', v_company_id, 'system') RETURNING id INTO v_stocked_item;+ INSERT INTO item ("readableId", name, type, "replenishmentSystem", "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")+ VALUES ('T-SERIAL', 'Serial machine', 'Part', 'Make', 'Serial', 'EA', v_company_id, 'system') RETURNING id INTO v_serial_item;+ INSERT INTO process (name, "processType", "defaultStandardFactor", "companyId", "createdBy")+ VALUES ('Assembly', 'Process', 'Hours/Piece', v_company_id, 'system') RETURNING id INTO v_process;+ INSERT INTO "workCenter" (name, "locationId", "laborRate", "machineRate", "overheadRate", "defaultStandardFactor", "companyId", "createdBy")+ VALUES ('Bench', v_location_id, 0, 0, 0, 'Hours/Piece', v_company_id, 'system') RETURNING id INTO v_work_center;++ -- THE BUG: a routing that ends in two parallel operations ("With Previous")+ -- has two final operations, and each reports every unit. Summing them+ -- completed the job at twice its quantity: a serial job then had too few+ -- units to receive and the last unit could never be completed in the MES.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, 'PAR-SERIAL', 3);+ v_first := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 1);+ v_left := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 2, v_first);+ v_right := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 3, v_first);++ v_error := COALESCE(pg_temp.try_report(v_first, 'Production', 3), pg_temp.try_report(v_left, 'Production', 3));+ ASSERT v_error IS NULL, 'Reporting the first operations failed: ' || COALESCE(v_error, '');+ v_error := pg_temp.try_report(v_right, 'Production', 3);+ ASSERT v_error IS NULL, 'Completing the last parallel operation failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.header(v_job) = 'Completed@3',+ 'Serial job with parallel final operations completed wrong: ' || pg_temp.header(v_job);+ ASSERT pg_temp.receipts(v_job) = '3:3',+ 'Serial job with parallel final operations received wrong: ' || pg_temp.receipts(v_job);++ -- The same routing on an untracked item has no units to run short of, so+ -- the double count was silent: it received twice the stock that was made.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_stocked_item, 'PAR-STOCKED', 2);+ v_first := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 2, 1);+ v_left := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 2, 2, v_first);+ v_right := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 2, 3, v_first);++ v_error := COALESCE(pg_temp.try_report(v_first, 'Production', 2), pg_temp.try_report(v_left, 'Production', 2),+ pg_temp.try_report(v_right, 'Production', 2));+ ASSERT v_error IS NULL, 'Completing the stocked parallel routing failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.header(v_job) = 'Completed@2',+ 'Stocked job with parallel final operations completed wrong: ' || pg_temp.header(v_job);+ ASSERT pg_temp.receipts(v_job) = '1:2',+ 'Stocked job with parallel final operations received wrong: ' || pg_temp.receipts(v_job);++ -- A parallel final operation over-reported by one: only the units that came+ -- through BOTH final operations are finished, never more than the job made.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, 'PAR-OVER', 3);+ v_first := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 1);+ v_left := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 2, v_first);+ v_right := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 3, v_first);++ v_error := COALESCE(pg_temp.try_report(v_first, 'Production', 3), pg_temp.try_report(v_left, 'Production', 4),+ pg_temp.try_report(v_right, 'Production', 3));+ ASSERT v_error IS NULL, 'Completing an over-reported parallel routing failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.receipts(v_job) = '3:3',+ 'An over-reported parallel operation changed the receipt: ' || pg_temp.receipts(v_job);++ -- A parallel final operation closed with Finish and no quantity says nothing+ -- about how many units were made; the operation that did report decides.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_stocked_item, 'PAR-FINISH', 2);+ v_first := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 2, 1);+ v_left := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 2, 2, v_first);+ v_right := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 2, 3, v_first);++ v_error := COALESCE(pg_temp.try_report(v_first, 'Production', 2), pg_temp.try_report(v_left, 'Production', 2),+ pg_temp.try_finish(v_right));+ ASSERT v_error IS NULL, 'Finishing a parallel operation without a quantity failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.receipts(v_job) = '1:2',+ 'A quantity-less parallel Finish changed the receipt: ' || pg_temp.receipts(v_job);++ -- Rework triggered at the final operation is a separate final BRANCH that+ -- carries only the reworked units (trigger-rework): the original operation+ -- reports 2 complete + 1 reworked, the branch completes the 1. Those add up.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_stocked_item, 'REWORK', 3);+ v_first := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 1);+ v_last := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 2, v_first);+ INSERT INTO rework ("jobId", "triggeredAtJobOperationId", "targetJobOperationId", reason, quantity, "requestedById", "companyId")+ VALUES (v_job, v_last, v_last, 'Out of tolerance', 1, 'system', v_company_id) RETURNING id INTO v_rework;+ v_right := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 1, 2.5, NULL, v_rework);++ v_error := COALESCE(pg_temp.try_report(v_first, 'Production', 3), pg_temp.try_report(v_last, 'Production', 2),+ pg_temp.try_report(v_last, 'Rework', 1));+ ASSERT v_error IS NULL, 'Reporting the reworked routing failed: ' || COALESCE(v_error, '');+ v_error := pg_temp.try_report(v_right, 'Production', 1);+ ASSERT v_error IS NULL, 'Completing the rework branch failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.header(v_job) = 'Completed@3',+ 'Rework branch completed wrong: ' || pg_temp.header(v_job);+ ASSERT pg_temp.receipts(v_job) = '1:3',+ 'Rework branch received wrong: ' || pg_temp.receipts(v_job);++ -- A plain single-path routing is unchanged.+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, 'LINE', 2);+ v_first := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 2, 1);+ v_last := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 2, 2, v_first);+ v_error := COALESCE(pg_temp.try_report(v_first, 'Production', 2), pg_temp.try_report(v_last, 'Production', 1),+ pg_temp.try_report(v_last, 'Production', 1));+ ASSERT v_error IS NULL, 'Completing a single-path routing failed: ' || COALESCE(v_error, '');+ ASSERT pg_temp.header(v_job) = 'Completed@2' AND pg_temp.receipts(v_job) = '2:2',+ 'Single-path routing completed wrong: ' || pg_temp.header(v_job) || ' / ' || pg_temp.receipts(v_job);++ RAISE NOTICE 'ALL TERMINAL-OPERATION CASES PASSED (parallel serial, parallel stocked, over-reported, quantity-less finish, rework branch, single path)';+END;+$cases$;++ROLLBACK;diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex 2913fbba58..afbe36783f 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261012043741",+ "schemaVersion": "20261012111443","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-12T04:41:12.765Z",+ "exportedAt": "2026-10-12T12:00:40.103Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",