Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(items): method import review fixes: lock, warn mode, versions, approvals

naveenkash3c1a6a92c02a
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 36c23ae28b..3fd6baca1a 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -4039,3 +4039,13 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Rule:** When a posting must ignore a line, filter it where every per-line collection is built, not only in the loop that writes the ledger. List every map or array derived from the lines and check each. Pin the skipped line's absence in a test: assert the side effects did not happen, not only that the ledger row is missing.
**Applies to:** `postReceipt` / `postShipment` and every posting in `inventory.service.ts` that builds update maps before its write loop.
+
+## An import wizard enum Default fills every blank cell before the server sees it
+
+**Context:** The method import (#1977) was made to fill a blank BOM Unit of Measure with the material's own unit and a blank Operation Type with the process's type, as the BOM and BOP editors do.
+
+**Problem:** `fieldMappings` in `imports.models.ts` preset `default: "EA"` and `default: "Process"`. The wizard writes an enum's Default into every blank and unmapped cell before the import runs, so the server never saw a blank and its fallbacks never ran. The server-side change and its tests looked right; only a run through the wizard showed every line still in EA.
+
+**Rule:** When the server derives a value for a blank cell, remove that field's `default` from `fieldMappings`, and pin the absence in a test (`shared.method-import-append.test.ts` → "presets no BOM unit and no operation type"). A wizard Default and a server fallback cannot both apply.
+
+**Applies to:** every table in `fieldMappings` (`apps/erp/app/modules/shared/imports.models.ts`) whose importer has a fallback for a blank cell.
diff --git a/.claude/rules/csv-import-system.md b/.claude/rules/csv-import-system.md
index ca215fabff..d1e3fec363 100644
--- a/.claude/rules/csv-import-system.md
+++ b/.claude/rules/csv-import-system.md
@@ -260,13 +260,19 @@ 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.
+ explicit one targets that version, created as a Draft when missing. An
+ explicit version must be above 0 with at most 2 decimals
+ (`methodVersionIssue`): `makeMethod.version` is `NUMERIC(10, 2)`, so Postgres
+ would store 1.555 as 1.56 and a re-run could not find it again.
+- **Locks** (`methodImportLock`, which returns the editors' `LockCheck`), the
+ same rules as the BOM and BOP editors: the target must be a Draft; a Draft
+ owned by a change notice follows the notice's engineering lock; 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. Under release control "warn" the
+ import writes, as the editors do, and returns the lock's message in
+ `warnings` for each part it wrote rows into; `ImportResultsModal` shows them
+ in a warning alert.
- **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 is the operation's `order`, so it must be a
@@ -307,23 +313,27 @@ continue.
Tool, with quantity above 0; times, costs and lead time are 0 or more; a
Process operation needs setup, labor and machine units, an Assembly operation
setup and labor; step min and max are 0 or more, max at least min; a List
- step needs one non-blank option; a Make Method Version must be a positive
- number. An Inspection operation is refused, because
+ step needs one non-blank option; a Make Method Version must be above 0 with
+ at most 2 decimals. An Inspection operation is refused, because
`methodOperationValidator` requires an Inspection Plan and a CSV has no
column for one. Pinned by `method-import-guards.test.ts`.
- **Concurrency.** `writeGroup` locks the part's `item` row (`FOR NO KEY
UPDATE`, so rows that reference the item can still be written) before it
reads the versions, so two imports that create the same new version create
it once. It then locks the target `makeMethod` row
- (`FOR UPDATE`) before it reads the version's lines, so two imports of one
- file write each line once. The refusals read the status and change notice
- of the locked row, so a Draft an editor activates or links to a notice
+ (`FOR NO KEY UPDATE`) before it reads the version's lines, so two imports of
+ one file write each line once. Not `FOR UPDATE`: that also blocks the
+ `KEY SHARE` lock the `materialMakeMethodId` foreign key takes, so every BOM
+ line elsewhere pointing at this method would wait for the import. The
+ refusals read the status and change notice of the locked row, so a Draft an editor activates or links to a notice
while the import waits is refused. A version the import created for a
refused part rolls back with it.
- **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.
+ `getChangeNoticeEngineeringLocks` (`items.service.ts`) reads pending approvals
+ for every notice in one service-role request (`pendingApprovalDocumentIds`,
+ `@carbon/ee/approvals.server`), 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 parent
in the file (parts are written in order of first appearance); a `PART` row
does not write the Unique ID mapping; the Supplier Process column is unused;
@@ -348,8 +358,9 @@ every other field is a column mapping) and calls `importCsvFile` (`shared.server
3. Validates `columnMappings` against `importSchemas[table]` (required fields mapped).
4. Calls `importCsv(ctx, { table, filePath, columnMappings, enumMappings })`
(quote tables go through `importQuotes` instead).
-5. Returns `{ inserted, updated, skipped, errors }`; `ImportCSVModal` reads it from the
- result's `data`.
+5. Returns `{ inserted, updated, skipped, errors, added, warnings }` (`added` is null
+ and `warnings` empty for all but the method imports); `ImportCSVModal` reads it
+ from the result's `data`.
The lookup values an import creates on the fly (`api+/csv+/create-lookup.tsx`) are
`createImportLookups` (`shared.server.ts`), gated on `create` of the lookup's module.
diff --git a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
index 5c6e2d7792..ec6c05ef9e 100644
--- a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
+++ b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
@@ -41,7 +41,8 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {
const fetcher = useAction<typeof action>({
onSuccess: (result) => {
if (!("data" in result) || !result.data) return;
- const { inserted, updated, errors, skipped, added } = result.data;
+ const { inserted, updated, errors, skipped, added, warnings } =
+ result.data;
// The results modal renders next (see the early return below); just
// surface a quick toast summary here.
if (added) {
@@ -52,8 +53,11 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {
skipped: skipped.length,
added
});
- if (errors.length > 0 || skipped.length > 0) toast.info(message);
- else toast.success(message);
+ if (errors.length > 0 || skipped.length > 0 || warnings.length > 0) {
+ toast.info(message);
+ } else {
+ toast.success(message);
+ }
} else if (errors.length > 0) {
toast.info(
`Imported ${inserted}, updated ${updated} — ${errors.length} row(s) need fixing.`
@@ -128,6 +132,7 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {
errors={imported.errors}
skipped={imported.skipped}
added={imported.added}
+ warnings={imported.warnings}
columns={fileColumns}
onClose={onClose}
/>
@@ -209,7 +214,8 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {
);
};
-// Method imports: inserted and updated count parts, the rest count rows.
+// Method imports: inserted and updated count parts, the rest count rows. The
+// same sentences as the results dialog's MethodImportCounts.
function methodImportMessage(counts: {
inserted: number;
updated: number;
@@ -218,34 +224,26 @@ function methodImportMessage(counts: {
added: MethodRowsAdded;
}) {
const { added } = counts;
+ const count = (n: number, one: string, other: string) =>
+ `${n} ${n === 1 ? one : other}`;
const parts = [
- counts.inserted > 0 ? `created ${counts.inserted} part(s)` : null,
- counts.updated > 0 ? `updated ${counts.updated} part(s)` : null
+ counts.inserted > 0 &&
+ count(counts.inserted, "part created", "parts created"),
+ counts.updated > 0 && count(counts.updated, "part updated", "parts updated")
+ ].filter(Boolean);
+ const rows = [
+ added.materials > 0 && count(added.materials, "BOM line", "BOM lines"),
+ added.operations > 0 && count(added.operations, "operation", "operations"),
+ added.steps > 0 && count(added.steps, "step", "steps"),
+ added.tools > 0 && count(added.tools, "tool", "tools"),
+ added.parameters > 0 && count(added.parameters, "parameter", "parameters")
+ ].filter(Boolean);
+ return [
+ parts.length > 0 ? `${parts.join(", ")}.` : "No parts changed.",
+ rows.length > 0 && `Added: ${rows.join(", ")}.`,
+ (counts.errors > 0 || counts.skipped > 0) &&
+ `${count(counts.errors, "row needs fixing", "rows need fixing")}, ${count(counts.skipped, "row skipped", "rows skipped")}.`
]
.filter(Boolean)
- .join(", ");
- const rows = (
- [
- [added.materials, "BOM line"],
- [added.operations, "operation"],
- [added.steps, "step"],
- [added.tools, "tool"],
- [added.parameters, "parameter"]
- ] as const
- )
- .filter(([count]) => count > 0)
- .map(([count, label]) => `${count} ${label}(s)`)
- .join(", ");
- const outcome =
- counts.errors > 0
- ? ` — ${counts.errors} row(s) need fixing${
- counts.skipped > 0 ? `, ${counts.skipped} skipped` : ""
- }`
- : counts.skipped > 0
- ? `, skipped ${counts.skipped} row(s)`
- : "";
- const message = rows
- ? `${parts}: added ${rows}${outcome}.`
- : `${parts || "no parts changed"}${outcome}.`;
- return message.charAt(0).toUpperCase() + message.slice(1);
+ .join(" ");
}
diff --git a/apps/erp/app/components/ImportCSVModal/ImportResultsModal.tsx b/apps/erp/app/components/ImportCSVModal/ImportResultsModal.tsx
index f52f790e6f..28e610ea1c 100644
--- a/apps/erp/app/components/ImportCSVModal/ImportResultsModal.tsx
+++ b/apps/erp/app/components/ImportCSVModal/ImportResultsModal.tsx
@@ -5,6 +5,9 @@
import { downloadText } from "@carbon/files";
import { CSV_CONTENT_TYPE, encodeCsvTable } from "@carbon/files/csv";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Button,
Count,
cn,
@@ -21,7 +24,13 @@ import {
} from "@carbon/react";
import { Plural, Trans, useLingui } from "@lingui/react/macro";
import { Fragment, type ReactNode, useState } from "react";
-import { LuCircleCheck, LuCircleX, LuDownload, LuInfo } from "react-icons/lu";
+import {
+ LuCircleCheck,
+ LuCircleX,
+ LuDownload,
+ LuInfo,
+ LuTriangleAlert
+} from "react-icons/lu";
import type { MethodRowsAdded } from "~/modules/shared/types";
// A row the importer did not insert/update. `values` holds the original CSV cells
@@ -43,6 +52,8 @@ type ImportResultsModalProps = {
skipped: RowIssue[];
// Method imports only: inserted and updated count parts there.
added?: MethodRowsAdded | null;
+ // Method imports only: parts written under a release-control warning.
+ warnings?: string[];
columns: string[];
onClose: () => void;
};
@@ -56,6 +67,7 @@ export const ImportResultsModal = ({
errors,
skipped,
added,
+ warnings = [],
columns,
onClose
}: ImportResultsModalProps) => {
@@ -120,6 +132,21 @@ export const ImportResultsModal = ({
</ModalDescription>
</ModalHeader>
<ModalBody className="min-w-0">
+ {warnings.length > 0 && (
+ <Alert variant="warning" className="mb-4">
+ <LuTriangleAlert />
+ <AlertTitle>
+ <Trans>Written with a warning</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <ul className="list-disc pl-4">
+ {warnings.map((warning) => (
+ <li key={warning}>{warning}</li>
+ ))}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ )}
{allClean ? (
<div className="flex flex-col items-center justify-center gap-2 py-10 text-center">
<LuCircleCheck className="h-8 w-8 text-emerald-500" />
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 857e9c7056..4ccf5f7f93 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -25,7 +25,10 @@ import type {
KyselyTx
} from "@carbon/database/client";
import { insertRows, many, maybeSingle } from "@carbon/database/rows";
-import { hasPendingApproval } from "@carbon/ee/approvals.server";
+import {
+ hasPendingApproval,
+ pendingApprovalDocumentIds
+} from "@carbon/ee/approvals.server";
import {
isUnsafeStoragePath,
storage,
@@ -9445,24 +9448,58 @@ 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.
-export async function getChangeNoticeEngineeringLock(
+async function getChangeNoticeEngineeringLock(
changeNoticeId: string,
status: string | null | undefined
): Promise<string | null> {
+ return engineeringLockMessage(
+ status,
+ needsApprovalLookup(status) &&
+ (await hasPendingApproval(
+ getCarbonServiceRole(),
+ "changeOrder",
+ changeNoticeId
+ ))
+ );
+}
+
+/**
+ * getChangeNoticeEngineeringLock for several notices, with one approval
+ * lookup for all of them: notice id → why it is locked, or null.
+ */
+export async function getChangeNoticeEngineeringLocks(
+ companyId: string,
+ notices: Array<{ id: string; status: string | null }>
+): Promise<Map<string, string | null>> {
+ const awaitingApproval = await pendingApprovalDocumentIds(
+ getCarbonServiceRole(),
+ {
+ documentType: "changeOrder",
+ documentIds: notices
+ .filter((notice) => needsApprovalLookup(notice.status))
+ .map((notice) => notice.id),
+ companyId
+ }
+ );
+ return new Map(
+ notices.map((notice) => [
+ notice.id,
+ engineeringLockMessage(notice.status, awaitingApproval.has(notice.id))
+ ])
+ );
+}
+
+const needsApprovalLookup = (status: string | null | undefined) =>
+ status === "Engineering Complete";
+
+function engineeringLockMessage(
+ status: string | null | undefined,
+ awaitingApproval: boolean
+): string | null {
if (!canEditChangeNoticeEngineering(status)) {
return changeNoticeLockedMessage(status);
}
- if (
- status === "Engineering Complete" &&
- (await hasPendingApproval(
- getCarbonServiceRole(),
- "changeOrder",
- changeNoticeId
- ))
- ) {
- return changeNoticeAwaitingApprovalMessage;
- }
- return null;
+ return awaitingApproval ? changeNoticeAwaitingApprovalMessage : null;
}
// One status read + predicate. Mutation routes call this before writing; the
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
index 328745c0c8..1fbd17066e 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,7 +10,8 @@ import { describe, expect, it } from "vitest";
import { LOCKED_REVISION_MESSAGE } from "~/modules/items/items.service";
import { fieldMappings } from "./imports.models";
import {
- methodImportRefusal,
+ methodImportLock,
+ methodVersionIssue,
opKey,
pickMethodImportTarget,
planMaterialAppend,
@@ -77,7 +78,25 @@ describe("pickMethodImportTarget", () => {
});
});
-describe("methodImportRefusal", () => {
+describe("methodVersionIssue", () => {
+ it("accepts a blank version and numbers above 0 with up to 2 decimals", () => {
+ for (const version of ["", " ", "1", "2", "1.5", "1.25", "1.50", "1.000"]) {
+ expect(methodVersionIssue(version)).toBeNull();
+ }
+ });
+
+ // makeMethod.version is NUMERIC(10, 2): 1.555 is stored as 1.56, and a
+ // re-run of the same file would then create 1.555 again and collide.
+ it("refuses what the version column cannot keep as written", () => {
+ for (const version of ["abc", "0", "-1", "1.555", "1e1", "1,5"]) {
+ expect(methodVersionIssue(version)).toBe(
+ `Make Method Version "${version}" must be a number above 0 with at most 2 decimals`
+ );
+ }
+ });
+});
+
+describe("methodImportLock", () => {
const base = {
status: "Draft",
version: 2,
@@ -87,33 +106,42 @@ describe("methodImportRefusal", () => {
};
it("allows a Draft on an unreleased revision", () => {
- expect(methodImportRefusal(base)).toBeNull();
+ expect(methodImportLock(base)).toEqual({ ok: true, warn: false });
});
it("refuses a version that is not a Draft", () => {
- expect(methodImportRefusal({ ...base, status: "Active" })).toMatch(
+ const active = methodImportLock({ ...base, status: "Active" });
+ expect(active.ok).toBe(false);
+ expect("message" in active && active.message).toMatch(
/^make method version 2 is Active, and only a Draft version can change/
);
- expect(methodImportRefusal({ ...base, status: "Archived" })).toMatch(
- /is Archived/
- );
+ const archived = methodImportLock({ ...base, status: "Archived" });
+ expect("message" in archived && archived.message).toMatch(/is Archived/);
});
it("refuses a Draft that a locked change notice holds", () => {
expect(
- methodImportRefusal({ ...base, changeNoticeLock: "Locked notice" })
- ).toBe("Locked notice");
+ methodImportLock({ ...base, changeNoticeLock: "Locked notice" })
+ ).toEqual({ ok: false, warn: false, message: "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();
+ expect(methodImportLock(released)).toEqual({
+ ok: false,
+ warn: false,
+ message: LOCKED_REVISION_MESSAGE
+ });
+ // The editors write under "warn" and show the message; so does the import.
+ expect(methodImportLock({ ...released, releaseControl: "warn" })).toEqual({
+ ok: true,
+ warn: true,
+ message: LOCKED_REVISION_MESSAGE
+ });
+ expect(methodImportLock({ ...released, releaseControl: "off" })).toEqual({
+ ok: true,
+ warn: false
+ });
});
});
diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.ts
index b320bca028..e20ac2ed44 100644
--- a/apps/erp/app/modules/shared/shared.server.ts
+++ b/apps/erp/app/modules/shared/shared.server.ts
@@ -288,6 +288,7 @@ export const importCsvFile = defineServiceFn({
errors?: RowIssue[];
skipped?: RowIssue[];
added?: MethodRowsAdded | null;
+ warnings?: string[];
};
return {
inserted: summary.inserted ?? 0,
@@ -295,7 +296,9 @@ export const importCsvFile = defineServiceFn({
errors: summary.errors ?? [],
skipped: summary.skipped ?? [],
// Method imports only: inserted and updated count parts there.
- added: summary.added ?? null
+ added: summary.added ?? null,
+ // Method imports only: parts written under a release-control warning.
+ warnings: summary.warnings ?? []
};
}
});
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index 6fd3060285..27db7d5d8b 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -169,8 +169,9 @@ import {
changeNoticeLockedMessage
} from "~/modules/items/items.models";
import {
- getChangeNoticeEngineeringLock,
+ getChangeNoticeEngineeringLocks,
getLockVerdict,
+ type LockCheck,
type ReleaseControl
} from "~/modules/items/items.service";
import { getMethod } from "~/modules/production/production.service";
@@ -2504,6 +2505,8 @@ type Summary = {
// Method imports only: the rows written, by kind. Inserted and updated
// count parts there, so the results name the rows separately.
added?: MethodRowsAdded;
+ // Method imports only: parts written under a release-control warning.
+ warnings?: string[];
};
// Company-scoped configuration lookups: small, flat, name-keyed tables a
@@ -3334,13 +3337,28 @@ const listValues = (s: string | undefined): string[] =>
.map((v) => v.trim())
.filter(Boolean);
-// A number cell that must hold 0 or more when it is filled in.
-const negative = (s: string | undefined) => {
+// A filled-in number cell that is not a number of 0 or more. Blank passes.
+const notZeroOrMore = (s: string | undefined) => {
if (text(s) === "") return false;
const n = num(s);
return n === undefined || n < 0;
};
+/**
+ * Why a Make Method Version cell is not a version number, or null. Blank
+ * passes. `makeMethod.version` keeps 2 decimals: Postgres would round 1.555
+ * to 1.56, and a re-run of the file could not find that version again.
+ */
+export function methodVersionIssue(version: string): string | null {
+ const value = version.trim();
+ if (!value) return null;
+ const n = num(value);
+ if (n === undefined || n <= 0 || !/^\d+(\.\d{1,2}0*)?$/.test(value)) {
+ return `Make Method Version "${value}" must be a number above 0 with at most 2 decimals`;
+ }
+ return null;
+}
+
function normalizeRowType(
raw: string | undefined,
table: string
@@ -3369,7 +3387,9 @@ export async function importMethods(
): Promise<void> {
const { table, mappedRecords, companyId, userId, summary } = args;
const added = noMethodRowsAdded();
+ const warnings: string[] = [];
summary.added = added;
+ summary.warnings = warnings;
// 1. classify + group by parent part ------------------------------------
const groups = new Map<string, Group>();
@@ -3621,12 +3641,11 @@ export async function importMethods(
// not something the user needs to fix, so a skip, not an error.
for (const s of result.skipped) summary.skipped.push(s);
addMethodRows(added, result.added);
+ warnings.push(...result.warnings);
// A part its PART row created counts as inserted; a part that existed
// counts as updated when the import wrote rows into its method.
if (result.createdPart) summary.inserted++;
- else if (Object.values(result.added).some((n) => n > 0)) {
- summary.updated++;
- }
+ else if (totalMethodRows(result.added) > 0) summary.updated++;
} catch (err) {
if (err instanceof MethodImportRefused) {
for (const issue of err.issues) summary.errors.push(issue);
@@ -3723,12 +3742,9 @@ function validateGroup(
}
for (const [version, bucket] of g.versions) {
- const versionNumber = num(version);
- if (text(version) && (versionNumber === undefined || versionNumber <= 0)) {
- errors.push({
- row: rowOf(firstIndexOf(bucket)),
- reason: `Make Method Version "${version}" is not a version number`
- });
+ const versionIssue = methodVersionIssue(version);
+ if (versionIssue) {
+ errors.push({ row: rowOf(firstIndexOf(bucket)), reason: versionIssue });
}
// An Op No is the operation's order, so it is a number and Op Nos compare
@@ -3833,7 +3849,7 @@ function validateGroup(
["operationUnitCost", "Unit Cost"],
["operationLeadTime", "Lead Time"]
] as const) {
- if (negative(e.record[field])) {
+ if (notZeroOrMore(e.record[field])) {
errors.push({
row: rowOf(e.index),
reason: `Op ${opNo}: ${label} must be a number of 0 or more`
@@ -3939,7 +3955,10 @@ function validateGroup(
}
const min = num(e.record.stepMinValue);
const max = num(e.record.stepMaxValue);
- if (negative(e.record.stepMinValue) || negative(e.record.stepMaxValue)) {
+ if (
+ notZeroOrMore(e.record.stepMinValue) ||
+ notZeroOrMore(e.record.stepMaxValue)
+ ) {
errors.push({
row: rowOf(e.index),
reason:
@@ -4028,38 +4047,43 @@ export function pickMethodImportTarget(
if (!version.trim()) {
const current = methods
.filter((m) => m.status !== "Archived")
- .sort((a, b) => Number(b.version) - Number(a.version))[0];
+ .sort((a, b) => b.version - 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);
+ const existing = methods.find((m) => 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.
+ * Whether the import may write into a make method version, with the same rules
+ * and verdict 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, which refuses, warns or allows.
*/
-export function methodImportRefusal(args: {
+export function methodImportLock(args: {
status: string;
version: number;
changeNoticeLock: string | null;
revisionStatus: string | null;
releaseControl: ReleaseControl;
-}): string | null {
+}): LockCheck {
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`;
+ return {
+ ok: false,
+ warn: false,
+ message: `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 { ok: false, warn: false, message: args.changeNoticeLock };
}
- if (args.changeNoticeLock) return args.changeNoticeLock;
- const verdict = getLockVerdict({
+ return getLockVerdict({
isLocked: args.revisionStatus === "Production",
releaseControl: args.releaseControl
});
- return verdict.ok ? null : verdict.message;
}
/**
@@ -4202,6 +4226,7 @@ async function writeGroup(
): Promise<{
added: MethodRowsAdded;
skipped: RowIssue[];
+ warnings: string[];
createdPart: boolean;
}> {
const { companyId, userId } = ctx;
@@ -4212,6 +4237,7 @@ async function writeGroup(
const added = noMethodRowsAdded();
const skipped: RowIssue[] = [];
const issues: RowIssue[] = [];
+ const warnings = new Set<string>();
// Resolve (or create) the parent item.
let parentItemId: string;
@@ -4333,16 +4359,17 @@ async function writeGroup(
// here, then reads what the first wrote and skips it. The refusal reads
// the locked row, so it sees an editor that activated the Draft or
// linked it to a change notice after the read above. A refused part
- // rolls back, with any version created for it.
+ // rolls back, with any version created for it. NO KEY UPDATE leaves
+ // BOM lines elsewhere that point at this method free to be written.
const locked = await trx
.selectFrom("makeMethod")
.select(["status", "changeOrderId"])
.where("id", "=", makeMethodId)
.where("companyId", "=", companyId)
- .forUpdate()
+ .forNoKeyUpdate()
.executeTakeFirst();
- const refusal = locked
- ? methodImportRefusal({
+ const lock: LockCheck = locked
+ ? methodImportLock({
status: locked.status,
version: methodVersion,
changeNoticeLock: locked.changeOrderId
@@ -4351,14 +4378,19 @@ async function writeGroup(
revisionStatus,
releaseControl: ctx.releaseControl
})
- : `make method version ${methodVersion} was deleted while the import ran. Run the import again`;
- if (refusal) {
+ : {
+ ok: false,
+ warn: false,
+ message: `make method version ${methodVersion} was deleted while the import ran. Run the import again`
+ };
+ if (!lock.ok) {
issues.push({
row: rowOf(firstIndexOf(bucket)),
- reason: `Part ${partLabel}: ${refusal}`
+ reason: `Part ${partLabel}: ${lock.message}`
});
continue;
}
+ const addedBefore = totalMethodRows(added);
const existingMaterials = await trx
.selectFrom("methodMaterial")
@@ -4663,10 +4695,16 @@ async function writeGroup(
.execute();
added.parameters += 1;
}
+
+ // The editors write into a released revision under release control
+ // "warn" and say so; the import says so for each part it wrote into.
+ if (lock.warn && totalMethodRows(added) > addedBefore) {
+ warnings.add(`Part ${partLabel}: ${lock.message}`);
+ }
}
if (issues.length > 0) throw new MethodImportRefused(issues);
- return { added, skipped, createdPart };
+ return { added, skipped, warnings: [...warnings], createdPart };
});
}
@@ -4771,23 +4809,16 @@ async function loadChangeNoticeLocks(
.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
- )
- )
- );
+ return getChangeNoticeEngineeringLocks(companyId, notices);
}
function noMethodRowsAdded(): MethodRowsAdded {
return { materials: 0, operations: 0, steps: 0, tools: 0, parameters: 0 };
}
+const totalMethodRows = (added: MethodRowsAdded) =>
+ Object.values(added).reduce((sum, n) => sum + n, 0);
+
function addMethodRows(total: MethodRowsAdded, part: MethodRowsAdded) {
for (const kind of Object.keys(total) as Array<keyof MethodRowsAdded>) {
total[kind] += part[kind];
@@ -6670,7 +6701,8 @@ export async function importCsvTable(
errors: [] as Array<{ row: number; reason: string }>,
// Rows intentionally not written (duplicates, already-existing) — informational.
skipped: [] as Array<{ row: number; reason: string }>,
- added: undefined as MethodRowsAdded | undefined
+ added: undefined as MethodRowsAdded | undefined,
+ warnings: undefined as string[] | undefined
};
const acceptedRows = await rejectForeignReferences(
@@ -8704,7 +8736,8 @@ export async function importCsvTable(
updated: summary.updated,
errors: withValues(summary.errors),
skipped: withValues(summary.skipped),
- added: summary.added ?? null
+ added: summary.added ?? null,
+ warnings: summary.warnings ?? []
};
}
diff --git a/apps/erp/test/database/method-import-append.test.ts b/apps/erp/test/database/method-import-append.test.ts
index 44081866af..faea07434a 100644
--- a/apps/erp/test/database/method-import-append.test.ts
+++ b/apps/erp/test/database/method-import-append.test.ts
@@ -152,7 +152,8 @@ async function fixture() {
updated: 0,
errors: [] as Array<{ row: number; reason: string }>,
skipped: [] as Array<{ row: number; reason: string }>,
- added: undefined as MethodRowsAdded | undefined
+ added: undefined as MethodRowsAdded | undefined,
+ warnings: undefined as string[] | undefined
};
await importMethods(db, {
table,
@@ -460,7 +461,14 @@ describe("method import onto an existing method", () => {
await f.setReleaseControl("warn");
const accepted = await f.run("bom", rows);
expect(accepted.errors).toEqual([]);
+ expect(accepted.warnings).toEqual([
+ `Part ASSY rev 0: ${LOCKED_REVISION_MESSAGE}`
+ ]);
expect(await f.materials()).toHaveLength(2);
+
+ // A re-run writes nothing, so there is nothing to warn about.
+ const rerun = await f.run("bom", rows);
+ expect(rerun.warnings).toEqual([]);
}
);
diff --git a/apps/erp/test/database/method-import-guards.test.ts b/apps/erp/test/database/method-import-guards.test.ts
index 424c26d070..41299a0c8c 100644
--- a/apps/erp/test/database/method-import-guards.test.ts
+++ b/apps/erp/test/database/method-import-guards.test.ts
@@ -145,7 +145,16 @@ const REFUSALS: Array<[string, Rows, string[]]> = [
[
"a version that is not a number",
[bom("ASSY", "COMP-1", "1", { makeMethodVersion: "abc" })],
- ['Make Method Version "abc" is not a version number']
+ [
+ 'Make Method Version "abc" must be a number above 0 with at most 2 decimals'
+ ]
+ ],
+ [
+ "a version with more decimals than the column keeps",
+ [bom("ASSY", "COMP-1", "1", { makeMethodVersion: "1.555" })],
+ [
+ 'Make Method Version "1.555" must be a number above 0 with at most 2 decimals'
+ ]
]
];
diff --git a/docs/content/docs/reference/import-export.mdx b/docs/content/docs/reference/import-export.mdx
index 0331fba715..39b581e2b0 100644
--- a/docs/content/docs/reference/import-export.mdx
+++ b/docs/content/docs/reference/import-export.mdx
@@ -38,12 +38,12 @@ Bulk import is available only for supported entities. Import each entity from th
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** 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.
+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; a version you name must be a number above 0 with at most 2 decimals. 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. When release control is set to warn, the import writes into a released revision as the editors do, and the results list that part under a warning.
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.
-<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.
+<Callout type="warn" title="Fixed assets 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. Create fixed assets in the app. BOM lines have no table import of their own (`methodMaterial`); add them with the **BOM** method import above or in the app.
</Callout>
## The import flow
diff --git a/packages/ee/src/approvals/service.ts b/packages/ee/src/approvals/service.ts
index a3f2c63c1c..1a8573bd73 100644
--- a/packages/ee/src/approvals/service.ts
+++ b/packages/ee/src/approvals/service.ts
@@ -827,6 +827,37 @@ export async function hasPendingApproval(
return result.data.length > 0;
}
+/** The documents among `documentIds` that have a pending approval request. */
+export async function pendingApprovalDocumentIds(
+ client: SupabaseClient<Database>,
+ args: {
+ documentType: (typeof approvalDocumentType)[number];
+ documentIds: string[];
+ companyId: string;
+ }
+): Promise<Set<string>> {
+ if (args.documentIds.length === 0) return new Set();
+ const result = await client
+ .from("approvalRequest")
+ .select("documentId")
+ .eq("documentType", args.documentType)
+ .in("documentId", args.documentIds)
+ .eq("companyId", args.companyId)
+ .eq("status", "Pending");
+
+ // Fail closed, as hasPendingApproval does.
+ if (result.error) {
+ logger.error("Failed to check for pending approval requests", {
+ documentType: args.documentType,
+ companyId: args.companyId,
+ error: result.error
+ });
+ throw new Error("Failed to read approval requests");
+ }
+
+ return new Set(result.data.map((row) => row.documentId));
+}
+
export async function isApprovalRequired(
client: SupabaseClient<Database>,
documentType: (typeof approvalDocumentType)[number],
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index a111428505..2cc0a4f838 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -26744,6 +26744,9 @@ msgstr "Ausbuchung von Bestand, der über Prüfungsablehnungen und NCR-Verwendun
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Den Wert eines Vermögenswerts über seine Lebensdauer abschreiben — ein monatlicher Batch, den Sie erstellen, als Entwurf überprüfen und dann buchen."
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index e279a1d189..99aa196211 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -26744,6 +26744,9 @@ msgstr "Write-off of stock scrapped or returned via inspection rejects and NCR d
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
+msgid "Written with a warning"
+msgstr "Written with a warning"
+
msgid "Wrote the missing journal of 1 document"
msgstr "Wrote the missing journal of 1 document"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index e7a96e988e..0a8f3d4563 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -26744,6 +26744,9 @@ msgstr "Cancelación contable de existencias desperdiciadas o devueltas a travé
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Reducir el valor de un activo a lo largo de su vida útil — un lote mensual que crea, revisa como borrador y luego contabiliza."
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index f4886b68d6..def92372e0 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -26744,6 +26744,9 @@ msgstr "Passage en perte du stock mis au rebut ou retourné par les rejets de co
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Réduire progressivement la valeur d'un bien sur sa durée de vie — un lot mensuel que vous créez, examinez en tant que brouillon, puis comptabilisez."
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 78c72b2f91..c7efc8d9bd 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -26744,6 +26744,9 @@ msgstr "निरीक्षण अस्वीकृतियों और NCR
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "किसी संपत्ति के मूल्य को उसके जीवन काल में कम करना — एक मासिक बैच जो आप बनाते हैं, ड्राफ्ट के रूप में समीक्षा करते हैं, फिर पोस्ट करते हैं।"
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 0d8075d37a..12e8a40a75 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -26744,6 +26744,9 @@ msgstr "Stralcio della giacenza scartata o restituita tramite rifiuti di control
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Ammortamento del valore di un bene nel corso della sua vita — un lotto mensile che crei, rivedi come bozza, poi registri."
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 8e065188e6..0036533825 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -26744,6 +26744,9 @@ msgstr "検査却下およびNCR処置によってスクラップされたまた
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "資産の価値を耐用年数にわたって減額する―毎月作成し、下書きとしてレビューしてから転記するバッチです。"
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 27292d7876..56090c205b 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -26744,6 +26744,9 @@ msgstr "검사 거부 및 NCR 처분 결정을 통해 폐기되거나 반품된
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "자산의 가치를 내용연수에 걸쳐 상각하는 것 — 매월 생성하여 초안으로 검토한 후 전기하는 배치 작업입니다."
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index da3e25429a..ce602b7c27 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -26744,6 +26744,9 @@ msgstr "Spisanie zapasu odrzuconego lub zwróconego w wyniku odrzuceń w kontrol
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Redukcja wartości aktywu w okresie użytkowania — miesięczna seria, którą tworzysz, przeglądzasz jako wersję roboczą, a następnie zaksięgujesz."
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 011895d4da..1067b04ebc 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -26744,6 +26744,9 @@ msgstr "Baixa contábil de estoque refugado ou devolvido via rejeições de insp
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Reduzir o valor de um ativo ao longo de sua vida útil — um lote mensal que você cria, revisa como rascunho e depois contabiliza."
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index be6de0d704..01c1c6d91e 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -26744,6 +26744,9 @@ msgstr "Списание запасов, забракованных или во
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Уменьшение стоимости актива в течение его жизни — ежемесячная серия, которую вы создаете, рассматриваете как черновик, затем проводите."
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index d99375eac8..8f85fffc8d 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -26744,6 +26744,9 @@ msgstr "Muayene reddiyesi ve NCR kararları yoluyla hurdaya çıkarılan veya ia
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "Bir varlığın değerini yaşamı boyunca azaltma — her ay oluşturduğunuz, taslak olarak incelediğiniz ve sonra muhasebeleştirdiğiniz bir işlem."
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 39c8556b9e..5aa9a06afa 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -26744,6 +26744,9 @@ msgstr "库存核销报废或通过检验拒收和 NCR 处置退回"
msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."
msgstr "在资产的生命周期内减少其价值——你创建的每月批次,作为草稿进行评审,然后过账。"
+msgid "Written with a warning"
+msgstr ""
+
msgid "Wrote the missing journal of 1 document"
msgstr ""