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 serial units inside complete_job_to_inventory

Raulcf9a771b8d9d
diff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.md
index c1bc12d980..b0f06d94f8 100644
--- a/.claude/rules/traceability-model.md
+++ b/.claude/rules/traceability-model.md
@@ -72,8 +72,10 @@ and MES services — NOT a single `post-production`:
`trackedActivity` and a `trackedActivityOutput` for the production event.
- **Scrap** (`.ai/specs/2026-08-06-scrap-unscrap-flow.md`): `issue` case
`jobOperationScrap` scraps the serial being made — `type: 'Scrap'` activity,
- entity → `Scrapped`, then **spawns the next serial** (same `getNextSerialNumbers`
- path as `jobOperationSerialComplete`) and reopens the make method's Done ops
+ entity → `Scrapped` (an unsplit seed is first cut to one unit, so only one unit
+ is scrapped), then **spawns a replacement unit**, numbered by
+ `getSpawnSerialNumber` like `jobOperationSerialComplete`'s next unit (left
+ unnumbered under the `production` serial number timing), and reopens the make method's Done ops
(`applyScrapReplacement`, `inventory.service.ts`) so the replacement runs the full routing. `issue`
case `scrapTrackedEntity` scraps a subcomponent, branching on entity **state**:
an `Available` part posts a `Scrap` (`Negative Adjmt.`) `itemLedger` at its
diff --git a/apps/erp/app/modules/inventory/inventory.server.ts b/apps/erp/app/modules/inventory/inventory.server.ts
index 6e48e316aa..8f7d4348bb 100644
--- a/apps/erp/app/modules/inventory/inventory.server.ts
+++ b/apps/erp/app/modules/inventory/inventory.server.ts
@@ -3511,6 +3511,13 @@ export const scanKanban = defineServiceFn({
error: failure
});
}
+ for (const warning of result.data?.warnings ?? []) {
+ logger.warn("A kanban job was released with a warning", {
+ companyId,
+ jobId,
+ warning: warning.message
+ });
+ }
// After the status is persisted: the scheduler only places released jobs.
if (released) {
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index bee691679c..561d8bddae 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -23117,13 +23117,6 @@ async function produceBatchOutput(
throw new NotFoundError("Tracked entity not found");
}
- // First-touch numbering (serialNumberTiming = 'production'). A no-op for a
- // unit already numbered, which is every unit under the default timing.
- await sequence.assignSerialNumberIfMissing(trx, {
- trackedEntityId,
- companyId
- });
-
if (trackedEntity.status !== "Consumed") {
const activityId = nanoid();
await trx
@@ -23591,47 +23584,14 @@ export async function issueMaterial(
// token; the reservation runs in this transaction, atomic with the spawn.
// Under the item's serialNumberTiming = 'production' the spawned
// unit stays unnumbered until it is first touched.
- let spawnReadableId: string | null = null;
- if (
- trackedEntity.itemId &&
- (await sequence.getSerialNumberTiming(
- trx,
- companyId,
- trackedEntity.itemId
- )) !== "production"
- ) {
- let locationCode: string | null = null;
- let locationName: string | null = null;
- const jobIdForLocation = (
- trackedEntity.attributes as Record<string, unknown>
- ).Job;
- if (typeof jobIdForLocation === "string") {
- const jobRow = await single(
- trx,
- "job",
- { id: jobIdForLocation, companyId },
- { columns: ["locationId"] }
- );
- if (jobRow.data?.locationId) {
- const loc = await single(
- trx,
- "location",
- { id: jobRow.data.locationId, companyId },
- { columns: ["code", "name"] }
- );
- locationCode = loc.data?.code ?? null;
- locationName = loc.data?.name ?? null;
- }
- }
- const spawnSerials = await sequence.getNextSerialNumbers(trx, {
- itemId: trackedEntity.itemId,
- companyId,
- count: 1,
- locationCode,
- locationName
- });
- spawnReadableId = spawnSerials[0] ?? null;
- }
+ const spawnReadableId = trackedEntity.itemId
+ ? await sequence.getSpawnSerialNumber(trx, {
+ itemId: trackedEntity.itemId,
+ companyId,
+ jobId: (trackedEntity.attributes as Record<string, unknown>)
+ .Job as string | undefined
+ })
+ : null;
// Create a new trackedEntity with the same attributes but status = Reserved
const newTrackedEntityResult = await trx
@@ -23948,36 +23908,13 @@ export async function issueMaterial(
if (existingEntityCount < capacity) {
// Under serialNumberTiming = 'production' the replacement stays
// unnumbered until it is first touched.
- let spawnReadableId: string | null = null;
- if (
- makeMethod.itemId &&
- (await sequence.getSerialNumberTiming(
- trx,
- companyId,
- makeMethod.itemId
- )) !== "production"
- ) {
- let locationCode: string | null = null;
- let locationName: string | null = null;
- if (job.locationId) {
- const loc = await single(
- trx,
- "location",
- { id: job.locationId, companyId },
- { columns: ["code", "name"] }
- );
- locationCode = loc.data?.code ?? null;
- locationName = loc.data?.name ?? null;
- }
- const spawnSerials = await sequence.getNextSerialNumbers(trx, {
- itemId: makeMethod.itemId,
- companyId,
- count: 1,
- locationCode,
- locationName
- });
- spawnReadableId = spawnSerials[0] ?? null;
- }
+ const spawnReadableId = makeMethod.itemId
+ ? await sequence.getSpawnSerialNumber(trx, {
+ itemId: makeMethod.itemId,
+ companyId,
+ jobId: job.id
+ })
+ : null;
const scrappedEntity = await trx
.selectFrom("trackedEntity")
@@ -24939,34 +24876,13 @@ export async function issueMaterial(
});
if (subMakeMethod.requiresSerialTracking && subMakeMethod.itemId) {
- let locationCode: string | null = null;
- let locationName: string | null = null;
- if (job.locationId) {
- const loc = await single(
- trx,
- "location",
- { id: job.locationId, companyId },
- { columns: ["code", "name"] }
- );
- locationCode = loc.data?.code ?? null;
- locationName = loc.data?.name ?? null;
- }
// Under serialNumberTiming = 'production' the replacement stays
// unnumbered until it is first touched.
- const spawnSerials =
- (await sequence.getSerialNumberTiming(
- trx,
- companyId,
- subMakeMethod.itemId
- )) === "production"
- ? []
- : await sequence.getNextSerialNumbers(trx, {
- itemId: subMakeMethod.itemId,
- companyId,
- count: 1,
- locationCode,
- locationName
- });
+ const spawnReadableId = await sequence.getSpawnSerialNumber(trx, {
+ itemId: subMakeMethod.itemId,
+ companyId,
+ jobId: job.id
+ });
await trx
.insertInto("trackedEntity")
.values({
@@ -24978,7 +24894,7 @@ export async function issueMaterial(
attributes: entity.attributes,
itemId: subMakeMethod.itemId,
expirationDate: entity.expirationDate ?? null,
- readableId: spawnSerials[0] ?? null,
+ readableId: spawnReadableId,
companyId,
createdBy: userId
})
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 7f76ddb8d2..f4522cdee5 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -38,9 +38,18 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
- `p_quantity_complete` is **CUMULATIVE**, not this completion's delta. The function receives `p_quantity_complete - job.quantityReceivedToInventory` and stores the cumulative value back, because `get_inventory_quantities` computes on-production supply as production + scrap − received − shipped. `backflush_job_materials` takes the same cumulative number and is idempotent, so a re-completion at the received quantity receives nothing and consumes nothing.
- It **refuses** a quantity ≤ 0 or below what was already received (stocked items), and a fractional quantity on a serial job. Those raises reach the `jobOperation` UPDATE when they happen under the trigger — `sync_finish_job_operation` therefore clamps with `GREATEST(computed, received)` before calling.
-- The serial branch receives the delta one numbered unit at a time — shop-floor-finished (`Available`) first, then by `readableId` — skipping `Consumed`/`Rejected`/`Scrapped` and any unit with a `Job Receipt` ledger row for this job, so re-completion never double-receives. 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.
+- The serial branch receives the delta one numbered unit at a time — shop-floor-finished (`Available`) first, then by `readableId` — skipping `Consumed`/`Rejected`/`Scrapped` and any unit with a `Job Receipt` ledger row for this job, so re-completion never double-receives. When the job's rows hold too few single units, an item with a serial sequence has the rest split off the seed (`split_serial_units_for_completion`) and the units picked again; the units taken are then numbered (`number_serial_units_for_receipt`). An item with **no serial sequence** keeps one whole-quantity seed entity and the delta is received against that seed instead.
- **Make to Asset branch.** A job with `fixedAssetClassId` completes into one new `fixedAsset` per unit (status `Active`, or `Under Construction` when the class `isConstructionInProgress`; `acquisitionCost` = swept WIP ÷ units; one Posted `fixedAssetTransfer` per asset, `type 'Capitalization'`, `sourceType 'Job'`); a job with `fixedAssetId` sweeps its WIP onto that Construction in Progress asset as one `fixedAssetCipCost` row + one transfer. The units never enter stock: no `itemLedger`, `costLedger`, `pickMethod` or `itemCost` write, and the WIP discharge posts Dr class `assetAccountId` / Cr WIP as an `'Asset Transfer'` journal (both lines still `documentId = jobId`, so the per-job WIP balance nets to zero). Each serial unit goes `Consumed` with `attributes["Fixed Asset"]` and a `'Capitalize'` `trackedActivity`; every company writes the asset cost (the journal is Provisional before the accounting cutover). Guards raise before anything moves: `'A job linked to a sales order line cannot complete to a fixed asset'`; `'A job that completes to a fixed asset class needs a serialized item'` (any quantity — every asset a class job makes is a fleet unit followed by its serial); `'Make to Asset needs a serialized item or a quantity of one'` (a job attached to an asset under construction); a job attached to a non-CIP asset is also refused (`'… is not in a Construction in Progress class'`). The item rule is `makeToAssetItemError` (`production.models.ts`), applied by `x+/job+/new.tsx` on save (a field error on the item), by `updateJobDetails` (the details form), by `setJobItem` on a property-panel item change and by `resumeJob` when a paused job goes back to `Ready`, with the sales order line gate. Covered by `packages/database/supabase/tests/job-completion-to-asset.test.sql`. Full flow: `.claude/rules/fixed-asset-lifecycle.md`.
-- **Serial number timing** (`companySettings.serialNumberTiming`, Settings → Production → Serial Numbers; an item's serial sequence overrides it with `itemSerialSequence.serialNumberTiming`, NULL follows the company, edited in Settings → Serial Numbers). Every reader resolves the item's own value first: `getSerialNumberTiming(db, companyId, itemId)` (`@carbon/database/sequence`), the SQL `number_serial_units_for_completion`, and the Complete dialog. `jobCreation` (default): `assignJobSerialNumbers` splits and numbers every unit when the job is created. `jobRelease`: the same split and numbering runs when `releaseCheckedJobs` flips the job to Ready (`assignJobSerialNumbersAtRelease`, best-effort: a failure is logged and the release goes on), so every release path (Release dialog, bulk, batch, kanban) numbers it; a unit spawned later is numbered at spawn, as under `jobCreation`. The timing is for serial units: a Batch item's lot is numbered at job creation whatever the timing (`assignJobSerialNumbers`). `production`: it is skipped, the job keeps its unnumbered seed, and a unit draws its number at its first touch through `assignSerialNumberIfMissing` (`@carbon/database/sequence`): the MES start (`start.$operationId.tsx`, `x+/event.tsx`, via `services/serial-number.server.ts`; only a unit already on its own, since a start leaves the job's unsplit seed whole and the seed's number comes from its first completion or scrap), the `issue` posting's serial completion, batch output and operation scrap, and the completion that receives it. A unit the serial completion or a scrap spawns stays unnumbered under `production`. An operation batch tracks no serial units, so a unit completed through one keeps no number until its next touch or the receipt. Both completion paths call the SQL `number_serial_units_for_completion` (`20261027064600_serial-number-timing-completion.sql`, marked `SECURITY INVOKER`, like `backflush_job_materials`) before `complete_job_to_inventory`: `completeJob` (through `numberSerialUnitsForCompletion`) and the `sync_finish_job_operation` interceptor (an operation marked Done). It does not read the timing: under `jobCreation` it finds every unit numbered and does nothing, unless the job was created under another timing before the item or company switched back, which would otherwise receive one unnumbered entity holding every unit. It reads what the job has received again after it locks the units, so a completion it waited on is not numbered a second time. It takes the units the RPC will take, in its receipt or Make to Asset order, splits what is missing off the seed and numbers every unit taken, so no unnumbered lump is received. The shop floor's first completion or scrap of the seed leaves it holding one unit (a serial scrap takes one unit, never the whole seed) and spawns the next units one at a time, so the rows can hold fewer units than the job quantity: the function creates the units no row holds yet, up to the job quantity less the units in rows (a scrapped unit does not count), and the Complete dialog counts them as receivable. Every serial is formatted by the SQL `get_next_serial_numbers`, which `getNextSerialNumbers` calls. The Complete dialog unlocks the quantity whenever the item has a serial sequence and units are unnumbered or have no row (`getSerialCompleteChoice`, mode `numberOnReceipt`) and says the serials are drawn at receipt; for an item with no sequence it stays locked to what the shop floor finished.
+- **Serial number timing**: when a produced unit draws its serial number.
+ - Setting: `companySettings.serialNumberTiming` (Settings → Production → Serial Numbers). An item's serial sequence overrides it with `itemSerialSequence.serialNumberTiming` (NULL follows the company; Settings → Serial Numbers). Readers resolve the item's value first: `getSerialNumberTiming` / `resolveSerialNumberTiming` (`@carbon/database/sequence`). Values: `serialNumberTimings` (`@carbon/database/serial-number-timing`, client-safe).
+ - `jobCreation` (default): `assignJobSerialNumbers` → the `assign-serial-numbers` posting splits and numbers every unit when the job is created. The posting takes `at` and numbers only when the item's timing is `at`.
+ - `jobRelease`: the same posting runs with `at: "jobRelease"` when `releaseCheckedJobs` flips the job to Ready (`assignJobSerialNumbersAtRelease`), on every release path. A failure does not stop the release: the job is listed in the result's `warnings` (`releaseJobs` passes it on).
+ - `production`: the job keeps its unnumbered seed. A unit draws its number at its first touch through `assignSerialNumberIfMissing`: the MES start (`services/serial-number.server.ts`; only a single unit of the operation's own make method, since the unit id comes from the request), the `issue` posting's serial completion and operation scrap, and the completion that receives it.
+ - A Batch lot is numbered at job creation whatever the timing; batch output never numbers.
+ - A unit spawned later (a serial completion's next unit, a scrap's replacement) is numbered by `getSpawnSerialNumber`, which leaves it unnumbered under `production`.
+ - Completion: `complete_job_to_inventory` (`20261027064600_serial-number-timing-completion.sql`) picks the units, splits what the rows lack off the seed and creates units no row holds yet, up to the job quantity less the units in rows (`split_serial_units_for_completion`), picks again, then numbers the unnumbered units it took (`number_serial_units_for_receipt`). Both helpers are `SECURITY INVOKER`. It does not read the timing: a job left unnumbered by a timing that changed back to `jobCreation` is numbered too. One query picks the units, so numbering and receipt take the same ones.
+ - Every serial is formatted by the SQL `get_next_serial_numbers`, which `getNextSerialNumbers` calls.
+ - Complete dialog: it 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 bee421f813..3512e01cc6 100644
--- a/apps/erp/app/modules/production/production.server.ts
+++ b/apps/erp/app/modules/production/production.server.ts
@@ -247,6 +247,10 @@ export const planDraftJob = defineServiceFn({
* each supplier's outside operations from every member job on one PO. The map
* is returned with those POs filled in, for a caller releasing job by job.
*
+ * Serial numbering at release never stops it: a job whose units could not be
+ * numbered is listed in `warnings` and released, and its units draw their
+ * numbers at their first touch or at completion.
+ *
* It stops at the first job that fails, and that is `failure`, not an error:
* `releasedJobIds` are the jobs that ARE Ready when this returns. After a
* failure past the status flip (purchase orders, release date) the job is
@@ -265,9 +269,11 @@ export const releaseCheckedJobs = defineServiceFn({
const userId = ctx.auditUserId;
const purchaseOrders = { ...purchaseOrdersBySupplierId };
const releasedJobIds: string[] = [];
+ const warnings: { jobId: string; message: string }[] = [];
const report = (failure: CarbonError<"internal" | "conflict"> | null) => ({
purchaseOrdersBySupplierId: purchaseOrders,
releasedJobIds,
+ warnings,
failure
});
@@ -330,12 +336,20 @@ 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: a failure is logged.
- await service.assignJobSerialNumbersAtRelease(
+ // company's) every unit is numbered now. The job is already Ready, so a
+ // failure is a warning, not a refusal.
+ const numbered = await service.assignJobSerialNumbersAtRelease(
ctx.asSystem.supabase,
ctx.asSystem.pg,
{ jobId: id, companyId, userId }
);
+ if (!numbered) {
+ warnings.push({
+ jobId: id,
+ message:
+ "The job is released, but its serial numbers could not be assigned"
+ });
+ }
const purchaseOrder = await invokeCreate(
{ db: ctx.asSystem.pg, companyId, userId },
@@ -414,7 +428,7 @@ type JobRef = { jobId: string; readableId: string };
* @param purchaseOrdersBySupplierId - For each supplier, `new` or the id of one of its Draft purchase orders to add to.
* @param carriedPurchaseOrders - The PO each supplier went on in an earlier call of the same release, as that call returned it
*
- * @returns `released`, `failed` (each with its reason), `skipped` (not Draft or Planned), `warnings` (released, but a purchase order failed), whether the locations were `scheduled`, and `purchaseOrdersBySupplierId` for the next call.
+ * @returns `released`, `failed` (each with its reason), `skipped` (not Draft or Planned), `warnings` (released, but a purchase order or its serial numbers failed), whether the locations were `scheduled`, and `purchaseOrdersBySupplierId` for the next call.
*
* @mcp
*/
@@ -540,6 +554,9 @@ export const releaseJobs = defineServiceFn({
continue;
}
if (failure) warnings.push({ ...ref, message: failure.message });
+ for (const warning of result.data?.warnings ?? []) {
+ warnings.push({ ...ref, message: warning.message });
+ }
if (job.locationId) locationIds.add(job.locationId);
released.push(ref);
}
@@ -883,13 +900,11 @@ export const closeJob = defineServiceFn({
* job's own), backflushes materials, rolls up cost and, for a Make to Asset
* job, creates the fixed assets. It refuses a quantity of zero or below what
* was received, a fractional quantity on a serial job, and the Make to Asset
- * rules; its message says what to fix (a `rule` error). When the item's serial
- * number timing (its own, else the company's) is release or production, the
- * units the completion takes are split off the job's seed, created when no
- * record holds them yet, and numbered first, in the completion's transaction,
- * so a refused completion spends no numbers. Then the picked material the job did not
- * consume is returned to the warehouse; a failure there leaves the job
- * completed and is returned as `warning`.
+ * rules; its message says what to fix (a `rule` error). Units it takes that
+ * have no serial number yet (a deferred serial number timing) are numbered by
+ * the same function, so a refused completion spends no numbers. Then the
+ * picked material the job did not consume is returned to the warehouse; a
+ * failure there leaves the job completed and is returned as `warning`.
*
* @mcp
*/
@@ -906,48 +921,23 @@ export const completeJob = defineServiceFn({
const companyId = ctx.company.id;
const userId = ctx.auditUserId;
- // 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 complete_job_to_inventory receives them. Both run in one
- // transaction, as in the sync_finish_job_operation interceptor, so a
- // refused completion spends no serial numbers.
- const completed = await ctx.transaction(async (tx) => {
- try {
- await service.numberSerialUnitsForCompletion(tx.asSystem.pg, {
- jobId,
- quantityComplete,
- companyId
- });
- } catch (error) {
- return ctx.error(
- "internal",
- "Failed to number the serial units being completed",
- error
- );
- }
-
- // It must NOT write job.quantityShipped: that column is advanced only by
- // post-shipment, and the shipment builder ships quantityComplete less it.
- try {
- await service.completeJobToInventory(tx.asSystem.pg, {
- jobId,
- quantityComplete,
- storageUnitId,
- locationId,
- companyId,
- userId
- });
- } catch (error) {
- return ctx.error(
- "rule",
- (error instanceof Error && error.message) || "Failed to complete job",
- error
- );
- }
- return null;
+ // It must NOT write job.quantityShipped: that column is advanced only by
+ // post-shipment, and the shipment builder ships quantityComplete less it.
+ const rpc = await ctx.asCaller.supabase.rpc("complete_job_to_inventory", {
+ p_job_id: jobId,
+ p_quantity_complete: quantityComplete,
+ p_storage_unit_id: storageUnitId,
+ p_location_id: locationId,
+ p_company_id: companyId,
+ p_user_id: userId
});
- if (completed.error) return completed.error;
+ if (rpc.error) {
+ return ctx.error(
+ "rule",
+ rpc.error.message || "Failed to complete job",
+ rpc.error
+ );
+ }
// A re-completion is supported; the job id is the idempotency key, so a
// repeat collapses rather than counting a second completion.
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index de6a3e6493..dba788fd90 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -80,7 +80,7 @@ import {
getNextRevisionSequence,
getNextSequence,
getNextSerialNumbers,
- getSerialNumberTiming
+ resolveSerialNumberTiming
} from "@carbon/database/sequence";
import { getStrictBackflushSettings } from "@carbon/database/strict-backflush";
import {
@@ -3866,16 +3866,14 @@ export async function insertJob(
/**
* Assign configured serial numbers to a job's tracked entities, when the job is
- * created or when it is released. Best-effort and cheap: it skips the operation
- * entirely unless the item has an `itemSerialSequence` configured. Shared by
- * every job-creation path (insertJob, sales-order conversion, ...) and by
- * `releaseCheckedJobs`, so serial numbering is applied consistently.
+ * created (`at: "jobCreation"`, the default) or released (`at: "jobRelease"`).
+ * Best-effort and cheap: it skips the operation entirely unless the item has an
+ * `itemSerialSequence` configured. Shared by every job-creation path
+ * (insertJob, sales-order conversion, ...) and by `releaseCheckedJobs`, so
+ * serial numbering is applied consistently. The `assign-serial-numbers`
+ * posting decides whether the item's serial number timing names this moment.
*
- * Runs only at the moment the item's timing names (`getSerialNumberTiming`):
- * `jobCreation` at creation, `jobRelease` at release. Under `production` the
- * job's units stay unnumbered and each draws its number the first time it is
- * touched (see `assignSerialNumberIfMissing` and
- * `numberSerialUnitsForCompletion`).
+ * Returns false when numbering failed (logged), true otherwise.
*/
export async function assignJobSerialNumbers(
client: SupabaseClient<Database>,
@@ -3885,9 +3883,9 @@ export async function assignJobSerialNumbers(
itemId: string;
companyId: string;
userId: string;
- moment?: "creation" | "release";
+ at?: "jobCreation" | "jobRelease";
}
-) {
+): Promise<boolean> {
const serialSequence = await client
.from("itemSerialSequence")
.select("id")
@@ -3902,64 +3900,48 @@ export async function assignJobSerialNumbers(
itemId: args.itemId,
companyId: args.companyId
});
- return;
- }
- if (!serialSequence.data) return;
- // The timing is for serial units. A Batch job's one lot is numbered when the
- // job is created, as before: number_serial_units_for_completion numbers
- // serial units only, so a deferred lot would be received with no number.
- const item = await db
- .selectFrom("item")
- .select("itemTrackingType")
- .where("id", "=", args.itemId)
- .where("companyId", "=", args.companyId)
- .executeTakeFirst();
- const timing =
- item?.itemTrackingType === "Batch"
- ? "jobCreation"
- : await getSerialNumberTiming(db, args.companyId, args.itemId);
- if (
- timing !==
- ((args.moment ?? "creation") === "creation" ? "jobCreation" : "jobRelease")
- ) {
- return;
+ return false;
}
+ if (!serialSequence.data) return true;
const { error } = await invokePosting(
{ client, db, companyId: args.companyId, userId: args.userId },
"assign-serial-numbers",
- { jobId: args.jobId },
+ { jobId: args.jobId, at: args.at ?? "jobCreation" },
assignSerialNumbers,
{ as: assignSerialNumbersPermission }
);
if (error) {
logger.error("Failed to assign serial numbers", { error });
+ return false;
}
+ return true;
}
/**
* 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`).
+ * `jobRelease` timing (the item's, else the company's). Returns false when
+ * numbering failed (logged): the job is already Ready, so the caller warns and
+ * the release goes on; the units then draw their numbers at their first touch
+ * or at completion (`complete_job_to_inventory`).
*/
export async function assignJobSerialNumbersAtRelease(
client: SupabaseClient<Database>,
db: Kysely<KyselyDatabase>,
args: { jobId: string; companyId: string; userId: string }
-) {
+): Promise<boolean> {
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, {
+ const job = await client
+ .from("job")
+ .select("itemId")
+ .eq("id", args.jobId)
+ .eq("companyId", args.companyId)
+ .maybeSingle();
+ if (job.error) throw job.error;
+ if (!job.data?.itemId) return true;
+ return await assignJobSerialNumbers(client, db, {
...args,
- itemId: job.itemId,
- moment: "release"
+ itemId: job.data.itemId,
+ at: "jobRelease"
});
} catch (error) {
logger.error("Failed to number serial units at release", {
@@ -3967,6 +3949,7 @@ export async function assignJobSerialNumbersAtRelease(
jobId: args.jobId,
companyId: args.companyId
});
+ return false;
}
}
@@ -12895,14 +12878,19 @@ export async function closeJob(
return { success: true };
}
export const assignSerialNumbersInput = z.object({
- jobId: z.string()
+ jobId: z.string(),
+ // The moment calling: it numbers only when the item's timing names it.
+ at: z.enum(["jobCreation", "jobRelease"]).default("jobCreation")
});
/**
- * Assigns configured serial numbers to a job's tracked entities at creation time.
+ * Assigns configured serial numbers to a job's tracked entities, at creation or
+ * release.
*
- * Run (best-effort) by `insertJob` only when the job's item has an
- * `itemSerialSequence`. For a Batch item it stamps one number on the single
+ * Run (best-effort) by `assignJobSerialNumbers` only when the job's item has an
+ * `itemSerialSequence`. It numbers only when the item's serial number timing
+ * (its own, else the company's) is `at`; a Batch lot is always numbered at
+ * creation, since the timing is for serial units. For a Batch item it stamps one number on the single
* whole-quantity seed entity; for a Serial item it splits the seed into N
* quantity-1 entities and stamps one number on each. Numbers come from the
* item's sequence (atomic counter) with %{...} date/week/location tokens.
@@ -12917,7 +12905,7 @@ export async function assignSerialNumbers(
ctx: ServiceContext,
raw: z.input<typeof assignSerialNumbersInput>
) {
- const { jobId } = assignSerialNumbersInput.parse(raw);
+ const { jobId, at } = assignSerialNumbersInput.parse(raw);
const db = ctx.asSystem.pg;
const companyId = ctx.company.id;
@@ -12946,12 +12934,24 @@ export async function assignSerialNumbers(
// 3. The item's serial sequence (optional, at most one)
const sequence = await trx
.selectFrom("itemSerialSequence")
- .select(["prefix", "suffix", "next", "size", "step"])
+ .select(["serialNumberTiming"])
.where("itemId", "=", job.itemId)
.where("companyId", "=", companyId)
.executeTakeFirst();
if (!sequence) return { assigned: 0 };
+ // 3b. Only at the moment the item's timing names. A Batch lot is numbered
+ // at creation: the completion numbers serial units only.
+ const timing =
+ trackingType === "Batch"
+ ? "jobCreation"
+ : await resolveSerialNumberTiming(
+ trx,
+ companyId,
+ sequence.serialNumberTiming
+ );
+ if (timing !== at) return { assigned: 0 };
+
// 4. Location context for the %{location} token (code, falling back to name)
let locationCode: string | null = null;
let locationName: string | null = null;
@@ -13055,66 +13055,6 @@ export async function assignSerialNumbers(
});
}
-/**
- * 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 when every unit taken is numbered, for an
- * item with no serial sequence, and when the job cannot cover the completion.
- * `completeJob` runs it in the completion's own transaction, so a refused
- * completion rolls the numbering back.
- */
-export async function numberSerialUnitsForCompletion(
- db: Kysely<KyselyDatabase>,
- args: { jobId: string; quantityComplete: number; companyId: string }
-): Promise<{ numbered: number }> {
- 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) };
-}
-
-/**
- * Receive a job's completion through `complete_job_to_inventory`, on the given
- * connection or transaction. It throws when the function refuses; the message
- * says what to fix.
- */
-export async function completeJobToInventory(
- db: Kysely<KyselyDatabase>,
- args: {
- jobId: string;
- quantityComplete: number;
- storageUnitId?: string;
- locationId?: string;
- companyId: string;
- userId: string;
- }
-) {
- await sql`
- SELECT complete_job_to_inventory(
- p_job_id := ${args.jobId},
- p_quantity_complete := ${args.quantityComplete}::numeric,
- p_storage_unit_id := ${args.storageUnitId ?? null},
- p_location_id := ${args.locationId ?? null},
- p_company_id := ${args.companyId},
- p_user_id := ${args.userId}
- )
- `.execute(db);
-}
-
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.tsx
index a9db627c9e..6dac5d4b16 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -102,7 +102,8 @@ import {
getDefaultSerialCompleteQuantity,
getFinishedUnreceivedQuantity,
getSerialCompleteChoice,
- type JobReceiptSnapshot
+ type JobReceiptSnapshot,
+ type SerialCompleteChoice
} from "./job-complete-logic";
import {
makeMethodsMissingOperations,
@@ -1419,18 +1420,19 @@ function JobCompleteModal({
job?.quantityComplete ?? 0
);
const [hasTrackedQuantity, setHasTrackedQuantity] = useState<boolean>(false);
- // Serial units the completion can still receive, in the order
- // complete_job_to_inventory receives them. Null when the quantity is not
- // chosen per serial unit.
- const [receivableSerials, setReceivableSerials] = useState<string[] | null>(
- null
- );
- // 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);
+ // How the quantity is chosen for a serial job: the serials a completion
+ // takes, units numbered as they are received, or locked.
+ const [serialChoice, setSerialChoice] = useState<SerialCompleteChoice>({
+ mode: "locked"
+ });
+ const receivableSerials =
+ serialChoice.mode === "serials" ? serialChoice.serials : null;
+ const receivableUnitCount =
+ serialChoice.mode === "serials"
+ ? serialChoice.serials.length
+ : serialChoice.mode === "numberOnReceipt"
+ ? serialChoice.receivableCount
+ : 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>(
@@ -1458,7 +1460,7 @@ function JobCompleteModal({
const hasLeftover = leftoverQuantity > 0;
// Serial units are received one at a time; the database refuses a fraction.
const hasFractionalSerialQuantity =
- (receivableSerials !== null || unitsNumberedOnReceipt !== null) &&
+ serialChoice.mode !== "locked" &&
Number.isFinite(quantityComplete) &&
!Number.isInteger(quantityComplete);
@@ -1528,14 +1530,15 @@ function JobCompleteModal({
? getSerialCompleteChoice({
trackedEntities: trackedEntities.data,
receivedEntityIds: receipts ? receivedEntityIds : null,
- // number_serial_units_for_completion numbers what the
- // completion takes whenever the item has a sequence. A failed
- // read keeps the quantity locked.
+ // complete_job_to_inventory 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);
+ setSerialChoice(choice);
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
@@ -1544,12 +1547,6 @@ function JobCompleteModal({
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({
@@ -1697,11 +1694,9 @@ function JobCompleteModal({
isDisabled={hasTrackedQuantity}
minValue={minimumQuantityComplete}
maxValue={
- receivableSerials
- ? priorReceivedQuantity + receivableSerials.length
- : unitsNumberedOnReceipt !== null
- ? priorReceivedQuantity + unitsNumberedOnReceipt
- : undefined
+ receivableUnitCount !== null
+ ? priorReceivedQuantity + receivableUnitCount
+ : undefined
}
helperText={
hasTrackedQuantity
@@ -1728,7 +1723,7 @@ function JobCompleteModal({
</Alert>
)}
- {unitsNumberedOnReceipt !== null &&
+ {serialChoice.mode === "numberOnReceipt" &&
quantityComplete > priorReceivedQuantity &&
!hasFractionalSerialQuantity && (
<span className="text-sm text-muted-foreground w-full">
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 b7f9d283dc..c63a3715c5 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
@@ -86,7 +86,7 @@ export function getReceivableSerialUnits(
* - `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
+ * (`complete_job_to_inventory`), so the quantity can be chosen up to
* `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.
@@ -116,15 +116,12 @@ export function getSerialCompleteChoice({
// received, whatever the timing.
if (!receivedEntityIds) return { mode: "locked" };
- // 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
// fewer units than the job quantity. Only a completion that numbers on
// receipt creates the missing units. A scrapped unit does not count: the job
// still owes it.
- const unitsWithoutRow = numbersOnReceipt
+ const unitsWithoutRow = hasSerialSequence
? Math.max(
jobQuantity -
trackedEntities
@@ -136,7 +133,8 @@ export function getSerialCompleteChoice({
const serials = getReceivableSerialUnits(trackedEntities, receivedEntityIds);
if (serials && unitsWithoutRow === 0) return { mode: "serials", serials };
- if (!numbersOnReceipt) return { mode: "locked" };
+ // With a sequence the completion numbers whatever it receives unnumbered.
+ if (!hasSerialSequence) return { mode: "locked" };
const receivableCount =
trackedEntities
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index a1437082fa..61ca62df22 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { serialNumberTimings } from "@carbon/database/serial-number-timing";
import {
blockSchema,
documentSectionPlacementSchema,
@@ -403,12 +404,10 @@ export const returnPickedMaterialTimingValidator = z.object({
// until the unit is first touched on the floor — its first production event,
// its first operation completion, its scrap, or its receipt. The company's
// choice is the default; an item's serial sequence can override it.
-export const serialNumberTimings = [
- "jobCreation",
- "jobRelease",
- "production"
-] as const;
-export type SerialNumberTiming = (typeof serialNumberTimings)[number];
+export {
+ type SerialNumberTiming,
+ serialNumberTimings
+} from "@carbon/database/serial-number-timing";
export const serialNumberTimingValidator = z.object({
serialNumberTiming: z.enum(serialNumberTimings).default("jobCreation")
diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.ts
index 720774e33e..4feb9b5220 100644
--- a/apps/erp/app/modules/settings/settings.server.ts
+++ b/apps/erp/app/modules/settings/settings.server.ts
@@ -371,8 +371,9 @@ export const updateItemsSettings = defineServiceFn({
* inventory or a sales job completes, whether opening an operation starts its
* timer, whether the job traveler lists materials and operations, whether
* tracked material is pre-selected without a picking list, when a produced
- * unit draws its serial number (when the job is created, or the first time
- * the unit is worked on, scrapped or received), and whether one location
+ * unit draws its serial number (when the job is created, when it is released,
+ * or the first time the unit is worked on, scrapped or received), and whether
+ * one location
* requires an assigned operator before the scheduler places work there. The
* staffing rule lives on the location row and is written for the company's
* own location only, so a settings admin without the resources permission can
@@ -2841,7 +2842,7 @@ export const updateItemSerialSequence = defineServiceFn({
.nullable()
.optional()
.describe(
- "When this item's units draw their serial numbers. Omit or null to follow the company setting."
+ "When this item's units draw their serial numbers. Null follows the company setting. Omitted, a new sequence follows the company setting and an update keeps the current value."
),
id: z
.string()
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.json
index 1db59d010a..47f2173292 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
@@ -1559,7 +1559,7 @@
{"name":"settings_updateDimensionSync","classification":"WRITE","schema":"42c99362fccd","response":"f95fa90d0071","permission":"settings:update","paginates":false},
{"name":"settings_updateInventorySettings","classification":"WRITE","schema":"a76084d47705","response":"d62a56ef4842","permission":"settings:update","paginates":false},
{"name":"settings_updateInvoicingSettings","classification":"WRITE","schema":"48fd9aba9ea8","response":"a32ee5ad2099","permission":"settings:update","paginates":false},
- {"name":"settings_updateItemSerialSequence","classification":"WRITE","schema":"43ad381904e2","response":"3797626bd17e","permission":"settings:update","paginates":false},
+ {"name":"settings_updateItemSerialSequence","classification":"WRITE","schema":"432dc38ca4a4","response":"3797626bd17e","permission":"settings:update","paginates":false},
{"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},
diff --git a/apps/erp/app/routes/x+/settings+/production.tsx b/apps/erp/app/routes/x+/settings+/production.tsx
index e800734a6a..ba7220b672 100644
--- a/apps/erp/app/routes/x+/settings+/production.tsx
+++ b/apps/erp/app/routes/x+/settings+/production.tsx
@@ -48,6 +48,7 @@ import {
} from "~/modules/settings/settings.models";
import type { updateProductionSettings } from "~/modules/settings/settings.server";
import { getCompanySettings } from "~/modules/settings/settings.service";
+import { useSerialNumberTimingLabels } from "~/modules/settings/ui/SerialNumbers/useSerialNumberTimingLabels";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -576,6 +577,7 @@ export default function ProductionSettingsRoute() {
// so the value posts with the surrounding ValidatedForm.
function SerialNumberTimingChoice() {
const { t } = useLingui();
+ const labels = useSerialNumberTimingLabels();
const [value, setValue] =
useControlField<SerialNumberTiming>("serialNumberTiming");
const current: SerialNumberTiming = value ?? "jobCreation";
@@ -587,19 +589,19 @@ function SerialNumberTimingChoice() {
options={[
{
value: "jobCreation",
- title: t`When the job is created`,
+ title: labels.jobCreation,
description: t`Every unit is numbered up front, so serials can be printed before work starts.`,
icon: <LuTicket />
},
{
value: "jobRelease",
- title: t`When the job is released`,
+ title: labels.jobRelease,
description: t`Every unit is numbered when the job goes to the shop floor, so travelers can still be printed and jobs cancelled before release burn none.`,
icon: <LuSend />
},
{
value: "production",
- title: t`When the unit is produced`,
+ title: labels.production,
description: t`A unit draws its number the first time it is worked on, scrapped or received, so cancelled jobs burn none.`,
icon: <LuFactory />
}
diff --git a/apps/erp/test/database/serial-number-timing.test.ts b/apps/erp/test/database/serial-number-timing.test.ts
index 18f52a2ed6..4d99e73edb 100644
--- a/apps/erp/test/database/serial-number-timing.test.ts
+++ b/apps/erp/test/database/serial-number-timing.test.ts
@@ -22,11 +22,7 @@ import {
completeJob,
releaseCheckedJobs
} from "../../app/modules/production/production.server";
-import {
- assignJobSerialNumbers,
- completeJobToInventory,
- numberSerialUnitsForCompletion
-} from "../../app/modules/production/production.service";
+import { assignJobSerialNumbers } from "../../app/modules/production/production.service";
import { invokePosting } from "../../app/modules/shared/shared.service";
import {
alwaysPostFixture,
@@ -68,6 +64,31 @@ function contextFor(f: Fixture, system: () => unknown = () => client) {
});
}
+/** complete_job_to_inventory on the given connection or transaction. */
+async function completeToInventory(
+ db: Fixture["db"],
+ args: { jobId: string; quantityComplete: number; companyId: string }
+) {
+ await sql`
+ SELECT complete_job_to_inventory(
+ p_job_id := ${args.jobId},
+ p_quantity_complete := ${args.quantityComplete}::numeric,
+ p_company_id := ${args.companyId},
+ p_user_id := ${USER}
+ )
+ `.execute(db);
+}
+
+/** The serial sequence's next value: how many numbers were drawn. */
+async function drawn(f: Fixture) {
+ const sequence = await f.db
+ .selectFrom("itemSerialSequence")
+ .select("next")
+ .where("itemId", "=", f.assemblyId)
+ .executeTakeFirstOrThrow();
+ return Number(sequence.next);
+}
+
/** A serial assembly with a sequence (SN-001, SN-002, ...) and the timing set. */
async function serialSetup(f: Fixture, timing: SerialNumberTiming) {
await seed(f, async (trx) => {
@@ -257,6 +278,30 @@ describe.skipIf(!client)("serial number timing", () => {
}
});
+ it("leaves a unit of another make method unnumbered on a touch scoped to one", async () => {
+ const f = await alwaysPostFixture();
+ try {
+ await serialSetup(f, "production");
+ const job = await untouchedSerialJob(f, "scoped", 1);
+ const other = await untouchedSerialJob(f, "scoped-other", 1);
+ const [seedUnit] = await units(f, job.makeMethodId);
+
+ const numbered = await f.db.transaction().execute((trx) =>
+ assignSerialNumberIfMissing(trx, {
+ trackedEntityId: seedUnit!.id,
+ companyId: f.companyId,
+ onlyIfSingleUnit: true,
+ jobMakeMethodId: other.makeMethodId
+ })
+ );
+
+ expect(numbered).toBeNull();
+ expect(await drawn(f)).toBe(0);
+ } finally {
+ await f.cleanup();
+ }
+ });
+
it("numbers a Batch lot when the job is created, whatever the timing", async () => {
const f = await alwaysPostFixture();
try {
@@ -275,7 +320,7 @@ describe.skipIf(!client)("serial number timing", () => {
itemId: f.assemblyId,
companyId: f.companyId,
userId: USER,
- moment: "creation"
+ at: "jobCreation"
});
expect(await units(f, job.makeMethodId)).toEqual([
@@ -303,10 +348,11 @@ describe.skipIf(!client)("serial number timing", () => {
{ readableId: "SN-001", quantity: 1 },
{ readableId: "SN-002", quantity: 1 }
]);
- // The seed is the job's last unit, still unnumbered and untouched.
+ // The receipt takes units in creation order: the seed (cut to one
+ // unit) and the first unit split off it. The last unit is untouched.
const after = await units(f, job.makeMethodId);
expect(after).toHaveLength(3);
- expect(after[0]).toMatchObject({ readableId: null, quantity: 1 });
+ expect(after[2]).toMatchObject({ readableId: null, quantity: 1 });
} finally {
await f.cleanup();
}
@@ -315,6 +361,7 @@ describe.skipIf(!client)("serial number timing", () => {
it("leaves the units of an item with no serial sequence alone", async () => {
const f = await alwaysPostFixture();
try {
+ await stockPart(f, 20);
await serialSetup(f, "jobCreation");
await seed(f, async (trx) => {
await trx
@@ -325,13 +372,13 @@ describe.skipIf(!client)("serial number timing", () => {
});
const job = await untouchedSerialJob(f, "3", 3);
- const numbered = await numberSerialUnitsForCompletion(f.db, {
+ const result = await completeJob(contextFor(f), {
jobId: job.jobId,
- quantityComplete: 2,
- companyId: f.companyId
+ quantityComplete: 2
});
+ expect(result.error).toBeNull();
- expect(numbered).toEqual({ numbered: 0 });
+ // Received against the seed, which stays one unnumbered entity.
expect(await units(f, job.makeMethodId)).toEqual([
expect.objectContaining({ readableId: null, quantity: 3 })
]);
@@ -368,25 +415,24 @@ describe.skipIf(!client)("serial number timing", () => {
}
});
- it("spends no number when the job cannot cover the completion", async () => {
+ it("refuses a completion the job cannot cover, and spends no number", async () => {
const f = await alwaysPostFixture();
try {
+ await stockPart(f, 20);
await serialSetup(f, "production");
const job = await untouchedSerialJob(f, "4", 2);
- const numbered = await numberSerialUnitsForCompletion(f.db, {
+ // Two units exist and none is left to create: three cannot be received.
+ const result = await completeJob(contextFor(f), {
jobId: job.jobId,
- quantityComplete: 3,
- companyId: f.companyId
+ quantityComplete: 3
});
- expect(numbered).toEqual({ numbered: 0 });
- const sequence = await f.db
- .selectFrom("itemSerialSequence")
- .select("next")
- .where("itemId", "=", f.assemblyId)
- .executeTakeFirstOrThrow();
- expect(Number(sequence.next)).toBe(0);
+ expect(result.error?.category).toBe("rule");
+ expect(await units(f, job.makeMethodId)).toEqual([
+ expect.objectContaining({ readableId: null, quantity: 2 })
+ ]);
+ expect(await drawn(f)).toBe(0);
} finally {
await f.cleanup();
}
@@ -448,23 +494,22 @@ describe.skipIf(!client)("serial number timing", () => {
// The first completion numbers and receives two units, and keeps its
// locks until it commits.
const first = f.db.transaction().execute(async (trx) => {
- await numberSerialUnitsForCompletion(trx, args);
- await completeJobToInventory(trx, { ...args, userId: USER });
+ await completeToInventory(trx, args);
holding();
await committed;
});
await held;
- // The same completion again reads the job before the first commits,
- // then waits for the units.
- const repeat = numberSerialUnitsForCompletion(second, args);
+ // The same completion again waits for the job row, then finds the two
+ // units already received.
+ const repeat = completeToInventory(second, args);
for (let attempt = 0; ; attempt++) {
const { rows } = await sql<{ waiting: number }>`
SELECT count(*)::int AS waiting FROM pg_stat_activity
WHERE datname = current_database()
AND pid <> pg_backend_pid()
AND wait_event_type = 'Lock'
- AND query ILIKE '%number_serial_units_for_completion%'`.execute(
+ AND query ILIKE '%complete_job_to_inventory%'`.execute(
watcher
);
if (rows[0]!.waiting > 0) break;
@@ -474,7 +519,8 @@ describe.skipIf(!client)("serial number timing", () => {
commit();
await first;
- expect(await repeat).toEqual({ numbered: 0 });
+ await repeat;
+ expect(await receivedUnits(f, job.jobId)).toHaveLength(2);
const sequence = await f.db
.selectFrom("itemSerialSequence")
.select("next")
@@ -666,7 +712,7 @@ describe.skipIf(!client)("serial number timing", () => {
itemId: f.assemblyId,
companyId: f.companyId,
userId: USER,
- moment: "creation"
+ at: "jobCreation"
});
expect(await units(f, job.makeMethodId)).toEqual([
expect.objectContaining({ readableId: null, quantity: 3 })
@@ -717,13 +763,15 @@ describe.skipIf(!client)("serial number timing", () => {
expect(await units(f, job.makeMethodId)).toEqual([
expect.objectContaining({ readableId: null, quantity: 2 })
]);
- expect(
- await numberSerialUnitsForCompletion(f.db, {
- jobId: job.jobId,
- quantityComplete: 2,
- companyId: f.companyId
- })
- ).toEqual({ numbered: 2 });
+ await completeToInventory(f.db, {
+ jobId: job.jobId,
+ quantityComplete: 2,
+ companyId: f.companyId
+ });
+ expect(await receivedUnits(f, job.jobId)).toEqual([
+ { readableId: "SN-001", quantity: 1 },
+ { readableId: "SN-002", quantity: 1 }
+ ]);
// The company numbers at production; this item at creation, so the
// job's units are numbered when it is created.
diff --git a/apps/erp/test/job-lifecycle.test.ts b/apps/erp/test/job-lifecycle.test.ts
index a0c1c8189c..3519b3f205 100644
--- a/apps/erp/test/job-lifecycle.test.ts
+++ b/apps/erp/test/job-lifecycle.test.ts
@@ -19,6 +19,7 @@ vi.mock("@carbon/planning", () => ({
import {
closeJob,
+ completeJob,
createProductionQuantity,
pauseJob,
reopenJob,
@@ -31,8 +32,11 @@ let statusWrites: { status: unknown; fromStatuses?: unknown }[] = [];
/** Every production quantity row inserted. */
let quantityInserts: Record<string, unknown>[] = [];
-/** The user client: the job as read and its status writes. */
-function callerWith(job: Record<string, unknown> | null) {
+/** The user client: the job as read, its status writes, and the completion RPC's answer. */
+function callerWith(
+ job: Record<string, unknown> | null,
+ rpc: { error: { message: string } | null } = { error: null }
+) {
const read: Record<string, unknown> = {};
for (const method of ["select", "eq"]) read[method] = () => read;
read.maybeSingle = async () => ({ data: job, error: null });
@@ -58,7 +62,10 @@ function callerWith(job: Record<string, unknown> | null) {
})
};
};
- return { from: () => ({ ...read, update, insert }) };
+ return {
+ from: () => ({ ...read, update, insert }),
+ rpc: async () => ({ data: null, ...rpc })
+ };
}
const contextWith = (caller: unknown) =>
@@ -209,6 +216,32 @@ describe("closeJob", () => {
});
});
+describe("completeJob", () => {
+ const complete = (caller: unknown) =>
+ completeJob(contextWith(caller), { jobId: "j1", quantityComplete: 5 });
+
+ it("returns the database's refusal as a rule", async () => {
+ const result = await complete(
+ callerWith(null, {
+ error: { message: "Quantity is below what was received" }
+ })
+ );
+ expect(result.error).toMatchObject({
+ category: "rule",
+ message: "Quantity is below what was received"
+ });
+ });
+
+ it("keeps the completion and warns when returning picked material fails", async () => {
+ // The sweep posts through `pg`, which this context lacks.
+ const result = await complete(callerWith(null));
+ expect(result).toEqual({
+ data: { jobId: "j1", warning: expect.any(String) },
+ error: null
+ });
+ });
+});
+
describe("createProductionQuantity", () => {
const record = (jobStatus: string, type: "Production" | "Scrap") =>
createProductionQuantity(
diff --git a/apps/erp/test/release-jobs.test.ts b/apps/erp/test/release-jobs.test.ts
index bc148b39fa..ef033824b1 100644
--- a/apps/erp/test/release-jobs.test.ts
+++ b/apps/erp/test/release-jobs.test.ts
@@ -173,7 +173,8 @@ describe("releaseCheckedJobs", () => {
expect(result.data).toEqual({
failure: null,
purchaseOrdersBySupplierId: {},
- releasedJobIds: ["job-1"]
+ releasedJobIds: ["job-1"],
+ warnings: []
});
expect(events).toEqual(["recalculate", "mrp", "ready:job-1"]);
});
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 2233d9f03c..8bca5b057f 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -2166,9 +2166,7 @@ export const JobOperation = ({
) : (
<>
<span className="font-medium text-muted-foreground truncate">
- <Trans>
- No serial number yet
- </Trans>
+ <Trans>No serial number</Trans>
</span>
<span className="text-xs text-muted-foreground font-mono truncate">
{entity.id}
diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsx
index c49ece162e..43bcdda656 100644
--- a/apps/mes/app/routes/x+/event.tsx
+++ b/apps/mes/app/routes/x+/event.tsx
@@ -171,10 +171,13 @@ async function productionEventAction({ request }: ActionFunctionArgs) {
await postEnded(startEvent.data.endedEventIds);
}
- // First touch: number the unit if the company numbers serials at
- // production.
+ // First touch: number the unit if it has no serial number yet.
if (trackedEntityId) {
- await assignSerialNumberOnFirstTouch({ trackedEntityId, companyId });
+ await assignSerialNumberOnFirstTouch({
+ trackedEntityId,
+ jobOperationId: d.jobOperationId,
+ companyId
+ });
}
return data(
diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsx
index b231ef2bb4..ef819d7c1c 100644
--- a/apps/mes/app/routes/x+/start.$operationId.tsx
+++ b/apps/mes/app/routes/x+/start.$operationId.tsx
@@ -316,9 +316,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
ids: ended
});
- // First touch: number the unit if the company numbers serials at production.
+ // First touch: number the unit if it has no serial number yet.
if (trackedEntityId) {
- await assignSerialNumberOnFirstTouch({ trackedEntityId, companyId });
+ await assignSerialNumberOnFirstTouch({
+ trackedEntityId,
+ jobOperationId: operationId,
+ companyId
+ });
}
throw redirect(path.to.operation(operationId));
diff --git a/apps/mes/app/services/serial-number.server.ts b/apps/mes/app/services/serial-number.server.ts
index 33ffca5793..8f692236ea 100644
--- a/apps/mes/app/services/serial-number.server.ts
+++ b/apps/mes/app/services/serial-number.server.ts
@@ -9,34 +9,52 @@ import { getDatabaseClient } from "~/services/database.server";
const log = getLogger("mes", "serial-number");
/**
- * Number a unit from its item's serial sequence when work first starts on it
- * (the `production` serial number timing, the item's own or else the
- * company's). A no-op for a unit that already has a number, which is every unit
- * under the `jobCreation` and `jobRelease` timings, so it is safe on every start.
+ * Number a unit from its item's serial sequence when work first starts on it.
+ * Under the `production` serial number timing (the item's own, else the
+ * company's) that is how the unit gets its number. Under `jobCreation` and
+ * `jobRelease` every unit is already numbered, so it does nothing, unless the
+ * job was created under `production` before the timing changed. Safe on every
+ * start.
*
- * Only a unit already on its own is numbered here. The job's first unit is
- * still the unsplit seed holding every unit, and a start leaves it whole, so
- * its number comes from its first completion or scrap, which cut it to one unit.
+ * Only a unit of the operation's own make method that is already on its own is
+ * numbered. The job's first unit is still the unsplit seed holding every unit,
+ * and a start leaves it whole, so its number comes from its first completion or
+ * scrap, which cut it to one unit.
*
* Best-effort: a failure never stops a timer from starting, and the ERP's
* completion and scrap postings number the unit later if this was lost. It
* writes as the system: the caller has already admitted the operator to start
- * the operation, and an operator need not hold `update: production`.
+ * the operation, and an operator need not hold `update: production`. The unit
+ * id comes from the request, so it must belong to the operation's make method.
*/
export async function assignSerialNumberOnFirstTouch(args: {
trackedEntityId: string;
+ jobOperationId: string;
companyId: string;
}) {
try {
await getDatabaseClient()
.transaction()
- .execute((trx) =>
- assignSerialNumberIfMissing(trx, { ...args, onlyIfSingleUnit: true })
- );
+ .execute(async (trx) => {
+ const operation = await trx
+ .selectFrom("jobOperation")
+ .select(["jobMakeMethodId"])
+ .where("id", "=", args.jobOperationId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!operation?.jobMakeMethodId) return null;
+ return assignSerialNumberIfMissing(trx, {
+ trackedEntityId: args.trackedEntityId,
+ companyId: args.companyId,
+ onlyIfSingleUnit: true,
+ jobMakeMethodId: operation.jobMakeMethodId
+ });
+ });
} catch (error) {
log.error("Failed to assign a serial number on first touch", {
error,
trackedEntityId: args.trackedEntityId,
+ jobOperationId: args.jobOperationId,
companyId: args.companyId
});
}
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index e933a20055..3071d76c14 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -103,7 +103,8 @@ pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/h
| `./accounting-cutover` | Client-safe. The pure planner (`buildOpeningJournalLines` — takes the Migration Clearing account with its class, refuses one that is not Equity and refuses unbalanced lines — `migrationClearingByAccount`, `isIgnorableOpenItem`, `applyCarbonToTrialBalance`, `planInventoryReset`, `unitCostAtCutover`, `recostOutbound`) and the values the ERP and the enable must agree on: `MIGRATION_CLEARING_TOLERANCE` / `isMigrationClearingZero`, `MIGRATION_CLEARING_ACCOUNT_CLASS`, `ACTIVATION_CUTOVER_PARAM`, `dayBeforeCutover` |
| `./legacy-documents` | Server-only. The one detection of legacy documents (`.ai/specs/implemented/2026-10-08-accounting-cutover.md` section 5a): posted, dated on or after the cutover, with no journal. Each function (`legacySalesInvoices`, `legacyPayments`, `legacyShipments`, `legacyAdjustmentCostRows`, `legacyJobMovements`, `legacyDepreciationRunLines`, …) returns a Kysely query, not rows: `activateAccounting` (`accounting.service.ts`, ported from the `activate-accounting` server function) executes it, and `getLegacyDocumentCounts` (`./accounting-cutover-reads`) counts the same rows for the wizard. Also `LEGACY_DOCUMENT_FAMILIES` (the families in the order the enable writes them), `LegacyDocumentCounts`, `assetsLeavingWithoutJournal` and `REBUILT_DISPOSAL_METHOD` |
| `./deposit-scope` | `loadSalesInvoiceDocumentIds` (the rental agreements / sales orders each sales invoice bills, one query) and `loadDepositScope` (a deposit payment's document + readable id) — the reads behind "a customer deposit funds only its own document", shared by `replaceInvoiceSettlements` and `post-payment` |
-| `./sequence` | `getNextSequences` (`count` numbers in one statement; `getNextSequence` is its count-of-one) / `getNextRevisionSequence` / `getNextSerialNumbers` — the one allocator for document and serial numbers (date tokens in the company timezone) |
+| `./sequence` | `getNextSequences` (`count` numbers in one statement; `getNextSequence` is its count-of-one) / `getNextRevisionSequence` — document numbers, formatted in TypeScript (date tokens in the company timezone). `getNextSerialNumbers` — serial numbers, a wrapper over SQL `get_next_serial_numbers`, which formats them so the job completion in SQL and TypeScript callers agree. Serial number timing: `getSerialNumberTiming` (the item's, else the company's), `resolveSerialNumberTiming` (the same from an item value already read), `assignSerialNumberIfMissing` (first-touch numbering of one unit), `getSpawnSerialNumber` (the number for a spawned unit, null under `production`) |
+| `./serial-number-timing` | Client-safe. `serialNumberTimings`, `SerialNumberTiming`, `asSerialNumberTiming` — the timing values the ERP's forms and tables import; `./sequence` re-exports them |
| `./receipt-serials` | `releaseReceiptSerialEntities(db, companyId, ids)` — the one way a receipt serial is taken off a receipt, inside the caller's Kysely transaction: an entity with no `itemLedger` history is deleted, one with history only loses its `Receipt` / `Receipt Line` / `Receipt Line Index` attributes. Shared by the ERP's receipt serial routes and the receipt line split (`receiptLineSplit` in `shared.service.ts`). `planReceiptSerialRelease` is the pure split; `idsWithStockHistory` is the one "has stock movements" test. `idsWithLiveStockHistory` is the same test without the rows of voided receipts (a void writes its reversal under the receipt's `documentId`), and `voidedReceiptIds` filters receipt ids to the voided ones — together they let a serial from a voided receipt be received again as the same entity |
| `./stock-transfer` | `expandSerialTrackedLines`, `isBelowReplenishmentLevel`, `levelReplenishmentQuantity` (the fewest whole kanban quantities that reach a level), `kanbanReplenishmentNote` — the stock-transfer line and kanban-note rules shared by the ERP's `insertStockTransfer` and `replenishKanban` (`inventory.service.ts`, ported from the `kanban-replenish` server function) |
| `./seed-data` | The company seed data (accounts, sequences, groups + `getGroupId`, …) used by `seedCompany` (`settings.service.ts`, ported from the `seed-company` server function) and the dataset tooling |
diff --git a/packages/database/package.json b/packages/database/package.json
index 7a630ba29e..896e353392 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -53,6 +53,7 @@
"./ratelimit": "./src/ratelimit.ts",
"./sampling": "./src/sampling.ts",
"./sequence": "./src/sequence.ts",
+ "./serial-number-timing": "./src/serial-number-timing.ts",
"./stock-transfer": "./src/stock-transfer.ts",
"./receipt-serials": "./src/receipt-serials.ts",
"./storage-objects": "./src/storage-objects.ts",
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 0bd851ad0b..793cc7fef1 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,16 +124,6 @@ BEGIN
-- received, and refusing here would block the Done update itself.
v_quantity_complete := GREATEST(v_quantity_complete, COALESCE(v_quantity_received, 0));
- -- 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,
- 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.ts
index 8570bfd7b1..9c1653eb9d 100644
--- a/packages/database/src/sequence.ts
+++ b/packages/database/src/sequence.ts
@@ -7,6 +7,10 @@
import { CalendarDate, getDayOfWeek, now } from "@internationalized/date";
import { type Kysely, sql, type Transaction } from "kysely";
import type { KyselyDatabase } from "./client.ts";
+import {
+ asSerialNumberTiming,
+ type SerialNumberTiming
+} from "./serial-number-timing.ts";
import { getCompanyTimeZone } from "./timezone.ts";
// ISO 8601 week number (1-53). Week 1 is the week containing the year's first
@@ -163,7 +167,7 @@ export async function getNextSerialNumbers(
): Promise<string[]> {
if (args.count < 1) return [];
// One allocator: get_next_serial_numbers formats in SQL, so the database's
- // own completion path (number_serial_units_for_completion) and every
+ // own completion path (complete_job_to_inventory) and every
// TypeScript caller produce the same numbers.
const result = await sql<{ serials: string[] | null }>`
SELECT get_next_serial_numbers(
@@ -177,16 +181,10 @@ export async function getNextSerialNumbers(
return result.rows[0]?.serials ?? [];
}
-export const serialNumberTimings = [
- "jobCreation",
- "jobRelease",
- "production"
-] as const;
-export type SerialNumberTiming = (typeof serialNumberTimings)[number];
-
-function asSerialNumberTiming(value: unknown): SerialNumberTiming | null {
- return serialNumberTimings.find((timing) => timing === value) ?? null;
-}
+export {
+ type SerialNumberTiming,
+ serialNumberTimings
+} from "./serial-number-timing.ts";
/**
* When a produced unit draws its serial number: `jobCreation` (the default)
@@ -205,16 +203,27 @@ export async function getSerialNumberTiming(
companyId: string,
itemId?: string | null
): Promise<SerialNumberTiming> {
- if (itemId) {
- const sequence = await db
- .selectFrom("itemSerialSequence")
- .select(["serialNumberTiming"])
- .where("itemId", "=", itemId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- const itemTiming = asSerialNumberTiming(sequence?.serialNumberTiming);
- if (itemTiming) return itemTiming;
- }
+ if (!itemId) return resolveSerialNumberTiming(db, companyId, null);
+ const sequence = await db
+ .selectFrom("itemSerialSequence")
+ .select(["serialNumberTiming"])
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ return resolveSerialNumberTiming(db, companyId, sequence?.serialNumberTiming);
+}
+
+/**
+ * The timing for an item whose sequence's own `serialNumberTiming` the caller
+ * already read: that value when it is set, else the company's.
+ */
+export async function resolveSerialNumberTiming(
+ db: Transaction<KyselyDatabase> | Kysely<KyselyDatabase>,
+ companyId: string,
+ itemTiming: unknown
+): Promise<SerialNumberTiming> {
+ const own = asSerialNumberTiming(itemTiming);
+ if (own) return own;
const settings = await db
.selectFrom("companySettings")
.select(["serialNumberTiming"])
@@ -228,8 +237,11 @@ export async function getSerialNumberTiming(
* number yet. Returns the assigned serial, or null when nothing was assigned:
* the entity is already numbered, has no item, or its item has no sequence.
*
- * This is the `serialNumberTiming = 'production'` path, so every call site is a
- * "first touch" hook and must be safe to fire repeatedly on the same unit:
+ * Every call site is a "first touch" hook. It does not read the serial number
+ * timing: under `production` it is how a unit gets its number, and under the
+ * other timings it numbers only a unit left unnumbered (a job created under
+ * `production` before its timing changed). Every call site must be safe to
+ * fire repeatedly on the same unit:
* hence the `readableId IS NULL` guard and the row lock. Two operators touching
* the same unit at once serialize on the entity row, and the second sees the
* first one's number instead of reserving and burning another. Runs inside the
@@ -239,6 +251,10 @@ export async function getSerialNumberTiming(
* `onlyIfSingleUnit` leaves an entity holding more than one unit unnumbered.
* A caller that does not cut the entity to one unit in the same transaction
* passes it, or a job's unsplit seed would carry one serial for every unit.
+ *
+ * `jobMakeMethodId` numbers the entity only when it is a unit of that make
+ * method. A caller whose entity id comes from a request passes it, so an id
+ * from another job cannot draw a number.
*/
export async function assignSerialNumberIfMissing(
trx: Transaction<KyselyDatabase>,
@@ -246,6 +262,7 @@ export async function assignSerialNumberIfMissing(
trackedEntityId: string;
companyId: string;
onlyIfSingleUnit?: boolean;
+ jobMakeMethodId?: string;
}
): Promise<string | null> {
const entity = await trx
@@ -258,12 +275,19 @@ export async function assignSerialNumberIfMissing(
if (!entity || entity.readableId || !entity.itemId) return null;
if (args.onlyIfSingleUnit && Number(entity.quantity) !== 1) return null;
+ const attributes = entity.attributes as Record<string, unknown> | null;
+ if (
+ args.jobMakeMethodId &&
+ attributes?.["Job Make Method"] !== args.jobMakeMethodId
+ ) {
+ return null;
+ }
const [readableId] = await getNextSerialNumbers(trx, {
itemId: entity.itemId,
companyId: args.companyId,
count: 1,
- ...(await getEntityJobLocation(trx, entity.attributes, args.companyId))
+ ...(await getJobLocation(trx, attributes?.Job, args.companyId))
});
if (!readableId) return null;
@@ -278,16 +302,38 @@ export async function assignSerialNumberIfMissing(
}
/**
- * The %{location} context for a job's unit: the location of the job named by
- * its `Job` attribute. A unit with no Job attribute interpolates the token to
- * nothing, as it would at job creation for a job with no location.
+ * The serial number for a unit spawned after a job's units were numbered (a
+ * serial completion's next unit, a scrap's replacement): the next number of
+ * the item's sequence, with the job's location for %{location}. Null under the
+ * `production` timing, where the unit is numbered at its first touch, and for
+ * an item with no sequence. Runs in the caller's transaction, so the
+ * reservation commits or rolls back with the spawn.
+ */
+export async function getSpawnSerialNumber(
+ trx: Transaction<KyselyDatabase>,
+ args: { itemId: string; companyId: string; jobId: string | null | undefined }
+): Promise<string | null> {
+ const timing = await getSerialNumberTiming(trx, args.companyId, args.itemId);
+ if (timing === "production") return null;
+ const [serial] = await getNextSerialNumbers(trx, {
+ itemId: args.itemId,
+ companyId: args.companyId,
+ count: 1,
+ ...(await getJobLocation(trx, args.jobId, args.companyId))
+ });
+ return serial ?? null;
+}
+
+/**
+ * The %{location} context for a job's unit: the location of its job. No job
+ * interpolates the token to nothing, as it would at job creation for a job with
+ * no location.
*/
-export async function getEntityJobLocation(
+async function getJobLocation(
trx: Transaction<KyselyDatabase>,
- attributes: unknown,
+ jobId: unknown,
companyId: string
): Promise<{ locationCode: string | null; locationName: string | null }> {
- const jobId = (attributes as Record<string, unknown> | null)?.Job;
if (typeof jobId !== "string") {
return { locationCode: null, locationName: null };
}
diff --git a/packages/database/src/serial-number-timing.ts b/packages/database/src/serial-number-timing.ts
new file mode 100644
index 0000000000..717c79c8db
--- /dev/null
+++ b/packages/database/src/serial-number-timing.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Client-safe: the ERP's forms and tables import the timings from here, and
+// `./sequence` (which pulls in Kysely) re-exports them. The SQL CHECKs on
+// companySettings and itemSerialSequence list the same values.
+export const serialNumberTimings = [
+ "jobCreation",
+ "jobRelease",
+ "production"
+] as const;
+export type SerialNumberTiming = (typeof serialNumberTimings)[number];
+
+export function asSerialNumberTiming(
+ value: unknown
+): SerialNumberTiming | null {
+ return serialNumberTimings.find((timing) => timing === value) ?? null;
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 025c2d5f40..8271e3fb99 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -102573,6 +102573,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.leaseReminderDays"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.serialNumberTiming"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.requireBackflushStorageUnit"
},
@@ -102582,9 +102585,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.receiptQuantitiesStartAtZero"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.serialNumberTiming"
- },
{
$ref: "#/parameters/select"
},
@@ -102857,6 +102857,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.leaseReminderDays"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.serialNumberTiming"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.requireBackflushStorageUnit"
},
@@ -102866,9 +102869,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.receiptQuantitiesStartAtZero"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.serialNumberTiming"
- },
{
$ref: "#/parameters/preferReturn"
}
@@ -103095,6 +103095,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.leaseReminderDays"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.serialNumberTiming"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.requireBackflushStorageUnit"
},
@@ -103104,9 +103107,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.receiptQuantitiesStartAtZero"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.serialNumberTiming"
- },
{
$ref: "#/parameters/body.companySettings"
},
@@ -113415,6 +113415,58 @@ export default {
tags: ["(rpc) get_supplier_ids_with_supplier_permission"]
}
},
+ "/rpc/split_serial_units_for_completion": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_count: {
+ format: "integer",
+ type: "integer"
+ },
+ p_job_id: {
+ format: "text",
+ type: "string"
+ },
+ p_make_method_id: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: [
+ "p_job_id",
+ "p_make_method_id",
+ "p_company_id",
+ "p_count"
+ ],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) split_serial_units_for_completion"]
+ }
+ },
"/rpc/attach_event_trigger": {
post: {
parameters: [
@@ -118200,6 +118252,61 @@ export default {
tags: ["(rpc) journalDimensionPivot"]
}
},
+ "/rpc/number_serial_units_for_receipt": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_item_id: {
+ format: "text",
+ type: "string"
+ },
+ p_location_id: {
+ format: "text",
+ type: "string"
+ },
+ p_unit_ids: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ }
+ },
+ required: [
+ "p_unit_ids",
+ "p_item_id",
+ "p_company_id",
+ "p_location_id"
+ ],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) number_serial_units_for_receipt"]
+ }
+ },
"/rpc/getConsolidationRates": {
post: {
parameters: [
@@ -167320,10 +167427,10 @@ export default {
"leaseIncrementalBorrowingRate",
"leaseShortTermExpedient",
"leaseReminderDays",
+ "serialNumberTiming",
"requireBackflushStorageUnit",
"preventNegativeBackflush",
- "receiptQuantitiesStartAtZero",
- "serialNumberTiming"
+ "receiptQuantitiesStartAtZero"
],
properties: {
id: {
@@ -167712,6 +167819,11 @@ export default {
format: "integer",
type: "integer"
},
+ serialNumberTiming: {
+ default: "jobCreation",
+ format: "text",
+ type: "string"
+ },
requireBackflushStorageUnit: {
default: false,
format: "boolean",
@@ -167726,11 +167838,6 @@ export default {
default: false,
format: "boolean",
type: "boolean"
- },
- serialNumberTiming: {
- default: "jobCreation",
- format: "text",
- type: "string"
}
},
type: "object"
@@ -223539,6 +223646,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.companySettings.serialNumberTiming": {
+ name: "serialNumberTiming",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.companySettings.requireBackflushStorageUnit": {
name: "requireBackflushStorageUnit",
required: false,
@@ -223557,12 +223670,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.companySettings.serialNumberTiming": {
- name: "serialNumberTiming",
- required: false,
- in: "query",
- type: "string"
- },
"body.part": {
name: "part",
description: "part",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 48140a5e31..900d95a4d0 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -94596,11 +94596,12 @@ export type Database = {
Args: { alphabet: string; mask: number; size: number; step: number }
Returns: string
}
- number_serial_units_for_completion: {
+ number_serial_units_for_receipt: {
Args: {
p_company_id: string
- p_job_id: string
- p_quantity_complete: number
+ p_item_id: string
+ p_location_id: string
+ p_unit_ids: string[]
}
Returns: number
}
@@ -94773,6 +94774,15 @@ export type Database = {
Args: { p_company_id: string; p_period_id: string; p_user_id: string }
Returns: undefined
}
+ split_serial_units_for_completion: {
+ Args: {
+ p_company_id: string
+ p_count: number
+ p_job_id: string
+ p_make_method_id: string
+ }
+ Returns: number
+ }
storage_unit_block_location_change_with_children: {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
diff --git a/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql b/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql
index 2b5cbe0e9f..811f547054 100644
--- a/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql
+++ b/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql
@@ -1,4 +1,5 @@
--- Serial numbers at production: number the units a job completion takes.
+-- Serial numbers at production: the receipt that completes a job numbers the
+-- units it takes.
--
-- 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
@@ -7,13 +8,16 @@
-- '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
--- every unit.
+-- unnumbered, whatever the timing.
+--
+-- complete_job_to_inventory does it itself, in both serial branches (receipt and
+-- Make to Asset): it picks the units, and when the job's rows hold too few it
+-- splits the rest off the unsplit seed (split_serial_units_for_completion) and
+-- picks again; then it numbers the unnumbered units it took
+-- (number_serial_units_for_receipt) and receives them. One query picks the units,
+-- so numbering and receipt cannot take different ones. Every caller (the ERP's
+-- completeJob, and the sync_finish_job_operation interceptor when the last
+-- operation is marked Done) gets it by calling complete_job_to_inventory.
--
-- get_next_serial_numbers is the one serial allocator: the TypeScript
-- getNextSerialNumbers (@carbon/database/sequence) calls it, so job creation,
@@ -115,31 +119,28 @@ BEGIN
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 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.
+-- Make up to p_count more of a serial job's units receivable one at a time.
+-- Splits them off the job's unsplit seed (the seed itself becomes the last unit
+-- when it gives all it holds), then creates the units no row holds yet, up to
+-- the job quantity less the units already in rows (a scrapped unit does not
+-- count: the job still owes it). The shop floor's first completion or scrap of
+-- the seed leaves it holding one unit and adds the next units one at a time, so
+-- the rows can cover fewer units than the job quantity. Returns how many units
+-- it made receivable, which can be fewer than p_count; the completion then
+-- refuses with its own message. The units are left unnumbered:
+-- number_serial_units_for_receipt numbers the ones the completion takes.
--
--- 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
--- time, so after it the rows cover fewer units than the job quantity. Those
--- units are created here, up to the job quantity less the units already in
--- rows (a scrapped unit does not count: the job still owes it).
+-- Only for an item with a serial sequence. Without one there is nothing to
+-- number, and the completion receives against the seed as it always has.
--
--- SECURITY INVOKER, like backflush_job_materials: its callers are the
--- sync_finish_job_operation interceptor, which the event dispatcher runs as the
--- owner, and completeJob on a direct connection. Called through the API it runs
--- under the caller's RLS, so it cannot split or number units the caller could
--- not update.
-CREATE OR REPLACE FUNCTION public.number_serial_units_for_completion(
+-- SECURITY INVOKER, like backflush_job_materials: complete_job_to_inventory
+-- calls it as the owner. Called through the API it runs under the caller's
+-- RLS, so it cannot split units the caller could not update.
+CREATE OR REPLACE FUNCTION public.split_serial_units_for_completion(
p_job_id text,
- p_quantity_complete numeric,
- p_company_id text
+ p_make_method_id text,
+ p_company_id text,
+ p_count integer
)
RETURNS integer
LANGUAGE plpgsql
@@ -148,37 +149,25 @@ CREATE OR REPLACE FUNCTION public.number_serial_units_for_completion(
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_template record;
v_from_seed integer := 0;
v_new_units integer := 0;
- v_seed_becomes_unit boolean := false;
v_missing integer := 0;
v_unstarted numeric;
- v_template record;
- v_count integer;
- v_serials text[];
- v_location record;
BEGIN
- PERFORM assert_company_access(p_company_id);
+ IF p_count IS NULL OR p_count < 1 THEN
+ RETURN 0;
+ END IF;
- SELECT j."itemId", j.quantity, j."quantityReceivedToInventory", j."fixedAssetClassId",
- j."fixedAssetId", j."locationId", i."itemTrackingType"
+ SELECT j."itemId", j.quantity
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
+ IF NOT FOUND THEN
RETURN 0;
END IF;
- -- 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;
@@ -186,222 +175,1339 @@ BEGIN
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
+ SELECT *
+ INTO v_seed
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = p_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
+ FOR UPDATE;
+ IF FOUND THEN
+ v_from_seed := LEAST(p_count, v_seed.quantity::integer);
+ v_new_units := CASE
+ WHEN v_seed.quantity = v_from_seed THEN v_from_seed - 1
+ ELSE v_from_seed
+ END;
+
+ UPDATE "trackedEntity"
+ SET quantity = v_seed.quantity - v_new_units
+ 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",
+ "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",
+ p_company_id, v_seed."createdBy"
+ FROM generate_series(1, v_new_units) AS n;
+ END IF;
+
+ v_missing := p_count - v_from_seed;
+ IF v_missing > 0 THEN
+ SELECT v_job.quantity - COALESCE(SUM(te.quantity), 0)
+ INTO v_unstarted
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = p_make_method_id
+ AND te."companyId" = p_company_id
+ AND te.status <> 'Scrapped';
+ v_missing := LEAST(v_missing, GREATEST(trunc(v_unstarted), 0)::integer);
+ END IF;
+ IF v_missing > 0 THEN
+ SELECT *
+ INTO v_template
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = p_make_method_id
+ AND te."companyId" = p_company_id
+ ORDER BY te."createdAt", te."id"
+ LIMIT 1;
+ IF NOT FOUND THEN
+ v_missing := 0;
+ END IF;
+ END IF;
+ IF v_missing > 0 THEN
+ INSERT INTO "trackedEntity" (
+ "createdAt", "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",
+ quantity, status, attributes, "itemId",
+ "companyId", "createdBy"
+ )
+ SELECT
+ now() + (v_new_units + n) * interval '1 millisecond',
+ v_template."sourceDocument", v_template."sourceDocumentId", v_template."sourceDocumentReadableId",
+ 1, 'Reserved'::"trackedEntityStatus",
+ jsonb_build_object('Job', p_job_id, 'Job Make Method', p_make_method_id),
+ v_job."itemId",
+ p_company_id, v_template."createdBy"
+ FROM generate_series(1, v_missing) AS n;
+ END IF;
+
+ RETURN v_from_seed + v_missing;
+END;
+$function$;
+
+-- Number the units of p_unit_ids that have no serial yet, in array order, from
+-- the item's sequence, with the location's %{location} context. Returns how
+-- many it numbered: none when every unit is numbered or the item has no
+-- sequence. SECURITY INVOKER for the same reason as
+-- split_serial_units_for_completion.
+CREATE OR REPLACE FUNCTION public.number_serial_units_for_receipt(
+ p_unit_ids text[],
+ p_item_id text,
+ p_company_id text,
+ p_location_id text
+)
+ RETURNS integer
+ LANGUAGE plpgsql
+ SECURITY INVOKER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ v_ids text[];
+ v_serials text[];
+ v_location record;
+BEGIN
+ v_ids := ARRAY(
+ SELECT te."id"
+ FROM "trackedEntity" te
+ JOIN unnest(p_unit_ids) WITH ORDINALITY AS u(id, ord) ON u.id = te."id"
+ WHERE te."companyId" = p_company_id
+ AND te."readableId" IS NULL
+ ORDER BY u.ord
+ );
+ IF cardinality(v_ids) = 0 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
+ SELECT "code", "name"
+ INTO v_location
+ FROM "location"
+ WHERE "id" = p_location_id
+ AND "companyId" = p_company_id;
+
+ v_serials := get_next_serial_numbers(
+ p_item_id, p_company_id, cardinality(v_ids), v_location."code", v_location."name"
+ );
+ IF cardinality(v_serials) < cardinality(v_ids) 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
+ UPDATE "trackedEntity" te
+ SET "readableId" = s.serial
+ FROM unnest(v_ids, v_serials) AS s(id, serial)
+ WHERE te."id" = s.id
+ AND te."companyId" = p_company_id;
+
+ RETURN cardinality(v_ids);
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.complete_job_to_inventory(p_job_id text, p_quantity_complete numeric, p_storage_unit_id text DEFAULT NULL::text, p_location_id text DEFAULT NULL::text, p_company_id text DEFAULT NULL::text, p_user_id text DEFAULT NULL::text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ v_item_id TEXT;
+ v_item_tracking_type "itemTrackingType";
+ v_cogs_account TEXT;
+ v_sales_order_line_id TEXT;
+ v_line_quantity_complete NUMERIC;
+ v_job_company_id TEXT;
+ v_prior_quantity_received NUMERIC;
+ v_quantity_received_to_inventory NUMERIC;
+ v_job_id_readable TEXT;
+ v_job_make_method RECORD;
+ v_tracked_entity RECORD;
+ v_posting_status "journalEntryStatus";
+ v_company_group_id TEXT;
+ v_raw_materials_account TEXT;
+ v_finished_goods_account TEXT;
+ v_item_inventory_account TEXT;
+ v_item_inventory_description TEXT;
+ v_wip_account TEXT;
+ v_labor_absorption_account TEXT;
+ v_overhead_absorption_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_item TEXT;
+ v_dimension_location TEXT;
+ v_dimension_cost_center TEXT;
+ v_dimension_employee TEXT;
+ v_event RECORD;
+ v_duration_hours NUMERIC;
+ v_rate NUMERIC;
+ v_labor_cost NUMERIC;
+ v_overhead_cost NUMERIC;
+ v_event_reference TEXT;
+ v_labor_journal_line_reference TEXT;
+ v_labor_accounting_period_id TEXT;
+ v_labor_journal_entry_id TEXT;
+ v_labor_journal_id TEXT;
+ v_labor_jl_id TEXT;
+ v_accumulated_wip_cost NUMERIC;
+ v_today DATE;
+ v_journal_line_reference TEXT;
+ v_accounting_period_id TEXT;
+ v_journal_entry_id TEXT;
+ v_journal_id TEXT;
+ v_jl_ids TEXT[];
+ v_new_per_unit_cost NUMERIC;
+ v_costing_method TEXT;
+ v_existing_unit_cost NUMERIC;
+ v_item_posting_group_id TEXT;
+ v_job_location_id TEXT;
+ v_total_qty_on_hand NUMERIC;
+ v_prior_qty NUMERIC;
+ v_prior_value NUMERIC;
+ v_new_unit_cost NUMERIC;
+ v_serial_unit_ids TEXT[];
+ v_issued_units_received NUMERIC := 0;
+ v_company_today DATE := company_today(p_company_id);
+ v_job_asset_class_id TEXT;
+ v_job_asset_id TEXT;
+ v_asset_target TEXT;
+ v_target_class RECORD;
+ v_asset_ids TEXT[] := '{}';
+ v_transfer_ids TEXT[] := '{}';
+ v_asset_unit_ids TEXT[];
+ v_split_done BOOLEAN := false;
+ v_new_asset_id TEXT;
+ v_transfer_id TEXT;
+ v_per_unit_cost NUMERIC;
+ v_activity_id TEXT;
+ v_asset_class_id TEXT;
+ v_journal_source_type "journalEntrySourceType" := 'Job Receipt';
+ v_journal_document_type "journalLineDocumentType" := 'Job Receipt';
+ v_journal_description TEXT;
+ v_dimension_fixed_asset_class TEXT;
+ i INTEGER;
+BEGIN
+ PERFORM assert_company_access(p_company_id);
+
+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator
+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));
+
+ -- Fetch job details. The row lock makes a concurrent completion wait and then
+ -- read this completion's cumulative quantity, so both cannot compute the same
+ -- receipt delta.
+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId", "salesOrderLineId", "companyId",
+ "fixedAssetClassId", "fixedAssetId"
+ INTO STRICT v_item_id, v_prior_quantity_received, v_job_id_readable, v_job_location_id, v_sales_order_line_id, v_job_company_id,
+ v_job_asset_class_id, v_job_asset_id
+ FROM "job"
+ WHERE id = p_job_id
FOR UPDATE;
- -- A completion this call waited on may have received units since the read
- -- above: take the delta from what is received now.
- SELECT COALESCE(j."quantityReceivedToInventory", 0)
- INTO v_job."quantityReceivedToInventory"
- FROM "job" j
- WHERE j."id" = p_job_id
- AND j."companyId" = p_company_id;
- v_delta := p_quantity_complete - v_job."quantityReceivedToInventory";
- IF v_delta IS NULL OR v_delta <= 0 OR v_delta <> trunc(v_delta) THEN
- RETURN 0;
+ -- SECURITY DEFINER bypasses RLS: bind the call to the job's own company so a
+ -- caller can never complete another tenant's job or post into a mismatched
+ -- company's ledger/journal.
+ IF p_company_id IS NULL OR v_job_company_id IS DISTINCT FROM p_company_id THEN
+ RAISE EXCEPTION 'Job % does not belong to company %', p_job_id, COALESCE(p_company_id, '<null>');
END IF;
- -- 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
- )
- )
+ -- Make to Asset: a job that targets a fixed asset class completes into one
+ -- new asset per unit; a job attached to a Construction in Progress asset
+ -- sweeps its cost onto that asset. Either way the units never enter stock.
+ v_asset_target := CASE
+ WHEN v_job_asset_id IS NOT NULL THEN 'asset'
+ WHEN v_job_asset_class_id IS NOT NULL THEN 'class'
+ END;
+
+ IF v_asset_target IS NOT NULL AND v_sales_order_line_id IS NOT NULL THEN
+ RAISE EXCEPTION 'A job linked to a sales order line cannot complete to a fixed asset';
+ END IF;
+
+ -- Non-Inventory items (services) never enter inventory
+ SELECT "itemTrackingType"
+ INTO v_item_tracking_type
+ FROM "item"
+ WHERE id = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- A job that targets a class makes new assets, and every one of them is a
+ -- fleet unit that rental, return to inventory and capitalization follow by
+ -- its serial. So the item must be serialized, whatever the quantity.
+ IF v_asset_target = 'class'
+ AND v_item_tracking_type IS DISTINCT FROM 'Serial' THEN
+ RAISE EXCEPTION 'A job that completes to a fixed asset class needs a serialized item';
+ END IF;
+
+ -- A sweep onto an asset under construction makes no new unit, so an
+ -- unserialized item is fine there, but only as a single unit: an untracked
+ -- or batch quantity cannot be told apart.
+ IF v_asset_target = 'asset'
+ AND v_item_tracking_type IS DISTINCT FROM 'Serial'
+ AND COALESCE(p_quantity_complete, 0) <> 1 THEN
+ RAISE EXCEPTION 'Make to Asset needs a serialized item or a quantity of one';
+ END IF;
+
+ -- A stocked item completed at zero marks the job Completed, receives nothing
+ -- and backflushes nothing. Refuse it at the one function every completion path
+ -- crosses (ERP complete route, API/MCP, sync_finish_job_operation).
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND COALESCE(p_quantity_complete, 0) <= 0 THEN
+ RAISE EXCEPTION 'Quantity completed must be greater than 0 for job %', v_job_id_readable;
+ END IF;
+
+ -- Delta for this completion: drives the itemLedger/costLedger quantities and
+ -- the WIP-discharge journal. The job column itself stores the CUMULATIVE
+ -- quantity (get_inventory_quantities computes on-production supply as
+ -- production + scrap - received - shipped, which requires cumulative).
+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_prior_quantity_received, 0);
+
+ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)
+ SELECT *
+ INTO STRICT v_job_make_method
+ FROM "jobMakeMethod"
+ WHERE "jobId" = p_job_id
+ AND "parentMaterialId" IS NULL;
+
+ -- Serial units are received one tracked entity at a time, so a fractional
+ -- quantity cannot be honoured; it would be stored on the job and rounded by
+ -- the receipt.
+ IF v_job_make_method."requiresSerialTracking"
+ AND p_quantity_complete <> trunc(p_quantity_complete) THEN
+ RAISE EXCEPTION 'Quantity completed must be a whole number for serial-tracked job %', v_job_id_readable;
+ END IF;
+
+ -- The quantity is cumulative, so a stocked job cannot be completed at less than
+ -- it has already received: the negative delta would post a negative receipt,
+ -- cost layer and WIP journal. Received stock is corrected through inventory
+ -- adjustments, not by re-completing the job. Non-Inventory jobs never receive.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND p_quantity_complete < COALESCE(v_prior_quantity_received, 0) THEN
+ RAISE EXCEPTION 'Quantity completed cannot be lower than the % already received for job %',
+ COALESCE(v_prior_quantity_received, 0), v_job_id_readable;
+ END IF;
+
+ -- Update job status. quantityReceivedToInventory is CUMULATIVE (not the
+ -- delta): re-completions previously overwrote it with the delta, corrupting
+ -- get_inventory_quantities' on-production supply math. Non-Inventory items
+ -- never receive to inventory, so their value is left unchanged.
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = p_quantity_complete,
+ "quantityReceivedToInventory" = CASE
+ WHEN v_item_tracking_type = 'Non-Inventory' THEN v_prior_quantity_received
+ ELSE p_quantity_complete
+ END,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = p_job_id;
+
+ -- Make to Asset: the newly completed units leave the job as fixed assets
+ -- instead of stock. Assets and their transfers are created at cost 0 here and
+ -- priced once the WIP journal exists below; with accounting disabled they stay
+ -- at 0, the same posture as registering an asset with accounting off.
+ IF v_asset_target IS NOT NULL AND v_quantity_received_to_inventory > 0 THEN
+ IF v_asset_target = 'class' THEN
+ SELECT fac.*
+ INTO STRICT v_target_class
+ FROM "fixedAssetClass" fac
+ WHERE fac.id = v_job_asset_class_id
+ AND fac."companyId" = p_company_id;
+ ELSE
+ SELECT fac.*
+ INTO STRICT v_target_class
+ FROM "fixedAsset" fa
+ JOIN "fixedAssetClass" fac ON fac.id = fa."fixedAssetClassId"
+ WHERE fa.id = v_job_asset_id
+ AND fa."companyId" = p_company_id;
+
+ -- Only a Construction in Progress asset accumulates cost; sweeping WIP
+ -- onto a live, depreciating asset would restate its basis.
+ IF NOT v_target_class."isConstructionInProgress" THEN
+ RAISE EXCEPTION 'Job % targets fixed asset % which is not in a Construction in Progress class',
+ v_job_id_readable, v_job_asset_id;
+ END IF;
+ END IF;
+ v_asset_class_id := v_target_class.id;
+
+ IF v_job_make_method."requiresSerialTracking" THEN
+ -- The same unit order as a receipt: shop-floor-finished units first, then
+ -- by serial number. A unit already turned into an asset is never taken
+ -- twice (it is Consumed and carries the asset id).
+ --
+ -- Units still on the job's unsplit seed (a deferred serial number timing)
+ -- are split off and the units picked again, then the units taken are
+ -- numbered: the completion is their first touch.
+ LOOP
+ v_asset_unit_ids := ARRAY(
+ SELECT te.id
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_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
+ FOR UPDATE OF te
+ );
+ EXIT WHEN v_split_done
+ OR COALESCE(array_length(v_asset_unit_ids, 1), 0) >= v_quantity_received_to_inventory;
+ v_split_done := true;
+ EXIT WHEN split_serial_units_for_completion(
+ p_job_id, v_job_make_method.id, p_company_id,
+ v_quantity_received_to_inventory::INTEGER - COALESCE(array_length(v_asset_unit_ids, 1), 0)
+ ) = 0;
+ END LOOP;
+
+ IF COALESCE(array_length(v_asset_unit_ids, 1), 0) < v_quantity_received_to_inventory THEN
+ RAISE EXCEPTION 'Job % has % serial unit(s) left to capitalize, fewer than the % being completed',
+ v_job_id_readable, COALESCE(array_length(v_asset_unit_ids, 1), 0), v_quantity_received_to_inventory;
+ END IF;
+
+ v_asset_unit_ids := v_asset_unit_ids[1:v_quantity_received_to_inventory::INTEGER];
+ PERFORM number_serial_units_for_receipt(
+ v_asset_unit_ids, v_item_id, p_company_id, v_job_location_id
+ );
+ ELSE
+ -- A class target makes one asset per serial unit. A job created before
+ -- its item was serialized has no units to follow, and would otherwise
+ -- make ONE asset for the whole quantity.
+ IF v_asset_target = 'class' THEN
+ RAISE EXCEPTION 'Job % does not track serial numbers, so it cannot complete to a fixed asset class',
+ v_job_id_readable;
+ END IF;
+ -- One untracked or batch unit swept onto an asset under construction; the
+ -- guard above holds the quantity at 1.
+ v_asset_unit_ids := ARRAY[NULL::TEXT];
+ END IF;
+
+ FOR i IN 1..array_length(v_asset_unit_ids, 1) LOOP
+ IF v_asset_target = 'class' THEN
+ INSERT INTO "fixedAsset" (
+ "fixedAssetId", "fixedAssetClassId", name, "serialNumber",
+ "itemId", "trackedEntityId", quantity, status,
+ "depreciationMethod", "usefulLifeMonths", "residualValuePercent",
+ "acquisitionCost", "acquisitionDate", "depreciationStartDate",
+ "locationId", "companyId", "createdBy"
)
- 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
+ SELECT
+ get_next_sequence('fixedAsset', p_company_id), v_job_asset_class_id,
+ it.name || ' ' || COALESCE(te."readableId", v_job_id_readable), te."readableId",
+ v_item_id, v_asset_unit_ids[i], 1,
+ CASE WHEN v_target_class."isConstructionInProgress" THEN 'Under Construction' ELSE 'Active' END::"fixedAssetStatus",
+ v_target_class."depreciationMethod", v_target_class."usefulLifeMonths", v_target_class."residualValuePercent",
+ 0, v_company_today, v_company_today,
+ v_job_location_id, p_company_id, p_user_id
+ FROM "item" it
+ LEFT JOIN "trackedEntity" te ON te.id = v_asset_unit_ids[i]
+ WHERE it.id = v_item_id
+ RETURNING id INTO v_new_asset_id;
+
+ INSERT INTO "fixedAssetTransfer" (
+ "transferId", type, "sourceType", "fixedAssetId", "itemId", "trackedEntityId",
+ "jobId", "locationId", quantity, "transferDate", amount, status,
+ "postedAt", "postedBy", "companyId", "createdBy"
+ ) VALUES (
+ get_next_sequence('fixedAssetTransfer', p_company_id), 'Capitalization', 'Job',
+ v_new_asset_id, v_item_id, v_asset_unit_ids[i],
+ p_job_id, v_job_location_id, 1, v_company_today, 0, 'Posted',
+ NOW(), p_user_id, p_company_id, p_user_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
- );
+ RETURNING id INTO v_transfer_id;
+
+ v_asset_ids := v_asset_ids || v_new_asset_id;
+ v_transfer_ids := v_transfer_ids || v_transfer_id;
+ ELSE
+ v_new_asset_id := v_job_asset_id;
+ END IF;
+
+ -- The unit is consumed into the asset: it is no longer stock, and the
+ -- asset id on its attributes is how the fleet finds it again.
+ IF v_asset_unit_ids[i] IS NOT NULL THEN
+ UPDATE "trackedEntity"
+ SET status = 'Consumed',
+ attributes = COALESCE(attributes, '{}'::jsonb) || jsonb_build_object('Fixed Asset', v_new_asset_id)
+ WHERE id = v_asset_unit_ids[i];
+
+ INSERT INTO "trackedActivity" (
+ type, "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",
+ attributes, "companyId", "createdBy"
+ )
+ SELECT
+ 'Capitalize', 'Fixed Asset', fa.id, fa."fixedAssetId",
+ jsonb_build_object('Fixed Asset', fa.id, 'Job', p_job_id), p_company_id, p_user_id
+ FROM "fixedAsset" fa
+ WHERE fa.id = v_new_asset_id
+ RETURNING id INTO v_activity_id;
+
+ INSERT INTO "trackedActivityInput" (
+ "trackedActivityId", "trackedEntityId", quantity, "companyId", "createdBy"
+ ) VALUES (
+ v_activity_id, v_asset_unit_ids[i], 1, p_company_id, p_user_id
+ );
+ END IF;
+ END LOOP;
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
- );
+ -- Complete the quantities behind the status: raise the terminal operations so
+ -- the routing agrees with a Completed job, and refuse a serial job whose units
+ -- still need serial numbers.
+ --
+ -- AFTER the status flip, never before. Closing an operation fires
+ -- sync_finish_job_operation, which re-enters this function for a job in
+ -- Ready/In Progress/Paused. Being a BEFORE row trigger it runs mid-statement,
+ -- so it reads the operation's OLD quantityComplete (still 0 on a desk
+ -- completion), falls back to the job's planned quantity and receives a second
+ -- time — while this call's own receipt delta was computed further up, before
+ -- any of it happened. With the job already Completed the interceptor's status
+ -- gate returns early, so the operations close without a second receipt.
+ PERFORM complete_job_remaining_quantities(p_job_id, p_quantity_complete, p_user_id);
+
+ -- Services never ship, so job completion is the fulfillment event: advance
+ -- the linked sales-order line the way post-shipment does for physical lines.
+ -- Lives HERE (not in app code) because completion has multiple entry points —
+ -- the ERP complete route AND the sync_finish_job_operation interceptor that
+ -- auto-completes when the last operation finishes. Recomputed from ALL jobs
+ -- on the line, so it is idempotent and lot-split safe. Runs before the
+ -- accounting-enabled / zero-WIP early returns.
+ -- NARROWED: only genuine Service lines (salesOrderLineType = 'Service') fulfill
+ -- by completion. They never receive a shipment line (the `create` edge fn skips
+ -- salesOrderLineType='Service'), so completion is their only fulfillment event.
+ -- A Non-Inventory *Part* (or Material/Tool/etc.) still ships via post-shipment and
+ -- must NOT be auto-fulfilled here — that was marking SO lines "Shipped" with no shipment.
+ IF v_item_tracking_type = 'Non-Inventory' AND v_sales_order_line_id IS NOT NULL
+ AND EXISTS (
+ SELECT 1 FROM "salesOrderLine" sol
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id
+ AND sol."salesOrderLineType" = 'Service'
+ ) THEN
+ SELECT COALESCE(SUM("quantityComplete"), 0)
+ INTO v_line_quantity_complete
+ FROM "job"
+ WHERE "salesOrderLineId" = v_sales_order_line_id
+ AND "companyId" = p_company_id
+ AND status != 'Cancelled';
+
+ UPDATE "salesOrderLine" sol
+ SET "quantitySent" = v_line_quantity_complete,
+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_line_quantity_complete >= sol."saleQuantity"),
+ "sentDate" = CASE
+ WHEN COALESCE(sol."saleQuantity", 0) > 0
+ AND v_line_quantity_complete >= sol."saleQuantity"
+ AND sol."sentDate" IS NULL
+ THEN v_company_today
+ ELSE sol."sentDate"
+ END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id;
+ END IF;
- v_short := v_delta::integer - COALESCE(array_length(v_taken, 1), 0);
- IF v_short > 0 THEN
+ -- Insert itemLedger entries based on tracking type.
+ -- Non-Inventory items (services) never enter inventory, and a re-completion at
+ -- the quantity already received has nothing new to receive.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND v_asset_target IS NULL
+ AND v_quantity_received_to_inventory > 0 THEN
+ IF v_job_make_method."requiresBatchTracking" 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"
+ INTO v_tracked_entity
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND "companyId" = p_company_id
+ AND status != 'Consumed'
+ ORDER BY "createdAt" DESC
LIMIT 1;
- IF FOUND THEN
- v_from_seed := LEAST(v_short, v_seed.quantity::integer);
- v_seed_becomes_unit := v_seed.quantity = v_from_seed;
- v_new_units := CASE WHEN v_seed_becomes_unit THEN v_from_seed - 1 ELSE v_from_seed END;
- IF v_seed_becomes_unit AND v_seed."readableId" IS NULL THEN
- v_to_number := v_to_number || v_seed."id";
- END IF;
+
+ -- The job's own lot can already be Consumed by a lot MERGE: the batch
+ -- completion prompt offers the merge before member jobs are received,
+ -- and the merge is identity-only (it moves no unreceived stock). This
+ -- job's receipt must then land on the merge's output lot — walk Merge
+ -- activities from the job's lot to the terminal, still-live output.
+ IF v_tracked_entity.id IS NULL THEN
+ WITH RECURSIVE merge_walk(id) AS (
+ SELECT te.id
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id
+ AND te."companyId" = p_company_id
+ UNION
+ SELECT tao."trackedEntityId"
+ FROM merge_walk
+ JOIN "trackedActivityInput" tai
+ ON tai."trackedEntityId" = merge_walk.id
+ AND tai."companyId" = p_company_id
+ JOIN "trackedActivity" ta
+ ON ta.id = tai."trackedActivityId"
+ AND ta."companyId" = p_company_id
+ AND ta.type = 'Merge'
+ JOIN "trackedActivityOutput" tao
+ ON tao."trackedActivityId" = ta.id
+ AND tao."companyId" = p_company_id
+ )
+ SELECT te.*
+ INTO v_tracked_entity
+ FROM merge_walk
+ JOIN "trackedEntity" te ON te.id = merge_walk.id
+ WHERE te.status != 'Consumed'
+ ORDER BY te."createdAt" DESC
+ LIMIT 1;
END IF;
- -- Units no row holds yet.
- v_missing := v_short - v_from_seed;
- IF v_missing > 0 THEN
- SELECT v_job.quantity - COALESCE(SUM(te.quantity), 0)
- INTO v_unstarted
- FROM "trackedEntity" te
- WHERE te.attributes->>'Job Make Method' = v_make_method."id"
- AND te."companyId" = p_company_id
- AND te.status <> 'Scrapped';
- IF v_unstarted < v_missing THEN
- RETURN 0;
- END IF;
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Tracked entity not found';
+ END IF;
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ ELSIF v_job_make_method."requiresSerialTracking" THEN
+ -- Receive exactly the newly completed units: finished units first (Available
+ -- on the shop floor, or already issued elsewhere), then by serial number. A
+ -- unit this job already received is never received again, so re-completion
+ -- cannot double-count. Rejected (failed inspection) and Scrapped units never
+ -- enter stock. The candidates are locked so a concurrent completion cannot
+ -- take the same units.
+ --
+ -- A finished unit can leave before its job is received: the MES issues it
+ -- into another job (or a shipment takes it), which marks it Consumed and
+ -- books it out of stock. It was still made here, so it is received too.
+ -- Skipping it left the job short of units, and its last unit could never
+ -- be completed. Only a unit that was booked out counts: receiving one that
+ -- never left stock would add a unit that is not there.
+ --
+ -- Units still on the job's unsplit seed (a deferred serial number timing)
+ -- are split off and the units picked again, then the units taken are
+ -- numbered: the completion is their first touch.
+ LOOP
+ v_serial_unit_ids := ARRAY(
+ SELECT te.id
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_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
+ FOR UPDATE OF te
+ );
+ EXIT WHEN v_split_done
+ OR COALESCE(array_length(v_serial_unit_ids, 1), 0) >= v_quantity_received_to_inventory;
+ v_split_done := true;
+ EXIT WHEN split_serial_units_for_completion(
+ p_job_id, v_job_make_method.id, p_company_id,
+ v_quantity_received_to_inventory::INTEGER - COALESCE(array_length(v_serial_unit_ids, 1), 0)
+ ) = 0;
+ END LOOP;
+
+ IF COALESCE(array_length(v_serial_unit_ids, 1), 0) >= v_quantity_received_to_inventory THEN
+ PERFORM number_serial_units_for_receipt(
+ v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER],
+ v_item_id, p_company_id, v_job_location_id
+ );
+
+ -- An issued unit is received where it was booked out, so its own
+ -- movements net to nothing in that bin.
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ )
+ SELECT
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, 1,
+ CASE WHEN issued.id IS NULL THEN p_location_id ELSE issued."locationId" END,
+ CASE WHEN issued.id IS NULL THEN p_storage_unit_id ELSE issued."storageUnitId" END,
+ te.id, p_user_id
+ FROM unnest(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER]) AS unit_id
+ JOIN "trackedEntity" te ON te.id = unit_id
+ LEFT JOIN LATERAL (
+ SELECT il.id, il."locationId", il."storageUnitId"
+ FROM "itemLedger" il
+ WHERE il."trackedEntityId" = te.id
+ AND il."companyId" = p_company_id
+ AND il.quantity < 0
+ AND te.status = 'Consumed'
+ ORDER BY il."createdAt" DESC
+ LIMIT 1
+ ) issued ON true;
+
+ SELECT COUNT(*)
+ INTO v_issued_units_received
+ FROM "trackedEntity"
+ WHERE id = ANY(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER])
+ AND status = 'Consumed';
+
+ -- An issued unit stays Consumed: it is in the job it went to.
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE id = ANY(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER])
+ AND status <> 'Consumed';
+
+ ELSE
+ -- An item with no serial sequence is never numbered or split, so the job
+ -- still holds ONE seed entity covering every unit and there is nothing to
+ -- receive one at a time. Receive the delta against that seed,
+ -- the way the batch branch does. Raising here instead would abort the
+ -- jobOperation UPDATE itself: completion also runs inside
+ -- sync_finish_job_operation, a BEFORE trigger interceptor.
SELECT *
- INTO v_template
+ INTO v_tracked_entity
FROM "trackedEntity" te
- WHERE te.attributes->>'Job Make Method' = v_make_method."id"
+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id
AND te."companyId" = p_company_id
- ORDER BY te."createdAt", te."id"
+ AND te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')
+ AND te.quantity > 1
+ ORDER BY te."createdAt"
+ LIMIT 1
+ FOR UPDATE;
+
+ -- Genuinely short of units (some scrapped, some already received) rather
+ -- than un-numbered: receiving fewer than completed would leave the job's
+ -- received quantity ahead of the ledger.
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Job % has % serial unit(s) left to receive, fewer than the % being completed',
+ v_job_id_readable, COALESCE(array_length(v_serial_unit_ids, 1), 0), v_quantity_received_to_inventory;
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE id = v_tracked_entity.id;
+ END IF;
+
+ ELSE
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ p_user_id
+ );
+ END IF;
+ END IF;
+
+ -- Update pickMethod defaultStorageUnitId if needed
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND v_asset_target IS NULL AND p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN
+ IF NOT EXISTS (
+ SELECT 1 FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id
+ AND "storageUnitId" IS NOT NULL
+ AND "storageUnitId" != p_storage_unit_id
+ LIMIT 1
+ ) THEN
+ IF EXISTS (
+ SELECT 1 FROM "pickMethod"
+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id
+ ) THEN
+ UPDATE "pickMethod"
+ SET "defaultStorageUnitId" = p_storage_unit_id,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id;
+ ELSE
+ INSERT INTO "pickMethod" (
+ "itemId", "locationId", "defaultStorageUnitId",
+ "companyId", "createdBy", "createdAt"
+ ) VALUES (
+ v_item_id, p_location_id, p_storage_unit_id,
+ p_company_id, p_user_id, NOW()
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ -- Backflush unissued materials (delegated to shared function)
+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+
+ -- Every company posts; the accounting cutover decides the status
+ -- (.ai/specs/2026-10-08-accounting-cutover.md section 1).
+ v_posting_status := journal_posting_status(p_company_id);
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount", "laborAbsorptionAccount", "overheadAbsorptionAccount", "costOfGoodsSoldAccount"
+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account, v_labor_absorption_account, v_overhead_absorption_account, v_cogs_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Resolve Raw Materials vs Finished Goods from the produced item:
+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.
+ SELECT
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END
+ INTO v_item_inventory_account, v_item_inventory_description
+ FROM "item" i
+ WHERE i."id" = v_item_id
+ AND i."companyId" = p_company_id;
+
+ -- Non-Inventory (Service): the produced output is never stocked, so completion
+ -- relieves WIP straight to Cost of Goods Sold (Epicor "Make Direct" pattern).
+ -- >>> REV-REC SEAM (spec .ai/specs/2026-07-04-revenue-recognition.md, issue #1048):
+ -- when revenue recognition lands, Percent-of-Completion elements will gate THIS
+ -- branch off and post COGS as-incurred in the recognition run instead. <<<
+ IF v_item_tracking_type = 'Non-Inventory' THEN
+ v_item_inventory_account := v_cogs_account;
+ v_item_inventory_description := 'Cost of Goods Sold';
+ END IF;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),
+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END),
+ MAX(CASE WHEN "entityType" = 'FixedAssetClass' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,
+ v_dimension_cost_center, v_dimension_employee, v_dimension_fixed_asset_class
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee', 'FixedAssetClass');
+
+ -- Post unposted production events as labor/machine + overhead absorption JEs
+ -- (mirrors post-production-event; this is the catch-up path for events that
+ -- were never posted individually)
+ FOR v_event IN
+ SELECT
+ pe.id,
+ pe.duration,
+ pe.type,
+ pe."employeeId",
+ wc."laborRate",
+ wc."machineRate",
+ wc."overheadRate"
+ FROM "productionEvent" pe
+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"
+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"
+ WHERE jo."jobId" = p_job_id
+ AND pe."endTime" IS NOT NULL
+ AND pe."postedToGL" = false
+ AND pe.duration > 0
+ ORDER BY pe.id
+ -- Waits for a concurrent post-production-event, then skips the event if
+ -- it posted it (the WHERE is re-checked on the committed row).
+ FOR UPDATE OF pe
+ LOOP
+ v_duration_hours := v_event.duration::NUMERIC / 3600;
+ v_rate := CASE
+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)
+ ELSE COALESCE(v_event."laborRate", 0)
+ END;
+ v_labor_cost := v_duration_hours * v_rate;
+ v_overhead_cost := v_duration_hours * COALESCE(v_event."overheadRate", 0);
+ v_event_reference := 'production-event:' || v_event.id;
+
+ IF (v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL)
+ OR (v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL) THEN
+ v_labor_journal_line_reference := nanoid();
+
+ -- Get current accounting period
+ SELECT id INTO v_labor_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_company_today
+ AND "endDate" >= v_company_today
+ AND status = 'Active'
LIMIT 1;
- IF NOT FOUND THEN
- RETURN 0;
+
+ IF v_labor_accounting_period_id IS NULL AND v_posting_status = 'Posted' THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_company_today
+ AND "endDate" >= v_company_today
+ RETURNING id INTO v_labor_accounting_period_id;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_company_today)::DATE,
+ (date_trunc('month', v_company_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_labor_accounting_period_id;
+ END IF;
+ END IF;
+
+ -- A Provisional journal has no accounting period (spec section 1).
+ IF v_posting_status <> 'Posted' THEN
+ v_labor_accounting_period_id := NULL;
+ END IF;
+
+ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_labor_journal_entry_id, v_labor_accounting_period_id,
+ v_event.type || ' Time — Job ' || v_job_id_readable,
+ v_company_today, p_company_id, 'Production Event', v_posting_status,
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_labor_journal_id;
+
+ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN
+ -- DR WIP (labor/machine)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account',
+ v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP line (the finished good this labor rolls into)
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Labor/Machine Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',
+ -v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+
+ IF v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL THEN
+ -- DR WIP (overhead)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account (Overhead)',
+ v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP overhead line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP overhead line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Overhead Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_overhead_absorption_account, 'Overhead Absorption',
+ -v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on overhead absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on overhead absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
END IF;
END IF;
+
+ UPDATE "productionEvent"
+ SET "postedToGL" = true
+ WHERE id = v_event.id;
+ END LOOP;
+
+ -- Calculate accumulated WIP cost for this job
+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)
+ INTO v_accumulated_wip_cost
+ FROM "journalLine" jl
+ INNER JOIN journal j ON j.id = jl."journalId"
+ WHERE jl."accountId" = v_wip_account
+ AND jl."documentId" = p_job_id
+ AND j."companyId" = p_company_id
+ AND j."status" IN ('Provisional', 'Posted', 'Reversed');
+
+ IF v_accumulated_wip_cost <= 0 THEN
+ RETURN;
END IF;
- v_count := COALESCE(array_length(v_to_number, 1), 0) + v_new_units + v_missing;
- IF v_count = 0 THEN
- RETURN 0;
+ -- A stocked re-completion at the quantity already received has no units to
+ -- carry this cost. The catch-up WIP above stays in WIP and is discharged with
+ -- the next receipt; the per-unit cost below would otherwise divide by zero.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND v_quantity_received_to_inventory <= 0 THEN
+ RETURN;
END IF;
- SELECT "code", "name"
- INTO v_location
- FROM "location"
- WHERE "id" = v_job."locationId"
- AND "companyId" = p_company_id;
+ -- Make to Asset: the swept WIP lands on the target class's asset account as
+ -- an Asset Transfer journal. Both lines stay documented against the job so
+ -- the WIP credit still nets this job's WIP to zero for a re-completion.
+ IF v_asset_target IS NOT NULL THEN
+ v_item_inventory_account := v_target_class."assetAccountId";
+ v_item_inventory_description := 'Fixed Asset';
+ v_journal_source_type := 'Asset Transfer';
+ v_journal_document_type := 'Asset Transfer';
+ v_journal_description := 'Job Completion to Fixed Asset ' || v_job_id_readable;
+ ELSE
+ v_journal_description := 'Job Completion ' || v_job_id_readable;
+ END IF;
- 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;
+ v_today := v_company_today;
+ v_journal_line_reference := nanoid();
+
+ -- Get accounting period for WIP discharge
+ SELECT id INTO v_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_accounting_period_id IS NULL AND v_posting_status = 'Posted' THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ RETURNING id INTO v_accounting_period_id;
+
+ IF v_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_today)::DATE,
+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_accounting_period_id;
+ END IF;
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;
+ -- A Provisional journal has no accounting period (spec section 1).
+ IF v_posting_status <> 'Posted' THEN
+ v_accounting_period_id := NULL;
END IF;
- IF v_from_seed > 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;
+ v_journal_entry_id := get_next_sequence('journalEntry', 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;
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_journal_entry_id, v_accounting_period_id,
+ v_journal_description,
+ v_today, p_company_id, v_journal_source_type, v_posting_status,
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_journal_id;
+
+ -- DR Inventory (Raw Materials or Finished Goods by item)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_item_inventory_account, v_item_inventory_description,
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ v_journal_document_type, p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := ARRAY[v_labor_jl_id];
+
+ -- CR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_wip_account, 'WIP Account',
+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ v_journal_document_type, p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := v_jl_ids || v_labor_jl_id;
+
+ -- Write costLedger entry for finished good (skipped for Non-Inventory: no
+ -- output layer exists for a service — its cost went straight to COGS above)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND v_asset_target IS NULL THEN
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Output', 'Direct Cost', false,
+ 'Job Receipt', p_job_id, v_item_id,
+ v_quantity_received_to_inventory, v_accumulated_wip_cost,
+ -- Units issued before the receipt are already gone: only the rest can
+ -- still be consumed from this layer.
+ v_quantity_received_to_inventory - v_issued_units_received, p_company_id
+ );
END IF;
- IF v_missing > 0 THEN
- INSERT INTO "trackedEntity" (
- "createdAt", "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",
- quantity, status, attributes, "itemId", "readableId",
- "companyId", "createdBy"
- )
- SELECT
- now() + (v_new_units + n) * interval '1 millisecond',
- v_template."sourceDocument", v_template."sourceDocumentId", v_template."sourceDocumentReadableId",
- 1, 'Reserved'::"trackedEntityStatus",
- jsonb_build_object('Job', p_job_id, 'Job Make Method', v_make_method."id"),
- v_job."itemId",
- v_serials[COALESCE(array_length(v_to_number, 1), 0) + v_new_units + n],
- p_company_id, v_template."createdBy"
- FROM generate_series(1, v_missing) AS n;
+ -- Update item cost
+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"
+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- Update itemCost.unitCost (skipped for Non-Inventory: a service has no
+ -- stocked unit cost; the read above still feeds the dimension inserts below)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND v_asset_target IS NULL THEN
+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;
+
+ IF v_costing_method = 'Average' THEN
+ SELECT COALESCE(SUM(quantity), 0)
+ INTO v_total_qty_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;
+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);
+
+ IF v_total_qty_on_hand > 0 THEN
+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_per_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
END IF;
- RETURN v_count;
+ -- Make to Asset: price the assets created above from the swept WIP and link
+ -- their transfers to the journal. A Construction in Progress target takes the
+ -- whole cost as one CIP cost row and one transfer.
+ IF v_asset_target = 'class' THEN
+ -- Rounded at persist; the last asset takes the residual so the assets add
+ -- up to exactly the WIP the journal debits to the asset account.
+ v_per_unit_cost := ROUND(v_accumulated_wip_cost / array_length(v_asset_ids, 1), 5);
+
+ UPDATE "fixedAsset"
+ SET "acquisitionCost" = CASE
+ WHEN id = v_asset_ids[array_length(v_asset_ids, 1)]
+ THEN v_accumulated_wip_cost - v_per_unit_cost * (array_length(v_asset_ids, 1) - 1)
+ ELSE v_per_unit_cost
+ END,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = ANY(v_asset_ids);
+
+ UPDATE "fixedAssetTransfer"
+ SET amount = CASE
+ WHEN id = v_transfer_ids[array_length(v_transfer_ids, 1)]
+ THEN v_accumulated_wip_cost - v_per_unit_cost * (array_length(v_transfer_ids, 1) - 1)
+ ELSE v_per_unit_cost
+ END,
+ "journalId" = v_journal_id,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = ANY(v_transfer_ids);
+ ELSIF v_asset_target = 'asset' THEN
+ INSERT INTO "fixedAssetCipCost" (
+ "fixedAssetId", "sourceType", "jobId", amount, "costDate", "journalId", "companyId", "createdBy"
+ ) VALUES (
+ v_job_asset_id, 'Job', p_job_id, v_accumulated_wip_cost, v_company_today, v_journal_id, p_company_id, p_user_id
+ );
+
+ UPDATE "fixedAsset"
+ SET "acquisitionCost" = "acquisitionCost" + v_accumulated_wip_cost,
+ status = 'Under Construction',
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = v_job_asset_id;
+
+ INSERT INTO "fixedAssetTransfer" (
+ "transferId", type, "sourceType", "fixedAssetId", "itemId", "jobId",
+ "locationId", quantity, "transferDate", amount, "journalId", status,
+ "postedAt", "postedBy", "companyId", "createdBy"
+ ) VALUES (
+ get_next_sequence('fixedAssetTransfer', p_company_id), 'Capitalization', 'Job',
+ v_job_asset_id, v_item_id, p_job_id,
+ v_job_location_id, v_quantity_received_to_inventory, v_company_today, v_accumulated_wip_cost, v_journal_id, 'Posted',
+ NOW(), p_user_id, p_company_id, p_user_id
+ );
+ END IF;
+
+ -- Insert dimensions on WIP discharge journal lines
+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN
+ FOR i IN 1..array_length(v_jl_ids, 1)
+ LOOP
+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id
+ );
+ END IF;
+
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+
+ IF v_asset_class_id IS NOT NULL AND v_dimension_fixed_asset_class IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_fixed_asset_class, v_asset_class_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
END;
$function$;
diff --git a/packages/database/supabase/migrations/20261027064700_serial-number-timing-finish-operation.sql b/packages/database/supabase/migrations/20261027064700_serial-number-timing-finish-operation.sql
deleted file mode 100644
index 9197ecfaa0..0000000000
--- a/packages/database/supabase/migrations/20261027064700_serial-number-timing-finish-operation.sql
+++ /dev/null
@@ -1,151 +0,0 @@
--- 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));
-
- -- 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,
- 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/database/supabase/tests/rpc-privileges.test.sql b/packages/database/supabase/tests/rpc-privileges.test.sql
index 034b06820d..b98038e605 100644
--- a/packages/database/supabase/tests/rpc-privileges.test.sql
+++ b/packages/database/supabase/tests/rpc-privileges.test.sql
@@ -69,7 +69,8 @@ BEGIN
END IF;
IF (SELECT prosecdef FROM pg_proc WHERE oid = 'backflush_job_materials(text,numeric,text,text)'::regprocedure)
- OR (SELECT prosecdef FROM pg_proc WHERE oid = 'number_serial_units_for_completion(text,numeric,text)'::regprocedure)
+ OR (SELECT prosecdef FROM pg_proc WHERE oid = 'split_serial_units_for_completion(text,text,text,integer)'::regprocedure)
+ OR (SELECT prosecdef FROM pg_proc WHERE oid = 'number_serial_units_for_receipt(text[],text,text,text)'::regprocedure)
OR NOT (SELECT prosecdef FROM pg_proc WHERE oid = 'dispatch_event_interceptors()'::regprocedure)
OR NOT (SELECT prosecdef FROM pg_proc WHERE oid = 'dispatch_event_after_interceptors()'::regprocedure) THEN
RAISE EXCEPTION 'FAIL: internal functions or dispatchers have the wrong security mode';
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index ea450b27c5..9690c166c3 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261027064700",
+ "schemaVersion": "20261027064600",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-27T07:24:31.836Z",
+ "exportedAt": "2026-10-27T11:39:06.156Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -482,10 +482,10 @@
"leaseIncrementalBorrowingRate",
"leaseShortTermExpedient",
"leaseReminderDays",
+ "serialNumberTiming",
"requireBackflushStorageUnit",
"preventNegativeBackflush",
- "receiptQuantitiesStartAtZero",
- "serialNumberTiming"
+ "receiptQuantitiesStartAtZero"
]
},
{
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index cfd6bce18d..e221fd4827 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -1247,8 +1247,8 @@ msgstr "Keine Proben erforderlich."
msgid "No scheduled time"
msgstr "Keine geplante Zeit"
-msgid "No serial number yet"
-msgstr "Noch keine Seriennummer"
+msgid "No serial number"
+msgstr "Keine Seriennummer"
msgid "No serial numbers"
msgstr "Keine Seriennummern"
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index 22a575c607..7d61b9bad3 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -1247,8 +1247,8 @@ msgstr "No samples required."
msgid "No scheduled time"
msgstr "No scheduled time"
-msgid "No serial number yet"
-msgstr "No serial number yet"
+msgid "No serial number"
+msgstr "No serial number"
msgid "No serial numbers"
msgstr "No serial numbers"
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index 918de3edf9..caceed2867 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -1247,8 +1247,8 @@ msgstr "No se requieren muestras."
msgid "No scheduled time"
msgstr "Sin tiempo programado"
-msgid "No serial number yet"
-msgstr "Aún sin número de serie"
+msgid "No serial number"
+msgstr "Sin número de serie"
msgid "No serial numbers"
msgstr "Sin números de serie"
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index c91c973eb4..4e285f1637 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -1247,8 +1247,8 @@ msgstr "Aucun échantillon requis."
msgid "No scheduled time"
msgstr "Aucun horaire planifié"
-msgid "No serial number yet"
-msgstr "Pas encore de numéro de série"
+msgid "No serial number"
+msgstr "Aucun numéro de série"
msgid "No serial numbers"
msgstr "Aucun numéro de série"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index 87a82f6a48..d7991d5e30 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -1247,8 +1247,8 @@ msgstr "कोई नमूना आवश्यक नहीं है।"
msgid "No scheduled time"
msgstr "कोई निर्धारित समय नहीं"
-msgid "No serial number yet"
-msgstr "अभी तक कोई सीरियल नंबर नहीं"
+msgid "No serial number"
+msgstr "कोई सीरियल नंबर नहीं"
msgid "No serial numbers"
msgstr "कोई सीरियल नंबर नहीं"
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index 04d51bf1d5..81422f5d48 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -1247,8 +1247,8 @@ msgstr "Nessun campione richiesto."
msgid "No scheduled time"
msgstr "Nessun orario programmato"
-msgid "No serial number yet"
-msgstr "Ancora nessun numero di serie"
+msgid "No serial number"
+msgstr "Nessun numero di serie"
msgid "No serial numbers"
msgstr "Nessun numero di serie"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index 1211d73393..4a54899e84 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -1247,8 +1247,8 @@ msgstr "サンプルは必要ありません。"
msgid "No scheduled time"
msgstr "予定時間なし"
-msgid "No serial number yet"
-msgstr "シリアル番号はまだありません"
+msgid "No serial number"
+msgstr "シリアル番号なし"
msgid "No serial numbers"
msgstr "シリアル番号なし"
diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.po
index e1d0644c49..16d114b994 100644
--- a/packages/locale/locales/ko/mes.po
+++ b/packages/locale/locales/ko/mes.po
@@ -1247,8 +1247,8 @@ msgstr "필요한 샘플이 없습니다."
msgid "No scheduled time"
msgstr "예정된 시간 없음"
-msgid "No serial number yet"
-msgstr "아직 일련번호 없음"
+msgid "No serial number"
+msgstr "일련번호 없음"
msgid "No serial numbers"
msgstr "시리얼 번호 없음"
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index 3e98013025..387c33ff21 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -1247,8 +1247,8 @@ msgstr "Nie wymagane żadne próbki."
msgid "No scheduled time"
msgstr "Brak zaplanowanego czasu"
-msgid "No serial number yet"
-msgstr "Jeszcze bez numeru seryjnego"
+msgid "No serial number"
+msgstr "Brak numeru seryjnego"
msgid "No serial numbers"
msgstr "Brak numerów seryjnych"
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index 061053cf89..4e8218e04e 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -1247,8 +1247,8 @@ msgstr "Nenhuma amostra necessária."
msgid "No scheduled time"
msgstr "Nenhum horário programado"
-msgid "No serial number yet"
-msgstr "Ainda sem número de série"
+msgid "No serial number"
+msgstr "Sem número de série"
msgid "No serial numbers"
msgstr "Nenhum número de série"
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index 77815e9e1e..94e9ff88a8 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -1247,8 +1247,8 @@ msgstr "Образцы не требуются."
msgid "No scheduled time"
msgstr "Нет запланированного времени"
-msgid "No serial number yet"
-msgstr "Серийный номер ещё не присвоен"
+msgid "No serial number"
+msgstr "Нет серийного номера"
msgid "No serial numbers"
msgstr "Нет серийных номеров"
diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.po
index 51361f0db8..1f33b106d6 100644
--- a/packages/locale/locales/tr/mes.po
+++ b/packages/locale/locales/tr/mes.po
@@ -1247,8 +1247,8 @@ msgstr "Örnek gerekli değil."
msgid "No scheduled time"
msgstr "Planlanmış zaman yok"
-msgid "No serial number yet"
-msgstr "Henüz seri numarası yok"
+msgid "No serial number"
+msgstr "Seri numarası yok"
msgid "No serial numbers"
msgstr "Seri numarası yok"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index f1999d94e8..c6294a289c 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -1247,8 +1247,8 @@ msgstr "不需要样本。"
msgid "No scheduled time"
msgstr "无排定时间"
-msgid "No serial number yet"
-msgstr "尚无序列号"
+msgid "No serial number"
+msgstr "无序列号"
msgid "No serial numbers"
msgstr "无序列号"