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: MES quantity modal double-count and opaque invoice errors

Anshul sharma1d1d25b794b6
diff --git a/.claude/rules/table-csv-export.md b/.claude/rules/table-csv-export.md
index a19408c4fd..8eefd39b32 100644
--- a/.claude/rules/table-csv-export.md
+++ b/.claude/rules/table-csv-export.md
@@ -71,15 +71,33 @@ optional, export/sort-related fields:
- **Library:** `json2csv` from `json-2-csv`. Called as
`json2csv(rows, { emptyFieldValue: "" })`.
- **Filename:** hardcoded `"data.csv"` (a Blob + anchor click; no server roundtrip).
-- **Column selection** (respects the saved view): uses `columnOrder` (or
+- **Column selection** (respects the saved view): delegated to the pure
+ `selectExportColumns({ columnAccessors, columnOrder, columnVisibility,
+ exportOnlyColumns })` in `utils.ts`. It uses `columnOrder` (or
`Object.keys(columnAccessors)` when order is empty), then keeps only ids that
are `in columnAccessors` AND (in `exportOnlyColumns` OR not
`columnVisibility[id] === false`). Synthetic columns (select / expand / actions)
are absent from `columnAccessors`, so they drop out. CSV headers are the
`columnAccessors` label values.
+ A saved view stores the column order from when it was saved, so its
+ `columnOrder` omits export-only columns added since — and the user can never
+ reorder an invisible column back in. `selectExportColumns` therefore appends
+ any `exportOnlyColumns` id the stored order missed instead of dropping it.
- **Export-only columns** (`exportOnlyColumns` prop, sourced from `meta.exportOnly`):
columns hidden in the grid but always included in the CSV regardless of the view's
`columnVisibility`. Use this for values you want in the export but not on screen.
+ Build one with the `exportOnlyColumn<T>({ id, header, value })` factory
+ (`utils.ts`, re-exported from `~/components`) rather than hand-writing the meta
+ blob — it sets `exportOnly`, uses `header` as `filterHeader` (the CSV heading),
+ and wires `value` as `exportValue`:
+
+ ```tsx
+ exportOnlyColumn<StockMovement>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.itemDescription ?? null
+ })
+ ```
- **Per-cell value:** for each kept column, if `exportValues[key]` exists it is
called with the full row to produce the value; otherwise the raw accessor read
is used, with the id→name substitution below. The result is then passed through
@@ -123,6 +141,14 @@ Just render `<Table>` — the button comes for free. No `enableExport`-style pro
- A column with a JSX header and no `meta.filterHeader` and no `meta.exportValue`
is absent from all three maps — it neither exports nor appears in the sort
picker. Give it a `filterHeader` (label) and/or an `exportValue` to include it.
+- The per-cell read is a **flat** `row[key]`, so a dot-path accessor
+ (`accessorKey: "item.name"`) exports blank. Supply a `meta.exportValue`.
+- **Item columns**: the convention is two CSV columns — the item column exports
+ the readable part id, and an `exportOnlyColumn` with `id: "itemName"` carries
+ the name/description the cell stacks underneath it. A column whose accessor is
+ `itemId` needs an explicit `meta.exportValue` returning the readable id,
+ otherwise the `idNameMaps` substitution overwrites the id with the name and the
+ part number never reaches the CSV.
## Unrelated standalone CSV
diff --git a/apps/erp/app/components/Table/components/Download.tsx b/apps/erp/app/components/Table/components/Download.tsx
index e56a84a3bd..3a1e2b2bf0 100644
--- a/apps/erp/app/components/Table/components/Download.tsx
+++ b/apps/erp/app/components/Table/components/Download.tsx
@@ -9,6 +9,7 @@ import { json2csv } from "json-2-csv";
import { useCallback, useMemo } from "react";
import { LuDownload } from "react-icons/lu";
import { useCustomers, useItems, usePeople, useSuppliers } from "~/stores";
+import { selectExportColumns } from "../utils";
type DownloadProps = {
data: object[];
@@ -64,21 +65,16 @@ const Download = ({
[items, suppliers, people, customers]
);
- // The visible columns, in the current view's order. The column id doubles as
- // the data accessor key; columns absent from columnAccessors (selection,
- // expand, actions) are dropped.
- const exportColumns = useMemo(() => {
- const order = columnOrder.length
- ? columnOrder
- : Object.keys(columnAccessors);
- return order.filter(
- (id) =>
- id in columnAccessors &&
- // Export-only columns export regardless of grid visibility; everything
- // else follows the visible-in-the-current-view rule.
- (exportOnlyColumns.includes(id) || columnVisibility[id] !== false)
- );
- }, [columnOrder, columnVisibility, columnAccessors, exportOnlyColumns]);
+ const exportColumns = useMemo(
+ () =>
+ selectExportColumns({
+ columnAccessors,
+ columnOrder,
+ columnVisibility,
+ exportOnlyColumns
+ }),
+ [columnOrder, columnVisibility, columnAccessors, exportOnlyColumns]
+ );
const onClick = useCallback(() => {
if (!data?.length) {
diff --git a/apps/erp/app/components/Table/index.ts b/apps/erp/app/components/Table/index.ts
index ec5c448a93..75ac45d663 100644
--- a/apps/erp/app/components/Table/index.ts
+++ b/apps/erp/app/components/Table/index.ts
@@ -1,3 +1,5 @@
import Table from "./Table";
+export { exportOnlyColumn } from "./utils";
+
export default Table;
diff --git a/apps/erp/app/components/Table/utils.test.ts b/apps/erp/app/components/Table/utils.test.ts
index 4413bbc912..54559bacb6 100644
--- a/apps/erp/app/components/Table/utils.test.ts
+++ b/apps/erp/app/components/Table/utils.test.ts
@@ -1,6 +1,10 @@
import type { ColumnDef } from "@tanstack/react-table";
import { describe, expect, it } from "vitest";
-import { buildColumnMaps } from "./utils";
+import {
+ buildColumnMaps,
+ exportOnlyColumn,
+ selectExportColumns
+} from "./utils";
type Row = {
id: string;
@@ -98,3 +102,72 @@ describe("buildColumnMaps", () => {
expect(sortKeyToLabel).toEqual({ type: "TYPE" });
});
});
+
+describe("exportOnlyColumn", () => {
+ it("exports under filterHeader, is flagged export-only, and never sorts", () => {
+ const value = (row: Row) => row.type;
+ const column = exportOnlyColumn<Row>({
+ id: "itemName",
+ header: "Item Name",
+ value
+ });
+
+ const { accessors, exportValues, sortKeyToLabel, exportOnlyColumns } =
+ buildColumnMaps(cols(column), upper);
+
+ expect(accessors).toEqual({ itemName: "ITEM NAME" });
+ expect(exportValues.itemName).toBe(value);
+ expect(exportOnlyColumns).toEqual(["itemName"]);
+ // no accessorKey, so it can never reach the server-sort picker
+ expect(sortKeyToLabel).toEqual({});
+ });
+});
+
+describe("selectExportColumns", () => {
+ const columnAccessors = { type: "Type", itemName: "Item Name" };
+
+ it("falls back to accessor order when the view has no column order", () => {
+ expect(
+ selectExportColumns({
+ columnAccessors,
+ columnOrder: [],
+ columnVisibility: {},
+ exportOnlyColumns: ["itemName"]
+ })
+ ).toEqual(["type", "itemName"]);
+ });
+
+ it("appends an export-only column a stale saved view's order omits", () => {
+ expect(
+ selectExportColumns({
+ columnAccessors,
+ // saved before itemName existed
+ columnOrder: ["type"],
+ columnVisibility: {},
+ exportOnlyColumns: ["itemName"]
+ })
+ ).toEqual(["type", "itemName"]);
+ });
+
+ it("keeps export-only columns despite being hidden, drops hidden normal ones", () => {
+ expect(
+ selectExportColumns({
+ columnAccessors,
+ columnOrder: ["type", "itemName"],
+ columnVisibility: { type: false, itemName: false },
+ exportOnlyColumns: ["itemName"]
+ })
+ ).toEqual(["itemName"]);
+ });
+
+ it("drops ids with no accessor (selection, expand, actions)", () => {
+ expect(
+ selectExportColumns({
+ columnAccessors,
+ columnOrder: ["select", "type", "actions"],
+ columnVisibility: {},
+ exportOnlyColumns: []
+ })
+ ).toEqual(["type"]);
+ });
+});
diff --git a/apps/erp/app/components/Table/utils.ts b/apps/erp/app/components/Table/utils.ts
index 8ac29947fc..4ecce9d7dd 100644
--- a/apps/erp/app/components/Table/utils.ts
+++ b/apps/erp/app/components/Table/utils.ts
@@ -78,6 +78,60 @@ export function buildColumnMaps<T>(
return { accessors, exportValues, sortKeyToLabel, exportOnlyColumns };
}
+// The columns a CSV export should emit, in the current view's order. A column
+// id doubles as its data accessor key; ids absent from columnAccessors
+// (selection, expand, actions) are dropped.
+export function selectExportColumns(args: {
+ columnAccessors: Record<string, string>;
+ columnOrder: string[];
+ columnVisibility: Record<string, boolean>;
+ exportOnlyColumns: string[];
+}): string[] {
+ const { columnAccessors, columnOrder, columnVisibility, exportOnlyColumns } =
+ args;
+
+ // A saved view stores the column order from when it was saved, so it omits
+ // export-only columns added since. They render nowhere in the grid, so the
+ // user can never reorder them back in — append any the stored order missed
+ // rather than silently dropping them from the export.
+ const order = columnOrder.length
+ ? [
+ ...columnOrder,
+ ...exportOnlyColumns.filter((id) => !columnOrder.includes(id))
+ ]
+ : Object.keys(columnAccessors);
+
+ return order.filter(
+ (id) =>
+ id in columnAccessors &&
+ // Export-only columns export regardless of grid visibility; everything
+ // else follows the visible-in-the-current-view rule.
+ (exportOnlyColumns.includes(id) || columnVisibility[id] !== false)
+ );
+}
+
+// A column that exists only to add a field to the CSV — never rendered in the
+// grid (Table force-hides `exportOnly`). `header` is blank so the column stays
+// out of the visibility menu; the CSV heading comes from `filterHeader`.
+export function exportOnlyColumn<T>(opts: {
+ // Column id, doubles as the export key. Cannot contain '_' (buildColumnMaps).
+ id: string;
+ // Already-translated heading, e.g. t`Item Name`.
+ header: string;
+ value: (row: T) => string | number | boolean | null | undefined;
+}): ColumnDef<T, unknown> {
+ return {
+ id: opts.id,
+ header: "",
+ cell: () => null,
+ meta: {
+ exportOnly: true,
+ filterHeader: opts.header,
+ exportValue: opts.value
+ }
+ };
+}
+
export function updateNestedProperty(
obj: object,
path: string | string[],
diff --git a/apps/erp/app/components/index.ts b/apps/erp/app/components/index.ts
index 5bc9573f1f..d4d2d2930e 100644
--- a/apps/erp/app/components/index.ts
+++ b/apps/erp/app/components/index.ts
@@ -40,7 +40,7 @@ import SearchFilter from "./SearchFilter";
import { SearchLandingPage } from "./SearchLandingPage";
import Select from "./Select";
import SupplierAvatar from "./SupplierAvatar";
-import Table from "./Table";
+import Table, { exportOnlyColumn } from "./Table";
export {
Assignee,
@@ -86,5 +86,6 @@ export {
Table,
TimeTypeIcon,
TrackingTypeIcon,
+ exportOnlyColumn,
useOptimisticAssignment
};
diff --git a/apps/erp/app/modules/accounting/accounting.server.ts b/apps/erp/app/modules/accounting/accounting.server.ts
index 244c30fbd2..96eb36b29a 100644
--- a/apps/erp/app/modules/accounting/accounting.server.ts
+++ b/apps/erp/app/modules/accounting/accounting.server.ts
@@ -1,39 +1,8 @@
-import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { getNextSequence } from "@carbon/database/sequence";
import { toStoredAmount } from "@carbon/utils";
-import { sql } from "kysely";
-import { interpolateSequenceDate } from "~/utils/string";
import { acquisitionLines } from "./accounting.utils";
-async function getNextSequence(
- trx: KyselyTx,
- tableName: string,
- companyId: string
-) {
- // Atomic increment: the UPDATE takes the row lock before reading, so two
- // concurrent transactions can't both read the same "next" and return the
- // same sequence number.
- const sequence = await trx
- .updateTable("sequence")
- .set({
- next: sql<number>`"next" + "step"`,
- updatedBy: "system"
- })
- .where("table", "=", tableName)
- .where("companyId", "=", companyId)
- .returning(["next", "prefix", "suffix", "size"])
- .executeTakeFirstOrThrow();
-
- const { prefix, suffix, next, size } = sequence;
- if (!Number.isInteger(next)) throw new Error("Next is not an integer");
- if (!Number.isInteger(size)) throw new Error("Size is not an integer");
-
- const nextSequence = next!.toString().padStart(size!, "0");
- const derivedPrefix = interpolateSequenceDate(prefix);
- const derivedSuffix = interpolateSequenceDate(suffix);
-
- return `${derivedPrefix}${nextSequence}${derivedSuffix}`;
-}
-
export async function postDisposal(
db: Kysely<KyselyDatabase>,
args: {
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index dee39e5b3e..4ba3404301 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -39,6 +39,7 @@ import {
} from "react-icons/lu";
import { useFetcher } from "react-router";
import {
+ exportOnlyColumn,
Hyperlink,
ItemThumbnail,
MethodItemTypeIcon,
@@ -139,6 +140,11 @@ const InventoryTable = memo(
icon: <LuBookMarked />
}
},
+ exportOnlyColumn<InventoryItem>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
accessorKey: "quantityOnHand",
diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx
index 3ec14fb332..e174431cc2 100644
--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx
@@ -18,6 +18,7 @@ import {
LuWarehouse
} from "react-icons/lu";
import {
+ exportOnlyColumn,
Hyperlink,
ItemThumbnail,
MethodItemTypeIcon,
@@ -217,8 +218,19 @@ const InventoryCountLines = ({
</HStack>
);
},
- meta: { icon: <LuPackage /> }
+ meta: {
+ icon: <LuPackage />,
+ // Display column (no accessorKey) — without an exportValue it is
+ // absent from the CSV entirely.
+ exportValue: (row) =>
+ row.itemReadableIdWithRevision ?? row.itemId ?? null
+ }
},
+ exportOnlyColumn<InventoryCountLine>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.itemName ?? null
+ }),
{
accessorKey: "readableId",
header: t`Batch / Serial`,
diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx
index a7fd5b576d..c381922a2d 100644
--- a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx
@@ -45,6 +45,7 @@ import {
import { Link } from "react-router";
import {
EmployeeAvatar,
+ exportOnlyColumn,
Hyperlink,
ItemThumbnail,
MethodItemTypeIcon,
@@ -121,9 +122,17 @@ const KanbansTable = memo(
label: item.readableIdWithRevision
}))
},
- icon: <LuBlocks />
+ icon: <LuBlocks />,
+ // Without this the exporter substitutes the item's name for the id
+ // (Download.tsx idNameMaps), losing the readable id.
+ exportValue: (row) => row.readableIdWithRevision ?? null
}
},
+ exportOnlyColumn<Kanban>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
id: "job",
header: "",
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx
index b3f6aee581..f9d8ddc27b 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx
@@ -98,6 +98,7 @@ const ShipmentForm = ({
const { t } = useLingui();
const {
locationId,
+ sourceDocument,
sourceDocuments,
customerId,
setLocationId,
@@ -279,6 +280,7 @@ const ShipmentForm = ({
isReadOnly={isPosted}
/>
<Combobox
+ key={sourceDocument}
name="sourceDocumentId"
label={t`Source Document ID`}
termId="shipment-source-document-id"
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx
index 8779a59e77..1de69b325f 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/useShipmentForm.tsx
@@ -122,6 +122,7 @@ export default function useShipmentForm({
error,
locationId,
customerId,
+ sourceDocument,
sourceDocuments,
setLocationId,
setSourceDocument,
diff --git a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx
index fc63ac49ba..d42c0de35a 100644
--- a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx
@@ -18,7 +18,13 @@ import {
LuWrench
} from "react-icons/lu";
import { Link } from "react-router";
-import { EmployeeAvatar, Hyperlink, ItemThumbnail, Table } from "~/components";
+import {
+ EmployeeAvatar,
+ exportOnlyColumn,
+ Hyperlink,
+ ItemThumbnail,
+ Table
+} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { useDateFormatter, usePermissions, useUser } from "~/hooks";
@@ -86,6 +92,11 @@ const StockMovementsTable = memo(
icon: <LuBlocks />
}
},
+ exportOnlyColumn<StockMovement>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.itemDescription ?? null
+ }),
{
accessorKey: "entryType",
header: t`Entry Type`,
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx
index 8a0c7968db..702f6b9e0a 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx
@@ -150,12 +150,10 @@ function WarehouseTransferLineListItem({
<ItemThumbnail
size="sm"
thumbnailPath={line.item?.thumbnailPath}
- // @ts-expect-error TS2339 - TODO: fix type
type={(item.type as "Part") ?? "Part"}
/>
<VStack spacing={0}>
<span className="text-sm font-medium truncate">
- {/* @ts-expect-error TS2339 */}
{item.name}
</span>
<span className="text-xs text-muted-foreground truncate">
diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
index 84749ac5de..6b3e08efe5 100644
--- a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
@@ -41,6 +41,7 @@ import { TbTargetArrow } from "react-icons/tb";
import { Link, useFetcher, useNavigate } from "react-router";
import {
EmployeeAvatar,
+ exportOnlyColumn,
Hyperlink,
ItemLifecycleBadge,
ItemThumbnail,
@@ -123,9 +124,17 @@ const ConsumablesTable = memo(
</HStack>
),
meta: {
- icon: <LuBookMarked />
+ icon: <LuBookMarked />,
+ // The accessor is the raw item id — export the readable id
+ // the cell shows instead of a UUID.
+ exportValue: (row) => row.readableIdWithRevision ?? null
}
},
+ exportOnlyColumn<Consumable>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
accessorKey: "description",
header: t`Description`,
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
index 2ddade2a75..d9ccd7bc51 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
@@ -52,6 +52,7 @@ import { TbTargetArrow } from "react-icons/tb";
import { Link, useFetcher, useNavigate } from "react-router";
import {
EmployeeAvatar,
+ exportOnlyColumn,
Hyperlink,
ItemLifecycleBadge,
ItemThumbnail,
@@ -141,9 +142,17 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {
</HStack>
),
meta: {
- icon: <LuBookMarked />
+ icon: <LuBookMarked />,
+ // The accessor is the raw item id — export the readable id
+ // the cell shows instead of a UUID.
+ exportValue: (row) => row.readableIdWithRevision ?? null
}
},
+ exportOnlyColumn<Material>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
accessorKey: "description",
header: t`Description`,
diff --git a/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx b/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx
index 17345cdc3f..394fa6de46 100644
--- a/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx
@@ -62,7 +62,12 @@ const MethodMaterialsTable = memo(
{
accessorKey: "item.name",
header: t`Description`,
- cell: ({ row }) => row.original.item?.name
+ cell: ({ row }) => row.original.item?.name,
+ meta: {
+ // The accessor is a dot path; the exporter does a flat `row[key]`
+ // read, so without this the column exports blank.
+ exportValue: (row) => row.item?.name ?? null
+ }
},
{
accessorKey: "methodType",
diff --git a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
index 3478b6eb5a..f395ed2835 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
@@ -46,6 +46,7 @@ import { TbTargetArrow } from "react-icons/tb";
import { Link, useFetcher, useNavigate } from "react-router";
import {
EmployeeAvatar,
+ exportOnlyColumn,
Hyperlink,
ItemLifecycleBadge,
ItemThumbnail,
@@ -137,9 +138,17 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {
</HStack>
),
meta: {
- icon: <LuBookMarked />
+ icon: <LuBookMarked />,
+ // The accessor is the raw item id — export the readable id
+ // the cell shows instead of a UUID.
+ exportValue: (row) => row.readableIdWithRevision ?? null
}
},
+ exportOnlyColumn<Part>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
accessorKey: "description",
header: t`Description`,
diff --git a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
index cef924dab6..045beca637 100644
--- a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
+++ b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
@@ -44,6 +44,7 @@ import { RxCodesandboxLogo } from "react-icons/rx";
import { Link, useFetcher, useNavigate } from "react-router";
import {
EmployeeAvatar,
+ exportOnlyColumn,
Hyperlink,
ItemLifecycleBadge,
ItemThumbnail,
@@ -120,9 +121,17 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {
</HStack>
),
meta: {
- icon: <LuBookMarked />
+ icon: <LuBookMarked />,
+ // The accessor is the raw item id — export the readable id
+ // the cell shows instead of a UUID.
+ exportValue: (row) => row.readableIdWithRevision ?? null
}
},
+ exportOnlyColumn<Service>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
accessorKey: "description",
header: t`Description`,
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
index 26442e3593..db591c8afe 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
@@ -46,6 +46,7 @@ import { TbTargetArrow } from "react-icons/tb";
import { Link, useFetcher, useNavigate } from "react-router";
import {
EmployeeAvatar,
+ exportOnlyColumn,
Hyperlink,
ItemLifecycleBadge,
ItemThumbnail,
@@ -137,9 +138,17 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {
</HStack>
),
meta: {
- icon: <LuBookMarked />
+ icon: <LuBookMarked />,
+ // The accessor is the raw item id — export the readable id
+ // the cell shows instead of a UUID.
+ exportValue: (row) => row.readableIdWithRevision ?? null
}
},
+ exportOnlyColumn<Tool>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
accessorKey: "description",
header: t`Description`,
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 6fcac9ddc5..53a2d57f96 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -134,6 +134,21 @@ export async function convertSalesOrderLinesToJobs(
return { data: null, error: "No lines found" };
}
+ // Lines converted individually must not be converted a second time here
+ const existingJobs = await client
+ .from("job")
+ .select("salesOrderLineId")
+ .eq("companyId", companyId)
+ .in("salesOrderLineId", lines.map((line) => line.id).filter(Boolean));
+
+ if (existingJobs.error) {
+ return existingJobs;
+ }
+
+ const lineIdsWithJobs = new Set(
+ existingJobs.data.map((job) => job.salesOrderLineId)
+ );
+
const opportunity = await client
.from("opportunity")
.select("*, quotes(*), salesOrders(*)")
@@ -147,7 +162,11 @@ export async function convertSalesOrderLinesToJobs(
let jobsCreated = 0;
for await (const line of lines) {
- if (line.methodType === "Make to Order" && line.itemId) {
+ if (
+ line.methodType === "Make to Order" &&
+ line.itemId &&
+ !lineIdsWithJobs.has(line.id)
+ ) {
const manufacturing = await client
.from("itemReplenishment")
.select("*")
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx
index a991c694ba..7f90cb7f86 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx
@@ -9,7 +9,7 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { formatDate } from "@carbon/utils";
+import { formatDate, getItemById, getItemReadableId } from "@carbon/utils";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo, useState } from "react";
import { flushSync } from "react-dom";
@@ -25,7 +25,7 @@ import {
LuTrash
} from "react-icons/lu";
import { useNavigate } from "react-router";
-import { Hyperlink, New, Table } from "~/components";
+import { exportOnlyColumn, Hyperlink, New, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
@@ -115,9 +115,18 @@ const AssemblyInstructionsTable = memo(
);
},
meta: {
- icon: <LuSquareStack />
+ icon: <LuSquareStack />,
+ // Without this the exporter substitutes the item's name for the id
+ // (Download.tsx idNameMaps), losing the readable id the cell shows.
+ exportValue: (row) => getItemReadableId(items, row.itemId) ?? null
}
},
+ exportOnlyColumn<AssemblyInstructionListItem>({
+ id: "itemName",
+ header: "Item Name",
+ value: (row) =>
+ row.itemId ? (getItemById(items, row.itemId)?.name ?? null) : null
+ }),
{
id: "model",
header: "Model",
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
index 0550f0ee32..b532c284d3 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
@@ -27,6 +27,7 @@ import {
} from "react-icons/lu";
import { useFetcher, useParams } from "react-router";
import {
+ exportOnlyColumn,
Hyperlink,
ItemLifecycleBadge,
ItemThumbnail,
@@ -199,9 +200,16 @@ const JobMaterialsTable = memo(
value: item.id,
label: item.readableIdWithRevision
}))
- }
+ },
+ // The accessor is a raw item id — export the readable id instead.
+ exportValue: (row) => row.itemReadableId ?? null
}
},
+ exportOnlyColumn<JobMaterial>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.description ?? null
+ }),
{
id: "orderStatus",
header: () => (
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
index 9c6dded132..444f8d26c7 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
@@ -42,6 +42,7 @@ import { useFetcher, useNavigate } from "react-router";
import {
CustomerAvatar,
EmployeeAvatar,
+ exportOnlyColumn,
Hyperlink,
ItemThumbnail,
New,
@@ -224,6 +225,11 @@ const JobsTable = memo(({ data, count, tags }: JobsTableProps) => {
icon: <AiOutlinePartition />
}
},
+ exportOnlyColumn<Job>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
id: "trackedEntityId",
header: t`Tracking`,
diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
index 322c448cc0..d8be61adfa 100644
--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
@@ -35,7 +35,12 @@ import {
LuSquareChartGantt
} from "react-icons/lu";
import { useFetcher } from "react-router";
-import { ItemThumbnail, MethodItemTypeIcon, Table } from "~/components";
+import {
+ exportOnlyColumn,
+ ItemThumbnail,
+ MethodItemTypeIcon,
+ Table
+} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
@@ -291,6 +296,11 @@ const ProductionPlanningTable = ({
icon: <LuBookMarked />
}
},
+ exportOnlyColumn<ProductionPlanningItem>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
accessorKey: "unitOfMeasureCode",
header: "",
diff --git a/apps/erp/app/modules/production/ui/Projection/DemandProjectionTable.tsx b/apps/erp/app/modules/production/ui/Projection/DemandProjectionTable.tsx
index fb02a0da50..04d70b95e4 100644
--- a/apps/erp/app/modules/production/ui/Projection/DemandProjectionTable.tsx
+++ b/apps/erp/app/modules/production/ui/Projection/DemandProjectionTable.tsx
@@ -22,7 +22,7 @@ import {
LuTrash2
} from "react-icons/lu";
import { Link } from "react-router";
-import { Hyperlink, New, Table } from "~/components";
+import { exportOnlyColumn, Hyperlink, New, Table } from "~/components";
import { useLocations } from "~/components/Form/Location";
import ItemThumbnail from "~/components/ItemThumbnail";
import { ConfirmDelete } from "~/components/Modals";
@@ -131,6 +131,11 @@ const DemandProjectionsTable = memo(
icon: <LuBookMarked />
}
},
+ exportOnlyColumn<DemandProjection>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
...periodColumns,
{
id: "actions",
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
index 925a776632..387fd124e2 100644
--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
@@ -40,6 +40,7 @@ import {
} from "react-icons/lu";
import { Link, useFetcher } from "react-router";
import {
+ exportOnlyColumn,
ItemThumbnail,
MethodItemTypeIcon,
SupplierAvatar,
@@ -382,6 +383,11 @@ const PlanningTable = memo(
icon: <LuBookMarked />
}
},
+ exportOnlyColumn<PurchasingPlanningItem>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => row.name ?? null
+ }),
{
accessorKey: "unitOfMeasureCode",
header: "",
diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx
index 89f74364a6..08f8938468 100644
--- a/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx
@@ -11,7 +11,12 @@ import {
LuHash,
LuTruck
} from "react-icons/lu";
-import { EmployeeAvatar, Hyperlink, Table } from "~/components";
+import {
+ EmployeeAvatar,
+ exportOnlyColumn,
+ Hyperlink,
+ Table
+} from "~/components";
import { useDateFormatter, useUrlParams } from "~/hooks";
import {
inspectionSourceDocuments,
@@ -84,9 +89,20 @@ const InspectionsTable = memo(({ data, count }: InspectionsTableProps) => {
value: item.id,
label: item.readableIdWithRevision
}))
- }
+ },
+ // Without this the exporter substitutes the item's name for the id
+ // (Download.tsx idNameMaps), losing the readable id the cell shows.
+ exportValue: (row) =>
+ getItemReadableId(items, (row as any).itemId) ??
+ (row as any).itemReadableId ??
+ null
}
},
+ exportOnlyColumn<Inspection>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) => (row as any).item?.name ?? null
+ }),
{
accessorKey: "sourceDocument",
header: t`Source`,
diff --git a/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx b/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx
index 87d55913fc..eb05dbdc82 100644
--- a/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx
+++ b/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx
@@ -1,5 +1,5 @@
import { MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
-import { getItemReadableId } from "@carbon/utils";
+import { getItemById, getItemReadableId } from "@carbon/utils";
import { useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo, useState } from "react";
@@ -16,7 +16,13 @@ import {
LuWrench
} from "react-icons/lu";
import { useNavigate } from "react-router";
-import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import {
+ EmployeeAvatar,
+ exportOnlyColumn,
+ Hyperlink,
+ New,
+ Table
+} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useWorkCenters } from "~/components/Form/WorkCenter";
import { Confirm } from "~/components/Modals";
@@ -117,9 +123,18 @@ const RiskRegistersTable = memo(({ data, count }: RiskRegistersTableProps) => {
value: item.id,
label: item.readableIdWithRevision
}))
- }
+ },
+ // Without this the exporter substitutes the item's name for the id
+ // (Download.tsx idNameMaps), losing the readable id the cell shows.
+ exportValue: (row) => getItemReadableId(items, row.itemId) ?? null
}
},
+ exportOnlyColumn<Risk>({
+ id: "itemName",
+ header: t`Item Name`,
+ value: (row) =>
+ row.itemId ? (getItemById(items, row.itemId)?.name ?? null) : null
+ }),
{
accessorKey: "source",
header: t`Source`,
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
index 810c0fa66e..c3b0f13471 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
@@ -22,6 +22,8 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
+import type { SalesOrderForProductionCheck } from "@carbon/utils";
+import { hasLinesRequiringJobs } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { Suspense, useEffect, useMemo, useState } from "react";
import {
@@ -204,10 +206,10 @@ const SalesOrderHeader = () => {
const confirmFetcher = useFetcher<typeof confirmAction>();
const { ship, invoice } = useSalesOrder();
- // Check if there are any lines with "Make" method type that would require jobs
- const hasMakeItems =
- routeData?.lines?.some((line) => line.methodType === "Make to Order") ??
- false;
+ const linesRequireJobs = hasLinesRequiringJobs({
+ jobs: routeData?.salesOrder?.jobs as SalesOrderForProductionCheck["jobs"],
+ lines: routeData?.salesOrder?.lines as SalesOrderForProductionCheck["lines"]
+ });
const salesOrderToJobsModal = useDisclosure();
const confirmDisclosure = useDisclosure();
@@ -290,8 +292,7 @@ const SalesOrderHeader = () => {
) ||
!permissions.can("create", "production") ||
!permissions.is("employee") ||
- !!routeData?.salesOrder?.jobs ||
- !hasMakeItems
+ !linesRequireJobs
}
onClick={salesOrderToJobsModal.onOpen}
>
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
index cce2c8cc8f..9119fd841d 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
@@ -20,7 +20,8 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { getSalesOrderJobStatus } from "@carbon/utils";
+import type { SalesOrderForProductionCheck } from "@carbon/utils";
+import { getSalesOrderJobStatus, hasLinesRequiringJobs } from "@carbon/utils";
import {
getLocalTimeZone,
isSameDay,
@@ -123,10 +124,10 @@ const SalesOrderSummary = ({
const total = subtotal + tax + convertedShippingCost;
const permissions = usePermissions();
- // Check if there are any lines with "Make" method type that would require jobs
- const hasMakeItems =
- routeData?.lines?.some((line) => line.methodType === "Make to Order") ??
- false;
+ const linesRequireJobs = hasLinesRequiringJobs({
+ jobs: routeData?.salesOrder?.jobs as SalesOrderForProductionCheck["jobs"],
+ lines: routeData?.salesOrder?.lines as SalesOrderForProductionCheck["lines"]
+ });
// Services never ship, so an all-service order confirms straight to
// "To Invoice" (getSalesOrderStatus counts Service lines as shipped) and
@@ -150,8 +151,7 @@ const SalesOrderSummary = ({
{jobsCardStatusMatches &&
permissions.can("create", "production") &&
permissions.is("employee") &&
- !routeData?.salesOrder?.jobs &&
- hasMakeItems && (
+ linesRequireJobs && (
<Card>
<CardHeader>
<CardTitle className="flex flex-row gap-2">
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index d92e0464e9..5a13a05403 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-07-31T03:26:04.196Z",
+ "generated": "2026-07-31T05:48:08.334Z",
"totalTools": 1405,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
index b3ecb01819..8200ab7228 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
@@ -19,6 +19,7 @@ import {
upsertPurchaseInvoiceLine
} from "~/modules/invoicing";
import { resolveItemIdFromExtractedText } from "~/modules/items";
+import { getEdgeFunctionErrorMessage } from "~/utils/error";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -57,7 +58,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
request.headers.get("Referer") ?? path.to.purchaseOrders,
await flash(
request,
- error(result.error, "Failed to create purchase invoice")
+ error(
+ result.error,
+ await getEdgeFunctionErrorMessage(
+ result.error,
+ "Failed to create purchase invoice"
+ )
+ )
)
);
}
diff --git a/apps/erp/app/routes/x+/sales-invoice+/new.tsx b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
index 37289f7112..ec6bb0050d 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
@@ -16,6 +16,7 @@ import {
salesInvoiceValidator
} from "~/modules/invoicing";
import SalesInvoiceForm from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm";
+import { getEdgeFunctionErrorMessage } from "~/utils/error";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -54,7 +55,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
request.headers.get("Referer") ?? path.to.salesOrders,
await flash(
request,
- error(result.error, "Failed to create sales invoice")
+ error(
+ result.error,
+ await getEdgeFunctionErrorMessage(
+ result.error,
+ "Failed to create sales invoice"
+ )
+ )
)
);
}
@@ -75,7 +82,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
request.headers.get("Referer") ?? path.to.shipment(sourceDocumentId),
await flash(
request,
- error(result.error, "Failed to create sales invoice")
+ error(
+ result.error,
+ await getEdgeFunctionErrorMessage(
+ result.error,
+ "Failed to create sales invoice"
+ )
+ )
)
);
}
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx
index 4fcde7d712..c1e33d9c98 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.details.tsx
@@ -20,6 +20,7 @@ import {
ShipmentNotes
} from "~/modules/inventory/ui/Shipments";
import type { Note } from "~/modules/shared";
+import { getEdgeFunctionErrorMessage } from "~/utils/error";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -81,7 +82,13 @@ export async function action({ request }: ActionFunctionArgs) {
path.to.shipment(id),
await flash(
request,
- error(salesOrderShipment.error, "Failed to create shipment")
+ error(
+ salesOrderShipment.error,
+ await getEdgeFunctionErrorMessage(
+ salesOrderShipment.error,
+ "Failed to create shipment"
+ )
+ )
)
);
}
@@ -107,7 +114,13 @@ export async function action({ request }: ActionFunctionArgs) {
path.to.shipment(id),
await flash(
request,
- error(purchaseOrderShipment.error, "Failed to create shipment")
+ error(
+ purchaseOrderShipment.error,
+ await getEdgeFunctionErrorMessage(
+ purchaseOrderShipment.error,
+ "Failed to create shipment"
+ )
+ )
)
);
}
@@ -137,7 +150,10 @@ export async function action({ request }: ActionFunctionArgs) {
request,
error(
warehouseTransferShipment.error,
- "Failed to create shipment"
+ await getEdgeFunctionErrorMessage(
+ warehouseTransferShipment.error,
+ "Failed to create shipment"
+ )
)
)
);
diff --git a/apps/erp/app/routes/x+/shipment+/new.tsx b/apps/erp/app/routes/x+/shipment+/new.tsx
index e6f75cd48d..facb536095 100644
--- a/apps/erp/app/routes/x+/shipment+/new.tsx
+++ b/apps/erp/app/routes/x+/shipment+/new.tsx
@@ -8,6 +8,7 @@ import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import type { ShipmentSourceDocument } from "~/modules/inventory";
import { getUserDefaults } from "~/modules/users/users.server";
+import { getEdgeFunctionErrorMessage } from "~/utils/error";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -53,7 +54,13 @@ export async function action({ request }: ActionFunctionArgs) {
path.to.salesOrder(sourceDocumentId),
await flash(
request,
- error(salesOrderShipment.error, "Failed to create shipment")
+ error(
+ salesOrderShipment.error,
+ await getEdgeFunctionErrorMessage(
+ salesOrderShipment.error,
+ "Failed to create shipment"
+ )
+ )
)
);
}
@@ -80,7 +87,13 @@ export async function action({ request }: ActionFunctionArgs) {
path.to.purchaseOrder(sourceDocumentId),
await flash(
request,
- error(purchaseOrderShipment.error, "Failed to create shipment")
+ error(
+ purchaseOrderShipment.error,
+ await getEdgeFunctionErrorMessage(
+ purchaseOrderShipment.error,
+ "Failed to create shipment"
+ )
+ )
)
);
}
@@ -106,7 +119,13 @@ export async function action({ request }: ActionFunctionArgs) {
path.to.warehouseTransferDetails(sourceDocumentId),
await flash(
request,
- error(warehouseTransferShipment.error, "Failed to create shipment")
+ error(
+ warehouseTransferShipment.error,
+ await getEdgeFunctionErrorMessage(
+ warehouseTransferShipment.error,
+ "Failed to create shipment"
+ )
+ )
)
);
}
@@ -132,7 +151,16 @@ export async function action({ request }: ActionFunctionArgs) {
});
throw redirect(
path.to.shipments,
- await flash(request, error(error, "Failed to create shipment"))
+ await flash(
+ request,
+ error(
+ defaultShipment.error,
+ await getEdgeFunctionErrorMessage(
+ defaultShipment.error,
+ "Failed to create shipment"
+ )
+ )
+ )
);
}
diff --git a/apps/erp/app/utils/error.ts b/apps/erp/app/utils/error.ts
index a32e223a2a..d2c636932f 100644
--- a/apps/erp/app/utils/error.ts
+++ b/apps/erp/app/utils/error.ts
@@ -21,15 +21,27 @@ export async function getEdgeFunctionErrorMessage(
if (ctx && typeof ctx.clone === "function") {
try {
const body = await ctx.clone().json();
- if (body && typeof body.message === "string") {
- return body.message;
+ const bodyMessage = body?.message;
+ if (
+ typeof bodyMessage === "string" &&
+ bodyMessage !== "" &&
+ bodyMessage !== "Edge Function returned a non-2xx status code"
+ ) {
+ return bodyMessage;
}
} catch {
// body wasn't JSON or already consumed — fall through
}
}
- if (err && typeof (err as { message?: string }).message === "string") {
- return (err as { message: string }).message;
+ const message = (err as { message?: unknown })?.message;
+ // FunctionsHttpError.message is always this fixed wrapper text, which says nothing —
+ // let the caller's fallback win instead of showing it to the user.
+ if (
+ typeof message === "string" &&
+ message !== "" &&
+ message !== "Edge Function returned a non-2xx status code"
+ ) {
+ return message;
}
return fallback;
}
diff --git a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx
index 0697e47ac3..0a645efb2d 100644
--- a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx
@@ -20,7 +20,7 @@ import {
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import { useFetcher } from "react-router";
import {
@@ -68,6 +68,17 @@ export function QuantityModal({
const [confirmedUnissued, setConfirmedUnissued] = useState(false);
const submitted = useRef(false);
const isSubmitting = fetcher.state !== "idle";
+ // `operation` is live-patched via realtime; after submit it already includes what we
+ // just logged, so snapshot at submit time — not mount — to avoid double-counting.
+ const [submittedBaseline, setSubmittedBaseline] = useState<{
+ complete: number;
+ reworked: number;
+ } | null>(null);
+
+ const baseline = submittedBaseline ?? {
+ complete: operation.quantityComplete,
+ reworked: operation.quantityReworked ?? 0
+ };
useEffect(() => {
if (submitted.current && fetcher.state === "idle") {
@@ -82,8 +93,7 @@ export function QuantityModal({
finish: t`Finish ${operation.itemReadableId}`
};
- const isOperationComplete =
- operation.quantityComplete >= operation.operationQuantity;
+ const isOperationComplete = baseline.complete >= operation.operationQuantity;
const descriptionMap = {
scrap: t`Select a scrap quantity and reason`,
@@ -113,25 +123,17 @@ export function QuantityModal({
finish: finishValidator
};
- const hasUnissuedTrackedMaterials = useMemo(() => {
- const totalPartsAfterCompletion = parentIsSerial
- ? 1
- : operation.quantityComplete + quantity;
+ const totalPartsAfterCompletion = parentIsSerial
+ ? 1
+ : baseline.complete + quantity;
- return materials.some(
- (material) =>
- (material.requiresSerialTracking || material.requiresBatchTracking) &&
- material.jobOperationId === operation.id &&
- (material?.quantityIssued ?? 0) <
- (material?.quantity ?? 0) * totalPartsAfterCompletion
- );
- }, [
- materials,
- operation.id,
- operation.quantityComplete,
- quantity,
- parentIsSerial
- ]);
+ const hasUnissuedTrackedMaterials = materials.some(
+ (material) =>
+ (material.requiresSerialTracking || material.requiresBatchTracking) &&
+ material.jobOperationId === operation.id &&
+ (material?.quantityIssued ?? 0) <
+ (material?.quantity ?? 0) * totalPartsAfterCompletion
+ );
return (
<Modal
@@ -161,6 +163,10 @@ export function QuantityModal({
fetcher={fetcher}
onSubmit={() => {
submitted.current = true;
+ setSubmittedBaseline({
+ complete: operation.quantityComplete,
+ reworked: operation.quantityReworked ?? 0
+ });
}}
>
<ModalHeader>
@@ -266,8 +272,8 @@ export function QuantityModal({
onClick={() =>
setQuantity(
operation.operationQuantity -
- operation.quantityComplete -
- (operation.quantityReworked ?? 0)
+ baseline.complete -
+ baseline.reworked
)
}
>
@@ -294,8 +300,8 @@ export function QuantityModal({
value={
quantity +
(type === "rework"
- ? operation.quantityReworked
- : operation.quantityComplete)
+ ? baseline.reworked
+ : baseline.complete)
}
isReadOnly
/>
diff --git a/packages/database/package.json b/packages/database/package.json
index 08e32a6606..939c7b232a 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -22,6 +22,7 @@
"./quality": "./src/quality.ts",
"./ratelimit": "./src/ratelimit.ts",
"./sampling": "./src/sampling.ts",
+ "./sequence": "./src/sequence.ts",
"./audit": "./src/audit.ts",
"./audit.config": "./src/audit.config.ts",
"./audit.types": "./src/audit.types.ts",
diff --git a/packages/database/src/sequence.ts b/packages/database/src/sequence.ts
new file mode 100644
index 0000000000..9638bc5cbc
--- /dev/null
+++ b/packages/database/src/sequence.ts
@@ -0,0 +1,3 @@
+// Node-side re-export keeps document-number allocation in one place;
+// duplicate implementations silently diverge and mint duplicate sequence IDs.
+export { getNextSequence } from "../supabase/functions/shared/get-next-sequence.ts";
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 1c8dc43bac..c23b831dad 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -811,13 +811,16 @@ serve(async (req: Request) => {
.single(),
]);
- if (!salesOrder.data) throw new Error("Purchase order not found");
+ if (salesOrder.error) throw new Error(salesOrder.error.message);
+ if (!salesOrder.data) throw new Error("Sales order not found");
if (salesOrderLines.error)
throw new Error(salesOrderLines.error.message);
+ if (salesOrderPayment.error) throw new Error(salesOrderPayment.error.message);
if (!salesOrderPayment.data)
- throw new Error("Purchase order payment not found");
+ throw new Error("Sales order payment details not found");
+ if (salesOrderShipment.error) throw new Error(salesOrderShipment.error.message);
if (!salesOrderShipment.data)
- throw new Error("Purchase order delivery not found");
+ throw new Error("Sales order delivery details not found");
const uninvoicedLines = salesOrderLines?.data?.reduce<
(typeof salesOrderLines)["data"]
@@ -878,7 +881,7 @@ serve(async (req: Request) => {
.returning(["id"])
.executeTakeFirstOrThrow();
- if (!salesInvoice.id) throw new Error("Purchase invoice not created");
+ if (!salesInvoice.id) throw new Error("Sales invoice not created");
salesInvoiceId = salesInvoice.id;
await trx
@@ -1334,9 +1337,9 @@ serve(async (req: Request) => {
.eq("shipped", true),
]);
+ if (shipment.error) throw shipment.error;
if (shipmentLines.error) throw shipmentLines.error;
- if (shipmentFixedAssetLines.error)
- throw shipmentFixedAssetLines.error;
+ if (shipmentFixedAssetLines.error) throw shipmentFixedAssetLines.error;
// Accumulate quantities for each sales order line
const quantitiesByLine = shipmentLines.data.reduce<
@@ -1359,7 +1362,9 @@ serve(async (req: Request) => {
!shipment.data?.sourceDocumentId ||
shipment.data?.sourceDocument !== "Sales Order"
) {
- throw new Error("Shipment has no source document id");
+ throw new Error(
+ "This shipment isn't linked to a sales order, so there's nothing to invoice."
+ );
}
const [
@@ -1386,13 +1391,16 @@ serve(async (req: Request) => {
.single(),
]);
- if (!salesOrder.data) throw new Error("Purchase order not found");
+ if (salesOrder.error) throw new Error(salesOrder.error.message);
+ if (!salesOrder.data) throw new Error("Sales order not found");
if (salesOrderLines.error)
throw new Error(salesOrderLines.error.message);
+ if (salesOrderPayment.error) throw new Error(salesOrderPayment.error.message);
if (!salesOrderPayment.data)
- throw new Error("Purchase order payment not found");
+ throw new Error("Sales order payment details not found");
+ if (salesOrderShipment.error) throw new Error(salesOrderShipment.error.message);
if (!salesOrderShipment.data)
- throw new Error("Purchase order delivery not found");
+ throw new Error("Sales order delivery details not found");
const uninvoicedLines = salesOrderLines?.data?.reduce<
(typeof salesOrderLines)["data"]
@@ -1466,7 +1474,7 @@ serve(async (req: Request) => {
.returning(["id"])
.executeTakeFirstOrThrow();
- if (!salesInvoice.id) throw new Error("Purchase invoice not created");
+ if (!salesInvoice.id) throw new Error("Sales invoice not created");
salesInvoiceId = salesInvoice.id;
await trx
@@ -2037,9 +2045,17 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ // JSON.stringify(err) → "{}" for Errors (non-enumerable properties); use .message
+ // duck-typing. Omit key when empty so the caller's fallback string wins.
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(
+ typeof message === "string" && message !== "" ? { message } : {}
+ ),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
});
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index 3ae4ac0133..87334b7e2d 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -708,10 +708,14 @@ serve(async (req: Request) => {
}
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
return new Response(
@@ -763,10 +767,14 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "receiptFromPurchaseOrder": {
@@ -1041,10 +1049,14 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "receiptFromInboundTransfer": {
@@ -1215,10 +1227,14 @@ serve(async (req: Request) => {
});
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "receiptFromWarehouseTransfer": {
@@ -1395,10 +1411,14 @@ serve(async (req: Request) => {
});
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "receiptLineSplit": {
@@ -1530,10 +1550,14 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "shipmentDefault": {
@@ -1576,10 +1600,14 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "shipmentFromWarehouseTransfer": {
@@ -1748,10 +1776,14 @@ serve(async (req: Request) => {
});
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "shipmentFromPurchaseOrder": {
@@ -1954,10 +1986,14 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "shipmentFromSalesOrder": {
@@ -2314,10 +2350,14 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "shipmentFromSalesOrderLine": {
@@ -2587,10 +2627,14 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "shipmentLineSplit": {
@@ -2656,10 +2700,14 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
case "journalEntry": {
@@ -2701,10 +2749,14 @@ serve(async (req: Request) => {
);
} catch (err) {
console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
+ const message = (err as { message?: unknown })?.message;
+ return new Response(
+ JSON.stringify(typeof message === "string" && message !== "" ? { message } : {}),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ }
+ );
}
}
default:
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index ce80cfa591..9425d232f8 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -6964,6 +6964,9 @@ msgstr "Element muss einem ausgewählten Typ UND einer ausgewählten Gruppe ents
msgid "Item must match a selected type OR a selected group"
msgstr "Artikel muss einem ausgewählten Typ ODER einer ausgewählten Gruppe entsprechen"
+msgid "Item Name"
+msgstr "Artikelname"
+
msgid "Item Scope"
msgstr "Artikelbereich"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 4341457156..4060614170 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -6964,6 +6964,9 @@ msgstr "Item must match a selected type AND a selected group"
msgid "Item must match a selected type OR a selected group"
msgstr "Item must match a selected type OR a selected group"
+msgid "Item Name"
+msgstr "Item Name"
+
msgid "Item Scope"
msgstr "Item Scope"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 87ee0a8862..9373ec0508 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -6964,6 +6964,9 @@ msgstr "El artículo debe coincidir con un tipo seleccionado Y un grupo seleccio
msgid "Item must match a selected type OR a selected group"
msgstr "El artículo debe coincidir con un tipo seleccionado O un grupo seleccionado"
+msgid "Item Name"
+msgstr "Nombre del artículo"
+
msgid "Item Scope"
msgstr "Alcance de Artículos"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 2cd34fbec0..f07fd890aa 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -6964,6 +6964,9 @@ msgstr "L'article doit correspondre à un type sélectionné ET à un groupe sé
msgid "Item must match a selected type OR a selected group"
msgstr "L'article doit correspondre à un type sélectionné OU à un groupe sélectionné"
+msgid "Item Name"
+msgstr "Nom de l'article"
+
msgid "Item Scope"
msgstr "Portée des articles"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index c11bd748e8..e3490c4ec7 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -6964,6 +6964,9 @@ msgstr "आइटम को एक चयनित प्रकार और ए
msgid "Item must match a selected type OR a selected group"
msgstr "आइटम को एक चयनित प्रकार OR एक चयनित समूह से मेल खाना चाहिए"
+msgid "Item Name"
+msgstr "आइटम नाम"
+
msgid "Item Scope"
msgstr "आइटम स्कोप"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 47e37bccf0..4aec2cf5c8 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -6964,6 +6964,9 @@ msgstr "L'articolo deve corrispondere a un tipo selezionato E a un gruppo selezi
msgid "Item must match a selected type OR a selected group"
msgstr "L'articolo deve corrispondere a un tipo selezionato O a un gruppo selezionato"
+msgid "Item Name"
+msgstr "Nome articolo"
+
msgid "Item Scope"
msgstr "Ambito Articolo"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index bdcc726a50..b2c7ae8e84 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -6964,6 +6964,9 @@ msgstr "アイテムは選択されたタイプと選択されたグループの
msgid "Item must match a selected type OR a selected group"
msgstr "アイテムは選択されたタイプまたは選択されたグループと一致する必要があります"
+msgid "Item Name"
+msgstr "品目名"
+
msgid "Item Scope"
msgstr "アイテムスコープ"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index e628087b83..8045913ae7 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -6964,6 +6964,9 @@ msgstr "품목은 선택한 유형과 선택한 그룹을 모두 충족해야
msgid "Item must match a selected type OR a selected group"
msgstr "품목은 선택한 유형 또는 선택한 그룹 중 하나를 충족해야 합니다"
+msgid "Item Name"
+msgstr "품목명"
+
msgid "Item Scope"
msgstr "품목 범위"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index f4e412fe9d..1f228b220b 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -6964,6 +6964,9 @@ msgstr "Element musi pasować do wybranego typu I wybranej grupy"
msgid "Item must match a selected type OR a selected group"
msgstr "Element musi pasować do wybranego typu LUB wybranej grupy"
+msgid "Item Name"
+msgstr "Nazwa pozycji"
+
msgid "Item Scope"
msgstr "Zakres Pozycji"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 275d6df596..0e0d87e9e9 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -6964,6 +6964,9 @@ msgstr "Item deve corresponder a um tipo selecionado E um grupo selecionado"
msgid "Item must match a selected type OR a selected group"
msgstr "Item deve corresponder a um tipo selecionado OU um grupo selecionado"
+msgid "Item Name"
+msgstr "Nome do item"
+
msgid "Item Scope"
msgstr "Escopo do Item"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index bf8b3023f5..e0f978764f 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -6964,6 +6964,9 @@ msgstr "Товар должен соответствовать выбранно
msgid "Item must match a selected type OR a selected group"
msgstr "Товар должен соответствовать выбранному типу ИЛИ выбранной группе"
+msgid "Item Name"
+msgstr "Название позиции"
+
msgid "Item Scope"
msgstr "Область применения товара"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index cb1e1adf87..28a17b9e32 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -6964,6 +6964,9 @@ msgstr "Öğe seçilen bir tür VE seçilen bir grup ile eşleşmelidir"
msgid "Item must match a selected type OR a selected group"
msgstr "Öğe seçilen bir tür VEYA seçilen bir gruba uymalıdır"
+msgid "Item Name"
+msgstr "Kalem Adı"
+
msgid "Item Scope"
msgstr "Ürün Kapsamı"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 759fbfd2ee..a143470b4e 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -6964,6 +6964,9 @@ msgstr "项目必须匹配选定的类型和选定的组"
msgid "Item must match a selected type OR a selected group"
msgstr "项目必须匹配选定的类型或选定的组"
+msgid "Item Name"
+msgstr "物料名称"
+
msgid "Item Scope"
msgstr "物品范围"
diff --git a/packages/utils/src/items.ts b/packages/utils/src/items.ts
index c10fd6514b..b02703733f 100644
--- a/packages/utils/src/items.ts
+++ b/packages/utils/src/items.ts
@@ -30,7 +30,10 @@ export function getItemReadableId(
* @param itemId - The item ID to look up
* @returns The item, or undefined if not found
*/
-export function getItemById(items: Item[], itemId: string): Item | undefined {
+export function getItemById<T extends Item>(
+ items: T[],
+ itemId: string
+): T | undefined {
const len = items.length;
for (let i = 0; i < len; i++) {
const item = items[i]!;
diff --git a/packages/utils/src/status.ts b/packages/utils/src/status.ts
index 4a8e15a5c1..68ca94446f 100644
--- a/packages/utils/src/status.ts
+++ b/packages/utils/src/status.ts
@@ -165,7 +165,7 @@ export const getSalesOrderJobStatus = (
return { jobVariant, jobLabel, jobs: filteredJobs };
};
-type SalesOrderForProductionCheck = {
+export type SalesOrderForProductionCheck = {
jobs?: Array<{
salesOrderLineId: string;
productionQuantity: number;
@@ -179,6 +179,22 @@ type SalesOrderForProductionCheck = {
}>;
};
+/**
+ * Checks if a Sales Order still has "Make" lines with no job at all.
+ * Gate the convert-to-jobs actions on this, not on whether the order has any
+ * job — converting one line individually must leave the rest convertible.
+ */
+export const hasLinesRequiringJobs = (
+ salesOrder: SalesOrderForProductionCheck
+): boolean => {
+ const jobs = salesOrder.jobs ?? [];
+ return (salesOrder.lines ?? []).some(
+ (line) =>
+ line.methodType === "Make to Order" &&
+ !jobs.some((job) => job.salesOrderLineId === line.id)
+ );
+};
+
/**
* Checks if a Sales Order has incomplete jobs.
* Returns true if any "Make" line item has incomplete jobs.