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): serial timing review fixes: single-unit first touch, Batch lots, invoker completion numbering

Raulf9110170cb97
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 72eac98bae..aeca593296 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -40,7 +40,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
- 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. An item with **no serial sequence** never reaches `assign-serial-numbers`, so its job keeps one whole-quantity seed entity and the delta is received against that seed instead.
- **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** (`companySettings.serialNumberTiming`, Settings → Production → Serial Numbers; an item's serial sequence overrides it with `itemSerialSequence.serialNumberTiming`, NULL follows the company, edited in Settings → Serial Numbers). Every reader resolves the item's own value first: `getSerialNumberTiming(db, companyId, itemId)` (`@carbon/database/sequence`), the SQL `number_serial_units_for_completion`, and the Complete dialog. `jobCreation` (default): `assignJobSerialNumbers` splits and numbers every unit when the job is created. `jobRelease`: the same split and numbering runs when `releaseCheckedJobs` flips the job to Ready (`assignJobSerialNumbersAtRelease`, best-effort: a failure is logged and the release goes on), so every release path (Release dialog, bulk, batch, kanban) numbers it; a unit spawned later is numbered at spawn, as under `jobCreation`. `production`: it is skipped, the job keeps its unnumbered seed, and a unit draws its number at its first touch through `assignSerialNumberIfMissing` (`@carbon/database/sequence`): the MES start (`start.$operationId.tsx`, `x+/event.tsx`, via `services/serial-number.server.ts`), the `issue` posting's serial completion, batch output and operation scrap, and the completion that receives it. A unit the serial completion or a scrap spawns stays unnumbered under `production`. Both completion paths call the SQL `number_serial_units_for_completion` (`20261022114200_serial-number-timing-completion.sql`) before `complete_job_to_inventory`: `completeJob` (through `numberSerialUnitsForCompletion`) and the `sync_finish_job_operation` interceptor (an operation marked Done). It does not read the timing: under `jobCreation` it finds every unit numbered and does nothing, unless the job was created under another timing before the item or company switched back, which would otherwise receive one unnumbered entity holding every unit. It takes the units the RPC will take, in its receipt or Make to Asset order, splits what is missing off the seed and numbers every unit taken, so no unnumbered lump is received. The shop floor's first completion or scrap of the seed leaves it holding one unit (a serial scrap takes one unit, never the whole seed) and spawns the next units one at a time, so the rows can hold fewer units than the job quantity: the function creates the units no row holds yet, up to the job quantity less the units in rows (a scrapped unit does not count), and the Complete dialog counts them as receivable. Every serial is formatted by the SQL `get_next_serial_numbers`, which `getNextSerialNumbers` calls. The Complete dialog unlocks the quantity whenever the item has a serial sequence and units are unnumbered or have no row (`getSerialCompleteChoice`, mode `numberOnReceipt`) and says the serials are drawn at receipt; for an item with no sequence it stays locked to what the shop floor finished.
+- **Serial number timing** (`companySettings.serialNumberTiming`, Settings → Production → Serial Numbers; an item's serial sequence overrides it with `itemSerialSequence.serialNumberTiming`, NULL follows the company, edited in Settings → Serial Numbers). Every reader resolves the item's own value first: `getSerialNumberTiming(db, companyId, itemId)` (`@carbon/database/sequence`), the SQL `number_serial_units_for_completion`, and the Complete dialog. `jobCreation` (default): `assignJobSerialNumbers` splits and numbers every unit when the job is created. `jobRelease`: the same split and numbering runs when `releaseCheckedJobs` flips the job to Ready (`assignJobSerialNumbersAtRelease`, best-effort: a failure is logged and the release goes on), so every release path (Release dialog, bulk, batch, kanban) numbers it; a unit spawned later is numbered at spawn, as under `jobCreation`. The timing is for serial units: a Batch item's lot is numbered at job creation whatever the timing (`assignJobSerialNumbers`). `production`: it is skipped, the job keeps its unnumbered seed, and a unit draws its number at its first touch through `assignSerialNumberIfMissing` (`@carbon/database/sequence`): the MES start (`start.$operationId.tsx`, `x+/event.tsx`, via `services/serial-number.server.ts`; only a unit already on its own, since a start leaves the job's unsplit seed whole and the seed's number comes from its first completion or scrap), the `issue` posting's serial completion, batch output and operation scrap, and the completion that receives it. A unit the serial completion or a scrap spawns stays unnumbered under `production`. Both completion paths call the SQL `number_serial_units_for_completion` (`20261022114200_serial-number-timing-completion.sql`, SECURITY INVOKER like `backflush_job_materials`) before `complete_job_to_inventory`: `completeJob` (through `numberSerialUnitsForCompletion`) and the `sync_finish_job_operation` interceptor (an operation marked Done). It does not read the timing: under `jobCreation` it finds every unit numbered and does nothing, unless the job was created under another timing before the item or company switched back, which would otherwise receive one unnumbered entity holding every unit. It takes the units the RPC will take, in its receipt or Make to Asset order, splits what is missing off the seed and numbers every unit taken, so no unnumbered lump is received. The shop floor's first completion or scrap of the seed leaves it holding one unit (a serial scrap takes one unit, never the whole seed) and spawns the next units one at a time, so the rows can hold fewer units than the job quantity: the function creates the units no row holds yet, up to the job quantity less the units in rows (a scrapped unit does not count), and the Complete dialog counts them as receivable. Every serial is formatted by the SQL `get_next_serial_numbers`, which `getNextSerialNumbers` calls. The Complete dialog unlocks the quantity whenever the item has a serial sequence and units are unnumbered or have no row (`getSerialCompleteChoice`, mode `numberOnReceipt`) and says the serials are drawn at receipt; for an item with no sequence it stays locked to what the shop floor finished.
- Dialog logic lives in `ui/Jobs/job-complete-logic.ts` (pure, no JSX/lingui, unit-tested by `apps/erp/test/job-complete-logic.test.ts`); the SQL is covered by `packages/database/supabase/tests/job-completion-received-quantity.test.sql`, hand-run like its siblings (nothing in CI runs `supabase/tests/`).
### Loaded operation and unattributed machine time
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 6afce1ea90..8550346acf 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -3841,7 +3841,19 @@ export async function assignJobSerialNumbers(
return;
}
if (!serialSequence.data) return;
- const timing = await getSerialNumberTiming(db, args.companyId, args.itemId);
+ // The timing is for serial units. A Batch job's one lot is numbered when the
+ // job is created, as before: number_serial_units_for_completion numbers
+ // serial units only, so a deferred lot would be received with no number.
+ const item = await db
+ .selectFrom("item")
+ .select("itemTrackingType")
+ .where("id", "=", args.itemId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ const timing =
+ item?.itemTrackingType === "Batch"
+ ? "jobCreation"
+ : await getSerialNumberTiming(db, args.companyId, args.itemId);
if (
timing !==
((args.moment ?? "creation") === "creation" ? "jobCreation" : "jobRelease")
diff --git a/apps/erp/test/database/serial-number-timing.test.ts b/apps/erp/test/database/serial-number-timing.test.ts
index de1ddaa238..fa7d03be98 100644
--- a/apps/erp/test/database/serial-number-timing.test.ts
+++ b/apps/erp/test/database/serial-number-timing.test.ts
@@ -231,6 +231,59 @@ describe.skipIf(!client)("serial number timing", () => {
}
});
+ it("leaves a seed holding several units unnumbered on a single-unit touch", async () => {
+ const f = await alwaysPostFixture();
+ try {
+ await serialSetup(f, "production");
+ const job = await untouchedSerialJob(f, "single", 3);
+ const [seedUnit] = await units(f, job.makeMethodId);
+
+ const numbered = await f.db.transaction().execute((trx) =>
+ assignSerialNumberIfMissing(trx, {
+ trackedEntityId: seedUnit!.id,
+ companyId: f.companyId,
+ onlyIfSingleUnit: true
+ })
+ );
+
+ expect(numbered).toBeNull();
+ expect(await units(f, job.makeMethodId)).toEqual([
+ expect.objectContaining({ readableId: null, quantity: 3 })
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ });
+
+ it("numbers a Batch lot when the job is created, whatever the timing", async () => {
+ const f = await alwaysPostFixture();
+ try {
+ await serialSetup(f, "production");
+ await seed(f, async (trx) => {
+ await trx
+ .updateTable("item")
+ .set({ itemTrackingType: "Batch" })
+ .where("id", "=", f.assemblyId)
+ .execute();
+ });
+ const job = await untouchedSerialJob(f, "batch", 3);
+
+ await assignJobSerialNumbers(client!, f.db, {
+ jobId: job.jobId,
+ itemId: f.assemblyId,
+ companyId: f.companyId,
+ userId: USER,
+ moment: "creation"
+ });
+
+ expect(await units(f, job.makeMethodId)).toEqual([
+ expect.objectContaining({ readableId: "SN-001", quantity: 3 })
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ });
+
it("splits and numbers the units a completion takes, and receives them", async () => {
const f = await alwaysPostFixture();
try {
diff --git a/apps/mes/app/services/serial-number.server.ts b/apps/mes/app/services/serial-number.server.ts
index dd1469689e..33ffca5793 100644
--- a/apps/mes/app/services/serial-number.server.ts
+++ b/apps/mes/app/services/serial-number.server.ts
@@ -14,6 +14,10 @@ const log = getLogger("mes", "serial-number");
* company's). A no-op for a unit that already has a number, which is every unit
* under the `jobCreation` and `jobRelease` timings, so it is safe on every start.
*
+ * Only a unit already on its own is numbered here. The job's first unit is
+ * still the unsplit seed holding every unit, and a start leaves it whole, so
+ * its number comes from its first completion or scrap, which cut it to one unit.
+ *
* Best-effort: a failure never stops a timer from starting, and the ERP's
* completion and scrap postings number the unit later if this was lost. It
* writes as the system: the caller has already admitted the operator to start
@@ -26,7 +30,9 @@ export async function assignSerialNumberOnFirstTouch(args: {
try {
await getDatabaseClient()
.transaction()
- .execute((trx) => assignSerialNumberIfMissing(trx, args));
+ .execute((trx) =>
+ assignSerialNumberIfMissing(trx, { ...args, onlyIfSingleUnit: true })
+ );
} catch (error) {
log.error("Failed to assign a serial number on first touch", {
error,
diff --git a/packages/database/src/sequence.ts b/packages/database/src/sequence.ts
index a62d5b3f31..8570bfd7b1 100644
--- a/packages/database/src/sequence.ts
+++ b/packages/database/src/sequence.ts
@@ -235,20 +235,29 @@ export async function getSerialNumberTiming(
* first one's number instead of reserving and burning another. Runs inside the
* caller's transaction, so the counter reservation commits or rolls back with
* the write that prompted it.
+ *
+ * `onlyIfSingleUnit` leaves an entity holding more than one unit unnumbered.
+ * A caller that does not cut the entity to one unit in the same transaction
+ * passes it, or a job's unsplit seed would carry one serial for every unit.
*/
export async function assignSerialNumberIfMissing(
trx: Transaction<KyselyDatabase>,
- args: { trackedEntityId: string; companyId: string }
+ args: {
+ trackedEntityId: string;
+ companyId: string;
+ onlyIfSingleUnit?: boolean;
+ }
): Promise<string | null> {
const entity = await trx
.selectFrom("trackedEntity")
- .select(["id", "itemId", "readableId", "attributes"])
+ .select(["id", "itemId", "readableId", "attributes", "quantity"])
.where("id", "=", args.trackedEntityId)
.where("companyId", "=", args.companyId)
.forUpdate()
.executeTakeFirst();
if (!entity || entity.readableId || !entity.itemId) return null;
+ if (args.onlyIfSingleUnit && Number(entity.quantity) !== 1) return null;
const [readableId] = await getNextSerialNumbers(trx, {
itemId: entity.itemId,
diff --git a/packages/database/supabase/migrations/20261022114200_serial-number-timing-completion.sql b/packages/database/supabase/migrations/20261022114200_serial-number-timing-completion.sql
index 2c42761f35..319883470f 100644
--- a/packages/database/supabase/migrations/20261022114200_serial-number-timing-completion.sql
+++ b/packages/database/supabase/migrations/20261022114200_serial-number-timing-completion.sql
@@ -47,7 +47,7 @@ $function$;
-- Reserve and format the next p_count serial numbers of an item's
-- itemSerialSequence. Empty when the item has no sequence. Runs as the caller:
-- the ERP and MES call it on a direct connection, and the completion below as
--- its owner.
+-- whoever runs the completion.
CREATE OR REPLACE FUNCTION public.get_next_serial_numbers(
p_item_id text,
p_company_id text,
@@ -130,6 +130,12 @@ $function$;
-- time, so after it the rows cover fewer units than the job quantity. Those
-- units are created here, up to the job quantity less the units already in
-- rows (a scrapped unit does not count: the job still owes it).
+--
+-- SECURITY INVOKER, like backflush_job_materials: its callers are the
+-- sync_finish_job_operation interceptor, which the event dispatcher runs as the
+-- owner, and completeJob on a direct connection. Called through the API it runs
+-- under the caller's RLS, so it cannot split or number units the caller could
+-- not update.
CREATE OR REPLACE FUNCTION public.number_serial_units_for_completion(
p_job_id text,
p_quantity_complete numeric,
@@ -137,7 +143,7 @@ CREATE OR REPLACE FUNCTION public.number_serial_units_for_completion(
)
RETURNS integer
LANGUAGE plpgsql
- SECURITY DEFINER
+ SECURITY INVOKER
SET search_path TO 'public'
AS $function$
DECLARE
diff --git a/packages/database/supabase/tests/rpc-privileges.test.sql b/packages/database/supabase/tests/rpc-privileges.test.sql
index e15ad6ecb8..9706f22a7f 100644
--- a/packages/database/supabase/tests/rpc-privileges.test.sql
+++ b/packages/database/supabase/tests/rpc-privileges.test.sql
@@ -69,6 +69,7 @@ BEGIN
END IF;
IF (SELECT prosecdef FROM pg_proc WHERE oid = 'backflush_job_materials(text,numeric,text,text)'::regprocedure)
+ OR (SELECT prosecdef FROM pg_proc WHERE oid = 'number_serial_units_for_completion(text,numeric,text)'::regprocedure)
OR NOT (SELECT prosecdef FROM pg_proc WHERE oid = 'dispatch_event_interceptors()'::regprocedure)
OR NOT (SELECT prosecdef FROM pg_proc WHERE oid = 'dispatch_event_after_interceptors()'::regprocedure) THEN
RAISE EXCEPTION 'FAIL: internal functions or dispatchers have the wrong security mode';
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 918ebcd9ae..e0c0cff190 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-22T11:44:59.436Z",
+ "exportedAt": "2026-10-22T12:52:40.069Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",