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(items): numeric Op Nos and change notice locks outside the transaction
Raule4de89ddb8fb
diff --git a/.ai/plans/2026-10-21-method-import-append.md b/.ai/plans/2026-10-21-method-import-append.mdindex cebc480026..b7622af7ee 100644--- a/.ai/plans/2026-10-21-method-import-append.md+++ b/.ai/plans/2026-10-21-method-import-append.md@@ -73,6 +73,8 @@ import match the BOM and Bill of Process editors.| An Inspection operation was created with no Inspection Plan, which the editor never allows. | The import refuses Inspection operations. || A non-numeric Make Method Version became version 1. | The import refuses it. || `customFields` was null where the editors write `{}`. | The import writes `{}`. |+| CodeRabbit: a non-numeric Op No never matched an existing operation, so a re-run added it again, and its fallback order could collide with a numeric Op No. | Op No must be a number. Op Nos compare by value. |+| CodeRabbit: the change notice approval check ran a separate request while a part's transaction was open. | The import reads every change notice lock before any transaction. |The parity test (`method-import-parity.test.ts`) and the guards test(`method-import-guards.test.ts`) pin the fixes.diff --git a/.claude/rules/csv-import-system.md b/.claude/rules/csv-import-system.mdindex 4439a825cd..833f3be358 100644--- a/.claude/rules/csv-import-system.md+++ b/.claude/rules/csv-import-system.md@@ -269,9 +269,12 @@ continue.that part is rolled back too.- **Append, not fill** (`planMaterialAppend`, `planOperationAppend`): new BOMlines are ordered after the highest existing line; a material already on the- version is skipped. An Op No equal to an existing operation's `order` names- that operation: the BOP row is skipped and STEP / TOOL / PARAM rows attach to- it (they may reference it with no BOP row). A step with the same name, a tool+ version is skipped. An Op No is the operation's `order`, so it must be a+ number of 0 or more, and Op Nos compare by value (`opKey`: "10", "10.0" and+ "010" are one). An Op No equal to an existing operation's `order` names that+ operation: the BOP row is skipped and STEP / TOOL / PARAM rows attach to it+ (they may reference it with no BOP row). A non-numeric Op No was refused+ because a re-run could not find its operation again and would add it twice. A step with the same name, a toolwith the same item and a parameter with the same key are skipped. Every skipgoes to `skipped`, so re-running a file writes nothing.- **Rows match the editors' rows.** BOM lines copy `methodType` /@@ -299,11 +302,14 @@ continue.- **Concurrency.** `writeGroup` locks the target `makeMethod` row(`FOR UPDATE`) before it reads the version's lines, so two imports of onefile write each line once.+- **Change notice locks are read before any transaction** (`loadChangeNoticeLocks`):+ `getChangeNoticeEngineeringLock` checks pending approvals through a separate+ service-role request, which must not run while a part's transaction is open.+ A Draft whose notice was linked after that read is refused.- Known gaps: a sub-assembly created by a `PART` row must come before its parentin the file (parts are written in order of first appearance); a `PART` rowdoes not write the Unique ID mapping; the Supplier Process column is unused;- an Op No matches an operation in the same file by exact text ("1.0" is not- "1"), but an existing operation by number; items are looked up by readable id+ items are looked up by readable idand revision only, so a readable id shared by two item types resolves toeither; the import needs only `update: parts`, while the editors' createroutes need `create: parts`.diff --git a/apps/erp/app/modules/shared/shared.method-import-append.test.ts b/apps/erp/app/modules/shared/shared.method-import-append.test.tsindex 36b07de3e7..5f883c26ee 100644--- a/apps/erp/app/modules/shared/shared.method-import-append.test.ts+++ b/apps/erp/app/modules/shared/shared.method-import-append.test.ts@@ -10,6 +10,7 @@ import { describe, expect, it } from "vitest";import { LOCKED_REVISION_MESSAGE } from "~/modules/items/items.service";import {methodImportRefusal,+ opKey,pickMethodImportTarget,planMaterialAppend,planOperationAppend@@ -155,24 +156,38 @@ describe("planMaterialAppend", () => {describe("planOperationAppend", () => {const partLabel = "P-1 rev 0";- it("orders new operations by Op No, else by position, on an empty version", () => {+ it("orders new operations by their Op No on an empty version", () => {const plan = planOperationAppend({bop: [{ index: 0, opNo: "10" },- { index: 1, opNo: "B" }+ { index: 1, opNo: "2" }],- children: [{ index: 2, opNo: "B", rowType: "STEP" }],+ children: [{ index: 2, opNo: "2.0", rowType: "STEP" }],existing: [],partLabel});expect(plan.insert).toEqual([{ index: 0, opNo: "10", order: 10 },- { index: 1, opNo: "B", order: 2 }+ { index: 1, opNo: "2", order: 2 }]);expect(plan.errors).toEqual([]);expect(plan.existingIdByOpNo.size).toBe(0);});+ it("refuses an Op No that is not a number", () => {+ const plan = planOperationAppend({+ bop: [{ index: 0, opNo: "Deburr" }],+ children: [{ index: 1, opNo: "Deburr", rowType: "STEP" }],+ existing: [{ id: "op-1", order: 1 }],+ partLabel+ });+ expect(plan.insert).toEqual([]);+ expect(plan.errors).toEqual([+ { row: 0, reason: 'Op No "Deburr" must be a number' },+ { row: 1, reason: 'Op No "Deburr" must be a number' }+ ]);+ });+it("matches an Op No to the existing operation with that order", () => {const plan = planOperationAppend({bop: [@@ -191,17 +206,23 @@ describe("planOperationAppend", () => {expect(plan.existingIdByOpNo.get("1")).toBe("op-1");});- it("places a non-numeric Op No after the existing operations", () => {+ it("matches Op Nos by value, not by text", () => {const plan = planOperationAppend({- bop: [{ index: 0, opNo: "Deburr" }],- children: [],+ bop: [{ index: 0, opNo: "01" }],+ children: [+ { index: 1, opNo: "1.0", rowType: "STEP" },+ { index: 2, opNo: "2.00", rowType: "PARAM" }+ ],existing: [{ id: "op-1", order: 1 },- { id: "op-2", order: 20 }+ { id: "op-2", order: 2 }],partLabel});- expect(plan.insert).toEqual([{ index: 0, opNo: "Deburr", order: 21 }]);+ expect(plan.errors).toEqual([]);+ expect(plan.skipped).toEqual([{ index: 0, opNo: "01" }]);+ expect(plan.existingIdByOpNo.get(opKey("1.0"))).toBe("op-1");+ expect(plan.existingIdByOpNo.get(opKey("2"))).toBe("op-2");});it("attaches child rows to an existing operation with no BOP row", () => {diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 3f4b0d43c5..b0df6deb1c 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -3334,6 +3334,17 @@ export async function importMethods(const releaseControl = (settings?.plmReleaseControl ??"enforce") as ReleaseControl;+ // Change notice locks, read before any part's transaction opens: the+ // pending-approval check behind them is a separate request.+ const changeNoticeLocks = await loadChangeNoticeLocks(+ db,+ companyId,+ [...groups.values()].flatMap((g) => {+ const parent = itemMap.get(key(g.readableId, g.revision));+ return parent ? [parent.id] : [];+ })+ );+// A process also gives an operation its default type and description, as// the Bill of Process editor fills them in when a process is picked.const processMap = new Map<string, string>();@@ -3420,7 +3431,8 @@ export async function importMethods(processById,workCenterMap,supplierMap,- releaseControl+ releaseControl,+ changeNoticeLocks});// Lines already on the method are skipped, never written twice. Benign:// not something the user needs to fix, so a skip, not an error.@@ -3537,24 +3549,34 @@ function validateGroup(});}- // Op No uniqueness within the parent.- const opNos = new Set<string>();+ // An Op No is the operation's order, so it is a number and Op Nos compare+ // by value: "10" and "10.0" name one operation. A re-run can only find an+ // operation it wrote before by that number.+ const opNoIssue = (e: Entry, rowType: string) => {+ const opNo = text(e.record.opNo);+ const order = num(opNo);+ if (!opNo) return `${rowType} row is missing Op No`;+ if (order === undefined || order < 0) {+ return `${rowType} row Op No "${opNo}" must be a number of 0 or more`;+ }+ return null;+ };+ const opNos = new Set<number>();for (const e of bucket.bop) {const opNo = text(e.record.opNo);- if (!opNo) {- errors.push({- row: rowOf(e.index),- reason: "BOP row is missing Op No"- });+ const issue = opNoIssue(e, "BOP");+ if (issue) {+ errors.push({ row: rowOf(e.index), reason: issue });continue;}- if (opNos.has(opNo)) {+ const order = num(opNo)!;+ if (opNos.has(order)) {errors.push({row: rowOf(e.index),reason: `Duplicate Op No "${opNo}" for ${partLabel}`});}- opNos.add(opNo);+ opNos.add(order);// process required + resolvableconst proc = text(e.record.process).toLowerCase();@@ -3688,6 +3710,16 @@ function validateGroup(// A STEP / TOOL / PARAM row's Op No may name an operation already on the// method, so writeGroup resolves it once the target version is known.+ for (const [rows, rowType] of [+ [bucket.step, "STEP"],+ [bucket.tool, "TOOL"],+ [bucket.param, "PARAM"]+ ] as const) {+ for (const e of rows) {+ const issue = opNoIssue(e, rowType);+ if (issue) errors.push({ row: rowOf(e.index), reason: issue });+ }+ }for (const e of bucket.step) {if (!text(e.record.stepName)) {errors.push({@@ -3876,12 +3908,20 @@ export function planMaterialAppend(args: {return { insert, skipped };}+/** An Op No as one key per number: "10", "10.0" and "010" are the same. */+export const opKey = (opNo: string): string => {+ const order = num(opNo);+ return order === undefined ? opNo : String(order);+};+/*** How a version's BOP rows and the STEP / TOOL / PARAM rows that reference- * them map onto the operations already on it. An Op No equal to an existing- * operation's order names that operation: its BOP row is skipped and its- * children attach to it. Any other BOP row is a new operation, ordered by its- * Op No when that is a number, else after the existing operations.+ * them map onto the operations already on it. An Op No is the operation's+ * order. An Op No equal to an existing operation's order names that+ * operation: its BOP row is skipped and its children attach to it. Any other+ * BOP row is a new operation at that order. An Op No that is not a number is+ * refused: nothing could find the operation again on a re-run.+ * `existingIdByOpNo` is keyed by `opKey`.*/export function planOperationAppend(args: {bop: Array<{ index: number; opNo: string }>;@@ -3904,18 +3944,14 @@ export function planOperationAppend(args: {ids.push(op.id);idsByOrder.set(Number(op.order), ids);}- const highest = args.existing.reduce(- (max, op) => Math.max(max, Number(op.order)),- 0- );- const matching = (opNo: string) => {- const order = num(opNo);- return order === undefined ? [] : (idsByOrder.get(order) ?? []);- };const ambiguous = (index: number, opNo: string, count: number) => ({row: rowOf(index),reason: `Op No "${opNo}" matches ${count} operations on ${args.partLabel}`});+ const notANumber = (index: number, opNo: string) => ({+ row: rowOf(index),+ reason: `Op No "${opNo}" must be a number`+ });const insert: Array<{ index: number; opNo: string; order: number }> = [];const skipped: Array<{ index: number; opNo: string }> = [];@@ -3923,29 +3959,35 @@ export function planOperationAppend(args: {const errors: RowIssue[] = [];for (const { index, opNo } of args.bop) {- const ids = matching(opNo);+ const order = num(opNo);+ if (order === undefined) {+ errors.push(notANumber(index, opNo));+ continue;+ }+ const ids = idsByOrder.get(order) ?? [];if (ids.length > 1) {errors.push(ambiguous(index, opNo, ids.length));} else if (ids.length === 1) {skipped.push({ index, opNo });- existingIdByOpNo.set(opNo, ids[0]!);+ existingIdByOpNo.set(opKey(opNo), ids[0]!);} else {- insert.push({- index,- opNo,- order: num(opNo) ?? highest + insert.length + 1- });+ insert.push({ index, opNo, order });}}- const fileOpNos = new Set(args.bop.map((b) => b.opNo));+ const fileOrders = new Set(args.bop.map((b) => num(b.opNo)));for (const { index, opNo, rowType } of args.children) {- if (fileOpNos.has(opNo)) continue;- const ids = matching(opNo);+ const order = num(opNo);+ if (order === undefined) {+ errors.push(notANumber(index, opNo));+ continue;+ }+ if (fileOrders.has(order)) continue;+ const ids = idsByOrder.get(order) ?? [];if (ids.length > 1) {errors.push(ambiguous(index, opNo, ids.length));} else if (ids.length === 1) {- existingIdByOpNo.set(opNo, ids[0]!);+ existingIdByOpNo.set(opKey(opNo), ids[0]!);} else {errors.push({row: rowOf(index),@@ -3973,6 +4015,7 @@ async function writeGroup(workCenterMap: Map<string, string>;supplierMap: Map<string, string>;releaseControl: ReleaseControl;+ changeNoticeLocks: Map<string, string | null>;}): Promise<{ wroteAny: boolean; skipped: RowIssue[] }> {const { companyId, userId } = ctx;@@ -4072,7 +4115,7 @@ async function writeGroup(status: method.status,version: method.version,changeNoticeLock: method.changeOrderId- ? await changeNoticeLockFor(trx, companyId, method.changeOrderId)+ ? changeNoticeLockOf(ctx.changeNoticeLocks, method.changeOrderId): null,revisionStatus,releaseControl: ctx.releaseControl@@ -4292,7 +4335,7 @@ async function writeGroup(]).returning(["id"]).execute();- opIdByNo.set(opNo, inserted[0]!.id);+ opIdByNo.set(opKey(opNo), inserted[0]!.id);wroteAny = true;}@@ -4310,7 +4353,7 @@ async function writeGroup(for (const e of bucket.step) {const r = e.record;const opNo = text(r.opNo);- const operationId = opIdByNo.get(opNo)!;+ const operationId = opIdByNo.get(opKey(opNo))!;const name = text(r.stepName);if (children.stepNames.get(operationId)?.has(name)) {skipped.push({@@ -4352,7 +4395,7 @@ async function writeGroup(for (const e of bucket.tool) {const r = e.record;const opNo = text(r.opNo);- const operationId = opIdByNo.get(opNo)!;+ const operationId = opIdByNo.get(opKey(opNo))!;const tool = await resolveItem(trx,companyId,@@ -4386,7 +4429,7 @@ async function writeGroup(for (const e of bucket.param) {const r = e.record;const opNo = text(r.opNo);- const operationId = opIdByNo.get(opNo)!;+ const operationId = opIdByNo.get(opKey(opNo))!;const paramKey = text(r.paramKey);if (children.paramKeys.get(operationId)?.has(paramKey)) {skipped.push({@@ -4501,20 +4544,45 @@ async function currentMakeMethodId(return rows[0]!.id;}-// Why the change notice that owns a Draft locks it, or null: the check-// checkRevisionLock runs before every BOM and BOP write.-async function changeNoticeLockFor(- trx: Transaction<KyselyDatabase>,+// Why each change notice that owns a Draft of these items locks it, or null:+// the check checkRevisionLock runs before every BOM and BOP write.+async function loadChangeNoticeLocks(+ db: Kysely<KyselyDatabase>,companyId: string,+ itemIds: string[]+): Promise<Map<string, string | null>> {+ if (itemIds.length === 0) return new Map();+ const notices = await db+ .selectFrom("makeMethod")+ .innerJoin("changeOrder", "changeOrder.id", "makeMethod.changeOrderId")+ .select(["changeOrder.id", "changeOrder.status"])+ .distinct()+ .where("makeMethod.itemId", "in", itemIds)+ .where("makeMethod.companyId", "=", companyId)+ .where("changeOrder.companyId", "=", companyId)+ .execute();+ return new Map(+ await Promise.all(+ notices.map(+ async (notice) =>+ [+ notice.id,+ await getChangeNoticeEngineeringLock(notice.id, notice.status)+ ] as const+ )+ )+ );+}++// A Draft whose change notice was not read before the import (it was linked+// while the import ran) is refused rather than written unchecked.+function changeNoticeLockOf(+ locks: Map<string, string | null>,changeOrderId: string-): Promise<string | null> {- const notice = await trx- .selectFrom("changeOrder")- .select(["status"])- .where("id", "=", changeOrderId)- .where("companyId", "=", companyId)- .executeTakeFirst();- return getChangeNoticeEngineeringLock(changeOrderId, notice?.status ?? null);+): string | null {+ return locks.has(changeOrderId)+ ? (locks.get(changeOrderId) ?? null)+ : "its change notice changed while the import ran. Run the import again";}// A new Draft version of the part's make method; never auto-activated.diff --git a/apps/erp/test/database/method-import-guards.test.ts b/apps/erp/test/database/method-import-guards.test.tsindex 01275f6e4e..86a031ad3f 100644--- a/apps/erp/test/database/method-import-guards.test.ts+++ b/apps/erp/test/database/method-import-guards.test.ts@@ -116,6 +116,14 @@ const REFUSALS: Array<[string, Rows, string[]]> = ["Op 10: an Inspection operation needs an Inspection Plan; add it in the app"]],+ [+ "an Op No that is not a number, and one Op No given twice",+ [bop("SUB", "Deburr"), bop("SUB", "10"), bop("SUB", "10.0")],+ [+ 'BOP row Op No "Deburr" must be a number of 0 or more',+ 'Duplicate Op No "10.0" for SUB rev 0'+ ]+ ],["a version that is not a number",[bom("ASSY", "COMP-1", "1", { makeMethodVersion: "abc" })],@@ -186,6 +194,65 @@ describe("method import guards", () => {});+ databaseTest(+ "an Op No written another way names the same operation on a re-run",+ async () => {+ f = await methodImportFixture();+ const step = (opNo: string) => ({+ rowType: "STEP",+ parentId: "SUB",+ opNo,+ stepName: "Deburr"+ });+ const first = await f.run("operations", [bop("SUB", "10"), step("10")]);+ expect(first.errors).toEqual([]);+ const again = await f.run("operations", [bop("SUB", "010"), step("10.0")]);+ expect(again.errors).toEqual([]);+ expect(again.updated).toBe(0);+ expect(again.skipped).toHaveLength(2);+ expect(await rowCounts()).toEqual({+ materials: 0,+ operations: 1,+ steps: 1+ });+ }+ );++ databaseTest(+ "refuses a Draft held by a change notice in Implementation",+ async () => {+ f = await methodImportFixture();+ const changeOrderId = `${f.companyId}-notice`;+ await f.db+ .insertInto("changeOrder")+ .values({+ id: changeOrderId,+ changeOrderId: "CN-TEST",+ name: "Test notice",+ openDate: "2026-10-21",+ status: "Implementation",+ companyId: f.companyId,+ createdBy: "system"+ })+ .execute();+ await f.db+ .updateTable("makeMethod")+ .set({ changeOrderId })+ .where("id", "=", await f.methodOf("ASSY"))+ .where("companyId", "=", f.companyId)+ .execute();+ const summary = await f.run("bom", [bom("ASSY", "COMP-1", "1")]);+ expect(summary.errors).toEqual([+ {+ row: 0,+ reason:+ "Part ASSY rev 0: This change notice is being implemented, so its changes are locked. Reopen it to make changes."+ }+ ]);+ expect((await rowCounts()).materials).toBe(0);+ }+ );+databaseTest("two imports of one file at the same time write each line once",async () => {diff --git a/docs/content/docs/reference/import-export.mdx b/docs/content/docs/reference/import-export.mdxindex ccbdbb0c85..7328d9e979 100644--- a/docs/content/docs/reference/import-export.mdx+++ b/docs/content/docs/reference/import-export.mdx@@ -38,7 +38,7 @@ Bulk import is available only for supported entities. Import each entity from thThe **Bulk Import** menu on the parts and tools lists also offers three **method** imports that load bills of materials and operations: **BOM**, **Operations**, and **Parts with Methods**, which creates parts and their full BOM and routing together. These are row-typed CSVs: each row is tagged `PART`, `BOM`, `BOP`, `STEP`, `TOOL`, or `PARAM` and names its parent part.-A method import adds to the make method that is already there. With **Make Method Version** blank it writes into the highest version that is not archived. New BOM lines go after the existing ones. An **Op No** that matches an existing operation's order adds its steps, tools, and parameters to that operation. Rows already on the method (the same material, operation, step name, tool, or parameter key) are skipped and listed, so a file can run again safely. The import changes only a Draft version and follows the same change notice and release locks as the BOM and BOP editors. A part it refuses is listed with the reason, and none of its rows are written.+A method import adds to the make method that is already there. With **Make Method Version** blank it writes into the highest version that is not archived. New BOM lines go after the existing ones. An **Op No** is the operation's order, so it must be a number: one that matches an existing operation's order adds its steps, tools, and parameters to that operation, and `10`, `10.0` and `010` all name the same operation. Rows already on the method (the same material, operation, step name, tool, or parameter key) are skipped and listed, so a file can run again safely. The import changes only a Draft version and follows the same change notice and release locks as the BOM and BOP editors. A part it refuses is listed with the reason, and none of its rows are written.Blank cells take the values the editors fill in: a BOM line with no **Unit of Measure** takes the material's own unit, and an operation with no **Operation Type** or **Operation Description** takes its process's type and name. The import also refuses what the editors refuse: a BOM line that is the part itself or a tool or service, a tool that is not a tool item, a negative quantity, time or cost, and a step whose maximum is below its minimum. An Inspection operation needs an Inspection Plan, which a CSV cannot carry, so add Inspection operations in the app.