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(inventory): reject ambiguous items and sub-scale quantities on stock import

Raul7d4a42d45131
diff --git a/packages/database/supabase/functions/import-csv/classify-stock-row.test.ts b/packages/database/supabase/functions/import-csv/classify-stock-row.test.ts
index 327fefa3d0..3a93bebe5c 100644
--- a/packages/database/supabase/functions/import-csv/classify-stock-row.test.ts
+++ b/packages/database/supabase/functions/import-csv/classify-stock-row.test.ts
@@ -291,6 +291,56 @@ Deno.test("items sharing Part Number + Revision: the one matching the import's t
);
});
+Deno.test("two items of the import's tracking type share the identity: rows are rejected", () => {
+ const candidates = [
+ { id: "a-part", readableId: "X-100", revision: "0", itemTrackingType: "Inventory", hasItemCost: true },
+ { id: "b-tool", readableId: "X-100", revision: "0", itemTrackingType: "Inventory", hasItemCost: true },
+ ];
+ const itemMap = buildStockItemMap("inventoryQuantity", candidates);
+ assertEquals(itemMap.get(itemKey("X-100", "0"))?.ambiguous, true);
+ assertEquals(
+ reason(
+ classify(
+ "inventoryQuantity",
+ { readableId: "X-100", locationId: "loc-1", quantity: "5" },
+ { itemMap }
+ )
+ ),
+ "error: More than one item is Inventory tracked with part number X-100 rev 0"
+ );
+ // One match plus one of another tracking type is still unambiguous.
+ const mixed = buildStockItemMap("inventoryQuantity", [
+ candidates[0],
+ { ...candidates[1], itemTrackingType: "Batch" },
+ ]);
+ assertEquals(mixed.get(itemKey("X-100", "0"))?.ambiguous, undefined);
+ assertEquals(mixed.get(itemKey("X-100", "0"))?.id, "a-part");
+});
+
+Deno.test("quantity is rounded to posting precision before it is validated", () => {
+ // Rounds to 0 at the ledger's scale, so it would post a movement that adds
+ // nothing: rejected instead.
+ assertEquals(
+ reason(
+ classify("inventoryQuantity", {
+ readableId: "PN-INV",
+ locationId: "loc-1",
+ quantity: "0.000001",
+ })
+ ),
+ "error: Quantity must be a positive number"
+ );
+ // A quantity finer than the scale carries the ROUNDED value, so the tracked
+ // entity and the item ledger agree.
+ const decision = classify("batchQuantity", {
+ readableId: "PN-BATCH",
+ locationId: "loc-1",
+ batchNumber: "L-ROUND",
+ quantity: "1.0000049",
+ });
+ assertEquals(decision.action === "post" ? decision.row.quantity : null, 1.00000);
+});
+
Deno.test("inventory rows have no natural key: identical rows both post", () => {
const record = { readableId: "PN-INV", locationId: "loc-1", quantity: "1" };
const seenTrackedKeys = new Set<string>();
diff --git a/packages/database/supabase/functions/import-csv/classify-stock-row.ts b/packages/database/supabase/functions/import-csv/classify-stock-row.ts
index 95b894f846..c2ce5f117a 100644
--- a/packages/database/supabase/functions/import-csv/classify-stock-row.ts
+++ b/packages/database/supabase/functions/import-csv/classify-stock-row.ts
@@ -6,6 +6,8 @@
// Every accepted row becomes ONE Positive Adjmt. — these imports only ever add
// stock, never reduce or set it.
+import { round } from "../shared/precision.ts";
+
export type StockImportTable =
| "inventoryQuantity"
| "batchQuantity"
@@ -27,6 +29,11 @@ const IMPORT_LABEL_BY_TRACKING_TYPE: Record<string, string> = {
};
export type StockItemInfo = {
+ // More than one item shares this part number + revision AND this import's
+ // tracking type, so the row cannot name one item. Reported per row rather
+ // than resolved arbitrarily: posting opening stock to the wrong item is
+ // silent and expensive to unwind.
+ ambiguous?: boolean;
id: string;
itemTrackingType: string | null;
hasItemCost: boolean;
@@ -75,11 +82,23 @@ export function buildStockItemMap(
for (const c of candidates) {
const key = itemKey(c.readableId, c.revision ?? "0");
const current = map.get(key);
- if (
- !current ||
- (current.itemTrackingType !== expected &&
- c.itemTrackingType === expected)
- ) {
+ if (!current) {
+ map.set(key, {
+ id: c.id,
+ itemTrackingType: c.itemTrackingType,
+ hasItemCost: c.hasItemCost,
+ });
+ continue;
+ }
+ const currentMatches = current.itemTrackingType === expected;
+ const candidateMatches = c.itemTrackingType === expected;
+ if (candidateMatches && currentMatches) {
+ // Two items of this import's tracking type share the identity: neither
+ // can be chosen, so mark the key and let classifyStockRow reject rows.
+ map.set(key, { ...current, ambiguous: true });
+ continue;
+ }
+ if (candidateMatches && !currentMatches) {
map.set(key, {
id: c.id,
itemTrackingType: c.itemTrackingType,
@@ -146,6 +165,11 @@ export function classifyStockRow(params: {
if (!item) return error(`Item ${readableId} rev ${revision} not found`);
const expectedTrackingType = STOCK_IMPORT_TRACKING_TYPE[table];
+ if (item.ambiguous) {
+ return error(
+ `More than one item is ${expectedTrackingType} tracked with part number ${readableId} rev ${revision}`
+ );
+ }
if (item.itemTrackingType !== expectedTrackingType) {
const other = IMPORT_LABEL_BY_TRACKING_TYPE[item.itemTrackingType ?? ""];
return error(
@@ -177,8 +201,14 @@ export function classifyStockRow(params: {
let quantity = 1;
if (table !== "serialQuantity") {
const raw = text(record.quantity);
- quantity = raw === "" ? Number.NaN : Number(raw);
- if (!Number.isFinite(quantity) || quantity <= 0) {
+ const parsed = raw === "" ? Number.NaN : Number(raw);
+ // Round to posting precision BEFORE validating, and carry the rounded
+ // value: buildItemLedgerRow rounds the same way, so a quantity finer than
+ // the scale (0.000001) would otherwise report an inserted movement that
+ // adds nothing, and leave trackedEntity.quantity disagreeing with the
+ // ledger.
+ quantity = round(parsed);
+ if (!Number.isFinite(parsed) || quantity <= 0) {
return error("Quantity must be a positive number");
}
}
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 4773478ec5..6c59a778f7 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -15662,7 +15662,7 @@ msgid "Serial or Batch Tracking Required"
msgstr "Seguimiento Serial o por Lote Requerido"
msgid "Serial Quantities"
-msgstr "Cantidades de Serie"
+msgstr "Cantidades por Número de Serie"
msgid "Serial tracking"
msgstr "Seguimiento de números de serie"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 41308d23e1..590b1b3d9b 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -15662,7 +15662,7 @@ msgid "Serial or Batch Tracking Required"
msgstr "Suivi en série ou par lot requis"
msgid "Serial Quantities"
-msgstr "Quantités de série"
+msgstr "Quantités par numéro de série"
msgid "Serial tracking"
msgstr "Suivi des numéros de série"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 20c3e5a912..f28fef6a3c 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -15662,7 +15662,7 @@ msgid "Serial or Batch Tracking Required"
msgstr "सीरियल या बैच ट्रैकिंग आवश्यक है"
msgid "Serial Quantities"
-msgstr "क्रमांक मात्राएं"
+msgstr "सीरियल नंबर मात्राएं"
msgid "Serial tracking"
msgstr "सीरियल ट्रैकिंग"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 161c9233e1..f37fe1b2ba 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -15662,7 +15662,7 @@ msgid "Serial or Batch Tracking Required"
msgstr "Wymagane śledzenie seryjne lub partyjne"
msgid "Serial Quantities"
-msgstr "Ilości seryjne"
+msgstr "Ilości wg numerów seryjnych"
msgid "Serial tracking"
msgstr "Śledzenie numerów seryjnych"