Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(production): a serial job with its units assigned completes from the desk (#1701)

Anshul sharma8213240df66d
diff --git a/packages/database/supabase/migrations/20260922183000_serial-job-desk-completion.sql b/packages/database/supabase/migrations/20260922183000_serial-job-desk-completion.sql
new file mode 100644
index 0000000000..850212bec7
--- /dev/null
+++ b/packages/database/supabase/migrations/20260922183000_serial-job-desk-completion.sql
@@ -0,0 +1,102 @@
+-- A serial job whose units already exist completes from the desk again.
+--
+-- 20260922050131 refused EVERY serial-tracked job that had an operation
+-- shortfall, on the assumption that a missing operation quantity meant a
+-- missing serial unit. It does not. Serial numbers are assigned at job
+-- CREATION (assignJobSerialNumbers, on the create paths only), so the ordinary
+-- desk flow -- create a serial job, release it, never open the Operations tab,
+-- press Complete -- has every numbered unit Reserved and ready to receive while
+-- each operation still reads 0. Those jobs completed before that migration and
+-- were refused after it, with "a serial number is required" naming serials that
+-- were sitting right there.
+--
+-- Fix: drop the guard. complete_job_to_inventory's serial branch already
+-- refuses a job genuinely short of units ("has N serial unit(s) left to
+-- receive, fewer than the M being completed") after trying the un-numbered seed
+-- fallback, and it runs in the same transaction, so a real shortage still rolls
+-- the completion back. The guard could only ever duplicate that decision from
+-- worse evidence: operation quantities rather than the tracked entities the
+-- receipt actually consumes. Deleting it removes the disagreement instead of
+-- teaching two places to agree.
+--
+-- Recreated VERBATIM from 20260922050131_mark-complete-completes-remaining-quantities.sql
+-- minus the serial guard and its now-unused v_serial_* locals.
+
+CREATE OR REPLACE FUNCTION complete_job_remaining_quantities(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_user_id TEXT
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_shortfall NUMERIC;
+BEGIN
+ -- Only the manual path closes operations. Under a trigger this is the MES
+ -- path, where the floor reports its own quantities — and where writing a
+ -- sibling jobOperation row fails with "tuple to be updated was already
+ -- modified by an operation triggered by the current command", since
+ -- sync_finish_job_operation is a BEFORE trigger mid-statement on those rows.
+ IF pg_trigger_depth() > 0 THEN
+ RETURN;
+ END IF;
+
+ -- The largest shortfall across the terminal operations. MAX, not SUM: these
+ -- are parallel paths to the same finished part and each must report the full
+ -- quantity, so summing them would invent units nobody required. Reworked
+ -- units already satisfy the auto-Done predicate, so they count as reported.
+ SELECT COALESCE(MAX(
+ p_quantity_complete
+ - COALESCE(t."quantityComplete", 0)
+ - COALESCE(t."quantityReworked", 0)
+ ), 0)
+ INTO v_shortfall
+ FROM terminal_job_operations(p_job_id) t;
+
+ IF v_shortfall <= 0 THEN
+ RETURN;
+ END IF;
+
+ -- Status as well as quantity. The auto-Done predicate lives in
+ -- sync_update_job_operation_quantities, which fires on productionQuantity
+ -- writes — not on a jobOperation update — so nothing else would close these
+ -- operations, and a quantity-only write would leave the routing open behind a
+ -- Completed job: the very symptom this function exists to remove.
+ --
+ -- Setting status here fires sync_finish_job_operation on each row. The caller
+ -- must therefore have marked the job Completed already: the interceptor's
+ -- status gate then returns early. Called while the job is still open it would
+ -- instead re-enter complete_job_to_inventory and, being a BEFORE row trigger
+ -- reading the pre-update quantityComplete, receive the goods a second time.
+ --
+ -- Every open terminal operation is closed, not only the short ones: an
+ -- operation whose quantity already meets the target is Done by the same
+ -- predicate the interceptor uses, so leaving it Ready on a Completed job
+ -- would recreate the inconsistency this function exists to remove.
+ --
+ -- Reworked units already count as reported, so the new quantityComplete is
+ -- the target MINUS them. Assigning the full target on top of a reworked unit
+ -- would report more units than the operation ever produced (target 3 with 1
+ -- complete + 1 reworked must end at 2 complete + 1 reworked, not 3 + 1).
+ -- GREATEST never lowers a quantity the floor already reported.
+ UPDATE "jobOperation" jo
+ SET "quantityComplete" = GREATEST(
+ COALESCE(t."quantityComplete", 0),
+ p_quantity_complete - COALESCE(t."quantityReworked", 0)
+ ),
+ status = 'Done',
+ "updatedBy" = COALESCE(p_user_id, jo."updatedBy", jo."createdBy"),
+ "updatedAt" = NOW()
+ FROM terminal_job_operations(p_job_id) t
+ WHERE jo.id = t.id;
+END;
+$$;
+
+-- SECURITY DEFINER with no p_company_id to bind the call to a tenant; it stays
+-- an internal helper of complete_job_to_inventory, which does enforce the
+-- company check. CREATE OR REPLACE preserves grants, but re-assert them so the
+-- revoke cannot be lost if this function is ever recreated from this file.
+REVOKE ALL ON FUNCTION complete_job_remaining_quantities(TEXT, NUMERIC, TEXT) FROM PUBLIC, anon, authenticated;
diff --git a/packages/database/supabase/tests/job-completion-operation-quantities.test.sql b/packages/database/supabase/tests/job-completion-operation-quantities.test.sql
index a15eb03d13..7d792d7c85 100644
--- a/packages/database/supabase/tests/job-completion-operation-quantities.test.sql
+++ b/packages/database/supabase/tests/job-completion-operation-quantities.test.sql
@@ -218,19 +218,56 @@ BEGIN
ASSERT v_row.status <> 'Done' AND v_row."quantityComplete" = 0,
'A sub-assembly operation must not be completed by the job: ' || v_row.status || ' @ ' || v_row."quantityComplete";
- -- Serial job with units still outstanding is refused, and nothing is applied.
+ -- REGRESSION: a serial job whose units already exist completes from the desk.
+ --
+ -- Serial numbers are assigned at job CREATION, so the ordinary desk flow --
+ -- create, release, never open the Operations tab, press Complete -- has every
+ -- numbered unit Reserved and ready while the operations still read 0. The
+ -- first version of this guard refused exactly that, naming a serial number
+ -- that was sitting right there. Operation shortfall is not evidence of a
+ -- missing serial; only the absence of un-received units is.
v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, v_part, 'SJ', 3);
v_op1 := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 1);
v_error := pg_temp.try_complete(v_job, 3);
- ASSERT v_error LIKE '%serial number is required%',
- 'Serial job with outstanding units was not refused: ' || COALESCE(v_error, '<succeeded>');
+ ASSERT v_error IS NULL,
+ 'Serial job with its units already assigned was refused: ' || COALESCE(v_error, '');
+ SELECT status, "quantityComplete" INTO v_row FROM job WHERE id = v_job;
+ ASSERT v_row.status = 'Completed' AND v_row."quantityComplete" = 3,
+ 'Serial job with assigned units did not complete from the desk';
+ ASSERT pg_temp.ops(v_job) = 'Done:3',
+ 'Serial desk completion left its operations open: ' || pg_temp.ops(v_job);
+ -- Serial receipts post one itemLedger row per numbered unit, so three units
+ -- are three rows totalling three -- not a single row of three.
+ ASSERT pg_temp.receipts(v_job) = '3:3',
+ 'Serial desk completion did not receive its three units: ' || pg_temp.receipts(v_job);
+
+ -- A serial job genuinely short of numbered units is still refused, and
+ -- nothing is applied. Here the units are consumed elsewhere, so there is
+ -- nothing left for this job to receive.
+ --
+ -- The refusal comes from complete_job_to_inventory's serial branch, not from
+ -- complete_job_remaining_quantities: the receipt is the code that knows which
+ -- tracked entities it can actually consume, so it is the only place that can
+ -- tell a numbered-but-unreported job from a genuinely short one.
+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, v_part, 'SJ-SHORT', 3);
+ v_op1 := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 1);
+ UPDATE "trackedEntity" SET status = 'Consumed'
+ WHERE attributes->>'Job Make Method' = (
+ SELECT id FROM "jobMakeMethod" WHERE "jobId" = v_job AND "parentMaterialId" IS NULL
+ );
+
+ v_error := pg_temp.try_complete(v_job, 3);
+ ASSERT v_error LIKE '%serial unit(s) left to receive%',
+ 'Serial job with no available units was not refused: ' || COALESCE(v_error, '<succeeded>');
SELECT status INTO v_row FROM job WHERE id = v_job;
ASSERT v_row.status <> 'Completed', 'A refused serial completion still completed the job';
ASSERT pg_temp.ops(v_job) = 'Ready:0',
'A refused serial completion still wrote quantities: ' || pg_temp.ops(v_job);
-- The same serial job completes once the floor has reported every unit.
+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_serial_item, v_part, 'SJ-MES', 3);
+ v_op1 := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3, 1);
UPDATE "jobOperation" SET "quantityComplete" = 3 WHERE id = v_op1;
v_error := pg_temp.try_complete(v_job, 3);
ASSERT v_error IS NULL, 'Serial job finished in MES failed to complete: ' || COALESCE(v_error, '');
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 13ba2d609c..08fba19476 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20260922050131",
+ "schemaVersion": "20260922183000",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-09-22T07:16:49.167Z",
+ "exportedAt": "2026-09-22T10:59:26.429Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",