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
feat(production): number serial units on every completion path, and unlock the Complete dialog
Raul90c12097238d
diff --git a/apps/erp/app/hooks/useCompanySettings.tsx b/apps/erp/app/hooks/useCompanySettings.tsxindex 8b5ef5d019..d718bce612 100644--- a/apps/erp/app/hooks/useCompanySettings.tsx+++ b/apps/erp/app/hooks/useCompanySettings.tsx@@ -28,6 +28,7 @@ type CompanySettings = Partial<| "digitalQuoteIncludesPurchaseOrders"| "mrpRunTime"| "requireBackflushStorageUnit"+ | "serialNumberTiming"| "showBomExplorerReadableId"| "showCurrencyTrailingZeros"| "showCustomerReadableId"diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 359f27a5b2..199fe68ff4 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -23356,8 +23356,14 @@ export async function issueMaterial(.executeTakeFirst();const capacity = Number(updatedOperation?.operationQuantity ?? 0);if (existingEntityCount < capacity) {+ // Under serialNumberTiming = 'production' the replacement stays+ // unnumbered until it is first touched.let spawnReadableId: string | null = null;- if (makeMethod.itemId) {+ if (+ makeMethod.itemId &&+ (await sequence.getSerialNumberTiming(trx, companyId)) !==+ "production"+ ) {let locationCode: string | null = null;let locationName: string | null = null;if (job.locationId) {@@ -24352,13 +24358,19 @@ export async function issueMaterial(locationCode = loc.data?.code ?? null;locationName = loc.data?.name ?? null;}- const spawnSerials = await sequence.getNextSerialNumbers(trx, {- itemId: subMakeMethod.itemId,- companyId,- count: 1,- locationCode,- locationName- });+ // Under serialNumberTiming = 'production' the replacement stays+ // unnumbered until it is first touched.+ const spawnSerials =+ (await sequence.getSerialNumberTiming(trx, companyId)) ===+ "production"+ ? []+ : await sequence.getNextSerialNumbers(trx, {+ itemId: subMakeMethod.itemId,+ companyId,+ count: 1,+ locationCode,+ locationName+ });await trx.insertInto("trackedEntity").values({diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 8f7909011f..99b2fcd9e8 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). `jobCreation` (default): `assignJobSerialNumbers` splits and numbers every unit when the job is created. `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 ERP completion. A unit the serial completion spawns stays unnumbered under `production`. `completeJob` runs `numberSerialUnitsForCompletion` before the RPC: it plans with `planSerialUnitsForCompletion` (the RPC's receipt or Make to Asset order), splits what the completion needs off the seed and numbers every unit it takes, so the RPC never receives an unnumbered lump. The `sync_finish_job_operation` path (an operation marked Done) calls the RPC from SQL and does not run it.+- **Serial number timing** (`companySettings.serialNumberTiming`, Settings → Production → Serial Numbers). `jobCreation` (default): `assignJobSerialNumbers` splits and numbers every unit when the job is created. `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 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. 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`) and says the serials are drawn at receipt; under `jobCreation` 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 timediff --git a/apps/erp/app/modules/production/production.service.test.ts b/apps/erp/app/modules/production/production.service.test.tsindex 1261aaa45a..2aa74add90 100644--- a/apps/erp/app/modules/production/production.service.test.ts+++ b/apps/erp/app/modules/production/production.service.test.ts@@ -37,8 +37,7 @@ const {planOrphanStepAdoption,maxToolQuantityByItem,buildAssemblyToolStepLinks,- duplicateJobOperationStep,- planSerialUnitsForCompletion+ duplicateJobOperationStep} = await import("./production.service");// ── Assembly → BoP sync: marker reconciliation ───────────────────────────────@@ -493,116 +492,3 @@ describe("duplicateJobOperationStep", () => {expect(inserts.some((i) => i.table === "jobMaterialStep")).toBe(false);});});--// ── Serial numbers at production: what a completion takes ───────────────────-describe("planSerialUnitsForCompletion", () => {- type Unit = Parameters<typeof planSerialUnitsForCompletion>[0][number];- const unit = (overrides: Partial<Unit> & { id: string }): Unit => ({- status: "Reserved",- quantity: 1,- readableId: null,- createdAt: "2026-10-19T09:00:00.000Z",- received: false,- bookedOut: false,- fixedAsset: false,- ...overrides- });-- it("splits an untouched seed into numbered units for a partial completion", () => {- const plan = planSerialUnitsForCompletion(- [unit({ id: "seed", quantity: 5 })],- 2,- "receipt"- );- expect(plan).toEqual({- numberUnitIds: [],- split: {- seedId: "seed",- seedQuantity: 5,- seedReadableId: null,- newUnits: 2,- seedBecomesUnit: false- }- });- });-- it("turns the seed itself into the last unit when the completion takes all of it", () => {- const plan = planSerialUnitsForCompletion(- [unit({ id: "seed", quantity: 3 })],- 3,- "receipt"- );- expect(plan?.split).toMatchObject({ newUnits: 2, seedBecomesUnit: true });- });-- it("takes finished units first and numbers only the unnumbered ones it takes", () => {- const plan = planSerialUnitsForCompletion(- [- unit({ id: "done-numbered", status: "Available", readableId: "SN-1" }),- unit({ id: "done-blank", status: "Available" }),- unit({ id: "waiting", status: "Reserved" })- ],- 2,- "receipt"- );- expect(plan).toEqual({ numberUnitIds: ["done-blank"], split: null });- });-- it("does nothing when every unit it takes is numbered", () => {- expect(- planSerialUnitsForCompletion(- [- unit({ id: "a", status: "Available", readableId: "SN-1" }),- unit({ id: "b", status: "Reserved" })- ],- 1,- "receipt"- )- ).toBeNull();- });-- it("skips received, scrapped and rejected units, and Consumed units never booked out", () => {- const plan = planSerialUnitsForCompletion(- [- unit({ id: "received", status: "Available", received: true }),- unit({ id: "scrapped", status: "Scrapped" }),- unit({ id: "rejected", status: "Rejected" }),- unit({ id: "consumed-in-place", status: "Consumed" }),- unit({ id: "issued", status: "Consumed", bookedOut: true }),- unit({ id: "next", status: "Reserved" })- ],- 2,- "receipt"- );- expect(plan).toEqual({ numberUnitIds: ["issued", "next"], split: null });- });-- it("refuses to plan when even the seed cannot cover the completion", () => {- expect(- planSerialUnitsForCompletion(- [unit({ id: "seed", quantity: 2 })],- 3,- "receipt"- )- ).toBeNull();- });-- it("uses the Make to Asset order: no Consumed units, none already an asset", () => {- const plan = planSerialUnitsForCompletion(- [- unit({ id: "issued", status: "Consumed", bookedOut: true }),- unit({ id: "asset", status: "Available", fixedAsset: true }),- unit({ id: "free", status: "Reserved" })- ],- 1,- "asset"- );- expect(plan).toEqual({ numberUnitIds: ["free"], split: null });- });-- it("ignores a fractional or non-positive completion", () => {- const units = [unit({ id: "seed", quantity: 4 })];- expect(planSerialUnitsForCompletion(units, 0, "receipt")).toBeNull();- expect(planSerialUnitsForCompletion(units, 1.5, "receipt")).toBeNull();- });-});diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 703d01c4a9..00d5edd97b 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -73,7 +73,6 @@ import {updateRows} from "@carbon/database/rows";import {- getEntityJobLocation,getNextRevisionSequence,getNextSequence,getNextSerialNumbers,@@ -12735,118 +12734,6 @@ export async function assignSerialNumbers(});}-/** A unit of a job's root make method, as a completion sees it. */-export type CompletionSerialUnit = {- id: string;- status: string;- quantity: number;- readableId: string | null;- createdAt: string;- /** Has a `Job Receipt` ledger row for this job. */- received: boolean;- /** Booked out of stock (a negative ledger row): issued before its receipt. */- bookedOut: boolean;- /** Already turned into a fixed asset. */- fixedAsset: boolean;-};--export type CompletionSerialPlan = {- /** Existing single units that this completion takes and that have no number. */- numberUnitIds: string[];- /**- * Units to split off the unsplit seed: `newUnits` new single units, plus the- * seed itself when the completion takes all of it (`seedBecomesUnit`).- */- split: {- seedId: string;- seedQuantity: number;- seedReadableId: string | null;- newUnits: number;- seedBecomesUnit: boolean;- } | null;-};--/**- * Which units a completion of `delta` units will take, in the order- * `complete_job_to_inventory` takes them (the receipt branch, or the Make to- * Asset branch for a job that completes to a fixed asset), and which of them- * still need a number or a split. Pure: `numberSerialUnitsForCompletion` reads- * the units and applies the plan.- *- * Null when there is nothing to do, or when the job cannot cover `delta` even- * after splitting its seed: the completion then refuses with its own message- * and no number is spent.- */-export function planSerialUnitsForCompletion(- units: CompletionSerialUnit[],- delta: number,- target: "receipt" | "asset"-): CompletionSerialPlan | null {- if (!Number.isInteger(delta) || delta <= 0) return null;-- const takeable = units.filter((unit) => {- if (unit.quantity !== 1) return false;- if (target === "asset") {- return (- !["Consumed", "Rejected", "Scrapped"].includes(unit.status) &&- !unit.fixedAsset- );- }- if (unit.received) return false;- if (unit.status === "Consumed") return unit.bookedOut;- return !["Rejected", "Scrapped"].includes(unit.status);- });-- const rank = (status: string) =>- status === "Available" || (target === "receipt" && status === "Consumed")- ? 0- : status === "Reserved"- ? 1- : 2;- // Numbered before unnumbered within a rank, as the RPC's `readableId NULLS- // LAST`. Once this plan numbers a unit it sorts ahead of every unnumbered- // one of its rank, so the RPC takes the same units.- const ordered = [...takeable].sort(- (a, b) =>- rank(a.status) - rank(b.status) ||- Number(a.readableId === null) - Number(b.readableId === null) ||- (a.readableId ?? "").localeCompare(b.readableId ?? "") ||- a.createdAt.localeCompare(b.createdAt) ||- a.id.localeCompare(b.id)- );-- const taken = ordered.slice(0, delta);- const numberUnitIds = taken- .filter((unit) => unit.readableId === null)- .map((unit) => unit.id);-- const short = delta - taken.length;- if (short === 0) {- return numberUnitIds.length > 0 ? { numberUnitIds, split: null } : null;- }-- const seed = units- .filter(- (unit) =>- unit.quantity > 1 &&- !["Consumed", "Rejected", "Scrapped"].includes(unit.status)- )- .sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];- if (!seed || seed.quantity < short) return null;-- const seedBecomesUnit = seed.quantity === short;- return {- numberUnitIds,- split: {- seedId: seed.id,- seedQuantity: seed.quantity,- seedReadableId: seed.readableId,- newUnits: seedBecomesUnit ? short - 1 : short,- seedBecomesUnit- }- };-}-/*** Receipt as first touch (`companySettings.serialNumberTiming = 'production'`):* before `complete_job_to_inventory` takes `quantityComplete` units of a serial@@ -12854,189 +12741,24 @@ export function planSerialUnitsForCompletion(* takes. Without this an untouched job would be received as one unnumbered* entity holding every unit.*- * No-op under the default `jobCreation` timing (every unit is numbered at- * creation), for an item with no serial sequence (its job keeps one seed by- * design), and when nothing taken is missing a number. Commits on its own, before- * the RPC: a completion the RPC then refuses for another reason keeps the units- * it split and numbered, which are the job's next units either way.+ * 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.*/export async function numberSerialUnitsForCompletion(db: Kysely<KyselyDatabase>,args: { jobId: string; quantityComplete: number; companyId: string }): Promise<{ numbered: number }> {- const { jobId, quantityComplete, companyId } = args;- return db.transaction().execute(async (trx) => {- if ((await getSerialNumberTiming(trx, companyId)) !== "production") {- return { numbered: 0 };- }-- const job = await trx- .selectFrom("job")- .innerJoin("item", "item.id", "job.itemId")- .leftJoin("itemSerialSequence", (join) =>- join- .onRef("itemSerialSequence.itemId", "=", "job.itemId")- .onRef("itemSerialSequence.companyId", "=", "job.companyId")- )- .innerJoin("jobMakeMethod", (join) =>- join- .onRef("jobMakeMethod.jobId", "=", "job.id")- .on("jobMakeMethod.parentMaterialId", "is", null)- )- .select([- "job.itemId",- "job.quantityReceivedToInventory",- "job.fixedAssetClassId",- "job.fixedAssetId",- "item.itemTrackingType",- "itemSerialSequence.id as sequenceId",- "jobMakeMethod.id as makeMethodId",- "jobMakeMethod.requiresSerialTracking"- ])- .where("job.id", "=", jobId)- .where("job.companyId", "=", companyId)- .executeTakeFirst();- if (- !job ||- job.itemTrackingType !== "Serial" ||- !job.requiresSerialTracking ||- !job.sequenceId- ) {- return { numbered: 0 };- }-- const delta =- quantityComplete - Number(job.quantityReceivedToInventory ?? 0);- const entities = await trx- .selectFrom("trackedEntity")- .select([- "id",- "status",- "quantity",- "readableId",- "createdAt",- "attributes"- ])- .where("companyId", "=", companyId)- .where(sql<boolean>`attributes->>'Job Make Method' = ${job.makeMethodId}`)- .forUpdate()- .execute();- if (entities.length === 0) return { numbered: 0 };-- const ids = entities.map((entity) => entity.id);- const ledger = await trx- .selectFrom("itemLedger")- .select([- "trackedEntityId",- sql<boolean>`bool_or("documentType" = 'Job Receipt' AND "documentId" = ${jobId})`.as(- "received"- ),- sql<boolean>`bool_or(quantity < 0)`.as("bookedOut")- ])- .where("companyId", "=", companyId)- .where("trackedEntityId", "in", ids)- .groupBy("trackedEntityId")- .execute();- const ledgerByEntity = new Map(- ledger.map((row) => [row.trackedEntityId, row])- );-- const plan = planSerialUnitsForCompletion(- entities.map((entity) => ({- id: entity.id,- status: entity.status,- quantity: Number(entity.quantity),- readableId: entity.readableId,- createdAt: String(entity.createdAt),- received: ledgerByEntity.get(entity.id)?.received === true,- bookedOut: ledgerByEntity.get(entity.id)?.bookedOut === true,- fixedAsset:- (entity.attributes as Record<string, unknown> | null)?.[- "Fixed Asset"- ] !== undefined- })),- delta,- job.fixedAssetClassId || job.fixedAssetId ? "asset" : "receipt"- );- if (!plan) return { numbered: 0 };-- const split = plan.split;- const numberSeed =- split?.seedBecomesUnit === true && split.seedReadableId === null;- const count =- plan.numberUnitIds.length + (split?.newUnits ?? 0) + (numberSeed ? 1 : 0);- const serials = await getNextSerialNumbers(trx, {- itemId: job.itemId,- companyId,- count,- ...(await getEntityJobLocation(trx, { Job: jobId }, companyId))- });- if (serials.length < count) return { numbered: 0 };-- const toNumber = [...plan.numberUnitIds];- if (numberSeed && split) toNumber.push(split.seedId);- const numberedSerials = serials.slice(0, toNumber.length);- const newSerials = serials.slice(toNumber.length);-- if (toNumber.length > 0) {- await sql`- UPDATE "trackedEntity" AS te- SET "readableId" = v.serial- FROM (VALUES ${sql.join(- toNumber.map((id, index) => sql`(${id}, ${numberedSerials[index]})`)- )}) AS v(id, serial)- WHERE te.id = v.id- AND te."companyId" = ${companyId}- AND te."readableId" IS NULL- `.execute(trx);- }-- if (split) {- const seed = entities.find((entity) => entity.id === split.seedId)!;- const fullSeed = await trx- .selectFrom("trackedEntity")- .selectAll()- .where("id", "=", split.seedId)- .where("companyId", "=", companyId)- .executeTakeFirstOrThrow();- await trx- .updateTable("trackedEntity")- .set({- quantity: split.seedBecomesUnit- ? 1- : Number(seed.quantity) - split.newUnits- })- .where("id", "=", split.seedId)- .where("companyId", "=", companyId)- .execute();- if (newSerials.length > 0) {- // One millisecond apart, after every existing unit: `createdAt` is the- // unit axis step records are indexed by (see assignSerialNumbers), so- // the new units take the next positions and no existing unit moves.- await trx- .insertInto("trackedEntity")- .values(- newSerials.map((readableId, offset) => ({- createdAt: sql<string>`now() + ${offset + 1}::int * interval '1 millisecond'`,- sourceDocument: fullSeed.sourceDocument,- sourceDocumentId: fullSeed.sourceDocumentId,- sourceDocumentReadableId: fullSeed.sourceDocumentReadableId,- quantity: 1,- status: fullSeed.status,- attributes: fullSeed.attributes,- itemId: fullSeed.itemId ?? null,- expirationDate: fullSeed.expirationDate ?? null,- readableId,- companyId,- createdBy: fullSeed.createdBy- }))- )- .execute();- }- }-- return { numbered: count };- });+ const result = await sql<{ numbered: number }>`+ SELECT number_serial_units_for_completion(+ ${args.jobId},+ ${args.quantityComplete}::numeric,+ ${args.companyId}+ ) AS numbered+ `.execute(db);+ return { numbered: Number(result.rows[0]?.numbered ?? 0) };}const sandboxLogger = getLogger("erp", "configuration-rule");diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsxindex 55a4f26be2..0d91754b32 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx@@ -101,7 +101,7 @@ import JobStatus from "./JobStatus";import {getDefaultSerialCompleteQuantity,getFinishedUnreceivedQuantity,- getReceivableSerialUnits,+ getSerialCompleteChoice,type JobReceiptSnapshot} from "./job-complete-logic";import {@@ -1414,6 +1414,10 @@ function JobCompleteModal({}) {const { carbon } = useCarbon();const { company } = useUser();+ const serialNumberTiming =+ useCompanySettings()?.serialNumberTiming === "production"+ ? "production"+ : "jobCreation";const [loading, setLoading] = useState(true);const { t } = useLingui();const [defaultStorageUnitId, setDefaultStorageUnitId] = useState<@@ -1430,6 +1434,11 @@ function JobCompleteModal({const [receivableSerials, setReceivableSerials] = useState<string[] | null>(null);+ // Under serialNumberTiming = 'production': how many units the completion can+ // still receive and number as it receives them. Null otherwise.+ const [unitsNumberedOnReceipt, setUnitsNumberedOnReceipt] = useState<+ number | null+ >(null);// The completed quantity is cumulative; this much was already received.// Refreshed when the dialog opens, since the route's job may be stale.const [priorReceivedQuantity, setPriorReceivedQuantity] = useState<number>(@@ -1457,7 +1466,7 @@ function JobCompleteModal({const hasLeftover = leftoverQuantity > 0;// Serial units are received one at a time; the database refuses a fraction.const hasFractionalSerialQuantity =- receivableSerials !== null &&+ (receivableSerials !== null || unitsNumberedOnReceipt !== null) &&Number.isFinite(quantityComplete) &&!Number.isInteger(quantityComplete);@@ -1514,17 +1523,30 @@ function JobCompleteModal({}, 0);const receivedEntityIds = new Set(receipts?.trackedEntityIds ?? []);- // Only unlock per-serial entry when the receipts are known: without them- // the list could offer a unit the job already received.- const serialUnits =- receipts && makeMethod.data?.requiresSerialTracking- ? getReceivableSerialUnits(trackedEntities.data, receivedEntityIds)- : null;-- if (serialUnits) {- // Every unit already exists as a numbered serial, so the quantity can- // be chosen here even when nothing was finished on the shop floor.- setReceivableSerials(serialUnits);+ // Only unlock the quantity when the receipts are known: without them+ // the dialog could offer a unit the job already received.+ const choice = makeMethod.data?.requiresSerialTracking+ ? getSerialCompleteChoice({+ trackedEntities: trackedEntities.data,+ receivedEntityIds: receipts ? receivedEntityIds : null,+ serialNumberTiming+ })+ : ({ mode: "locked" } as const);++ if (choice.mode !== "locked") {+ // Every unit is a numbered serial, or the completion numbers the+ // units it receives: either way the quantity can be chosen here even+ // when nothing was finished on the shop floor.+ const receivableCount =+ choice.mode === "serials"+ ? choice.serials.length+ : choice.receivableCount;+ setReceivableSerials(+ choice.mode === "serials" ? choice.serials : null+ );+ setUnitsNumberedOnReceipt(+ choice.mode === "numberOnReceipt" ? choice.receivableCount : null+ );setHasTrackedQuantity(false);setQuantityComplete(getDefaultSerialCompleteQuantity({@@ -1534,7 +1556,7 @@ function JobCompleteModal({),jobQuantity: job?.quantity ?? 0,priorReceivedQuantity: currentReceivedQuantity,- receivableSerialCount: serialUnits.length+ receivableSerialCount: receivableCount}));} else {@@ -1674,7 +1696,9 @@ function JobCompleteModal({maxValue={receivableSerials? priorReceivedQuantity + receivableSerials.length- : undefined+ : unitsNumberedOnReceipt !== null+ ? priorReceivedQuantity + unitsNumberedOnReceipt+ : undefined}helperText={hasTrackedQuantity@@ -1701,6 +1725,16 @@ function JobCompleteModal({</Alert>)}+ {unitsNumberedOnReceipt !== null &&+ quantityComplete > priorReceivedQuantity &&+ !hasFractionalSerialQuantity && (+ <span className="text-sm text-muted-foreground w-full">+ <Trans>+ Serial numbers are drawn when the units are received.+ </Trans>+ </span>+ )}+{receivableSerials &&quantityComplete > priorReceivedQuantity &&!hasFractionalSerialQuantity && (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.tsindex 29d6c24927..893eba1dc0 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@@ -78,6 +78,50 @@ export function getReceivableSerialUnits(.map((entity) => entity.readableId as string);}+/**+ * 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 (either timing).+ * - `numberOnReceipt`: the company numbers serials at production+ * (`serialNumberTiming = 'production'`) and some units are unnumbered or+ * still one unsplit seed. The completion numbers the units it receives+ * (`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.+ */+export type SerialCompleteChoice =+ | { mode: "serials"; serials: string[] }+ | { mode: "numberOnReceipt"; receivableCount: number }+ | { mode: "locked" };++export function getSerialCompleteChoice({+ trackedEntities,+ receivedEntityIds,+ serialNumberTiming+}: {+ trackedEntities: JobSerialUnit[];+ /** Null when the job's receipts could not be read. */+ receivedEntityIds: ReadonlySet<string> | null;+ serialNumberTiming: "jobCreation" | "production";+}): SerialCompleteChoice {+ // Without the receipts the dialog could offer a unit the job already+ // received, whatever the timing.+ if (!receivedEntityIds) return { mode: "locked" };++ const serials = getReceivableSerialUnits(trackedEntities, receivedEntityIds);+ if (serials) return { mode: "serials", serials };+ if (serialNumberTiming !== "production") return { mode: "locked" };++ const receivableCount = trackedEntities+ .filter((entity) => isUnreceived(entity, receivedEntityIds))+ .reduce((total, entity) => total + Number(entity.quantity), 0);+ return receivableCount > 0+ ? { mode: "numberOnReceipt", receivableCount }+ : { mode: "locked" };+}+/** Units finished on the shop floor that the job has not received yet. */export function getFinishedUnreceivedQuantity(trackedEntities: JobSerialUnit[],diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 93646700c1..c94c341b0a 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1520,7 +1520,7 @@{"name":"settings_getApiKeys","classification":"WRITE","schema":"cd40ae40fad5","response":"14fbafc2ddf8","permission":"users:update","paginates":true},{"name":"settings_getCompanies","classification":"READ","schema":"31b84d65b2ac","response":"5783a32e0f4a","permission":"settings:view","paginates":false},{"name":"settings_getCompany","classification":"READ","schema":"31b84d65b2ac","response":"81a93f0029ec","permission":"settings:view","paginates":false},- {"name":"settings_getCompanySettings","classification":"READ","schema":"31b84d65b2ac","response":"dfb93f1739df","permission":"settings:view","paginates":false},+ {"name":"settings_getCompanySettings","classification":"READ","schema":"31b84d65b2ac","response":"60f2d2fca190","permission":"settings:view","paginates":false},{"name":"settings_getConfig","classification":"READ","schema":"31b84d65b2ac","response":"aa1021ff34cf","permission":"settings:view","paginates":false},{"name":"settings_getCurrentSequence","classification":"READ","schema":"31018ffa701d","response":"00404e686415","permission":"settings:view","paginates":false},{"name":"settings_getCustomField","classification":"READ","schema":"7f8214d1083f","response":"a533a796c094","permission":"settings:view","paginates":false},@@ -1562,7 +1562,7 @@{"name":"settings_updateItemsSettings","classification":"WRITE","schema":"b4f7e7addad9","response":"03604adb2677","permission":"settings:update","paginates":false},{"name":"settings_updatePlanningSettings","classification":"WRITE","schema":"0c543ed217a3","response":"0b9572e63423","permission":"settings:update","paginates":false},{"name":"settings_updatePostingSync","classification":"WRITE","schema":"a545e3ef8da3","response":"f95fa90d0071","permission":"settings:update","paginates":false},- {"name":"settings_updateProductionSettings","classification":"WRITE","schema":"aab377266e08","response":"be6b8045779d","permission":"settings:update","paginates":false},+ {"name":"settings_updateProductionSettings","classification":"WRITE","schema":"d5c37cc53911","response":"4ba764a5dab1","permission":"settings:update","paginates":false},{"name":"settings_updatePurchasingSettings","classification":"WRITE","schema":"bac40d77d38a","response":"b3fda8ac0d5f","permission":"settings:update","paginates":false},{"name":"settings_updateQualitySettings","classification":"WRITE","schema":"1bcfa3043aa1","response":"e87697c359ae","permission":"settings:update","paginates":false},{"name":"settings_updateResourcesSettings","classification":"WRITE","schema":"ba1b98fe944a","response":"ec0f37163627","permission":"settings:update","paginates":false},diff --git a/apps/erp/test/database/serial-number-timing.test.ts b/apps/erp/test/database/serial-number-timing.test.tsindex ecda63291d..7ce4564cf8 100644--- a/apps/erp/test/database/serial-number-timing.test.ts+++ b/apps/erp/test/database/serial-number-timing.test.ts@@ -10,8 +10,10 @@import { createServiceContext } from "@carbon/api/service-fn.server";import {assignSerialNumberIfMissing,+ getNextSerialNumbers,getSerialNumberTiming} from "@carbon/database/sequence";+import { now } from "@internationalized/date";import { sql } from "kysely";import { describe, expect, it } from "vitest";import { completeJob } from "../../app/modules/production/production.server";@@ -22,6 +24,7 @@ import {jobFixture,seed,stockPart,+ TIME_ZONE,USER} from "./fixtures/always-post";import { hasLocalDatabase } from "./fixtures/local-database";@@ -265,4 +268,59 @@ describe.skipIf(!client)("serial number timing", () => {await f.cleanup();}});++ it("numbers and receives untouched units when the last operation is marked Done", async () => {+ const f = await alwaysPostFixture();+ try {+ await stockPart(f, 20);+ await serialSetup(f, "production");+ const job = await untouchedSerialJob(f, "5", 3);++ // 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("formats serials in SQL with the company's date and the job's location", async () => {+ const f = await alwaysPostFixture();+ try {+ await serialSetup(f, "production");+ await seed(f, async (trx) => {+ await trx+ .updateTable("itemSerialSequence")+ .set({ prefix: "%{location}-%{yyyy}-", suffix: "-X", next: 41 })+ .where("itemId", "=", f.assemblyId)+ .execute();+ });++ const serials = await f.db.transaction().execute((trx) =>+ getNextSerialNumbers(trx, {+ itemId: f.assemblyId,+ companyId: f.companyId,+ count: 2,+ locationCode: " HQ ",+ locationName: "Headquarters"+ })+ );++ const year = now(TIME_ZONE).year;+ expect(serials).toEqual([`HQ-${year}-042-X`, `HQ-${year}-043-X`]);+ } finally {+ await f.cleanup();+ }+ });});diff --git a/apps/erp/test/job-complete-logic.test.ts b/apps/erp/test/job-complete-logic.test.tsindex 5153cf6418..bb03f97b2d 100644--- a/apps/erp/test/job-complete-logic.test.ts+++ b/apps/erp/test/job-complete-logic.test.ts@@ -9,6 +9,7 @@ import {getDefaultSerialCompleteQuantity,getFinishedUnreceivedQuantity,getReceivableSerialUnits,+ getSerialCompleteChoice,type JobSerialUnit} from "../app/modules/production/ui/Jobs/job-complete-logic";@@ -165,3 +166,85 @@ describe("getDefaultSerialCompleteQuantity", () => {).toBe(3);});});++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", () => {+ const units = [unit({ readableId: "SN-0001" }), unit({ readableId: "SN-0002" })];+ for (const serialNumberTiming of ["jobCreation", "production"] as const) {+ expect(+ getSerialCompleteChoice({+ trackedEntities: units,+ receivedEntityIds: none,+ serialNumberTiming+ })+ ).toEqual({ mode: "serials", serials: ["SN-0001", "SN-0002"] });+ }+ });++ it("stays locked for an unsplit seed under the default timing", () => {+ expect(+ getSerialCompleteChoice({+ trackedEntities: [seed],+ receivedEntityIds: none,+ serialNumberTiming: "jobCreation"+ })+ ).toEqual({ mode: "locked" });+ });++ it("unlocks an unsplit seed when serials are numbered at production", () => {+ expect(+ getSerialCompleteChoice({+ trackedEntities: [seed],+ receivedEntityIds: none,+ serialNumberTiming: "production"+ })+ ).toEqual({ mode: "numberOnReceipt", receivableCount: 3 });+ });++ it("counts numbered and unnumbered units left to receive, not received or scrapped ones", () => {+ const units = [+ unit({ id: "done", status: "Available", readableId: "SN-0001" }),+ unit({ id: "blank", status: "Reserved" }),+ unit({ id: "received", status: "Available", readableId: "SN-0002" }),+ unit({ id: "scrapped", status: "Scrapped" }),+ unit({ id: "issued", status: "Consumed", readableId: "SN-0003" })+ ];+ expect(+ getSerialCompleteChoice({+ trackedEntities: units,+ receivedEntityIds: new Set(["received"]),+ serialNumberTiming: "production"+ })+ ).toEqual({ mode: "numberOnReceipt", receivableCount: 2 });+ expect(+ getSerialCompleteChoice({+ trackedEntities: units,+ receivedEntityIds: new Set(["received"]),+ serialNumberTiming: "jobCreation"+ })+ ).toEqual({ mode: "locked" });+ });++ it("stays locked when the receipts could not be read", () => {+ expect(+ getSerialCompleteChoice({+ trackedEntities: [seed],+ receivedEntityIds: null,+ serialNumberTiming: "production"+ })+ ).toEqual({ mode: "locked" });+ });++ it("stays locked when nothing is left to receive", () => {+ expect(+ getSerialCompleteChoice({+ trackedEntities: [unit({ id: "received", status: "Available" })],+ receivedEntityIds: new Set(["received"]),+ serialNumberTiming: "production"+ })+ ).toEqual({ mode: "locked" });+ });+});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 793cc7fef1..21260e271d 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,6 +124,15 @@ 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.+ PERFORM number_serial_units_for_completion(+ p_new->>'jobId',+ v_quantity_complete,+ p_new->>'companyId'+ );+PERFORM complete_job_to_inventory(p_job_id := p_new->>'jobId',p_quantity_complete := v_quantity_complete,diff --git a/packages/database/src/sequence.ts b/packages/database/src/sequence.tsindex f30bb155bf..c435d0fead 100644--- a/packages/database/src/sequence.ts+++ b/packages/database/src/sequence.ts@@ -23,7 +23,8 @@ const isoWeekFromYmd = (year: number, month: number, day: number): number => {// Date tokens derive in the company's business timezone so document prefixes// roll over at the company's midnight, not the process's. The ERP's live// preview (`interpolateSequenceDate` in apps/erp/app/utils/string.ts) mirrors-// this — keep the two in sync, along with get_next_sequence (SQL) and+// this — keep the two in sync, along with get_next_sequence (SQL),+// interpolate_serial_segment (SQL, the serial numbers' tokens) and// util.document_sequence_pattern (src/event-system/functions), which reads a// saved number back to keep the counter ahead of it.const interpolateSequenceDate = (value?: string | null, timezone = "UTC") => {@@ -46,22 +47,6 @@ const interpolateSequenceDate = (value?: string | null, timezone = "UTC") => {return result;};-// Serial-number segment interpolation: the date/week tokens above, plus the-// job-context %{location} token (location.code, falling back to location.name).-const interpolateSerialNumber = (- value: string | null | undefined,- context: {- locationCode?: string | null;- locationName?: string | null;- timezone?: string;- }-) => {- const withDates = interpolateSequenceDate(value, context.timezone);- if (!withDates.includes("%{location}")) return withDates;- const location = (context.locationCode ?? context.locationName ?? "").trim();- return withDates.replace(/%{location}/g, location);-};-export async function getNextSequence(trx: Transaction<KyselyDatabase>,tableName: string,@@ -150,13 +135,15 @@ export async function getNextRevisionSequence(/*** Atomically reserve and format the next `count` serial numbers for an item from- * its configured `itemSerialSequence`. Returns `[]` when the item has no sequence- * (so callers leave `readableId` null, exactly as before). Runs inside the- * caller's Kysely transaction, so the counter reservation commits — or rolls back- * — together with the write that consumes the numbers.+ * its configured `itemSerialSequence`, through the SQL `get_next_serial_numbers`.+ * Returns `[]` when the item has no sequence (so callers leave `readableId` null,+ * exactly as before). Runs inside the caller's Kysely transaction, so the counter+ * reservation commits — or rolls back — together with the write that consumes+ * the numbers.*- * Each number interpolates the date/week tokens (%{yyyy} %{yy} %{mm} %{ww} %{dd})- * plus %{location} (location.code, falling back to the location name).+ * Each number interpolates the date/week tokens (%{yyyy} %{yy} %{mm} %{ww} %{dd}+ * %{hh} %{ss}) in the company's timezone, plus %{location} (location.code,+ * falling back to the location name).** Used by `assign-serial-numbers` (the N units that exist at job creation),* `issue` (a unit spawned lazily on completion, e.g. after the job quantity was@@ -175,39 +162,19 @@ export async function getNextSerialNumbers(}): Promise<string[]> {if (args.count < 1) return [];-- const reserved = await trx- .updateTable("itemSerialSequence")- .set({- next: sql<number>`"next" + ${args.count} * "step"`,- updatedBy: "system",- updatedAt: new Date().toISOString()- })- .where("itemId", "=", args.itemId)- .where("companyId", "=", args.companyId)- .returning(["next", "prefix", "suffix", "size", "step"])- .executeTakeFirst();-- if (!reserved) return []; // item has no serial sequence configured-- const size = reserved.size ?? 5;- const step = reserved.step ?? 1;- const startNext = reserved.next - args.count * step;- const context = {- locationCode: args.locationCode,- locationName: args.locationName,- timezone: await getCompanyTimeZone(trx, args.companyId)- };-- const serials: string[] = [];- for (let i = 1; i <= args.count; i++) {- const value = startNext + i * step;- const counter = value.toString().padStart(size, "0");- const prefix = interpolateSerialNumber(reserved.prefix, context);- const suffix = interpolateSerialNumber(reserved.suffix, context);- serials.push(`${prefix}${counter}${suffix}`);- }- return serials;+ // One allocator: get_next_serial_numbers formats in SQL, so the database's+ // own completion path (number_serial_units_for_completion) and every+ // TypeScript caller produce the same numbers.+ const result = await sql<{ serials: string[] | null }>`+ SELECT get_next_serial_numbers(+ ${args.itemId},+ ${args.companyId},+ ${args.count}::integer,+ ${args.locationCode ?? null},+ ${args.locationName ?? null}+ ) AS serials+ `.execute(trx);+ return result.rows[0]?.serials ?? [];}/**diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex b82b512da0..75445f0cac 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -93119,6 +93119,16 @@ export type Database = {Args: { company_id: string; sequence_name: string }Returns: string}+ get_next_serial_numbers: {+ Args: {+ p_company_id: string+ p_count: number+ p_item_id: string+ p_location_code?: string+ p_location_name?: string+ }+ Returns: string[]+ }get_opportunity_with_related_records: {Args: { opportunity_id: string }Returns: {@@ -94194,6 +94204,10 @@ export type Database = {Args: { p_company_id: string; p_entries: Json[] }Returns: number}+ interpolate_serial_segment: {+ Args: { p_location: string; p_now: string; p_value: string }+ Returns: string+ }is_claims_admin: { Args: { company: string }; Returns: boolean }is_last_job_operation: {Args: { operation_id: string }@@ -94327,6 +94341,14 @@ export type Database = {Args: { alphabet: string; mask: number; size: number; step: number }Returns: string}+ number_serial_units_for_completion: {+ Args: {+ p_company_id: string+ p_job_id: string+ p_quantity_complete: number+ }+ Returns: number+ }populate_company_search_index: {Args: { p_company_id: string }Returns: undefineddiff --git a/packages/database/supabase/migrations/20261021103400_serial-number-timing-completion.sql b/packages/database/supabase/migrations/20261021103400_serial-number-timing-completion.sqlnew file mode 100644index 0000000000..02bb60aada--- /dev/null+++ b/packages/database/supabase/migrations/20261021103400_serial-number-timing-completion.sql@@ -0,0 +1,334 @@+-- Serial numbers at production: number the units a job completion takes.+--+-- Under companySettings."serialNumberTiming" = 'production' a job's units stay+-- unnumbered until they are first touched, and the completion that receives+-- them is a first touch. 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+-- every unit.+--+-- get_next_serial_numbers is the one serial allocator: the TypeScript+-- getNextSerialNumbers (@carbon/database/sequence) calls it, so job creation,+-- first-touch numbering and completion format serials the same way. Its date+-- tokens follow get_next_sequence: the company's timezone, ISO weeks.++CREATE OR REPLACE FUNCTION public.interpolate_serial_segment(+ p_value text,+ p_now timestamp,+ p_location text+)+ RETURNS text+ LANGUAGE sql+ STABLE+ SET search_path TO 'public'+AS $function$+ SELECT replace(+ replace(replace(replace(replace(replace(replace(replace(+ COALESCE(p_value, ''),+ '%{yyyy}', to_char(p_now, 'YYYY')),+ '%{yy}', to_char(p_now, 'YY')),+ '%{mm}', to_char(p_now, 'MM')),+ '%{ww}', to_char(p_now, 'IW')),+ '%{dd}', to_char(p_now, 'DD')),+ '%{hh}', to_char(p_now, 'HH24')),+ '%{ss}', to_char(p_now, 'SS')),+ '%{location}', COALESCE(p_location, '')+ );+$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.+CREATE OR REPLACE FUNCTION public.get_next_serial_numbers(+ p_item_id text,+ p_company_id text,+ p_count integer,+ p_location_code text DEFAULT NULL,+ p_location_name text DEFAULT NULL+)+ RETURNS text[]+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_next integer;+ v_prefix text;+ v_suffix text;+ v_size integer;+ v_step integer;+ v_now timestamp;+ v_location text;+ v_value integer;+ v_serials text[] := '{}';+BEGIN+ IF p_count IS NULL OR p_count < 1 THEN+ RETURN v_serials;+ END IF;++ UPDATE "itemSerialSequence"+ SET next = next + p_count * step,+ "updatedBy" = 'system',+ "updatedAt" = now()+ WHERE "itemId" = p_item_id+ AND "companyId" = p_company_id+ RETURNING next, prefix, suffix, size, step+ INTO v_next, v_prefix, v_suffix, v_size, v_step;++ IF NOT FOUND THEN+ RETURN v_serials;+ END IF;++ v_now := now() AT TIME ZONE COALESCE(+ (SELECT "timezone" FROM "company" WHERE "id" = p_company_id),+ 'UTC'+ );+ -- The location code, falling back to its name, with surrounding space trimmed.+ v_location := regexp_replace(+ COALESCE(p_location_code, p_location_name, ''),+ '^\s+|\s+$', '', 'g'+ );+ v_prefix := interpolate_serial_segment(v_prefix, v_now, v_location);+ v_suffix := interpolate_serial_segment(v_suffix, v_now, v_location);++ FOR i IN 1..p_count LOOP+ v_value := v_next - p_count * v_step + i * v_step;+ v_serials := v_serials || (+ v_prefix+ || CASE+ WHEN length(v_value::text) >= COALESCE(v_size, 5) THEN v_value::text+ ELSE lpad(v_value::text, COALESCE(v_size, 5), '0')+ END+ || v_suffix+ );+ END LOOP;++ RETURN v_serials;+END;+$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).+CREATE OR REPLACE FUNCTION public.number_serial_units_for_completion(+ p_job_id text,+ p_quantity_complete numeric,+ p_company_id text+)+ RETURNS integer+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ v_job record;+ v_make_method record;+ v_delta numeric;+ v_target text;+ v_taken text[];+ v_to_number text[];+ v_short integer;+ v_seed record;+ v_new_units integer := 0;+ v_seed_becomes_unit boolean := false;+ v_count integer;+ v_serials text[];+ v_location record;+BEGIN+ PERFORM assert_company_access(p_company_id);++ IF COALESCE(+ (SELECT "serialNumberTiming" FROM "companySettings" WHERE "id" = p_company_id),+ 'jobCreation'+ ) <> 'production' THEN+ RETURN 0;+ END IF;++ SELECT j."itemId", j."quantityReceivedToInventory", j."fixedAssetClassId",+ j."fixedAssetId", j."locationId", i."itemTrackingType"+ INTO v_job+ FROM "job" j+ JOIN "item" i ON i."id" = j."itemId"+ WHERE j."id" = p_job_id+ AND j."companyId" = p_company_id;+ IF NOT FOUND OR v_job."itemTrackingType" IS DISTINCT FROM 'Serial' THEN+ RETURN 0;+ END IF;+ IF NOT EXISTS (+ SELECT 1 FROM "itemSerialSequence"+ WHERE "itemId" = v_job."itemId" AND "companyId" = p_company_id+ ) THEN+ RETURN 0;+ END IF;++ SELECT "id", "requiresSerialTracking"+ INTO v_make_method+ FROM "jobMakeMethod"+ WHERE "jobId" = p_job_id+ AND "parentMaterialId" IS NULL;+ IF NOT FOUND OR NOT COALESCE(v_make_method."requiresSerialTracking", false) THEN+ RETURN 0;+ END IF;++ v_delta := p_quantity_complete - COALESCE(v_job."quantityReceivedToInventory", 0);+ IF v_delta IS NULL OR v_delta <= 0 OR v_delta <> trunc(v_delta) THEN+ RETURN 0;+ END IF;+ v_target := CASE+ WHEN v_job."fixedAssetClassId" IS NOT NULL OR v_job."fixedAssetId" IS NOT NULL+ THEN 'asset'+ ELSE 'receipt'+ END;++ PERFORM 1+ FROM "trackedEntity" te+ WHERE te.attributes->>'Job Make Method' = v_make_method."id"+ AND te."companyId" = p_company_id+ FOR UPDATE;++ -- The units the completion takes, by the same filter and order as+ -- complete_job_to_inventory (20261015161847_job-receipt-takes-issued-serial-units).+ IF v_target = 'asset' THEN+ v_taken := ARRAY(+ SELECT te."id"+ FROM "trackedEntity" te+ WHERE te.attributes->>'Job Make Method' = v_make_method."id"+ AND te."companyId" = p_company_id+ AND te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')+ AND te.quantity = 1+ AND NOT (te.attributes ? 'Fixed Asset')+ ORDER BY+ CASE te.status WHEN 'Available' THEN 0 WHEN 'Reserved' THEN 1 ELSE 2 END,+ te."readableId" NULLS LAST,+ te."createdAt",+ te."id"+ LIMIT v_delta::integer+ );+ ELSE+ v_taken := ARRAY(+ SELECT te."id"+ FROM "trackedEntity" te+ WHERE te.attributes->>'Job Make Method' = v_make_method."id"+ AND te."companyId" = p_company_id+ AND (+ te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')+ OR (+ te.status = 'Consumed'+ AND EXISTS (+ SELECT 1+ FROM "itemLedger" il+ WHERE il."trackedEntityId" = te."id"+ AND il."companyId" = p_company_id+ AND il.quantity < 0+ )+ )+ )+ AND te.quantity = 1+ AND NOT EXISTS (+ SELECT 1+ FROM "itemLedger" il+ WHERE il."trackedEntityId" = te."id"+ AND il."documentType" = 'Job Receipt'+ AND il."documentId" = p_job_id+ )+ ORDER BY+ CASE te.status WHEN 'Available' THEN 0 WHEN 'Consumed' THEN 0 WHEN 'Reserved' THEN 1 ELSE 2 END,+ te."readableId" NULLS LAST,+ te."createdAt",+ te."id"+ LIMIT v_delta::integer+ );+ END IF;++ -- Numbered units sort ahead of unnumbered ones of their rank, so once these+ -- are numbered the completion takes the same units.+ v_to_number := ARRAY(+ SELECT te."id"+ FROM "trackedEntity" te+ JOIN unnest(v_taken) WITH ORDINALITY AS t(id, ord) ON t.id = te."id"+ WHERE te."readableId" IS NULL+ ORDER BY t.ord+ );++ v_short := v_delta::integer - COALESCE(array_length(v_taken, 1), 0);+ IF v_short > 0 THEN+ SELECT *+ INTO v_seed+ FROM "trackedEntity" te+ WHERE te.attributes->>'Job Make Method' = v_make_method."id"+ AND te."companyId" = p_company_id+ AND te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')+ AND te.quantity > 1+ ORDER BY te."createdAt"+ LIMIT 1;+ IF NOT FOUND OR v_seed.quantity < v_short THEN+ RETURN 0;+ END IF;+ v_seed_becomes_unit := v_seed.quantity = v_short;+ v_new_units := CASE WHEN v_seed_becomes_unit THEN v_short - 1 ELSE v_short END;+ IF v_seed_becomes_unit AND v_seed."readableId" IS NULL THEN+ v_to_number := v_to_number || v_seed."id";+ END IF;+ END IF;++ v_count := COALESCE(array_length(v_to_number, 1), 0) + v_new_units;+ IF v_count = 0 THEN+ RETURN 0;+ END IF;++ SELECT "code", "name"+ INTO v_location+ FROM "location"+ WHERE "id" = v_job."locationId"+ AND "companyId" = p_company_id;++ v_serials := get_next_serial_numbers(+ v_job."itemId", p_company_id, v_count, v_location."code", v_location."name"+ );+ IF COALESCE(array_length(v_serials, 1), 0) < v_count THEN+ RETURN 0;+ END IF;++ IF COALESCE(array_length(v_to_number, 1), 0) > 0 THEN+ UPDATE "trackedEntity" te+ SET "readableId" = s.serial+ FROM unnest(+ v_to_number,+ v_serials[1:array_length(v_to_number, 1)]+ ) AS s(id, serial)+ WHERE te."id" = s.id+ AND te."companyId" = p_company_id+ AND te."readableId" IS NULL;+ END IF;++ IF v_short > 0 THEN+ UPDATE "trackedEntity"+ SET quantity = CASE WHEN v_seed_becomes_unit THEN 1 ELSE v_seed.quantity - v_new_units END+ WHERE "id" = v_seed."id"+ AND "companyId" = p_company_id;++ -- One millisecond apart, after every existing unit: createdAt is the unit+ -- axis step records are indexed by, so no existing unit moves.+ INSERT INTO "trackedEntity" (+ "createdAt", "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ quantity, status, attributes, "itemId", "expirationDate", "readableId",+ "companyId", "createdBy"+ )+ SELECT+ now() + n * interval '1 millisecond',+ v_seed."sourceDocument", v_seed."sourceDocumentId", v_seed."sourceDocumentReadableId",+ 1, v_seed.status, v_seed.attributes, v_seed."itemId", v_seed."expirationDate",+ v_serials[COALESCE(array_length(v_to_number, 1), 0) + n],+ p_company_id, v_seed."createdBy"+ FROM generate_series(1, v_new_units) AS n;+ END IF;++ RETURN v_count;+END;+$function$;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.sqlnew file mode 100644index 0000000000..a77cc6f2e8--- /dev/null+++ b/packages/database/supabase/migrations/20261021103500_serial-number-timing-finish-operation.sql@@ -0,0 +1,150 @@+-- 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));++ -- 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.+ PERFORM number_serial_units_for_completion(+ p_new->>'jobId',+ v_quantity_complete,+ p_new->>'companyId'+ );++ 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$;diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex e48b3fcb6a..645da80f0c 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Seriennummern werden nur für Artikel mit Serien- oder Chargenverfolgung generiert."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex f923a84972..8944822cc0 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -20779,6 +20779,9 @@ msgstr "Serial numbers are drawn when a unit is produced"msgid "Serial numbers are drawn when the job is created"msgstr "Serial numbers are drawn when the job is created"+msgid "Serial numbers are drawn when the units are received."+msgstr "Serial numbers are drawn when the units are received."+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Serial numbers are only generated for serial- or batch-tracked items."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 6ba59987f5..3bc58b2e33 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Los números de serie se generan solo para artículos con seguimiento de serie o lote."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex f088a8d566..6905f12b20 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Les numéros de série ne sont générés que pour les articles suivis en série ou en lot."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex bef9831afd..a0f662e322 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "सीरियल नंबर केवल सीरियल या बैच-ट्रैक किए गए आइटम के लिए उत्पन्न होते हैं।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 49d94ab2d2..e42557bdcc 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "I numeri di serie vengono generati solo per articoli tracciati in serie o per lotto."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex e220950af2..fdfc65e49a 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "シリアル番号は、シリアルまたはバッチ追跡アイテムに対してのみ生成されます。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex e68304b887..f935586042 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "시리얼 번호는 시리얼 또는 배치 추적 항목에만 생성됩니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 312d0c686d..2d0457432d 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Numery seryjne są generowane tylko dla elementów śledzonych numerem seryjnym lub partią."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 6edb78f673..e7ce4159dc 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Números de série são gerados apenas para itens rastreados por série ou lote."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 244f0cc8ed..a68ef8a054 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Серийные номера генерируются только для серийных или партионно отслеживаемых товаров."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 50b7b93c2e..2677a58922 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "Seri numaraları yalnızca seri- veya batch-izlenen öğeler için oluşturulur."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex b6e68d268b..0762757a75 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -20779,6 +20779,9 @@ msgstr ""msgid "Serial numbers are drawn when the job is created"msgstr ""+msgid "Serial numbers are drawn when the units are received."+msgstr ""+msgid "Serial numbers are only generated for serial- or batch-tracked items."msgstr "序列号仅为序列号或批次跟踪的物料生成。"