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.

feat(items): method CSV imports append to an existing make method

Raul5fc571605797
diff --git a/.ai/plans/2026-10-21-method-import-append.md b/.ai/plans/2026-10-21-method-import-append.md
new file mode 100644
index 0000000000..ce40ecfc55
--- /dev/null
+++ b/.ai/plans/2026-10-21-method-import-append.md
@@ -0,0 +1,76 @@
+# Method import: append to existing methods
+
+The BOM, Operations and Parts with Methods CSV imports (`importMethods`,
+`apps/erp/app/modules/shared/shared.service.ts`) write a make method version
+only when it has no materials and no operations. So a file cannot add BOM lines
+or a bill of process to a part that already has a BOM. If a user imports a BOM
+and then imports Operations for the same parts, the second import skips every
+part.
+
+This change makes the import append to the target version. The import becomes
+the bulk form of the add buttons in the BOM and Bill of Process editors. A
+re-run of a file stays safe: the import skips and reports the lines and
+operations that are already on the target version.
+
+## Behavior
+
+- Target version
+ - Explicit Make Method Version: that version. The import creates it as a
+ Draft when it does not exist (unchanged).
+ - Blank: the highest non-archived version. Before this change, blank
+ preferred the Active version, which the editors never change.
+- Refusals. The import checks these per part before it writes. A refused part
+ gets one error and writes nothing. Other parts continue.
+ - The target version is not a Draft. The editors are read-only on any other
+ status (`BillOfMaterial.tsx`, `BillOfProcess.tsx`:
+ `makeMethod.status !== "Draft"`).
+ - The target version belongs to a change notice whose engineering content is
+ locked. `checkRevisionLock` applies the same check
+ (`getChangeNoticeEngineeringLock`) to every BOM and BOP mutation route.
+ - The item is a released (Production) revision and `plmReleaseControl` is
+ `enforce` (`getLockVerdict`).
+- BOM lines
+ - The import orders new lines after the highest existing line
+ (`max(order) + 1`, as `onAddItem` in `BillOfMaterial.tsx`).
+ - The import skips and reports a line whose material item is already on the
+ target version. Lines repeated inside one file are all written (unchanged).
+- Operations
+ - An Op No equal to the order of an existing operation refers to that
+ operation. The import skips and reports the BOP row. STEP, TOOL and PARAM
+ rows with that Op No attach to the existing operation.
+ - If two existing operations have that order, the row is an error.
+ - A new numeric Op No becomes the order of the new operation (unchanged).
+ - A new non-numeric Op No goes after the highest existing or assigned order.
+ - A STEP, TOOL or PARAM row can reference an existing operation with no BOP
+ row in the file.
+- Steps, tools and parameters on an existing operation
+ - The import skips and reports a step with the same name, a tool with the
+ same tool item, and a parameter with the same key.
+ - The import sorts new steps after the highest existing step.
+- Counts: a part counts as inserted (new part) or updated (existing part) when
+ the import writes at least one row for it. Each skipped line is listed.
+
+## Out of scope
+
+- Updates to existing lines (quantity, unit, times) and deletes.
+- A new version that copies another version.
+- The other findings from the PR #911 review: same-file sub-assembly order,
+ Unique ID not written by Parts with Methods, BOM unit default `EA`, the unused
+ Supplier Process column, and a non-numeric version that becomes 1.
+
+## Steps
+
+- [x] Export `getChangeNoticeEngineeringLock` from `items.service.ts`.
+- [x] `importMethods`: load `plmReleaseControl` once; add `revisionStatus` to the
+ item lookup.
+- [x] `writeGroup`: replace the fill-if-empty gate with target resolution,
+ refusals, existing-state reads and append writes.
+- [x] Move the STEP/TOOL/PARAM Op No check from the pure validation into the
+ transaction, where existing operations are known.
+- [x] Pure helpers for the append decisions, with unit tests.
+- [x] Database test (`apps/erp/test/database/method-import-append.test.ts`, 6 cases, pass on the local stack): append BOM lines, add
+ operations to a part with a BOM, attach steps to an existing operation,
+ re-run writes nothing, Active and locked targets refused.
+- [x] Update `.claude/rules/csv-import-system.md` and the import docs.
+- [x] Scoped typecheck, Biome, unit tests.
+- [x] Browser check on the local stack: BOM and Operations imports, then the Operations file again (4 rows skipped, nothing written).
diff --git a/.claude/rules/csv-import-system.md b/.claude/rules/csv-import-system.md
index 7da24a4db7..9447cfec57 100644
--- a/.claude/rules/csv-import-system.md
+++ b/.claude/rules/csv-import-system.md
@@ -248,6 +248,40 @@ and resolved to ids by the FieldMappings enum-mapping step (fetchers on
`materialSubstance` / `materialForm`), so parents must already exist — an unresolved
parent is an `errors` row. New rows get a DB-generated `xid()` id.
+### Method imports (append to the target version)
+
+`bom`, `operations` and `partWithMethod` are handled by `importMethods`
+(`shared.service.ts`). Rows carry a Row Type (`PART`, `BOM`, `BOP`, `STEP`,
+`TOOL`, `PARAM`; blank means `BOM` in the `bom` file) and name their parent part
+(`parentId` + `parentRevision`). The import groups rows by parent part, validates
+each group (`validateGroup`, pure), then writes each part in its own Kysely
+transaction (`writeGroup`): a part with any error writes nothing, other parts
+continue.
+
+- **Target version** (`pickMethodImportTarget`): a blank Make Method Version
+ targets the highest non-archived version that existed before the import; an
+ explicit one targets that version, created as a Draft when missing.
+- **Refusals** (`methodImportRefusal`), the same rules as the BOM and BOP
+ editors: the target must be a Draft; a Draft owned by a change notice follows
+ `getChangeNoticeEngineeringLock`; a Production revision follows
+ `plmReleaseControl` through `getLockVerdict`. A refusal throws
+ `MethodImportRefused` inside the transaction, so a Draft the file created for
+ that part is rolled back too.
+- **Append, not fill** (`planMaterialAppend`, `planOperationAppend`): new BOM
+ lines 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
+ with the same item and a parameter with the same key are skipped. Every skip
+ goes to `skipped`, so re-running a file writes nothing.
+- BOM lines copy `methodType` / `sourcingType` / `materialMakeMethodId` /
+ `storageUnitIds` from the component item, as `upsertMethodMaterial` does.
+- Known gaps: a sub-assembly created by a `PART` row must come before its parent
+ in the file (parts are written in order of first appearance); a `PART` row
+ does not write the Unique ID mapping; an unmapped BOM unit of measure is `EA`;
+ the Supplier Process column is unused; a non-numeric Make Method Version
+ becomes 1.
+
> The models also include `customerStatus` / `customerType` field-mapping entries (used by
> creatable lookups), but only the tables above appear in `importPermissions`.
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index a0d82e99b7..4a4b834c5f 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -9445,7 +9445,7 @@ type ChangeNoticeEditScope = "engineering" | "workflow";
// approval request can only be pending at Engineering Complete (approval gates
// the move to Implementation), so only that stage pays for the lookup;
// approvalRequest is service-role only.
-async function getChangeNoticeEngineeringLock(
+export async function getChangeNoticeEngineeringLock(
changeNoticeId: string,
status: string | null | undefined
): Promise<string | null> {
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.ts
new file mode 100644
index 0000000000..36b07de3e7
--- /dev/null
+++ b/apps/erp/app/modules/shared/shared.method-import-append.test.ts
@@ -0,0 +1,251 @@
+// 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.
+
+// The decisions the method import makes when a make method version already
+// has lines: which version it writes into, when it refuses, and what it
+// appends or skips.
+
+import { describe, expect, it } from "vitest";
+import { LOCKED_REVISION_MESSAGE } from "~/modules/items/items.service";
+import {
+ methodImportRefusal,
+ pickMethodImportTarget,
+ planMaterialAppend,
+ planOperationAppend
+} from "./shared.service";
+
+const method = (
+ version: number,
+ status: string,
+ changeOrderId: string | null = null
+) => ({ id: `mm-${version}`, version, status, changeOrderId });
+
+describe("pickMethodImportTarget", () => {
+ it("targets the highest non-archived version when the version is blank", () => {
+ const methods = [
+ method(1, "Archived"),
+ method(2, "Active"),
+ method(3, "Draft")
+ ];
+ expect(pickMethodImportTarget(methods, "")).toEqual({
+ method: methods[2]
+ });
+ });
+
+ it("targets the Active version when it is the highest", () => {
+ const methods = [method(1, "Archived"), method(2, "Active")];
+ expect(pickMethodImportTarget(methods, " ")).toEqual({
+ method: methods[1]
+ });
+ });
+
+ it("creates the next version when every version is archived", () => {
+ expect(pickMethodImportTarget([method(1, "Archived")], "")).toEqual({
+ createVersion: 2
+ });
+ expect(pickMethodImportTarget([], "")).toEqual({ createVersion: 1 });
+ });
+
+ it("targets an explicit version, or creates it when it is missing", () => {
+ const methods = [method(1, "Active"), method(2, "Draft")];
+ expect(pickMethodImportTarget(methods, "1")).toEqual({
+ method: methods[0]
+ });
+ expect(pickMethodImportTarget(methods, "4")).toEqual({
+ createVersion: 4
+ });
+ });
+});
+
+describe("methodImportRefusal", () => {
+ const base = {
+ status: "Draft",
+ version: 2,
+ changeNoticeLock: null,
+ revisionStatus: "Design",
+ releaseControl: "enforce" as const
+ };
+
+ it("allows a Draft on an unreleased revision", () => {
+ expect(methodImportRefusal(base)).toBeNull();
+ });
+
+ it("refuses a version that is not a Draft", () => {
+ expect(methodImportRefusal({ ...base, status: "Active" })).toMatch(
+ /^make method version 2 is Active, and only a Draft version can change/
+ );
+ expect(methodImportRefusal({ ...base, status: "Archived" })).toMatch(
+ /is Archived/
+ );
+ });
+
+ it("refuses a Draft that a locked change notice holds", () => {
+ expect(
+ methodImportRefusal({ ...base, changeNoticeLock: "Locked notice" })
+ ).toBe("Locked notice");
+ });
+
+ it("follows release control on a released revision", () => {
+ const released = { ...base, revisionStatus: "Production" };
+ expect(methodImportRefusal(released)).toBe(LOCKED_REVISION_MESSAGE);
+ expect(
+ methodImportRefusal({ ...released, releaseControl: "warn" })
+ ).toBeNull();
+ expect(
+ methodImportRefusal({ ...released, releaseControl: "off" })
+ ).toBeNull();
+ });
+});
+
+describe("planMaterialAppend", () => {
+ it("numbers lines from 1 on an empty version", () => {
+ expect(
+ planMaterialAppend({
+ lines: [
+ { index: 0, itemId: "a" },
+ { index: 1, itemId: "b" }
+ ],
+ existing: []
+ })
+ ).toEqual({
+ insert: [
+ { index: 0, order: 1 },
+ { index: 1, order: 2 }
+ ],
+ skipped: []
+ });
+ });
+
+ it("appends after the highest line and skips materials already on it", () => {
+ expect(
+ planMaterialAppend({
+ lines: [
+ { index: 0, itemId: "a" },
+ { index: 1, itemId: "c" },
+ { index: 2, itemId: "d" }
+ ],
+ existing: [
+ { itemId: "a", order: 1 },
+ { itemId: "b", order: 5 }
+ ]
+ })
+ ).toEqual({
+ insert: [
+ { index: 1, order: 6 },
+ { index: 2, order: 7 }
+ ],
+ skipped: [0]
+ });
+ });
+
+ it("writes every copy of a material repeated inside the file", () => {
+ expect(
+ planMaterialAppend({
+ lines: [
+ { index: 0, itemId: "a" },
+ { index: 1, itemId: "a" }
+ ],
+ existing: []
+ }).insert
+ ).toHaveLength(2);
+ });
+});
+
+describe("planOperationAppend", () => {
+ const partLabel = "P-1 rev 0";
+
+ it("orders new operations by Op No, else by position, on an empty version", () => {
+ const plan = planOperationAppend({
+ bop: [
+ { index: 0, opNo: "10" },
+ { index: 1, opNo: "B" }
+ ],
+ children: [{ index: 2, opNo: "B", rowType: "STEP" }],
+ existing: [],
+ partLabel
+ });
+ expect(plan.insert).toEqual([
+ { index: 0, opNo: "10", order: 10 },
+ { index: 1, opNo: "B", order: 2 }
+ ]);
+ expect(plan.errors).toEqual([]);
+ expect(plan.existingIdByOpNo.size).toBe(0);
+ });
+
+ it("matches an Op No to the existing operation with that order", () => {
+ const plan = planOperationAppend({
+ bop: [
+ { index: 0, opNo: "1" },
+ { index: 1, opNo: "30" }
+ ],
+ children: [],
+ existing: [
+ { id: "op-1", order: 1 },
+ { id: "op-2", order: 2 }
+ ],
+ partLabel
+ });
+ expect(plan.skipped).toEqual([{ index: 0, opNo: "1" }]);
+ expect(plan.insert).toEqual([{ index: 1, opNo: "30", order: 30 }]);
+ expect(plan.existingIdByOpNo.get("1")).toBe("op-1");
+ });
+
+ it("places a non-numeric Op No after the existing operations", () => {
+ const plan = planOperationAppend({
+ bop: [{ index: 0, opNo: "Deburr" }],
+ children: [],
+ existing: [
+ { id: "op-1", order: 1 },
+ { id: "op-2", order: 20 }
+ ],
+ partLabel
+ });
+ expect(plan.insert).toEqual([{ index: 0, opNo: "Deburr", order: 21 }]);
+ });
+
+ it("attaches child rows to an existing operation with no BOP row", () => {
+ const plan = planOperationAppend({
+ bop: [],
+ children: [
+ { index: 0, opNo: "2", rowType: "STEP" },
+ { index: 1, opNo: "2", rowType: "PARAM" }
+ ],
+ existing: [
+ { id: "op-1", order: 1 },
+ { id: "op-2", order: 2 }
+ ],
+ partLabel
+ });
+ expect(plan.errors).toEqual([]);
+ expect(plan.existingIdByOpNo.get("2")).toBe("op-2");
+ });
+
+ it("reports a child row whose Op No matches nothing", () => {
+ const plan = planOperationAppend({
+ bop: [],
+ children: [{ index: 4, opNo: "9", rowType: "TOOL" }],
+ existing: [{ id: "op-1", order: 1 }],
+ partLabel
+ });
+ expect(plan.errors).toEqual([
+ { row: 4, reason: 'TOOL references unknown Op No "9"' }
+ ]);
+ });
+
+ it("reports an Op No that matches two existing operations", () => {
+ const plan = planOperationAppend({
+ bop: [{ index: 0, opNo: "1" }],
+ children: [{ index: 1, opNo: "1", rowType: "STEP" }],
+ existing: [
+ { id: "op-1", order: 1 },
+ { id: "op-2", order: 1 }
+ ],
+ partLabel
+ });
+ expect(plan.errors).toEqual([
+ { row: 0, reason: 'Op No "1" matches 2 operations on P-1 rev 0' }
+ ]);
+ expect(plan.insert).toEqual([]);
+ });
+});
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index 5a379c88e6..c186940a8f 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -168,6 +168,11 @@ import {
canEditChangeNoticeWorkflow,
changeNoticeLockedMessage
} from "~/modules/items/items.models";
+import {
+ getChangeNoticeEngineeringLock,
+ getLockVerdict,
+ type ReleaseControl
+} from "~/modules/items/items.service";
import { getMethod } from "~/modules/production/production.service";
import { getLocationsList } from "~/modules/resources/resources.service";
import {
@@ -3086,8 +3091,19 @@ type ItemInfo = {
type: string;
defaultMethodType: string | null;
sourcingType: string | null;
+ revisionStatus: string | null;
};
+type RowIssue = { row: number; reason: string };
+
+// A part's recipe the import refuses as a whole. Thrown inside the part's
+// transaction so nothing it wrote survives, then reported as errors.
+class MethodImportRefused extends Error {
+ constructor(readonly issues: RowIssue[]) {
+ super("Method import refused");
+ }
+}
+
// ---------------------------------------------------------------------------
// small helpers
// ---------------------------------------------------------------------------
@@ -3269,7 +3285,8 @@ export async function importMethods(
"revision",
"type",
"defaultMethodType",
- "sourcingType"
+ "sourcingType",
+ "revisionStatus"
])
.where("companyId", "=", companyId)
.where("readableId", "in", Array.from(readableIds))
@@ -3281,12 +3298,23 @@ export async function importMethods(
id: r.id,
type: r.type,
defaultMethodType: r.defaultMethodType ?? null,
- sourcingType: r.sourcingType ?? null
+ sourcingType: r.sourcingType ?? null,
+ revisionStatus: r.revisionStatus ?? null
});
}
}
}
+ // The BOM and BOP editors refuse a released (Production) revision when
+ // release control is "enforce"; the import applies the same verdict.
+ const settings = await db
+ .selectFrom("companySettings")
+ .select(["plmReleaseControl"])
+ .where("id", "=", companyId)
+ .executeTakeFirst();
+ const releaseControl = (settings?.plmReleaseControl ??
+ "enforce") as ReleaseControl;
+
const { map: processMap, ambiguous: processAmbiguous } = await nameMap(
db,
"process",
@@ -3355,24 +3383,25 @@ export async function importMethods(
itemMap,
processMap,
workCenterMap,
- supplierMap
+ supplierMap,
+ releaseControl
});
- if (result.filledAny) {
+ // Lines already on the method are skipped, never written twice. Benign:
+ // not something the user needs to fix, so a skip, not an error.
+ for (const s of result.skipped) summary.skipped.push(s);
+ if (result.wroteAny) {
// A new part counts as imported; an existing part as updated.
if (g.partRow) summary.inserted++;
else summary.updated++;
- } else if (result.skippedExisting) {
- // The targeted version already had content — create-only, never clobber.
- // Benign: not something the user needs to fix, so it's a skip, not an error.
- summary.skipped.push({
- row: rowOf(g.firstIndex),
- reason: `Part ${partLabel} already has a method; skipped`
- });
} else if (g.partRow) {
// A PART row with no BOM/BOP rows — only the part itself was created.
summary.inserted++;
}
} catch (err) {
+ if (err instanceof MethodImportRefused) {
+ for (const issue of err.issues) summary.errors.push(issue);
+ continue;
+ }
summary.errors.push({
row: rowOf(g.firstIndex),
reason: `Part ${partLabel} failed to import: ${
@@ -3449,7 +3478,7 @@ function validateGroup(
}
for (const bucket of g.versions.values()) {
- // Op No uniqueness within the parent + a set to validate child references.
+ // Op No uniqueness within the parent.
const opNos = new Set<string>();
for (const e of bucket.bop) {
const opNo = text(e.record.opNo);
@@ -3551,15 +3580,9 @@ function validateGroup(
}
}
- // STEP / TOOL / PARAM must reference a known Op No within this version.
+ // 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 e of bucket.step) {
- const opNo = text(e.record.opNo);
- if (!opNos.has(opNo)) {
- errors.push({
- row: rowOf(e.index),
- reason: `STEP references unknown Op No "${opNo}"`
- });
- }
if (!text(e.record.stepName)) {
errors.push({
row: rowOf(e.index),
@@ -3587,13 +3610,6 @@ function validateGroup(
}
}
for (const e of bucket.tool) {
- const opNo = text(e.record.opNo);
- if (!opNos.has(opNo)) {
- errors.push({
- row: rowOf(e.index),
- reason: `TOOL references unknown Op No "${opNo}"`
- });
- }
const toolId = text(e.record.toolId);
if (!toolId) {
errors.push({
@@ -3617,13 +3633,6 @@ function validateGroup(
}
}
for (const e of bucket.param) {
- const opNo = text(e.record.opNo);
- if (!opNos.has(opNo)) {
- errors.push({
- row: rowOf(e.index),
- reason: `PARAM references unknown Op No "${opNo}"`
- });
- }
if (!text(e.record.paramKey)) {
errors.push({
row: rowOf(e.index),
@@ -3642,6 +3651,172 @@ function validateGroup(
return errors;
}
+// ---------------------------------------------------------------------------
+// append planning (pure)
+// ---------------------------------------------------------------------------
+
+type MakeMethodVersion = {
+ id: string;
+ version: number;
+ status: string;
+ changeOrderId: string | null;
+};
+
+/**
+ * The make method version a part's rows go into. Blank: the highest
+ * non-archived version, the one being worked on. Explicit: that version. A
+ * version that does not exist is created as a Draft.
+ */
+export function pickMethodImportTarget(
+ methods: MakeMethodVersion[],
+ version: string
+): { method: MakeMethodVersion } | { createVersion: number } {
+ if (!version.trim()) {
+ const current = methods
+ .filter((m) => m.status !== "Archived")
+ .sort((a, b) => Number(b.version) - Number(a.version))[0];
+ if (current) return { method: current };
+ const highest = methods.reduce((max, m) => Math.max(max, m.version), 0);
+ return { createVersion: highest + 1 };
+ }
+ const versionNumber = num(version) ?? 1;
+ const existing = methods.find((m) => Number(m.version) === versionNumber);
+ return existing ? { method: existing } : { createVersion: versionNumber };
+}
+
+/**
+ * Why the import may not write into a make method version, or null. The same
+ * rules as the BOM and BOP editors: only a Draft is editable, a change notice
+ * past engineering locks its Draft, and a released (Production) revision
+ * follows release control.
+ */
+export function methodImportRefusal(args: {
+ status: string;
+ version: number;
+ changeNoticeLock: string | null;
+ revisionStatus: string | null;
+ releaseControl: ReleaseControl;
+}): string | null {
+ if (args.status !== "Draft") {
+ return `make method version ${args.version} is ${args.status}, and only a Draft version can change. Create a new version, then set Make Method Version to it`;
+ }
+ if (args.changeNoticeLock) return args.changeNoticeLock;
+ const verdict = getLockVerdict({
+ isLocked: args.revisionStatus === "Production",
+ releaseControl: args.releaseControl
+ });
+ return verdict.ok ? null : verdict.message;
+}
+
+/**
+ * The BOM lines to write onto a version that may already have lines. A line
+ * whose material is already on the version is skipped. The rest are ordered
+ * after the highest existing line, as the editor's add button does. Lines
+ * repeated inside the file are all written.
+ */
+export function planMaterialAppend(args: {
+ lines: Array<{ index: number; itemId: string }>;
+ existing: Array<{ itemId: string; order: number }>;
+}): { insert: Array<{ index: number; order: number }>; skipped: number[] } {
+ const onMethod = new Set(args.existing.map((m) => m.itemId));
+ let order = args.existing.reduce(
+ (max, m) => Math.max(max, Number(m.order)),
+ 0
+ );
+ const insert: Array<{ index: number; order: number }> = [];
+ const skipped: number[] = [];
+ for (const line of args.lines) {
+ if (onMethod.has(line.itemId)) {
+ skipped.push(line.index);
+ continue;
+ }
+ order++;
+ insert.push({ index: line.index, order });
+ }
+ return { insert, skipped };
+}
+
+/**
+ * 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.
+ */
+export function planOperationAppend(args: {
+ bop: Array<{ index: number; opNo: string }>;
+ children: Array<{
+ index: number;
+ opNo: string;
+ rowType: "STEP" | "TOOL" | "PARAM";
+ }>;
+ existing: Array<{ id: string; order: number }>;
+ partLabel: string;
+}): {
+ insert: Array<{ index: number; opNo: string; order: number }>;
+ skipped: Array<{ index: number; opNo: string }>;
+ existingIdByOpNo: Map<string, string>;
+ errors: RowIssue[];
+} {
+ const idsByOrder = new Map<number, string[]>();
+ for (const op of args.existing) {
+ const ids = idsByOrder.get(Number(op.order)) ?? [];
+ 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 insert: Array<{ index: number; opNo: string; order: number }> = [];
+ const skipped: Array<{ index: number; opNo: string }> = [];
+ const existingIdByOpNo = new Map<string, string>();
+ const errors: RowIssue[] = [];
+
+ for (const { index, opNo } of args.bop) {
+ const ids = matching(opNo);
+ 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]!);
+ } else {
+ insert.push({
+ index,
+ opNo,
+ order: num(opNo) ?? highest + insert.length + 1
+ });
+ }
+ }
+
+ const fileOpNos = new Set(args.bop.map((b) => b.opNo));
+ for (const { index, opNo, rowType } of args.children) {
+ if (fileOpNos.has(opNo)) continue;
+ const ids = matching(opNo);
+ if (ids.length > 1) {
+ errors.push(ambiguous(index, opNo, ids.length));
+ } else if (ids.length === 1) {
+ existingIdByOpNo.set(opNo, ids[0]!);
+ } else {
+ errors.push({
+ row: rowOf(index),
+ reason: `${rowType} references unknown Op No "${opNo}"`
+ });
+ }
+ }
+
+ return { insert, skipped, existingIdByOpNo, errors };
+}
+
// ---------------------------------------------------------------------------
// write (one transaction per part group → atomic per part, ADR-0001)
// ---------------------------------------------------------------------------
@@ -3656,17 +3831,21 @@ async function writeGroup(
processMap: Map<string, string>;
workCenterMap: Map<string, string>;
supplierMap: Map<string, string>;
+ releaseControl: ReleaseControl;
}
-): Promise<{ filledAny: boolean; skippedExisting: boolean }> {
+): Promise<{ wroteAny: boolean; skipped: RowIssue[] }> {
const { companyId, userId } = ctx;
const now = () => datetime.timestamp();
+ const partLabel = `${g.readableId} rev ${g.revision}`;
return await db.transaction().execute(async (trx) => {
- let filledAny = false;
- let skippedExisting = false;
+ let wroteAny = false;
+ const skipped: RowIssue[] = [];
+ const issues: RowIssue[] = [];
// Resolve (or create) the parent item.
let parentItemId: string;
+ let revisionStatus: string | null;
if (g.partRow) {
const r = g.partRow.record;
const inserted = await trx
@@ -3695,9 +3874,10 @@ async function writeGroup(
updatedBy: userId
} as never)
)
- .returning(["id"])
+ .returning(["id", "revisionStatus"])
.execute();
parentItemId = inserted[0]!.id;
+ revisionStatus = inserted[0]!.revisionStatus ?? null;
// The makeMethod Draft v1 is created by the AFTER INSERT trigger on item.
// The part row links to the item by readableId (part.id = item.readableId).
@@ -3715,48 +3895,148 @@ async function writeGroup(
.onConflict((oc) => oc.columns(["id", "companyId"]).doNothing())
.execute();
} else {
- const parent = ctx.itemMap.get(key(g.readableId, g.revision));
- parentItemId = parent!.id;
+ const parent = ctx.itemMap.get(key(g.readableId, g.revision))!;
+ parentItemId = parent.id;
+ revisionStatus = parent.revisionStatus;
}
+ const methods: MakeMethodVersion[] =
+ g.versions.size === 0
+ ? []
+ : (
+ await trx
+ .selectFrom("makeMethod")
+ .select(["id", "version", "status", "changeOrderId"])
+ .where("itemId", "=", parentItemId)
+ .where("companyId", "=", companyId)
+ .execute()
+ ).map((m) => ({ ...m, version: Number(m.version) }));
+ // Versions this file creates. A blank version still resolves against the
+ // versions that existed before the import, whatever the row order.
+ const createdIds = new Map<number, string>();
+
for (const [version, bucket] of g.versions) {
- const makeMethodId = await ensureMakeMethod(
- trx,
- parentItemId,
- version,
- companyId,
- userId
- );
+ const target = pickMethodImportTarget(methods, version);
+ const method =
+ "method" in target
+ ? target.method
+ : {
+ id: "",
+ version: target.createVersion,
+ status: "Draft",
+ changeOrderId: null
+ };
+
+ const refusal = methodImportRefusal({
+ status: method.status,
+ version: method.version,
+ changeNoticeLock: method.changeOrderId
+ ? await changeNoticeLockFor(trx, companyId, method.changeOrderId)
+ : null,
+ revisionStatus,
+ releaseControl: ctx.releaseControl
+ });
+ if (refusal) {
+ issues.push({
+ row: rowOf(firstIndexOf(bucket)),
+ reason: `Part ${partLabel}: ${refusal}`
+ });
+ continue;
+ }
- // Create-only: fill a version only if it has no method content yet.
- const hasMaterial = await trx
+ let makeMethodId = method.id || createdIds.get(method.version);
+ if (!makeMethodId) {
+ makeMethodId = await insertDraftMakeMethod(
+ trx,
+ parentItemId,
+ method.version,
+ companyId,
+ userId
+ );
+ createdIds.set(method.version, makeMethodId);
+ }
+
+ const existingMaterials = await trx
.selectFrom("methodMaterial")
- .select("id")
+ .select(["itemId", "order"])
.where("makeMethodId", "=", makeMethodId)
- .limit(1)
- .executeTakeFirst();
- const hasOperation = await trx
+ .where("companyId", "=", companyId)
+ .execute();
+ const existingOperations = await trx
.selectFrom("methodOperation")
- .select("id")
+ .select(["id", "order"])
.where("makeMethodId", "=", makeMethodId)
- .limit(1)
- .executeTakeFirst();
- if (hasMaterial || hasOperation) {
- skippedExisting = true;
+ .where("companyId", "=", companyId)
+ .execute();
+
+ const opPlan = planOperationAppend({
+ bop: bucket.bop.map((e) => ({
+ index: e.index,
+ opNo: text(e.record.opNo)
+ })),
+ children: [
+ ...bucket.step.map((e) => ({
+ index: e.index,
+ opNo: text(e.record.opNo),
+ rowType: "STEP" as const
+ })),
+ ...bucket.tool.map((e) => ({
+ index: e.index,
+ opNo: text(e.record.opNo),
+ rowType: "TOOL" as const
+ })),
+ ...bucket.param.map((e) => ({
+ index: e.index,
+ opNo: text(e.record.opNo),
+ rowType: "PARAM" as const
+ }))
+ ],
+ existing: existingOperations.map((op) => ({
+ id: op.id,
+ order: Number(op.order)
+ })),
+ partLabel
+ });
+ if (opPlan.errors.length > 0) {
+ issues.push(...opPlan.errors);
continue;
}
- // --- materials (BOM), in file row order ---
- let order = 1;
+ // --- materials (BOM), in file row order after the existing lines ---
+ const components = new Map<number, ItemInfo>();
for (const e of bucket.bom) {
- const r = e.record;
- const component = await resolveItem(
- trx,
- companyId,
- text(r.componentId),
- text(r.componentRevision),
- ctx.itemMap
+ components.set(
+ e.index,
+ await resolveItem(
+ trx,
+ companyId,
+ text(e.record.componentId),
+ text(e.record.componentRevision),
+ ctx.itemMap
+ )
);
+ }
+ const materialPlan = planMaterialAppend({
+ lines: bucket.bom.map((e) => ({
+ index: e.index,
+ itemId: components.get(e.index)!.id
+ })),
+ existing: existingMaterials.map((m) => ({
+ itemId: m.itemId,
+ order: Number(m.order)
+ }))
+ });
+ const bomByIndex = new Map(bucket.bom.map((e) => [e.index, e.record]));
+ for (const index of materialPlan.skipped) {
+ const r = bomByIndex.get(index)!;
+ skipped.push({
+ row: rowOf(index),
+ reason: `Material ${text(r.componentId)} rev ${text(r.componentRevision) || "0"} is already on the BOM of ${partLabel}; skipped`
+ });
+ }
+ for (const { index, order } of materialPlan.insert) {
+ const r = bomByIndex.get(index)!;
+ const component = components.get(index)!;
const methodType = component.defaultMethodType ?? "Pull from Inventory";
const sourcingType = component.sourcingType ?? "Specified";
@@ -3792,16 +4072,20 @@ async function writeGroup(
} as never
])
.execute();
- order++;
- filledAny = true;
+ wroteAny = true;
}
// --- operations (BOP), keyed by Op No ---
- const opIdByNo = new Map<string, string>();
- let opIndex = 1;
- for (const e of bucket.bop) {
- const r = e.record;
- const opNo = text(r.opNo);
+ const opIdByNo = new Map(opPlan.existingIdByOpNo);
+ for (const { opNo, index } of opPlan.skipped) {
+ skipped.push({
+ row: rowOf(index),
+ reason: `Op ${opNo} already exists on ${partLabel}; skipped`
+ });
+ }
+ const bopByIndex = new Map(bucket.bop.map((e) => [e.index, e.record]));
+ for (const { index, opNo, order } of opPlan.insert) {
+ const r = bopByIndex.get(index)!;
const opType =
normalizeOperationType(text(r.operationType)) || "Process";
const processId = ctx.processMap.get(text(r.process).toLowerCase())!;
@@ -3824,7 +4108,7 @@ async function writeGroup(
.values([
{
makeMethodId,
- order: num(opNo) ?? opIndex,
+ order,
operationOrder: text(r.operationOrder) || "After Previous",
operationType: opType,
processId,
@@ -3849,15 +4133,32 @@ async function writeGroup(
.returning(["id"])
.execute();
opIdByNo.set(opNo, inserted[0]!.id);
- opIndex++;
- filledAny = true;
+ wroteAny = true;
}
// --- steps / tools / parameters per operation ---
- const sortByOp = new Map<string, number>();
+ // An existing operation keeps what it has: a step with the same name, a
+ // tool with the same item and a parameter with the same key are skipped.
+ const children = await loadOperationChildren(
+ trx,
+ companyId,
+ [...new Set(opPlan.existingIdByOpNo.values())],
+ bucket
+ );
+
+ const sortByOp = new Map(children.maxStepSortOrder);
for (const e of bucket.step) {
const r = e.record;
- const operationId = opIdByNo.get(text(r.opNo))!;
+ const opNo = text(r.opNo);
+ const operationId = opIdByNo.get(opNo)!;
+ const name = text(r.stepName);
+ if (children.stepNames.get(operationId)?.has(name)) {
+ skipped.push({
+ row: rowOf(e.index),
+ reason: `Op ${opNo} on ${partLabel} already has a step named "${name}"; skipped`
+ });
+ continue;
+ }
const sortOrder = (sortByOp.get(operationId) ?? 0) + 1;
sortByOp.set(operationId, sortOrder);
const stepType = text(r.stepType) || "Task";
@@ -3866,7 +4167,7 @@ async function writeGroup(
.values([
{
operationId,
- name: text(r.stepName),
+ name,
description: plainTextToTiptap(text(r.stepDescription)),
type: stepType,
required: bool(r.stepRequired),
@@ -3890,11 +4191,13 @@ async function writeGroup(
} as never
])
.execute();
+ wroteAny = true;
}
for (const e of bucket.tool) {
const r = e.record;
- const operationId = opIdByNo.get(text(r.opNo))!;
+ const opNo = text(r.opNo);
+ const operationId = opIdByNo.get(opNo)!;
const tool = await resolveItem(
trx,
companyId,
@@ -3902,6 +4205,13 @@ async function writeGroup(
text(r.toolRevision),
ctx.itemMap
);
+ if (children.toolIds.get(operationId)?.has(tool.id)) {
+ skipped.push({
+ row: rowOf(e.index),
+ reason: `Op ${opNo} on ${partLabel} already has tool ${text(r.toolId)} rev ${text(r.toolRevision) || "0"}; skipped`
+ });
+ continue;
+ }
await trx
.insertInto("methodOperationTool")
.values([
@@ -3915,17 +4225,27 @@ async function writeGroup(
} as never
])
.execute();
+ wroteAny = true;
}
for (const e of bucket.param) {
const r = e.record;
- const operationId = opIdByNo.get(text(r.opNo))!;
+ const opNo = text(r.opNo);
+ const operationId = opIdByNo.get(opNo)!;
+ const paramKey = text(r.paramKey);
+ if (children.paramKeys.get(operationId)?.has(paramKey)) {
+ skipped.push({
+ row: rowOf(e.index),
+ reason: `Op ${opNo} on ${partLabel} already has parameter "${paramKey}"; skipped`
+ });
+ continue;
+ }
await trx
.insertInto("methodOperationParameter")
.values([
{
operationId,
- key: text(r.paramKey),
+ key: paramKey,
value: text(r.paramValue),
companyId,
createdBy: userId,
@@ -3933,10 +4253,12 @@ async function writeGroup(
} as never
])
.execute();
+ wroteAny = true;
}
}
- return { filledAny, skippedExisting };
+ if (issues.length > 0) throw new MethodImportRefused(issues);
+ return { wroteAny, skipped };
});
}
@@ -3944,6 +4266,19 @@ async function writeGroup(
// transaction-scoped resolution helpers
// ---------------------------------------------------------------------------
+// The row a version's refusal is reported on: the first of its rows.
+function firstIndexOf(bucket: VersionBucket): number {
+ return Math.min(
+ ...[
+ ...bucket.bom,
+ ...bucket.bop,
+ ...bucket.step,
+ ...bucket.tool,
+ ...bucket.param
+ ].map((e) => e.index)
+ );
+}
+
// Resolve an item id by readableId + revision. Falls back to a DB lookup for a
// part created earlier in this same file (not present in the prefetched map).
async function resolveItem(
@@ -3959,7 +4294,13 @@ async function resolveItem(
const row = await trx
.selectFrom("item")
- .select(["id", "type", "defaultMethodType", "sourcingType"])
+ .select([
+ "id",
+ "type",
+ "defaultMethodType",
+ "sourcingType",
+ "revisionStatus"
+ ])
.where("companyId", "=", companyId)
.where("readableId", "=", readableId)
.where("revision", "=", revision || "0")
@@ -3972,7 +4313,8 @@ async function resolveItem(
id: row.id,
type: row.type,
defaultMethodType: row.defaultMethodType ?? null,
- sourcingType: row.sourcingType ?? null
+ sourcingType: row.sourcingType ?? null,
+ revisionStatus: row.revisionStatus ?? null
};
itemMap.set(k, info);
return info;
@@ -4002,55 +4344,37 @@ async function currentMakeMethodId(
return rows[0]!.id;
}
-// Resolve the target make method for a version. Blank → the part's current
-// method (the trigger-created Draft v1 for a new part). Explicit → find-or-create
-// that version as a Draft; never auto-activate.
-async function ensureMakeMethod(
+// 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>,
- itemId: string,
- version: string,
companyId: string,
- userId: string
-): Promise<string> {
- if (!version.trim()) {
- const current = await currentMakeMethodId(trx, itemId, companyId);
- if (current) return current;
- // No make method yet (e.g. a non-trigger item type) — create Draft v1.
- const inserted = await trx
- .insertInto("makeMethod")
- .values([
- {
- itemId,
- companyId,
- version: 1,
- status: "Draft",
- createdBy: userId,
- createdAt: datetime.timestamp()
- } as never
- ])
- .returning(["id"])
- .execute();
- return inserted[0]!.id;
- }
-
- const versionNumber = num(version) ?? 1;
- const existing = await trx
- .selectFrom("makeMethod")
- .select(["id"])
- .where("itemId", "=", itemId)
+ changeOrderId: string
+): Promise<string | null> {
+ const notice = await trx
+ .selectFrom("changeOrder")
+ .select(["status"])
+ .where("id", "=", changeOrderId)
.where("companyId", "=", companyId)
- .where("version", "=", versionNumber)
- .limit(1)
.executeTakeFirst();
- if (existing) return existing.id;
+ return getChangeNoticeEngineeringLock(changeOrderId, notice?.status ?? null);
+}
+// A new Draft version of the part's make method; never auto-activated.
+async function insertDraftMakeMethod(
+ trx: Transaction<KyselyDatabase>,
+ itemId: string,
+ version: number,
+ companyId: string,
+ userId: string
+): Promise<string> {
const inserted = await trx
.insertInto("makeMethod")
.values([
{
itemId,
companyId,
- version: versionNumber,
+ version,
status: "Draft",
createdBy: userId,
createdAt: datetime.timestamp()
@@ -4061,6 +4385,77 @@ async function ensureMakeMethod(
return inserted[0]!.id;
}
+type OperationChildren = {
+ stepNames: Map<string, Set<string>>;
+ maxStepSortOrder: Map<string, number>;
+ toolIds: Map<string, Set<string>>;
+ paramKeys: Map<string, Set<string>>;
+};
+
+// What the existing operations a file's rows attach to already hold. Only the
+// child tables the file has rows for are read.
+async function loadOperationChildren(
+ trx: Transaction<KyselyDatabase>,
+ companyId: string,
+ operationIds: string[],
+ bucket: VersionBucket
+): Promise<OperationChildren> {
+ const children: OperationChildren = {
+ stepNames: new Map(),
+ maxStepSortOrder: new Map(),
+ toolIds: new Map(),
+ paramKeys: new Map()
+ };
+ if (operationIds.length === 0) return children;
+
+ const add = (map: Map<string, Set<string>>, id: string, value: string) => {
+ const values = map.get(id) ?? new Set<string>();
+ values.add(value);
+ map.set(id, values);
+ };
+
+ if (bucket.step.length > 0) {
+ const steps = await trx
+ .selectFrom("methodOperationStep")
+ .select(["operationId", "name", "sortOrder"])
+ .where("operationId", "in", operationIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ for (const step of steps) {
+ add(children.stepNames, step.operationId, step.name.trim());
+ children.maxStepSortOrder.set(
+ step.operationId,
+ Math.max(
+ children.maxStepSortOrder.get(step.operationId) ?? 0,
+ Number(step.sortOrder)
+ )
+ );
+ }
+ }
+ if (bucket.tool.length > 0) {
+ const tools = await trx
+ .selectFrom("methodOperationTool")
+ .select(["operationId", "toolId"])
+ .where("operationId", "in", operationIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ for (const tool of tools)
+ add(children.toolIds, tool.operationId, tool.toolId);
+ }
+ if (bucket.param.length > 0) {
+ const params = await trx
+ .selectFrom("methodOperationParameter")
+ .select(["operationId", "key"])
+ .where("operationId", "in", operationIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ for (const param of params) {
+ add(children.paramKeys, param.operationId, param.key.trim());
+ }
+ }
+ return children;
+}
+
// Seed storageUnitIds from the component's pickMethod default bins (mirrors
// resolveMethodMaterialStorageUnitIds in items.service.ts).
async function seedStorageUnitIds(
diff --git a/apps/erp/test/database/method-import-append.test.ts b/apps/erp/test/database/method-import-append.test.ts
new file mode 100644
index 0000000000..841cebae9e
--- /dev/null
+++ b/apps/erp/test/database/method-import-append.test.ts
@@ -0,0 +1,461 @@
+// 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.
+
+// The method import against a real database: it appends BOM lines and
+// operations to a make method that already has them, skips what is already
+// there, and refuses the versions the BOM and BOP editors refuse. Skips
+// without a local database.
+
+import { sql } from "kysely";
+import { afterEach, describe, expect } from "vitest";
+import { LOCKED_REVISION_MESSAGE } from "../../app/modules/items/items.service";
+import { importMethods } from "../../app/modules/shared/shared.service";
+import {
+ connectLocalTestDatabase,
+ databaseTest
+} from "./fixtures/local-database";
+
+const USER = "system";
+
+type Fixture = Awaited<ReturnType<typeof fixture>>;
+
+/**
+ * A scratch company with an assembly `ASSY` (Draft v1 from the item
+ * interceptor) whose BOM has `COMP-1` and whose BOP has operation 1 (Saw) with
+ * the step "Measure". `COMP-2`, `COMP-3` and the process `Machining` exist.
+ */
+async function fixture() {
+ const db = await connectLocalTestDatabase();
+ const prefix = `mimp-${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;
+ const companyId = `${prefix}-company`;
+ const groupId = `${prefix}-group`;
+ const itemId = (readableId: string) => `${prefix}-${readableId}`;
+ const processId = `${prefix}-machining`;
+
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx
+ .insertInto("companyGroup")
+ .values({ id: groupId, name: prefix, createdBy: USER })
+ .execute();
+ await trx
+ .insertInto("company")
+ .values({
+ id: companyId,
+ name: prefix,
+ companyGroupId: groupId,
+ baseCurrencyCode: "USD",
+ timezone: "America/New_York"
+ })
+ .execute();
+ await trx
+ .insertInto("companySettings")
+ .values({ id: companyId })
+ .onConflict((oc) => oc.column("id").doNothing())
+ .execute();
+ await trx
+ .insertInto("unitOfMeasure")
+ .values({ code: "EA", name: "Each", companyId, createdBy: USER })
+ .execute();
+ await trx
+ .insertInto("process")
+ .values({
+ id: processId,
+ name: "Machining",
+ defaultStandardFactor: "Minutes/Piece",
+ companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("item")
+ .values(
+ ["ASSY", "COMP-1", "COMP-2", "COMP-3"].map((readableId) => ({
+ id: itemId(readableId),
+ readableId,
+ name: readableId,
+ type: "Part" as const,
+ itemTrackingType: "Inventory" as const,
+ unitOfMeasureCode: "EA",
+ companyId,
+ createdBy: USER
+ }))
+ )
+ .execute();
+ });
+
+ const makeMethodId = (
+ await db
+ .selectFrom("makeMethod")
+ .select("id")
+ .where("itemId", "=", itemId("ASSY"))
+ .where("companyId", "=", companyId)
+ .executeTakeFirstOrThrow()
+ ).id;
+
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx
+ .insertInto("methodMaterial")
+ .values({
+ makeMethodId,
+ itemId: itemId("COMP-1"),
+ itemType: "Part" as const,
+ quantity: 1,
+ unitOfMeasureCode: "EA",
+ order: 1,
+ companyId,
+ createdBy: USER
+ })
+ .execute();
+ const operation = await trx
+ .insertInto("methodOperation")
+ .values({
+ makeMethodId,
+ order: 1,
+ processId,
+ description: "Saw",
+ setupUnit: "Total Minutes",
+ laborUnit: "Minutes/Piece",
+ machineUnit: "Minutes/Piece",
+ companyId,
+ createdBy: USER
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("methodOperationStep")
+ .values({
+ operationId: operation.id,
+ name: "Measure",
+ type: "Task",
+ sortOrder: 1,
+ companyId,
+ createdBy: USER
+ })
+ .execute();
+ });
+
+ return {
+ db,
+ companyId,
+ makeMethodId,
+ assyId: itemId("ASSY"),
+ async run(
+ table: "bom" | "operations" | "partWithMethod",
+ mappedRecords: Record<string, string>[]
+ ) {
+ const summary = {
+ inserted: 0,
+ updated: 0,
+ errors: [] as Array<{ row: number; reason: string }>,
+ skipped: [] as Array<{ row: number; reason: string }>
+ };
+ await importMethods(db, {
+ table,
+ mappedRecords,
+ companyId,
+ userId: USER,
+ summary
+ });
+ return summary;
+ },
+ async materials(methodId = makeMethodId) {
+ const rows = await db
+ .selectFrom("methodMaterial")
+ .innerJoin("item", "item.id", "methodMaterial.itemId")
+ .select([
+ "item.readableId",
+ "methodMaterial.quantity",
+ "methodMaterial.order"
+ ])
+ .where("methodMaterial.makeMethodId", "=", methodId)
+ .where("methodMaterial.companyId", "=", companyId)
+ .orderBy("methodMaterial.order")
+ .execute();
+ return rows.map((r) => ({
+ readableId: r.readableId,
+ quantity: Number(r.quantity),
+ order: Number(r.order)
+ }));
+ },
+ async operations() {
+ const rows = await db
+ .selectFrom("methodOperation")
+ .select(["order", "description"])
+ .where("makeMethodId", "=", makeMethodId)
+ .where("companyId", "=", companyId)
+ .orderBy("order")
+ .execute();
+ return rows.map((r) => ({
+ order: Number(r.order),
+ description: r.description
+ }));
+ },
+ async steps() {
+ const rows = await db
+ .selectFrom("methodOperationStep")
+ .innerJoin(
+ "methodOperation",
+ "methodOperation.id",
+ "methodOperationStep.operationId"
+ )
+ .select([
+ "methodOperation.order as operationOrder",
+ "methodOperationStep.name",
+ "methodOperationStep.sortOrder"
+ ])
+ .where("methodOperation.makeMethodId", "=", makeMethodId)
+ .where("methodOperationStep.companyId", "=", companyId)
+ .orderBy("methodOperation.order")
+ .orderBy("methodOperationStep.sortOrder")
+ .execute();
+ return rows.map((r) => ({
+ operationOrder: Number(r.operationOrder),
+ name: r.name,
+ sortOrder: Number(r.sortOrder)
+ }));
+ },
+ async setMethodStatus(status: "Draft" | "Active") {
+ await db
+ .updateTable("makeMethod")
+ .set({ status })
+ .where("id", "=", makeMethodId)
+ .where("companyId", "=", companyId)
+ .execute();
+ },
+ async setRevisionStatus(revisionStatus: "Design" | "Production") {
+ await db
+ .updateTable("item")
+ .set({ revisionStatus })
+ .where("id", "=", itemId("ASSY"))
+ .where("companyId", "=", companyId)
+ .execute();
+ },
+ async setReleaseControl(plmReleaseControl: "enforce" | "warn") {
+ await db
+ .updateTable("companySettings")
+ .set({ plmReleaseControl })
+ .where("id", "=", companyId)
+ .execute();
+ },
+ async cleanup() {
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx.deleteFrom("company").where("id", "=", companyId).execute();
+ await trx
+ .deleteFrom("companyGroup")
+ .where("id", "=", groupId)
+ .execute();
+ await sql`DROP TABLE IF EXISTS ${sql.id(`searchIndex_${companyId}`)}`.execute(
+ trx
+ );
+ await sql`DROP TABLE IF EXISTS ${sql.id(`auditLog_${companyId}`)}`.execute(
+ trx
+ );
+ });
+ await db.destroy();
+ }
+ };
+}
+
+const bop = (opNo: string, extra: Record<string, string> = {}) => ({
+ rowType: "BOP",
+ parentId: "ASSY",
+ opNo,
+ process: "Machining",
+ setupUnit: "Total Minutes",
+ laborUnit: "Minutes/Piece",
+ machineUnit: "Minutes/Piece",
+ ...extra
+});
+
+const step = (opNo: string, stepName: string) => ({
+ rowType: "STEP",
+ parentId: "ASSY",
+ opNo,
+ stepName
+});
+
+describe("method import onto an existing method", () => {
+ let f: Fixture | undefined;
+ afterEach(async () => {
+ await f?.cleanup();
+ f = undefined;
+ });
+
+ databaseTest(
+ "appends BOM lines after the existing ones and skips materials already on it",
+ async () => {
+ f = await fixture();
+ const summary = await f.run("bom", [
+ { parentId: "ASSY", componentId: "COMP-1", quantity: "5" },
+ { parentId: "ASSY", componentId: "COMP-2", quantity: "2" },
+ { parentId: "ASSY", componentId: "COMP-3", quantity: "3" }
+ ]);
+
+ expect(summary.errors).toEqual([]);
+ expect(summary.updated).toBe(1);
+ expect(summary.skipped).toEqual([
+ {
+ row: 0,
+ reason:
+ "Material COMP-1 rev 0 is already on the BOM of ASSY rev 0; skipped"
+ }
+ ]);
+ expect(await f.materials()).toEqual([
+ { readableId: "COMP-1", quantity: 1, order: 1 },
+ { readableId: "COMP-2", quantity: 2, order: 2 },
+ { readableId: "COMP-3", quantity: 3, order: 3 }
+ ]);
+ }
+ );
+
+ databaseTest(
+ "adds operations to a part with a BOM and attaches steps to an existing operation",
+ async () => {
+ f = await fixture();
+ const summary = await f.run("operations", [
+ bop("10", { operationDescription: "Mill" }),
+ step("10", "Deburr"),
+ step("1", "Measure"),
+ step("1", "Clean")
+ ]);
+
+ expect(summary.errors).toEqual([]);
+ expect(summary.updated).toBe(1);
+ expect(summary.skipped).toEqual([
+ {
+ row: 2,
+ reason: 'Op 1 on ASSY rev 0 already has a step named "Measure"; skipped'
+ }
+ ]);
+ expect(await f.operations()).toEqual([
+ { order: 1, description: "Saw" },
+ { order: 10, description: "Mill" }
+ ]);
+ expect(await f.steps()).toEqual([
+ { operationOrder: 1, name: "Measure", sortOrder: 1 },
+ { operationOrder: 1, name: "Clean", sortOrder: 2 },
+ { operationOrder: 10, name: "Deburr", sortOrder: 1 }
+ ]);
+ expect(await f.materials()).toHaveLength(1);
+ }
+ );
+
+ databaseTest("writes nothing when the same file runs again", async () => {
+ f = await fixture();
+ const rows: Record<string, string>[] = [
+ { rowType: "BOM", parentId: "ASSY", componentId: "COMP-2", quantity: "2" },
+ bop("10"),
+ step("10", "Deburr"),
+ {
+ rowType: "PARAM",
+ parentId: "ASSY",
+ opNo: "10",
+ paramKey: "Feed",
+ paramValue: "0.2"
+ }
+ ];
+ const first = await f.run("partWithMethod", rows);
+ expect(first.errors).toEqual([]);
+ expect(first.updated).toBe(1);
+
+ const second = await f.run("partWithMethod", rows);
+ expect(second.errors).toEqual([]);
+ expect(second.updated).toBe(0);
+ expect(second.skipped.map((s) => s.row)).toEqual([0, 1, 2, 3]);
+ expect(await f.materials()).toHaveLength(2);
+ expect(await f.operations()).toHaveLength(2);
+ expect(await f.steps()).toHaveLength(2);
+ });
+
+ databaseTest(
+ "refuses an Active version and writes into an explicit new Draft",
+ async () => {
+ f = await fixture();
+ await f.setMethodStatus("Active");
+
+ const refused = await f.run("bom", [
+ { parentId: "ASSY", componentId: "COMP-2", quantity: "1" }
+ ]);
+ expect(refused.updated).toBe(0);
+ expect(refused.errors).toEqual([
+ {
+ row: 0,
+ reason:
+ "Part ASSY rev 0: make method version 1 is Active, and only a Draft version can change. Create a new version, then set Make Method Version to it"
+ }
+ ]);
+ expect(await f.materials()).toHaveLength(1);
+
+ const accepted = await f.run("bom", [
+ {
+ parentId: "ASSY",
+ makeMethodVersion: "2",
+ componentId: "COMP-2",
+ quantity: "1"
+ }
+ ]);
+ expect(accepted.errors).toEqual([]);
+ const draft = await f.db
+ .selectFrom("makeMethod")
+ .select(["id", "status"])
+ .where("itemId", "=", f.assyId)
+ .where("companyId", "=", f.companyId)
+ .where("version", "=", 2)
+ .executeTakeFirstOrThrow();
+ expect(draft.status).toBe("Draft");
+ expect(await f.materials(draft.id)).toEqual([
+ { readableId: "COMP-2", quantity: 1, order: 1 }
+ ]);
+ }
+ );
+
+ databaseTest(
+ "follows release control on a released revision",
+ async () => {
+ f = await fixture();
+ await f.setRevisionStatus("Production");
+ const rows = [{ parentId: "ASSY", componentId: "COMP-2", quantity: "1" }];
+
+ const refused = await f.run("bom", rows);
+ expect(refused.errors).toEqual([
+ { row: 0, reason: `Part ASSY rev 0: ${LOCKED_REVISION_MESSAGE}` }
+ ]);
+ expect(await f.materials()).toHaveLength(1);
+
+ await f.setReleaseControl("warn");
+ const accepted = await f.run("bom", rows);
+ expect(accepted.errors).toEqual([]);
+ expect(await f.materials()).toHaveLength(2);
+ }
+ );
+
+ databaseTest(
+ "rolls back the whole part when one version is refused",
+ async () => {
+ f = await fixture();
+ await f.setMethodStatus("Active");
+ const summary = await f.run("bom", [
+ {
+ parentId: "ASSY",
+ makeMethodVersion: "2",
+ componentId: "COMP-2",
+ quantity: "1"
+ },
+ { parentId: "ASSY", componentId: "COMP-3", quantity: "1" }
+ ]);
+ expect(summary.errors).toHaveLength(1);
+ expect(summary.updated).toBe(0);
+ const versions = await f.db
+ .selectFrom("makeMethod")
+ .select("version")
+ .where("companyId", "=", f.companyId)
+ .where("itemId", "=", f.assyId)
+ .execute();
+ expect(versions.map((v) => Number(v.version))).toEqual([1]);
+ }
+ );
+});
diff --git a/docs/content/docs/reference/import-export.mdx b/docs/content/docs/reference/import-export.mdx
index f060416bce..7dffea6d83 100644
--- a/docs/content/docs/reference/import-export.mdx
+++ b/docs/content/docs/reference/import-export.mdx
@@ -36,7 +36,9 @@ Bulk import is available only for supported entities. Import each entity from th
<Field name="Inventory, Batch, and Serial Quantities">From **Inventory → Quantities**. Adds opening stock for items that already exist, one import per <Term id="item-tracking-type">tracking type</Term>. See [Opening stock](#opening-stock).</Field>
</FieldTable>
-Beyond these table buttons, the importer also understands three **method** formats used to load bills of materials and operations against parts: a focused BOM file, a focused Operations file, and a combined part-with-method file that creates parts and their full BOM and routing together. These are richer, row-typed CSVs (each row is tagged `PART`, `BOM`, `BOP`, `STEP`, `TOOL`, or `PARAM`) driven from the method-building UI rather than a plain list screen.
+The **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.
<Callout type="warn" title="Fixed assets and BOM components aren't importable here">
The models list a `fixedAsset` import shape, but the import function's own table list omits it, so a fixed-asset CSV is rejected. Individual BOM material lines (`methodMaterial`) are likewise not wired up. Import the entities above; create assets and one-off BOM lines in the app.