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(database): receive no more against a seed than it holds and the job owes

Raulb15308f3345e
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index e0b6fc68da..1b4031a2db 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -34,11 +34,11 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
### Job completion
-`complete_job_to_inventory` (SQL, newest `20261014135003_lock-production-events-at-job-completion.sql` (locks the unposted events it posts), before it `20261009010412_job-costing-always-post.sql` and `20261006221601_complete-job-to-asset.sql`, forked from the guarded definition in `20260925121735_rpc-function-guards.sql`) is the single choke point: `completeJob` (the ERP complete route and the API/MCP tool) and the `sync_finish_job_operation` trigger interceptor both go through it.
+`complete_job_to_inventory` (SQL, newest `20261027064600_serial-number-timing-completion.sql`, before it `20261015161847_job-receipt-takes-issued-serial-units.sql`, `20261014171619_receive-consumed-serial-units.sql`, `20261014135003_lock-production-events-at-job-completion.sql` (locks the unposted events it posts), `20261009010412_job-costing-always-post.sql` and `20261006221601_complete-job-to-asset.sql`, forked from the guarded definition in `20260925121735_rpc-function-guards.sql`) is the single choke point: `completeJob` (the ERP complete route and the API/MCP tool) and the `sync_finish_job_operation` trigger interceptor both go through it.
- `p_quantity_complete` is **CUMULATIVE**, not this completion's delta. The function receives `p_quantity_complete - job.quantityReceivedToInventory` and stores the cumulative value back, because `get_inventory_quantities` computes on-production supply as production + scrap − received − shipped. `backflush_job_materials` takes the same cumulative number and is idempotent, so a re-completion at the received quantity receives nothing and consumes nothing.
- It **refuses** a quantity ≤ 0 or below what was already received (stocked items), and a fractional quantity on a serial job. Those raises reach the `jobOperation` UPDATE when they happen under the trigger — `sync_finish_job_operation` therefore clamps with `GREATEST(computed, received)` before calling.
-- The serial branch receives the delta one numbered unit at a time — shop-floor-finished (`Available`) first, then by `readableId` — skipping `Consumed`/`Rejected`/`Scrapped` and any unit with a `Job Receipt` ledger row for this job, so re-completion never double-receives. When the job's rows hold too few single units, an item with a serial sequence has the rest split off the seed (`split_serial_units_for_completion`) and the units picked again; the units taken are then numbered (`number_serial_units_for_receipt`). An item with **no serial sequence** is never split: its single units are received first, then the rest of the delta against its seed (one entity holding the units the shop floor has not touched).
+- The serial branch receives the delta one numbered unit at a time — shop-floor-finished (`Available`) first, then by `readableId` — skipping `Consumed`/`Rejected`/`Scrapped` and any unit with a `Job Receipt` ledger row for this job, so re-completion never double-receives. When the job's rows hold too few single units, an item with a serial sequence has the rest split off the seed (`split_serial_units_for_completion`) and the units picked again; the units taken are then numbered (`number_serial_units_for_receipt`). An item with **no serial sequence** is never split: its single units are received first, then the rest of the delta against its seed (one entity holding the units the shop floor has not touched). The seed gives the units the job has not received from it, plus the units no row holds up to the job quantity (it grows by those); a completion beyond that is refused.
- **Make to Asset branch.** A job with `fixedAssetClassId` completes into one new `fixedAsset` per unit (status `Active`, or `Under Construction` when the class `isConstructionInProgress`; `acquisitionCost` = swept WIP ÷ units; one Posted `fixedAssetTransfer` per asset, `type 'Capitalization'`, `sourceType 'Job'`); a job with `fixedAssetId` sweeps its WIP onto that Construction in Progress asset as one `fixedAssetCipCost` row + one transfer. The units never enter stock: no `itemLedger`, `costLedger`, `pickMethod` or `itemCost` write, and the WIP discharge posts Dr class `assetAccountId` / Cr WIP as an `'Asset Transfer'` journal (both lines still `documentId = jobId`, so the per-job WIP balance nets to zero). Each serial unit goes `Consumed` with `attributes["Fixed Asset"]` and a `'Capitalize'` `trackedActivity`; every company writes the asset cost (the journal is Provisional before the accounting cutover). Guards raise before anything moves: `'A job linked to a sales order line cannot complete to a fixed asset'`; `'A job that completes to a fixed asset class needs a serialized item'` (any quantity — every asset a class job makes is a fleet unit followed by its serial); `'Make to Asset needs a serialized item or a quantity of one'` (a job attached to an asset under construction); a job attached to a non-CIP asset is also refused (`'… is not in a Construction in Progress class'`). The item rule is `makeToAssetItemError` (`production.models.ts`), applied by `x+/job+/new.tsx` on save (a field error on the item), by `updateJobDetails` (the details form), by `setJobItem` on a property-panel item change and by `resumeJob` when a paused job goes back to `Ready`, with the sales order line gate. Covered by `packages/database/supabase/tests/job-completion-to-asset.test.sql`. Full flow: `.claude/rules/fixed-asset-lifecycle.md`.
- **Serial number timing**: when a produced unit draws its serial number.
- Setting: `companySettings.serialNumberTiming` (Settings → Production → Serial Numbers). An item's serial sequence overrides it with `itemSerialSequence.serialNumberTiming` (NULL follows the company; Settings → Serial Numbers). Readers resolve the item's value first: `getSerialNumberTiming` / `resolveSerialNumberTiming` (`@carbon/database/sequence`). Values: `serialNumberTimings` (`@carbon/database/serial-number-timing`, client-safe).
diff --git a/apps/erp/test/database/serial-number-timing.test.ts b/apps/erp/test/database/serial-number-timing.test.ts
index f60338ee60..190c60015a 100644
--- a/apps/erp/test/database/serial-number-timing.test.ts
+++ b/apps/erp/test/database/serial-number-timing.test.ts
@@ -772,6 +772,51 @@ describe.skipIf(!client)("serial number timing", () => {
}
});
+ it("receives no more than an item with no serial sequence holds, and grows its seed to a raised job quantity", async () => {
+ const f = await alwaysPostFixture();
+ try {
+ await stockPart(f, 20);
+ await serialSetup(f, "production");
+ await seed(f, async (trx) => {
+ await trx
+ .deleteFrom("itemSerialSequence")
+ .where("itemId", "=", f.assemblyId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ });
+ const job = await untouchedSerialJob(f, "7e", 3);
+ // The job quantity is raised after its seed of three was made.
+ await seed(f, async (trx) => {
+ await trx
+ .updateTable("job")
+ .set({ quantity: 4 })
+ .where("id", "=", job.jobId)
+ .execute();
+ });
+
+ const beyond = await completeJob(contextFor(f), {
+ jobId: job.jobId,
+ quantityComplete: 5
+ });
+ expect(beyond.error?.category).toBe("rule");
+ expect(await receivedUnits(f, job.jobId)).toEqual([]);
+
+ const result = await completeJob(contextFor(f), {
+ jobId: job.jobId,
+ quantityComplete: 4
+ });
+ expect(result.error).toBeNull();
+ expect(await receivedUnits(f, job.jobId)).toEqual([
+ { readableId: null, quantity: 4 }
+ ]);
+ expect(await units(f, job.makeMethodId)).toEqual([
+ expect.objectContaining({ quantity: 4, status: "Available" })
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ });
+
it("refuses to scrap a unit already received to stock", async () => {
const f = await alwaysPostFixture();
try {
diff --git a/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql b/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql
index 21b218fc18..c07b2df7ae 100644
--- a/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql
+++ b/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql
@@ -17,7 +17,7 @@
-- (number_serial_units_for_receipt) and receives them. One query picks the units,
-- so numbering and receipt cannot take different ones. An item with no serial
-- sequence is never split: its single units are received, then the rest against
--- its seed. Every caller (the ERP's
+-- its seed, up to the units it holds and the job still owes. Every caller (the ERP's
-- completeJob, and the sync_finish_job_operation interceptor when the last
-- operation is marked Done) gets it by calling complete_job_to_inventory.
--
@@ -374,6 +374,8 @@ DECLARE
v_serial_unit_ids TEXT[];
v_issued_units_received NUMERIC := 0;
v_units_taken INTEGER;
+ v_seed_units_left NUMERIC := 0;
+ v_units_without_row NUMERIC := 0;
v_company_today DATE := company_today(p_company_id);
v_job_asset_class_id TEXT;
v_job_asset_id TEXT;
@@ -862,12 +864,42 @@ BEGIN
LIMIT 1
FOR UPDATE;
+ -- The seed gives the units this job has not received from it, and the
+ -- units no row holds yet (the job quantity was raised after the seed was
+ -- made), as the sequence path creates them; a scrapped unit does not
+ -- count: the job still owes it.
+ IF v_tracked_entity.id IS NOT NULL THEN
+ SELECT v_tracked_entity.quantity - COALESCE(SUM(il.quantity), 0)
+ INTO v_seed_units_left
+ FROM "itemLedger" il
+ WHERE il."trackedEntityId" = v_tracked_entity.id
+ AND il."companyId" = p_company_id
+ AND il."documentType" = 'Job Receipt'
+ AND il."documentId" = p_job_id;
+
+ SELECT GREATEST(
+ (SELECT j.quantity FROM "job" j WHERE j.id = p_job_id AND j."companyId" = p_company_id)
+ - COALESCE(SUM(te.quantity), 0),
+ 0
+ )
+ INTO v_units_without_row
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id
+ AND te."companyId" = p_company_id
+ AND te.status <> 'Scrapped';
+ END IF;
+
-- Genuinely short of units (some scrapped, some already received) rather
-- than un-numbered: receiving fewer than completed would leave the job's
-- received quantity ahead of the ledger.
- IF v_tracked_entity.id IS NULL THEN
+ IF v_tracked_entity.id IS NULL
+ OR GREATEST(v_seed_units_left, 0) + v_units_without_row
+ < v_quantity_received_to_inventory - v_units_taken THEN
RAISE EXCEPTION 'Job % has % serial unit(s) left to receive, fewer than the % being completed',
- v_job_id_readable, COALESCE(array_length(v_serial_unit_ids, 1), 0), v_quantity_received_to_inventory;
+ v_job_id_readable,
+ COALESCE(array_length(v_serial_unit_ids, 1), 0)
+ + GREATEST(v_seed_units_left, 0) + v_units_without_row,
+ v_quantity_received_to_inventory;
END IF;
END IF;
@@ -928,8 +960,14 @@ BEGIN
v_tracked_entity.id, p_user_id
);
+ -- The seed grows by the units no row held, so it holds what it received.
UPDATE "trackedEntity"
- SET status = 'Available'
+ SET status = 'Available',
+ quantity = quantity + GREATEST(
+ v_quantity_received_to_inventory - v_units_taken
+ - GREATEST(v_seed_units_left, 0),
+ 0
+ )
WHERE id = v_tracked_entity.id;
END IF;