Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(production): keep an unsplit seed's units on serial completion, and refuse scrapping stock
Raul254bd79c4e93
diff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.mdindex 026dfa0aa7..ad056a2306 100644--- a/.claude/rules/traceability-model.md+++ b/.claude/rules/traceability-model.md@@ -76,7 +76,8 @@ and MES services — NOT a single `post-production`:is scrapped), then **spawns a replacement unit**, numbered by`getSpawnSerialNumber` like `jobOperationSerialComplete`'s next unit (leftunnumbered under the `production` serial number timing; the replacement of- an unsplit seed carries the seed's other units and stays unnumbered), and reopens the make method's Done ops+ an unsplit seed carries the seed's other units and stays unnumbered; a unit+ already received to stock is refused), 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 itsdiff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex cf1cf8df3a..2e5c8b1d21 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -23579,10 +23579,22 @@ export async function issueMaterial(.execute();}- if (- trackedEntities.data.length <- (jobOperation.data.operationQuantity ?? 0)- ) {+ // An unsplit seed is cut to one unit above; its other units go to the+ // next unit, since the completion of an item with no serial sequence+ // receives them against a seed. Otherwise the next unit is spawned+ // while the units number fewer than the operation quantity.+ const seedUnitsLeft =+ trackedEntity.status !== "Consumed"+ ? Math.max(Number(trackedEntity.quantity) - 1, 0)+ : 0;+ const nextUnits =+ seedUnitsLeft > 0+ ? seedUnitsLeft+ : trackedEntities.data.length <+ (jobOperation.data.operationQuantity ?? 0)+ ? 1+ : 0;+ if (nextUnits > 0) {// Number this lazily-spawned unit from the item's serial sequence, if// one is configured. This unit wasn't part of the initial pre-split at// job creation (e.g. the job quantity was increased afterwards, or the@@ -23590,15 +23602,16 @@ export async function issueMaterial(// a null readableId. Resolve the job's location for the %{location}// 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.- const spawnReadableId = trackedEntity.itemId- ? await sequence.getSpawnSerialNumber(trx, {- itemId: trackedEntity.itemId,- companyId,- jobId: (trackedEntity.attributes as Record<string, unknown>)- .Job as string | undefined- })- : null;+ // unit stays unnumbered until it is first touched, and so does a seed.+ const spawnReadableId =+ nextUnits === 1 && 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 = Reservedconst newTrackedEntityResult = await trx@@ -23607,7 +23620,7 @@ export async function issueMaterial(sourceDocument: trackedEntity.sourceDocument,sourceDocumentId: trackedEntity.sourceDocumentId,sourceDocumentReadableId: trackedEntity.sourceDocumentReadableId,- quantity: 1,+ quantity: nextUnits,status: "Reserved",attributes: trackedEntity.attributes,itemId: trackedEntity.itemId ?? null,@@ -23840,11 +23853,25 @@ export async function issueMaterial(.selectAll().where("id", "=", scrapEntityId).where("companyId", "=", companyId)+ .forUpdate().executeTakeFirst();if (!entity) throw new NotFoundError("Tracked entity not found");if (entity.status === "Consumed" || entity.status === "Scrapped") {throw new Error("Tracked entity is not in progress");}+ // A unit already received holds stock, and this scrap writes no+ // ledger row: the stock would stay on a Scrapped unit.+ const onHand = await trx+ .selectFrom("itemLedger")+ .select((eb) => eb.fn.sum<number>("quantity").as("quantity"))+ .where("trackedEntityId", "=", scrapEntityId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (Number(onHand?.quantity ?? 0) > 0) {+ throw new InvalidInputError(+ "The unit is already in stock. Scrap it from inventory instead."+ );+ }scrappedEntityAttributes =entity.attributes as TrackedEntityAttributes;seedUnitsLeft = Math.max(Number(entity.quantity) - 1, 0);diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex ecdfcf4b7f..e0b6fc68da 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -38,7 +38,7 @@ 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. 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.+- The serial branch receives the delta one numbered unit at a time — shop-floor-finished (`Available`) first, then by `readableId` — skipping `Consumed`/`Rejected`/`Scrapped` and any unit with a `Job Receipt` ledger row for this job, so re-completion never double-receives. When the job's rows hold too few single units, an item with a serial sequence has the rest split off the seed (`split_serial_units_for_completion`) and the units picked again; the units taken are then numbered (`number_serial_units_for_receipt`). An item with **no serial sequence** is never split: its single units are received first, then the rest of the delta against its seed (one entity holding the units the shop floor has not touched).- **Make to Asset branch.** A job with `fixedAssetClassId` completes into one new `fixedAsset` per unit (status `Active`, or `Under Construction` when the class `isConstructionInProgress`; `acquisitionCost` = swept WIP ÷ units; one Posted `fixedAssetTransfer` per asset, `type 'Capitalization'`, `sourceType 'Job'`); a job with `fixedAssetId` sweeps its WIP onto that Construction in Progress asset as one `fixedAssetCipCost` row + one transfer. The units never enter stock: no `itemLedger`, `costLedger`, `pickMethod` or `itemCost` write, and the WIP discharge posts Dr class `assetAccountId` / Cr WIP as an `'Asset Transfer'` journal (both lines still `documentId = jobId`, so the per-job WIP balance nets to zero). Each serial unit goes `Consumed` with `attributes["Fixed Asset"]` and a `'Capitalize'` `trackedActivity`; every company writes the asset cost (the journal is Provisional before the accounting cutover). Guards raise before anything moves: `'A job linked to a sales order line cannot complete to a fixed asset'`; `'A job that completes to a fixed asset class needs a serialized item'` (any quantity — every asset a class job makes is a fleet unit followed by its serial); `'Make to Asset needs a serialized item or a quantity of one'` (a job attached to an asset under construction); a job attached to a non-CIP asset is also refused (`'… is not in a Construction in Progress class'`). The item rule is `makeToAssetItemError` (`production.models.ts`), applied by `x+/job+/new.tsx` on save (a field error on the item), by `updateJobDetails` (the details form), by `setJobItem` on a property-panel item change and by `resumeJob` when a paused job goes back to `Ready`, with the sales order line gate. Covered by `packages/database/supabase/tests/job-completion-to-asset.test.sql`. Full flow: `.claude/rules/fixed-asset-lifecycle.md`.- **Serial number timing**: when a produced unit draws its serial number.- Setting: `companySettings.serialNumberTiming` (Settings → Production → Serial Numbers). An item's serial sequence overrides it with `itemSerialSequence.serialNumberTiming` (NULL follows the company; Settings → Serial Numbers). Readers resolve the item's value first: `getSerialNumberTiming` / `resolveSerialNumberTiming` (`@carbon/database/sequence`). Values: `serialNumberTimings` (`@carbon/database/serial-number-timing`, client-safe).@@ -46,7 +46,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced- `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`. The replacement of a scrapped unsplit seed carries the seed's other units and stays unnumbered, so a job with no serial sequence still has a seed to receive against.+ - A unit spawned later (a serial completion's next unit, a scrap's replacement) is numbered by `getSpawnSerialNumber`, which leaves it unnumbered under `production`. When the unit touched is an unsplit seed, the next unit or the replacement carries the seed's other units and stays unnumbered, so a job with no serial sequence still has a seed to receive against. The operation scrap refuses a unit already received to stock.- 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.diff --git a/apps/erp/test/database/serial-number-timing.test.ts b/apps/erp/test/database/serial-number-timing.test.tsindex 16079ad780..f60338ee60 100644--- a/apps/erp/test/database/serial-number-timing.test.ts+++ b/apps/erp/test/database/serial-number-timing.test.ts@@ -574,7 +574,7 @@ describe.skipIf(!client)("serial number timing", () => {const [seedUnit] = await units(f, job.makeMethodId);// The shop floor completes one unit: the seed keeps one unit and the- // next is spawned, so the rows hold two of the job's three units.+ // next unit carries the other two.unwrap(await invokePosting(handlesOf(f.ctx),@@ -590,21 +590,30 @@ describe.skipIf(!client)("serial number timing", () => {);expect(await units(f, job.makeMethodId)).toEqual([expect.objectContaining({ readableId: "SN-001", quantity: 1 }),- expect.objectContaining({ readableId: null, quantity: 1 })+ expect.objectContaining({ readableId: null, quantity: 2 })]);+ // A fourth unit added to the job afterwards is held by no row.+ await seed(f, async (trx) => {+ await trx+ .updateTable("job")+ .set({ quantity: 4 })+ .where("id", "=", job.jobId)+ .execute();+ });const result = await completeJob(contextFor(f), {jobId: job.jobId,- quantityComplete: 3+ quantityComplete: 4});expect(result.error).toBeNull();expect(await receivedUnits(f, job.jobId)).toEqual([{ readableId: "SN-001", quantity: 1 },{ readableId: "SN-002", quantity: 1 },- { readableId: "SN-003", quantity: 1 }+ { readableId: "SN-003", quantity: 1 },+ { readableId: "SN-004", quantity: 1 }]);- expect(await units(f, job.makeMethodId)).toHaveLength(3);+ expect(await units(f, job.makeMethodId)).toHaveLength(4);} finally {await f.cleanup();}@@ -717,6 +726,96 @@ describe.skipIf(!client)("serial number timing", () => {}});+ it("receives a finished unit and the seed's other units for an item with no serial sequence", async () => {+ const f = await alwaysPostFixture();+ try {+ await stockPart(f, 20);+ await serialSetup(f, "production");+ await seed(f, async (trx) => {+ await trx+ .deleteFrom("itemSerialSequence")+ .where("itemId", "=", f.assemblyId)+ .where("companyId", "=", f.companyId)+ .execute();+ });+ const job = await untouchedSerialJob(f, "7c", 3);+ const [seedUnit] = await units(f, job.makeMethodId);++ unwrap(+ await invokePosting(+ handlesOf(f.ctx),+ "issue",+ {+ type: "jobOperationSerialComplete",+ trackedEntityId: seedUnit!.id,+ quantity: 1,+ jobOperationId: job.operationId+ },+ issue+ )+ );++ const result = await completeJob(contextFor(f), {+ jobId: job.jobId,+ quantityComplete: 3+ });+ expect(result.error).toBeNull();++ // The finished unit on its own, the other two against the seed.+ const received = await receivedUnits(f, job.jobId);+ expect(received.sort((a, b) => a.quantity - b.quantity)).toEqual([+ { readableId: null, quantity: 1 },+ { readableId: null, quantity: 2 }+ ]);+ } finally {+ await f.cleanup();+ }+ });++ it("refuses to scrap a unit already received to stock", async () => {+ const f = await alwaysPostFixture();+ try {+ await stockPart(f, 20);+ await serialSetup(f, "production");+ const job = await untouchedSerialJob(f, "7d", 3);+ const completed = await completeJob(contextFor(f), {+ jobId: job.jobId,+ quantityComplete: 1+ });+ expect(completed.error).toBeNull();+ const received = (await units(f, job.makeMethodId)).find(+ (unit) => unit.readableId === "SN-001"+ );+ const scrapReason = await f.db+ .insertInto("scrapReason")+ .values({ name: "Damaged", companyId: f.companyId, createdBy: USER })+ .returning("id")+ .executeTakeFirstOrThrow();++ const result = await invokePosting(+ handlesOf(f.ctx),+ "issue",+ {+ type: "jobOperationScrap",+ jobOperationId: job.operationId,+ quantity: 1,+ scrapReasonId: scrapReason.id,+ trackedEntityId: received!.id+ },+ issue+ );++ expect(result.error?.status).toBe(400);+ expect(+ (await units(f, job.makeMethodId)).find(+ (unit) => unit.id === received!.id+ )+ ).toMatchObject({ quantity: 1, status: "Available" });+ } finally {+ await f.cleanup();+ }+ });+it("refuses to scrap another job's unit, and leaves that unit whole", async () => {const f = await alwaysPostFixture();try {diff --git a/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql b/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sqlindex 811f547054..21b218fc18 100644--- a/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql+++ b/packages/database/supabase/migrations/20261027064600_serial-number-timing-completion.sql@@ -15,7 +15,9 @@-- 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+-- so numbering and receipt cannot take different ones. An item with no serial+-- sequence is never split: its single units are received, then the rest against+-- its seed. Every caller (the ERP's-- completeJob, and the sync_finish_job_operation interceptor when the last-- operation is marked Done) gets it by calling complete_job_to_inventory.--@@ -371,6 +373,7 @@ DECLAREv_new_unit_cost NUMERIC;v_serial_unit_ids TEXT[];v_issued_units_received NUMERIC := 0;+ v_units_taken INTEGER;v_company_today DATE := company_today(p_company_id);v_job_asset_class_id TEXT;v_job_asset_id TEXT;@@ -837,9 +840,40 @@ BEGIN) = 0;END LOOP;- IF COALESCE(array_length(v_serial_unit_ids, 1), 0) >= v_quantity_received_to_inventory THEN+ -- Short of single units: an item with no serial sequence is never split,+ -- so the units the shop floor has not touched are still on its seed (one+ -- entity holding several). The single units are received first, then the+ -- rest against that seed, the way the batch branch receives. Raising+ -- instead would abort the jobOperation UPDATE itself: completion also runs+ -- inside sync_finish_job_operation, a BEFORE trigger interceptor.+ v_units_taken := LEAST(+ COALESCE(array_length(v_serial_unit_ids, 1), 0),+ v_quantity_received_to_inventory::INTEGER+ );+ IF v_units_taken < v_quantity_received_to_inventory THEN+ SELECT *+ INTO v_tracked_entity+ 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+ 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;+ END IF;++ IF v_units_taken > 0 THENPERFORM number_serial_units_for_receipt(- v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER],+ v_serial_unit_ids[1:v_units_taken],v_item_id, p_company_id, v_job_location_id);@@ -856,7 +890,7 @@ BEGINCASE 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+ FROM unnest(v_serial_unit_ids[1:v_units_taken]) AS unit_idJOIN "trackedEntity" te ON te.id = unit_idLEFT JOIN LATERAL (SELECT il.id, il."locationId", il."storageUnitId"@@ -872,48 +906,25 @@ BEGINSELECT COUNT(*)INTO v_issued_units_receivedFROM "trackedEntity"- WHERE id = ANY(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER])+ WHERE id = ANY(v_serial_unit_ids[1:v_units_taken])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])+ WHERE id = ANY(v_serial_unit_ids[1:v_units_taken])AND status <> 'Consumed';+ END IF;- 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_tracked_entity- 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- 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;-+ IF v_units_taken < v_quantity_received_to_inventory THENINSERT 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_item_id, v_quantity_received_to_inventory - v_units_taken,+ p_location_id, p_storage_unit_id,v_tracked_entity.id, p_user_id);