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): refuse to complete another operation's unit, and keep a scrapped seed's units
Raul26c2ebec0561
diff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.mdindex b0f06d94f8..026dfa0aa7 100644--- a/.claude/rules/traceability-model.md+++ b/.claude/rules/traceability-model.md@@ -75,7 +75,8 @@ and MES services — NOT a single `post-production`:entity → `Scrapped` (an unsplit seed is first cut to one unit, so only one unitis 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+ unnumbered 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(`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 571daffa12..cf1cf8df3a 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -23446,7 +23446,6 @@ export async function issueMaterial(if (!jobOperation.data || !jobOperation.data.jobMakeMethodId) {throw new NotFoundError("Job operation not found");}- const completedMakeMethodId = jobOperation.data.jobMakeMethodId;// UNIT-AXIS order, identical to the apps' getTrackedEntitiesByMakeMethodId:// position here is the `index` step records are stored under, so the@@ -23475,6 +23474,13 @@ export async function issueMaterial(const completedUnitIndex = trackedEntities.data.findIndex((entity: { id: string }) => entity.id === trackedEntityId);+ // The unit id comes from the request, and a completion cuts an unsplit+ // seed to one unit: another job's seed would lose the units it holds.+ if (completedUnitIndex < 0) {+ throw new InvalidInputError(+ "The unit does not belong to this operation"+ );+ }const relatedTrackedEntities = trackedEntities.data.filter((trackedEntity) =>@@ -23516,13 +23522,10 @@ export async function issueMaterial(// the timing (under 'production' every unit; otherwise only a unit// left unnumbered by a timing change). A Consumed entity is not cut to// one unit below, so it is numbered only when it already holds one.- // The unit id comes from the request, so only a unit of this- // operation's make method draws a number.await sequence.assignSerialNumberIfMissing(trx, {trackedEntityId,companyId,- onlyIfSingleUnit: trackedEntity.status === "Consumed",- jobMakeMethodId: completedMakeMethodId+ onlyIfSingleUnit: trackedEntity.status === "Consumed"});if (trackedEntity.status !== "Consumed") {@@ -23543,7 +23546,7 @@ export async function issueMaterial(Job: jobOperation.data.jobId,"Job Operation": row.jobOperationId,Employee: userId,- ...(completedUnitIndex >= 0 ? { Unit: completedUnitIndex } : {})+ Unit: completedUnitIndex},companyId,createdBy: userId@@ -23829,6 +23832,8 @@ export async function issueMaterial(// 3. Serial: terminal status + Scrap genealogy on the selected unit.// The entity keeps its consumed-material input tree.let scrappedEntityAttributes: TrackedEntityAttributes | null = null;+ // The units an unsplit seed held besides the one scrapped.+ let seedUnitsLeft = 0;if (isSerial && scrapEntityId) {const entity = await trx.selectFrom("trackedEntity")@@ -23842,6 +23847,7 @@ export async function issueMaterial(}scrappedEntityAttributes =entity.attributes as TrackedEntityAttributes;+ seedUnitsLeft = Math.max(Number(entity.quantity) - 1, 0);// A unit scrapped before it completed an operation never reached a// completion hook, so number it here if it has no number yet (it is@@ -23885,8 +23891,7 @@ export async function issueMaterial(// this operation; status is the terminal marker.// One unit is scrapped. An unsplit seed (serialNumberTiming =// 'production', or an item with no serial sequence) holds every unit- // of the job, so it keeps one; the rest are spawned one at a time,- // as after a serial completion.+ // of the job, so it keeps one; its replacement carries the rest.await trx.updateTable("trackedEntity").set({@@ -23916,6 +23921,9 @@ export async function issueMaterial(// operationQuantity; the top-up above grew operationQuantity by// the beyond-allowance scrap, and pre-created allowance units// (job.scrapQuantity at release) already cover in-allowance scrap.+ // A scrapped unsplit seed's other units go with it: the completion+ // of an item with no serial sequence receives against a seed, so+ // they would otherwise be lost.if (isSerial && scrapEntityId && scrappedEntityAttributes) {const updatedOperation = await trx.selectFrom("jobOperation")@@ -23923,16 +23931,19 @@ export async function issueMaterial(.where("id", "=", jobOperationId).executeTakeFirst();const capacity = Number(updatedOperation?.operationQuantity ?? 0);- if (existingEntityCount < capacity) {+ const replacementUnits =+ seedUnitsLeft + (existingEntityCount < capacity ? 1 : 0);+ if (replacementUnits > 0) {// Under serialNumberTiming = 'production' the replacement stays- // unnumbered until it is first touched.- const spawnReadableId = makeMethod.itemId- ? await sequence.getSpawnSerialNumber(trx, {- itemId: makeMethod.itemId,- companyId,- jobId: job.id- })- : null;+ // unnumbered until it is first touched, and so does a seed.+ const spawnReadableId =+ replacementUnits === 1 && makeMethod.itemId+ ? await sequence.getSpawnSerialNumber(trx, {+ itemId: makeMethod.itemId,+ companyId,+ jobId: job.id+ })+ : null;const scrappedEntity = await trx.selectFrom("trackedEntity")@@ -23947,7 +23958,7 @@ export async function issueMaterial(scrappedEntity?.sourceDocumentId ?? makeMethod.itemId ?? "",sourceDocumentReadableId:scrappedEntity?.sourceDocumentReadableId,- quantity: 1,+ quantity: replacementUnits,status: "Reserved",attributes: scrappedEntityAttributes as unknown as Json,itemId: makeMethod.itemId ?? null,diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex f4522cdee5..ecdfcf4b7f 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -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`.+ - 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.- 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 22cb61ad6f..16079ad780 100644--- a/apps/erp/test/database/serial-number-timing.test.ts+++ b/apps/erp/test/database/serial-number-timing.test.ts@@ -637,6 +637,7 @@ describe.skipIf(!client)("serial number timing", () => {issue));+ // The replacement carries the seed's two other units and the one owed.expect(await units(f, job.makeMethodId)).toEqual([expect.objectContaining({readableId: "SN-001",@@ -645,7 +646,7 @@ describe.skipIf(!client)("serial number timing", () => {}),expect.objectContaining({readableId: null,- quantity: 1,+ quantity: 3,status: "Reserved"})]);@@ -666,6 +667,56 @@ describe.skipIf(!client)("serial number timing", () => {}});+ it("completes a job with no serial sequence after its seed was scrapped", 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, "7b", 3);+ const [seedUnit] = await units(f, job.makeMethodId);+ const scrapReason = await f.db+ .insertInto("scrapReason")+ .values({ name: "Damaged", companyId: f.companyId, createdBy: USER })+ .returning("id")+ .executeTakeFirstOrThrow();++ unwrap(+ await invokePosting(+ handlesOf(f.ctx),+ "issue",+ {+ type: "jobOperationScrap",+ jobOperationId: job.operationId,+ quantity: 1,+ scrapReasonId: scrapReason.id,+ trackedEntityId: seedUnit!.id+ },+ issue+ )+ );++ const result = await completeJob(contextFor(f), {+ jobId: job.jobId,+ quantityComplete: 3+ });+ expect(result.error).toBeNull();++ // Received against the seed the replacement carries on.+ expect(await receivedUnits(f, job.jobId)).toEqual([+ { readableId: null, quantity: 3 }+ ]);+ } finally {+ await f.cleanup();+ }+ });+it("refuses to scrap another job's unit, and leaves that unit whole", async () => {const f = await alwaysPostFixture();try {@@ -707,6 +758,46 @@ describe.skipIf(!client)("serial number timing", () => {}});+ it("refuses to complete another job's unit, and leaves that unit whole", async () => {+ const f = await alwaysPostFixture();+ try {+ await stockPart(f, 20);+ await serialSetup(f, "production");+ const job = await untouchedSerialJob(f, "10", 3);+ const otherJob = await untouchedSerialJob(f, "11", 3);+ const [otherSeed] = await units(f, otherJob.makeMethodId);++ const result = await invokePosting(+ handlesOf(f.ctx),+ "issue",+ {+ type: "jobOperationSerialComplete",+ trackedEntityId: otherSeed!.id,+ quantity: 1,+ jobOperationId: job.operationId+ },+ issue+ );++ expect(result.error?.status).toBe(400);+ expect(await units(f, otherJob.makeMethodId)).toEqual([+ expect.objectContaining({+ readableId: null,+ quantity: 3,+ status: "Reserved"+ })+ ]);+ const quantities = await f.db+ .selectFrom("productionQuantity")+ .select("id")+ .where("jobOperationId", "=", job.operationId)+ .execute();+ expect(quantities).toEqual([]);+ } finally {+ await f.cleanup();+ }+ });+it("numbers and receives untouched units when the last operation is marked Done", async () => {const f = await alwaysPostFixture();try {