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): number unnumbered serial units at completion whatever the timing

Raula44ff4b6ed7a
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 52f772ff30..d560903ff8 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 (`moment: "release"`), 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`. Under `jobRelease` and `production` both completion paths call the SQL `number_serial_units_for_completion` (`20261021103400_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 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 for such a job (`getSerialCompleteChoice`, mode `numberOnReceipt`, for either deferred timing) and says the serials are drawn at receipt; under `jobCreation` 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`. `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` (`20261021103400_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.
- 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.server.ts b/apps/erp/app/modules/production/production.server.ts
index bfebd68049..6e9f1d1081 100644
--- a/apps/erp/app/modules/production/production.server.ts
+++ b/apps/erp/app/modules/production/production.server.ts
@@ -323,26 +323,12 @@ export const releaseCheckedJobs = defineServiceFn({
releasedJobIds.push(id);
// Under the jobRelease serial number timing (the item's, else the
- // company's) every unit is numbered now. Best-effort, as at creation.
- const releasedJob = await ctx.asSystem.pg
- .selectFrom("job")
- .select(["itemId"])
- .where("id", "=", id)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (releasedJob?.itemId) {
- await service.assignJobSerialNumbers(
- ctx.asSystem.supabase,
- ctx.asSystem.pg,
- {
- jobId: id,
- itemId: releasedJob.itemId,
- companyId,
- userId,
- moment: "release"
- }
- );
- }
+ // company's) every unit is numbered now. Best-effort: a failure is logged.
+ await service.assignJobSerialNumbersAtRelease(
+ ctx.asSystem.supabase,
+ ctx.asSystem.pg,
+ { jobId: id, companyId, userId }
+ );
const purchaseOrder = await invokeCreate(
{ db: ctx.asSystem.pg, companyId, userId },
@@ -909,10 +895,10 @@ export const completeJob = defineServiceFn({
const companyId = ctx.company.id;
const userId = ctx.auditUserId;
- // Under the release or production serial number timing the units this
- // completion takes may be unnumbered, or still one unsplit seed: the
- // receipt is their first touch, so split and number them before the RPC
- // receives them.
+ // The units this completion takes may be unnumbered, or still one unsplit
+ // seed (a deferred serial number timing, or a job left so when its timing
+ // changed): the receipt is their first touch, so split and number them
+ // before the RPC receives them.
try {
await service.numberSerialUnitsForCompletion(ctx.asSystem.pg, {
jobId,
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 8b762d3be6..6afce1ea90 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -3860,6 +3860,40 @@ export async function assignJobSerialNumbers(
}
}
+/**
+ * Number a job's units when `releaseCheckedJobs` releases it, under the
+ * `jobRelease` timing (the item's, else the company's). Best-effort: the job is
+ * already Ready, so a failure is logged and the release goes on; the units then
+ * draw their numbers at their first touch or at completion
+ * (`number_serial_units_for_completion`).
+ */
+export async function assignJobSerialNumbersAtRelease(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: { jobId: string; companyId: string; userId: string }
+) {
+ try {
+ const job = await db
+ .selectFrom("job")
+ .select(["itemId"])
+ .where("id", "=", args.jobId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!job?.itemId) return;
+ await assignJobSerialNumbers(client, db, {
+ ...args,
+ itemId: job.itemId,
+ moment: "release"
+ });
+ } catch (error) {
+ logger.error("Failed to number serial units at release", {
+ error,
+ jobId: args.jobId,
+ companyId: args.companyId
+ });
+ }
+}
+
/** The row write only; `updateJobDetails` also checks the job and recalculates it. */
export async function updateJob(
client: SupabaseClient<Database>,
@@ -12747,18 +12781,21 @@ export async function assignSerialNumbers(
}
/**
- * Receipt as first touch (the item's serial number timing is `jobRelease` or
- * `production`):
- * before `complete_job_to_inventory` takes `quantityComplete` units of a serial
- * job, split what it needs off the job's unsplit seed and number every unit it
- * takes. Without this an untouched job would be received as one unnumbered
- * entity holding every unit.
+ * Receipt as first touch: before `complete_job_to_inventory` takes
+ * `quantityComplete` units of a serial job, split what it needs off the job's
+ * unsplit seed and number every unit it takes. Without this an untouched job
+ * would be received as one unnumbered entity holding every unit.
+ *
+ * Under the `jobRelease` and `production` timings that is the normal case.
+ * Under `jobCreation` every unit is numbered at creation, so it numbers
+ * nothing, unless the job was created under another timing before the item or
+ * company switched back. The timing is not read here for that reason.
*
* The SQL `number_serial_units_for_completion` does the work, so this path and
* the `sync_finish_job_operation` interceptor (an operation marked Done) share
- * one implementation. It is a no-op under the default `jobCreation` timing, for
- * an item with no serial sequence, and when the job cannot cover the
- * completion. It commits on its own, before the RPC.
+ * one implementation. It is a no-op when every unit taken is numbered, for an
+ * item with no serial sequence, and when the job cannot cover the completion.
+ * It commits on its own, before the RPC.
*/
export async function numberSerialUnitsForCompletion(
db: Kysely<KyselyDatabase>,
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
index 93c38309dc..f9ba144d1d 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -88,7 +88,6 @@ import {
} from "~/hooks";
import { useCompanySettings } from "~/hooks/useCompanySettings";
import { usePullFromLocationIds } from "~/hooks/usePullFromLocationIds";
-import type { SerialNumberTiming } from "~/modules/settings/settings.models";
import type { action as cancelAction } from "~/routes/x+/job+/$jobId.cancel";
import type { action as completeAction } from "~/routes/x+/job+/$jobId.complete";
import type { action as statusAction } from "~/routes/x+/job+/$jobId.status";
@@ -1415,12 +1414,6 @@ function JobCompleteModal({
}) {
const { carbon } = useCarbon();
const { company } = useUser();
- // The company's serial number timing; an item's serial sequence can
- // override it (read with the job's data below).
- const companySerialNumberTiming =
- (useCompanySettings()?.serialNumberTiming as
- | SerialNumberTiming
- | undefined) ?? "jobCreation";
const [loading, setLoading] = useState(true);
const { t } = useLingui();
const [defaultStorageUnitId, setDefaultStorageUnitId] = useState<
@@ -1437,8 +1430,9 @@ function JobCompleteModal({
const [receivableSerials, setReceivableSerials] = useState<string[] | null>(
null
);
- // Under the jobRelease or production timing: how many units the completion can
- // still receive and number as it receives them. Null otherwise.
+ // For an item with a serial sequence whose units are not all numbered: how
+ // many units the completion can still receive and number as it receives
+ // them. Null otherwise.
const [unitsNumberedOnReceipt, setUnitsNumberedOnReceipt] = useState<
number | null
>(null);
@@ -1494,7 +1488,7 @@ function JobCompleteModal({
getJobReceipts(job?.id!),
carbon
.from("itemSerialSequence")
- .select("serialNumberTiming")
+ .select("id")
.eq("itemId", job?.itemId!)
.eq("companyId", company.id)
.maybeSingle()
@@ -1539,13 +1533,10 @@ function JobCompleteModal({
? getSerialCompleteChoice({
trackedEntities: trackedEntities.data,
receivedEntityIds: receipts ? receivedEntityIds : null,
- // The item's own timing, else the company's, as
- // getSerialNumberTiming resolves it on the server.
- serialNumberTiming:
- (serialSequence.data?.serialNumberTiming as
- | SerialNumberTiming
- | null
- | undefined) ?? companySerialNumberTiming,
+ // number_serial_units_for_completion numbers what the
+ // completion takes whenever the item has a sequence. A failed
+ // read keeps the quantity locked.
+ hasSerialSequence: !serialSequence.error && !!serialSequence.data,
jobQuantity: job?.quantity ?? 0
})
: ({ mode: "locked" } as const);
diff --git a/apps/erp/app/modules/production/ui/Jobs/job-complete-logic.ts b/apps/erp/app/modules/production/ui/Jobs/job-complete-logic.ts
index 48e3f1272b..b7f9d283dc 100644
--- a/apps/erp/app/modules/production/ui/Jobs/job-complete-logic.ts
+++ b/apps/erp/app/modules/production/ui/Jobs/job-complete-logic.ts
@@ -10,8 +10,6 @@
// works on the units the job has not received yet, so the dialog and the
// database always agree on which units a completion takes.
-import type { SerialNumberTiming } from "~/modules/settings/settings.models";
-
export type JobSerialUnit = {
id: string;
status: string;
@@ -84,15 +82,17 @@ export function getReceivableSerialUnits(
* How the Complete dialog lets the quantity be chosen for a serial job.
*
* - `serials`: every unit left to receive is a numbered single unit, so the
- * dialog lists the serials a completion takes (any timing).
- * - `numberOnReceipt`: the item's serial number timing (its own, else the
- * company's) is `jobRelease` or `production`, and some units are unnumbered,
- * still one unsplit seed, or held by no row yet. The completion numbers the
- * units it receives and creates the missing ones
+ * dialog lists the serials a completion takes.
+ * - `numberOnReceipt`: the item has a serial sequence and some units are
+ * unnumbered, still one unsplit seed, or held by no row yet. The completion
+ * numbers the units it receives and creates the missing ones
* (`number_serial_units_for_completion`), so the quantity can be chosen up to
- * `receivableCount` even though the serials cannot be named yet.
- * - `locked`: the quantity stays what the shop floor finished — the default
- * timing with unnumbered units, or receipts that could not be read.
+ * `receivableCount` even though the serials cannot be named yet. This does
+ * not depend on the serial number timing: a job left unnumbered by a timing
+ * that has since changed to `jobCreation` is numbered on receipt too.
+ * - `locked`: the quantity stays what the shop floor finished — unnumbered
+ * units of an item with no serial sequence, or receipts that could not be
+ * read.
*/
export type SerialCompleteChoice =
| { mode: "serials"; serials: string[] }
@@ -102,22 +102,22 @@ export type SerialCompleteChoice =
export function getSerialCompleteChoice({
trackedEntities,
receivedEntityIds,
- serialNumberTiming,
+ hasSerialSequence,
jobQuantity
}: {
trackedEntities: JobSerialUnit[];
/** Null when the job's receipts could not be read. */
receivedEntityIds: ReadonlySet<string> | null;
- serialNumberTiming: SerialNumberTiming;
+ /** Whether the item has a serial sequence the completion can draw from. */
+ hasSerialSequence: boolean;
jobQuantity: number;
}): SerialCompleteChoice {
// Without the receipts the dialog could offer a unit the job already
// received, whatever the timing.
if (!receivedEntityIds) return { mode: "locked" };
- // Under the default timing every unit was numbered when the job was created;
- // under the other two the completion numbers what it receives.
- const numbersOnReceipt = serialNumberTiming !== "jobCreation";
+ // With a sequence the completion numbers whatever it receives unnumbered.
+ const numbersOnReceipt = hasSerialSequence;
// The shop floor's first completion or scrap of an unsplit seed leaves it
// holding one unit and spawns the rest one at a time, so the rows can hold
diff --git a/apps/erp/test/database/serial-number-timing.test.ts b/apps/erp/test/database/serial-number-timing.test.ts
index c5ff5816e1..de1ddaa238 100644
--- a/apps/erp/test/database/serial-number-timing.test.ts
+++ b/apps/erp/test/database/serial-number-timing.test.ts
@@ -257,10 +257,17 @@ describe.skipIf(!client)("serial number timing", () => {
}
});
- it("leaves a job alone under the default timing", async () => {
+ it("leaves the units of an item with no serial sequence alone", async () => {
const f = await alwaysPostFixture();
try {
await serialSetup(f, "jobCreation");
+ await seed(f, async (trx) => {
+ await trx
+ .deleteFrom("itemSerialSequence")
+ .where("itemId", "=", f.assemblyId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ });
const job = await untouchedSerialJob(f, "3", 3);
const numbered = await numberSerialUnitsForCompletion(f.db, {
@@ -278,6 +285,34 @@ describe.skipIf(!client)("serial number timing", () => {
}
});
+ it("numbers a job left unnumbered when its timing changed back to job creation", async () => {
+ const f = await alwaysPostFixture();
+ try {
+ await stockPart(f, 20);
+ // Created under production, so its units are still one unnumbered seed.
+ await serialSetup(f, "production");
+ const job = await untouchedSerialJob(f, "3b", 3);
+ await itemTiming(f, "jobCreation");
+
+ // Through PostgREST, as the ERP and MES write it, so the interceptors run.
+ const done = await client!
+ .from("jobOperation")
+ .update({ status: "Done" })
+ .eq("id", job.operationId)
+ .eq("companyId", f.companyId);
+ expect(done.error).toBeNull();
+
+ expect(await receivedUnits(f, job.jobId)).toEqual([
+ { readableId: "SN-001", quantity: 1 },
+ { readableId: "SN-002", quantity: 1 },
+ { readableId: "SN-003", quantity: 1 }
+ ]);
+ expect(await units(f, job.makeMethodId)).toHaveLength(3);
+ } finally {
+ await f.cleanup();
+ }
+ });
+
it("spends no number when the job cannot cover the completion", async () => {
const f = await alwaysPostFixture();
try {
@@ -509,7 +544,7 @@ describe.skipIf(!client)("serial number timing", () => {
).toEqual({ numbered: 2 });
// The company numbers at production; this item at creation, so the
- // completion leaves its units to the creation path.
+ // job's units are numbered when it is created.
await seed(f, async (trx) => {
await trx
.updateTable("companySettings")
@@ -519,13 +554,21 @@ describe.skipIf(!client)("serial number timing", () => {
});
await itemTiming(f, "jobCreation");
const second = await untouchedSerialJob(f, "10", 2);
+ await assignJobSerialNumbers(client!, f.db, {
+ jobId: second.jobId,
+ itemId: f.assemblyId,
+ companyId: f.companyId,
+ userId: USER
+ });
+ const numberedAtCreation = await units(f, second.makeMethodId);
expect(
- await numberSerialUnitsForCompletion(f.db, {
- jobId: second.jobId,
- quantityComplete: 2,
- companyId: f.companyId
- })
- ).toEqual({ numbered: 0 });
+ numberedAtCreation
+ .map((unit) => [unit.readableId, Number(unit.quantity)])
+ .sort()
+ ).toEqual([
+ ["SN-003", 1],
+ ["SN-004", 1]
+ ]);
} finally {
await f.cleanup();
}
diff --git a/apps/erp/test/job-complete-logic.test.ts b/apps/erp/test/job-complete-logic.test.ts
index 60756287eb..6870f6fb9c 100644
--- a/apps/erp/test/job-complete-logic.test.ts
+++ b/apps/erp/test/job-complete-logic.test.ts
@@ -171,37 +171,37 @@ describe("getSerialCompleteChoice", () => {
const seed = unit({ id: "seed", quantity: 3 });
const none = new Set<string>();
- it("lists the serials when every unit left is numbered, under either timing", () => {
+ it("lists the serials when every unit left is numbered, with or without a sequence", () => {
const units = [unit({ readableId: "SN-0001" }), unit({ readableId: "SN-0002" })];
- for (const serialNumberTiming of ["jobCreation", "production"] as const) {
+ for (const hasSerialSequence of [false, true]) {
expect(
getSerialCompleteChoice({
trackedEntities: units,
receivedEntityIds: none,
- serialNumberTiming,
+ hasSerialSequence,
jobQuantity: 2
})
).toEqual({ mode: "serials", serials: ["SN-0001", "SN-0002"] });
}
});
- it("stays locked for an unsplit seed under the default timing", () => {
+ it("stays locked for an unsplit seed when the item has no serial sequence", () => {
expect(
getSerialCompleteChoice({
trackedEntities: [seed],
receivedEntityIds: none,
- serialNumberTiming: "jobCreation",
+ hasSerialSequence: false,
jobQuantity: 3
})
).toEqual({ mode: "locked" });
});
- it("unlocks an unsplit seed when serials are numbered at production", () => {
+ it("unlocks an unsplit seed when the item has a serial sequence", () => {
expect(
getSerialCompleteChoice({
trackedEntities: [seed],
receivedEntityIds: none,
- serialNumberTiming: "production",
+ hasSerialSequence: true,
jobQuantity: 3
})
).toEqual({ mode: "numberOnReceipt", receivableCount: 3 });
@@ -219,7 +219,7 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: units,
receivedEntityIds: new Set(["received"]),
- serialNumberTiming: "production",
+ hasSerialSequence: true,
jobQuantity: 4
})
).toEqual({ mode: "numberOnReceipt", receivableCount: 2 });
@@ -227,7 +227,7 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: units,
receivedEntityIds: new Set(["received"]),
- serialNumberTiming: "jobCreation",
+ hasSerialSequence: false,
jobQuantity: 4
})
).toEqual({ mode: "locked" });
@@ -238,7 +238,7 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: [seed],
receivedEntityIds: null,
- serialNumberTiming: "production",
+ hasSerialSequence: true,
jobQuantity: 3
})
).toEqual({ mode: "locked" });
@@ -249,7 +249,7 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: [unit({ id: "received", status: "Available" })],
receivedEntityIds: new Set(["received"]),
- serialNumberTiming: "production",
+ hasSerialSequence: true,
jobQuantity: 1
})
).toEqual({ mode: "locked" });
@@ -265,7 +265,7 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: units,
receivedEntityIds: none,
- serialNumberTiming: "production",
+ hasSerialSequence: true,
jobQuantity: 3
})
).toEqual({ mode: "numberOnReceipt", receivableCount: 3 });
@@ -273,13 +273,13 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: units,
receivedEntityIds: none,
- serialNumberTiming: "jobCreation",
+ hasSerialSequence: false,
jobQuantity: 3
})
).toEqual({ mode: "locked" });
});
- it("does not list the serials while units are still missing at production", () => {
+ it("does not list the serials while units are still missing", () => {
const units = [
unit({ id: "done", status: "Available", readableId: "SN-0001" }),
unit({ id: "started", status: "Reserved", readableId: "SN-0002" })
@@ -288,7 +288,7 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: units,
receivedEntityIds: none,
- serialNumberTiming: "production",
+ hasSerialSequence: true,
jobQuantity: 3
})
).toEqual({ mode: "numberOnReceipt", receivableCount: 3 });
@@ -296,7 +296,7 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: units,
receivedEntityIds: none,
- serialNumberTiming: "jobCreation",
+ hasSerialSequence: false,
jobQuantity: 3
})
).toEqual({ mode: "serials", serials: ["SN-0001", "SN-0002"] });
@@ -311,19 +311,20 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: units,
receivedEntityIds: none,
- serialNumberTiming: "production",
+ hasSerialSequence: true,
jobQuantity: 3
})
).toEqual({ mode: "numberOnReceipt", receivableCount: 3 });
});
- it("numbers on receipt under the release timing, as under production", () => {
- // A job completed before it was released still holds its unsplit seed.
+ it("numbers on receipt a seed left by a timing that changed back to job creation", () => {
+ // Created under a deferred timing, the job still holds its unsplit seed
+ // after the item switched to jobCreation: only the receipt can number it.
expect(
getSerialCompleteChoice({
trackedEntities: [seed],
receivedEntityIds: none,
- serialNumberTiming: "jobRelease",
+ hasSerialSequence: true,
jobQuantity: 3
})
).toEqual({ mode: "numberOnReceipt", receivableCount: 3 });
@@ -339,7 +340,7 @@ describe("getSerialCompleteChoice", () => {
getSerialCompleteChoice({
trackedEntities: units,
receivedEntityIds: none,
- serialNumberTiming: "jobRelease",
+ hasSerialSequence: true,
jobQuantity: 3
})
).toEqual({ mode: "serials", serials: ["SN-0001", "SN-0002", "SN-0003"] });
diff --git a/apps/erp/test/job-lifecycle.test.ts b/apps/erp/test/job-lifecycle.test.ts
index 6bdfa691d7..32a0af45a2 100644
--- a/apps/erp/test/job-lifecycle.test.ts
+++ b/apps/erp/test/job-lifecycle.test.ts
@@ -58,6 +58,8 @@ vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {
vi.mock("@carbon/planning", () => ({ runLocationSchedule: vi.fn() }));
vi.mock("../app/modules/production/production.service", async (importOriginal) => ({
...(await importOriginal<object>()),
+ // The SQL numbering needs a database; serial-number-timing.test.ts covers it.
+ numberSerialUnitsForCompletion: vi.fn(async () => ({ numbered: 0 })),
recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),
runMRP: vi.fn(async () => ({ data: null, error: null })),
returnPickedRemaindersForJob: vi.fn(async () => ({ data: {}, error: null })),
diff --git a/apps/erp/test/release-jobs.test.ts b/apps/erp/test/release-jobs.test.ts
index 838c07dfe9..c3c3a15dbc 100644
--- a/apps/erp/test/release-jobs.test.ts
+++ b/apps/erp/test/release-jobs.test.ts
@@ -61,6 +61,7 @@ vi.mock("@carbon/planning", () => ({
}));
vi.mock("../app/modules/production/production.service", async (importOriginal) => ({
...(await importOriginal<object>()),
+ assignJobSerialNumbersAtRelease: vi.fn(async () => {}),
getJobReleaseReadiness: vi.fn(),
recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),
runMRP: vi.fn(async () => ({ data: null, error: null })),
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.sql
index 21260e271d..0bd851ad0b 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
@@ -124,9 +124,10 @@ BEGIN
-- received, and refusing here would block the Done update itself.
v_quantity_complete := GREATEST(v_quantity_complete, COALESCE(v_quantity_received, 0));
- -- Under serialNumberTiming = 'production' the units this completion takes
- -- may be unnumbered, or still one unsplit seed: the receipt is their first
- -- touch, so split and number them first, as completeJob does.
+ -- The units this completion takes may be unnumbered, or still one unsplit
+ -- seed (a deferred serial number timing, or a job left so when its timing
+ -- changed): the receipt is their first touch, so split and number them
+ -- first, as completeJob does.
PERFORM number_serial_units_for_completion(
p_new->>'jobId',
v_quantity_complete,
diff --git a/packages/database/supabase/migrations/20261021103400_serial-number-timing-completion.sql b/packages/database/supabase/migrations/20261021103400_serial-number-timing-completion.sql
index b2d6e57ed2..2c42761f35 100644
--- a/packages/database/supabase/migrations/20261021103400_serial-number-timing-completion.sql
+++ b/packages/database/supabase/migrations/20261021103400_serial-number-timing-completion.sql
@@ -3,9 +3,13 @@
-- Under the 'production' timing a job's units stay unnumbered until they are
-- first touched, and the completion that receives them is a first touch. Under
-- 'jobRelease' they are numbered at release, so the completion only numbers what
--- release did not (a job completed before release, or units added since). The
--- timing is the item's serial sequence's, else the company's. Both completion paths call number_serial_units_for_completion
--- before complete_job_to_inventory: the ERP's completeJob, and the
+-- release did not (a job completed before release, or units added since). Under
+-- 'jobCreation' every unit is numbered at creation, so it numbers nothing, unless
+-- a job still holds unnumbered units: one created under another timing before
+-- the item or company switched back. The completion numbers whatever it takes
+-- unnumbered, whatever the timing. Both completion paths call
+-- number_serial_units_for_completion before complete_job_to_inventory: the
+-- ERP's completeJob, and the
-- sync_finish_job_operation interceptor when the last operation is marked Done.
-- It splits what the completion takes off the job's unsplit seed and numbers
-- every unit it takes, so the receipt never takes one unnumbered entity holding
@@ -114,10 +118,12 @@ $function$;
-- Receipt as first touch. Takes the units complete_job_to_inventory will take
-- for p_quantity_complete, in its own order (the receipt branch, or the Make to
-- Asset branch), splits what is missing off the unsplit seed and numbers every
--- unit taken. Returns how many numbers it drew. Writes nothing when the timing
--- is 'jobCreation', the item is not serial-tracked or has no sequence, or the
--- job cannot cover the completion (the completion then refuses with its own
--- message).
+-- unit taken. Returns how many numbers it drew. Writes nothing when every unit
+-- taken is already numbered, the item is not serial-tracked or has no sequence,
+-- or the job cannot cover the completion (the completion then refuses with its
+-- own message). It does not read the serial number timing: a job left
+-- unnumbered by a timing that has since changed to 'jobCreation' is numbered
+-- here too, rather than received as one unnumbered entity.
--
-- A unit can also have no row at all. The shop floor's first completion or
-- scrap of the seed leaves it holding one unit and adds the next units one at a
@@ -137,7 +143,6 @@ AS $function$
DECLARE
v_job record;
v_make_method record;
- v_timing text;
v_delta numeric;
v_target text;
v_taken text[];
@@ -166,21 +171,14 @@ BEGIN
IF NOT FOUND OR v_job."itemTrackingType" IS DISTINCT FROM 'Serial' THEN
RETURN 0;
END IF;
- SELECT "serialNumberTiming"
- INTO v_timing
+ -- An item with no sequence has nothing to draw from: the completion takes
+ -- its units as it always has.
+ PERFORM 1
FROM "itemSerialSequence"
WHERE "itemId" = v_job."itemId" AND "companyId" = p_company_id;
IF NOT FOUND THEN
RETURN 0;
END IF;
- -- Under 'jobCreation' every unit was numbered when the job was created.
- IF COALESCE(
- v_timing,
- (SELECT "serialNumberTiming" FROM "companySettings" WHERE "id" = p_company_id),
- 'jobCreation'
- ) = 'jobCreation' THEN
- RETURN 0;
- END IF;
SELECT "id", "requiresSerialTracking"
INTO v_make_method
diff --git a/packages/database/supabase/migrations/20261021103500_serial-number-timing-finish-operation.sql b/packages/database/supabase/migrations/20261021103500_serial-number-timing-finish-operation.sql
index a77cc6f2e8..9197ecfaa0 100644
--- a/packages/database/supabase/migrations/20261021103500_serial-number-timing-finish-operation.sql
+++ b/packages/database/supabase/migrations/20261021103500_serial-number-timing-finish-operation.sql
@@ -128,9 +128,10 @@ BEGIN
-- received, and refusing here would block the Done update itself.
v_quantity_complete := GREATEST(v_quantity_complete, COALESCE(v_quantity_received, 0));
- -- Under serialNumberTiming = 'production' the units this completion takes
- -- may be unnumbered, or still one unsplit seed: the receipt is their first
- -- touch, so split and number them first, as completeJob does.
+ -- The units this completion takes may be unnumbered, or still one unsplit
+ -- seed (a deferred serial number timing, or a job left so when its timing
+ -- changed): the receipt is their first touch, so split and number them
+ -- first, as completeJob does.
PERFORM number_serial_units_for_completion(
p_new->>'jobId',
v_quantity_complete,