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): resolve uuid vs readable id in typed item upserts so MCP updates save

Raul0241a87855e9
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index abdff380c9..693d7c951b 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -3308,6 +3308,66 @@ async function cascadeSourcingAndMethodTypeToMethodMaterials(
.execute();
}
+/**
+ * Resolves the item row that an update to a typed item (part, material, tool,
+ * consumable, service) addresses. `item` is keyed by uuid while the typed
+ * tables are keyed by the item's readable id plus companyId, so writing the
+ * pair needs both keys. Accepts either one: the uuid every read tool and
+ * route hands out, or the readable id a person types. A readable id shared by
+ * several revisions is refused rather than guessed.
+ */
+async function resolveTypedItemForUpdate(
+ client: SupabaseClient<Database>,
+ args: {
+ id: string;
+ companyId: string;
+ type: Database["public"]["Enums"]["itemType"];
+ }
+): Promise<
+ | { data: { id: string; readableId: string }; error: null }
+ | { data: null; error: PostgrestError | { message: string; code?: string } }
+> {
+ const byId = await client
+ .from("item")
+ .select("id, readableId")
+ .eq("id", args.id)
+ .eq("companyId", args.companyId)
+ .eq("type", args.type)
+ .maybeSingle();
+ if (byId.error) return { data: null, error: byId.error };
+ if (byId.data) return { data: byId.data, error: null };
+
+ const byReadableId = await client
+ .from("item")
+ .select("id, readableId")
+ .eq("readableId", args.id)
+ .eq("companyId", args.companyId)
+ .eq("type", args.type);
+ if (byReadableId.error) return { data: null, error: byReadableId.error };
+ if (byReadableId.data.length === 1) {
+ return { data: byReadableId.data[0], error: null };
+ }
+ if (byReadableId.data.length > 1) {
+ return {
+ data: null,
+ error: {
+ message: `${args.type} ${args.id} has ${byReadableId.data.length} revisions; pass the item id of the revision to update`
+ }
+ };
+ }
+ // PGRST116 is what a `.single()` miss reports, so the API layer maps this to
+ // its "no matching record" message instead of the generic failure text.
+ return {
+ data: null,
+ error: { code: "PGRST116", message: `${args.type} ${args.id} not found` }
+ };
+}
+
+/**
+ * Creates a consumable (item row and consumable row) or updates one; on update
+ * `id` is the item id (uuid) or the consumable's readable id and the write is
+ * a full replace, so omitted optional fields are cleared.
+ */
export async function upsertConsumable(
client: SupabaseClient<Database>,
consumable:
@@ -3317,6 +3377,7 @@ export async function upsertConsumable(
customFields?: Json;
})
| (z.infer<typeof consumableValidator> & {
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
@@ -3394,8 +3455,15 @@ export async function upsertConsumable(
return newConsumable;
}
- const itemUpdate = {
+ const item = await resolveTypedItemForUpdate(client, {
id: consumable.id,
+ companyId: consumable.companyId,
+ type: "Consumable"
+ });
+ if (item.error) return item;
+ const { id: itemId, readableId } = item.data;
+
+ const itemUpdate = {
name: consumable.name,
description: consumable.description,
replenishmentSystem: consumable.replenishmentSystem,
@@ -3409,35 +3477,47 @@ export async function upsertConsumable(
customFields: consumable.customFields
};
+ // item is keyed by uuid, consumable by readableId + companyId. Each update
+ // selects its row back so a miss fails instead of reporting success.
const [updateItem, updateConsumable] = await Promise.all([
client
.from("item")
.update({
...sanitize(itemUpdate),
+ updatedBy: consumable.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", consumable.id),
+ .eq("id", itemId)
+ .eq("companyId", consumable.companyId)
+ .select("id")
+ .single(),
client
.from("consumable")
.update({
...sanitize(consumableUpdate),
+ updatedBy: consumable.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", consumable.id)
+ .eq("id", readableId)
+ .eq("companyId", consumable.companyId)
+ .select("id")
+ .single()
]);
if (updateItem.error) return updateItem;
+ if (updateConsumable.error) return updateConsumable;
const pickMethod = await upsertItemDefaultPickMethod(client, {
- itemId: consumable.id,
+ itemId,
userId: consumable.updatedBy,
storageUnitId: consumable.defaultStorageUnitId
});
if (pickMethod.error) return pickMethod;
const shelfLife = await upsertItemShelfLife(client, {
- itemId: consumable.id,
+ itemId,
userId: consumable.updatedBy,
+ companyId: consumable.companyId,
mode: consumable.shelfLifeMode,
days: consumable.shelfLifeDays,
triggerProcessId: consumable.shelfLifeTriggerProcessId,
@@ -3446,7 +3526,7 @@ export async function upsertConsumable(
});
if (shelfLife.error) return shelfLife;
- return updateConsumable;
+ return updateItem;
}
/**
@@ -3592,6 +3672,11 @@ export async function resolveItemIdFromExtractedText(
return matchItemIdByText(client, companyId, candidates);
}
+/**
+ * Creates a part (item row and part row) or updates one; on update `id` is the
+ * item id (uuid) or the part's readable id and the write is a full replace, so
+ * omitted optional fields are cleared.
+ */
export async function upsertPart(
client: SupabaseClient<Database>,
part:
@@ -3601,6 +3686,7 @@ export async function upsertPart(
customFields?: Json;
})
| (z.infer<typeof partValidator> & {
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
@@ -3694,8 +3780,15 @@ export async function upsertPart(
return newPart;
}
- const itemUpdate = {
+ const item = await resolveTypedItemForUpdate(client, {
id: part.id,
+ companyId: part.companyId,
+ type: "Part"
+ });
+ if (item.error) return item;
+ const { id: itemId, readableId } = item.data;
+
+ const itemUpdate = {
name: part.name,
description: part.description,
replenishmentSystem: part.replenishmentSystem,
@@ -3709,35 +3802,47 @@ export async function upsertPart(
customFields: part.customFields
};
+ // item is keyed by uuid, part by readableId + companyId. Each update
+ // selects its row back so a miss fails instead of reporting success.
const [updateItem, updatePart] = await Promise.all([
client
.from("item")
.update({
...sanitize(itemUpdate),
+ updatedBy: part.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", part.id),
+ .eq("id", itemId)
+ .eq("companyId", part.companyId)
+ .select("id")
+ .single(),
client
.from("part")
.update({
...sanitize(partUpdate),
+ updatedBy: part.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", part.id)
+ .eq("id", readableId)
+ .eq("companyId", part.companyId)
+ .select("id")
+ .single()
]);
if (updateItem.error) return updateItem;
+ if (updatePart.error) return updatePart;
const pickMethod = await upsertItemDefaultPickMethod(client, {
- itemId: part.id,
+ itemId,
userId: part.updatedBy,
storageUnitId: part.defaultStorageUnitId
});
if (pickMethod.error) return pickMethod;
const shelfLife = await upsertItemShelfLife(client, {
- itemId: part.id,
+ itemId,
userId: part.updatedBy,
+ companyId: part.companyId,
mode: part.shelfLifeMode,
days: part.shelfLifeDays,
triggerProcessId: part.shelfLifeTriggerProcessId,
@@ -3746,7 +3851,7 @@ export async function upsertPart(
});
if (shelfLife.error) return shelfLife;
- return updatePart;
+ return updateItem;
}
export async function updateItem(
@@ -4792,6 +4897,11 @@ export async function setMethodOperationToolStepLink(
.eq("methodOperationStepId", args.methodOperationStepId);
}
+/**
+ * Creates a material (its item rows and material row) or updates one; on
+ * update `id` is the item id (uuid) or the material's readable id and the
+ * write is a full replace, so omitted optional fields are cleared.
+ */
export async function upsertMaterial(
client: SupabaseClient<Database>,
material:
@@ -4802,6 +4912,7 @@ export async function upsertMaterial(
sizes?: string[];
})
| (z.infer<typeof materialValidator> & {
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
@@ -4946,8 +5057,15 @@ export async function upsertMaterial(
};
}
- const itemUpdate = {
+ const item = await resolveTypedItemForUpdate(client, {
id: material.id,
+ companyId: material.companyId,
+ type: "Material"
+ });
+ if (item.error) return item;
+ const { id: itemId, readableId } = item.data;
+
+ const itemUpdate = {
name: material.name,
description: material.description,
replenishmentSystem: material.replenishmentSystem,
@@ -4967,35 +5085,47 @@ export async function upsertMaterial(
customFields: material.customFields
};
+ // item is keyed by uuid, material by readableId + companyId. Each update
+ // selects its row back so a miss fails instead of reporting success.
const [updateItem, updateMaterial] = await Promise.all([
client
.from("item")
.update({
...sanitize(itemUpdate),
+ updatedBy: material.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", material.id),
+ .eq("id", itemId)
+ .eq("companyId", material.companyId)
+ .select("id")
+ .single(),
client
.from("material")
.update({
...sanitize(materialUpdate),
+ updatedBy: material.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", material.id)
+ .eq("id", readableId)
+ .eq("companyId", material.companyId)
+ .select("id")
+ .single()
]);
if (updateItem.error) return updateItem;
+ if (updateMaterial.error) return updateMaterial;
const pickMethod = await upsertItemDefaultPickMethod(client, {
- itemId: material.id,
+ itemId,
userId: material.updatedBy,
storageUnitId: material.defaultStorageUnitId
});
if (pickMethod.error) return pickMethod;
const shelfLife = await upsertItemShelfLife(client, {
- itemId: material.id,
+ itemId,
userId: material.updatedBy,
+ companyId: material.companyId,
mode: material.shelfLifeMode,
days: material.shelfLifeDays,
triggerProcessId: material.shelfLifeTriggerProcessId,
@@ -5004,7 +5134,7 @@ export async function upsertMaterial(
});
if (shelfLife.error) return shelfLife;
- return updateMaterial;
+ return updateItem;
}
export async function upsertMaterialDimension(
@@ -5238,6 +5368,11 @@ export async function upsertMaterialSubstance(
);
}
+/**
+ * Creates a service (item row and service row) or updates one; on update `id`
+ * is the item id (uuid) or the service's readable id and the write is a full
+ * replace, so omitted optional fields are cleared.
+ */
export async function upsertService(
client: SupabaseClient<Database>,
service:
@@ -5247,6 +5382,7 @@ export async function upsertService(
customFields?: Json;
})
| (z.infer<typeof serviceValidator> & {
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
@@ -5309,15 +5445,15 @@ export async function upsertService(
return newService;
}
- const item = await client
- .from("item")
- .select("readableId, companyId")
- .eq("id", service.id)
- .single();
+ const item = await resolveTypedItemForUpdate(client, {
+ id: service.id,
+ companyId: service.companyId,
+ type: "Service"
+ });
if (item.error) return item;
+ const { id: itemId, readableId } = item.data;
const itemUpdate = {
- id: service.id,
name: service.name,
description: service.description,
replenishmentSystem: service.replenishmentSystem,
@@ -5331,27 +5467,36 @@ export async function upsertService(
customFields: service.customFields
};
+ // item is keyed by uuid, service by readableId + companyId. Each update
+ // selects its row back so a miss fails instead of reporting success.
const [updateItem, updateService] = await Promise.all([
client
.from("item")
.update({
...sanitize(itemUpdate),
+ updatedBy: service.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", service.id),
- // service.id is the item uuid; the service row is keyed by readableId
+ .eq("id", itemId)
+ .eq("companyId", service.companyId)
+ .select("id")
+ .single(),
client
.from("service")
.update({
...sanitize(serviceUpdate),
+ updatedBy: service.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", item.data.readableId ?? "")
- .eq("companyId", item.data.companyId ?? "")
+ .eq("id", readableId)
+ .eq("companyId", service.companyId)
+ .select("id")
+ .single()
]);
if (updateItem.error) return updateItem;
- return updateService;
+ if (updateService.error) return updateService;
+ return updateItem;
}
export async function upsertUnitOfMeasure(
@@ -5384,6 +5529,11 @@ export async function upsertUnitOfMeasure(
.single();
}
+/**
+ * Creates a tool (item row and tool row) or updates one; on update `id` is the
+ * item id (uuid) or the tool's readable id and the write is a full replace, so
+ * omitted optional fields are cleared.
+ */
export async function upsertTool(
client: SupabaseClient<Database>,
tool:
@@ -5393,6 +5543,7 @@ export async function upsertTool(
customFields?: Json;
})
| (z.infer<typeof toolValidator> & {
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
@@ -5472,8 +5623,15 @@ export async function upsertTool(
return newTool;
}
- const itemUpdate = {
+ const item = await resolveTypedItemForUpdate(client, {
id: tool.id,
+ companyId: tool.companyId,
+ type: "Tool"
+ });
+ if (item.error) return item;
+ const { id: itemId, readableId } = item.data;
+
+ const itemUpdate = {
name: tool.name,
description: tool.description,
replenishmentSystem: tool.replenishmentSystem,
@@ -5487,35 +5645,47 @@ export async function upsertTool(
customFields: tool.customFields
};
+ // item is keyed by uuid, tool by readableId + companyId. Each update
+ // selects its row back so a miss fails instead of reporting success.
const [updateItem, updateTool] = await Promise.all([
client
.from("item")
.update({
...sanitize(itemUpdate),
+ updatedBy: tool.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", tool.id),
+ .eq("id", itemId)
+ .eq("companyId", tool.companyId)
+ .select("id")
+ .single(),
client
.from("tool")
.update({
...sanitize(toolUpdate),
+ updatedBy: tool.updatedBy,
updatedAt: datetime.timestamp()
})
- .eq("id", tool.id)
+ .eq("id", readableId)
+ .eq("companyId", tool.companyId)
+ .select("id")
+ .single()
]);
if (updateItem.error) return updateItem;
+ if (updateTool.error) return updateTool;
const pickMethod = await upsertItemDefaultPickMethod(client, {
- itemId: tool.id,
+ itemId,
userId: tool.updatedBy,
storageUnitId: tool.defaultStorageUnitId
});
if (pickMethod.error) return pickMethod;
const shelfLife = await upsertItemShelfLife(client, {
- itemId: tool.id,
+ itemId,
userId: tool.updatedBy,
+ companyId: tool.companyId,
mode: tool.shelfLifeMode,
days: tool.shelfLifeDays,
triggerProcessId: tool.shelfLifeTriggerProcessId,
@@ -5524,7 +5694,7 @@ export async function upsertTool(
});
if (shelfLife.error) return shelfLife;
- return updateTool;
+ return updateItem;
}
/**
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 814093f103..f82180da6a 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -569,7 +569,7 @@
{"name":"items_upsertPart","classification":"WRITE","paramCount":21,"schema":"37a9a8506af0","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertPickMethod","classification":"WRITE","paramCount":5,"schema":"b14e368c85f6","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertPickMethodWithShelfLife","classification":"DESTRUCTIVE","paramCount":6,"schema":"3af3fd086443","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},
- {"name":"items_upsertService","classification":"WRITE","paramCount":19,"schema":"ca47ea7769d4","response":"245d08618b2e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
+ {"name":"items_upsertService","classification":"WRITE","paramCount":19,"schema":"ca47ea7769d4","response":"40609a62e7f3","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertSupplierPart","classification":"WRITE","paramCount":10,"schema":"4885a2836c70","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertTool","classification":"WRITE","paramCount":21,"schema":"37a9a8506af0","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertUnitOfMeasure","classification":"WRITE","paramCount":4,"schema":"e954af0763b4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.details.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.details.tsx
index 39acad474d..c0fd0a764e 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.details.tsx
@@ -21,7 +21,7 @@ import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -38,6 +38,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateConsumable = await upsertConsumable(client, {
...validation.data,
id: itemId,
+ companyId,
customFields: setCustomFields(formData),
updatedBy: userId
});
diff --git a/apps/erp/app/routes/x+/material+/$itemId.details.tsx b/apps/erp/app/routes/x+/material+/$itemId.details.tsx
index a294c59d0b..96c2826019 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.details.tsx
@@ -20,7 +20,7 @@ import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -37,6 +37,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateMaterial = await upsertMaterial(client, {
...validation.data,
id: itemId,
+ companyId,
customFields: setCustomFields(formData),
updatedBy: userId
});
diff --git a/apps/erp/app/routes/x+/part+/$itemId.details.tsx b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
index 90422ae135..482c22305a 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
@@ -166,7 +166,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -221,6 +221,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updatePart = await upsertPart(client, {
...validation.data,
id: itemId,
+ companyId,
customFields: setCustomFields(formData),
updatedBy: userId
});
diff --git a/apps/erp/app/routes/x+/service+/$itemId.details.tsx b/apps/erp/app/routes/x+/service+/$itemId.details.tsx
index 6e3eef2b2c..d773147f87 100644
--- a/apps/erp/app/routes/x+/service+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/service+/$itemId.details.tsx
@@ -92,7 +92,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -110,6 +110,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateService = await upsertService(client, {
...validation.data,
id: itemId,
+ companyId,
customFields: setCustomFields(formData),
updatedBy: userId
});
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx b/apps/erp/app/routes/x+/tool+/$itemId.details.tsx
index f59d53a0c7..0b7482ff7e 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.details.tsx
@@ -138,7 +138,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -192,6 +192,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateTool = await upsertTool(client, {
...validation.data,
id: itemId,
+ companyId,
customFields: setCustomFields(formData),
updatedBy: userId
});
diff --git a/apps/erp/test/upsert-typed-item-keys.test.ts b/apps/erp/test/upsert-typed-item-keys.test.ts
new file mode 100644
index 0000000000..5c57bc4c39
--- /dev/null
+++ b/apps/erp/test/upsert-typed-item-keys.test.ts
@@ -0,0 +1,264 @@
+import { describe, expect, it, vi } from "vitest";
+
+// The items.service graph transitively loads @carbon/glossary, whose
+// module-load-time Lingui `msg` macro isn't transformed under plain vitest.
+// Stub it; the upserts under test stay the genuine implementation.
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn()
+}));
+
+const { upsertConsumable, upsertMaterial, upsertPart, upsertService, upsertTool } =
+ await import("~/modules/items/items.service");
+
+// Pins the key resolution in the typed-item update branches. `item` is keyed
+// by uuid; part/material/tool/consumable/service are keyed by the item's
+// readableId + companyId. Filtering both tables by one id saved the item half
+// and silently matched zero typed rows (or the reverse when a readable id was
+// passed), with no error either way. Every read tool hands out the uuid, so
+// over MCP the typed fields never saved.
+
+type Call = {
+ table: string;
+ op: "select" | "update" | "insert" | "upsert" | "delete";
+ payload?: Record<string, unknown>;
+ filters: Array<[string, string, unknown]>;
+ single?: "single" | "maybeSingle";
+};
+type Response = { data: unknown; error: unknown };
+
+/** A supabase stub that records every query and answers from `respond`. */
+function makeClient(respond: (call: Call) => Response) {
+ const calls: Call[] = [];
+ const from = (table: string) => {
+ const call: Call = { table, op: "select", filters: [] };
+ let started = false;
+ const builder: Record<string, unknown> = {};
+ builder.select = () => {
+ // A select after a write is the "return the row" modifier.
+ if (!started) {
+ started = true;
+ call.op = "select";
+ }
+ return builder;
+ };
+ for (const op of ["update", "insert", "upsert", "delete"] as const) {
+ builder[op] = (payload?: Record<string, unknown>) => {
+ started = true;
+ call.op = op;
+ call.payload = payload;
+ return builder;
+ };
+ }
+ builder.eq = (column: string, value: unknown) => {
+ call.filters.push(["eq", column, value]);
+ return builder;
+ };
+ builder.in = (column: string, value: unknown) => {
+ call.filters.push(["in", column, value]);
+ return builder;
+ };
+ builder.single = () => {
+ call.single = "single";
+ return builder;
+ };
+ builder.maybeSingle = () => {
+ call.single = "maybeSingle";
+ return builder;
+ };
+ builder.then = (
+ resolve: (value: Response) => unknown,
+ reject?: (reason: unknown) => unknown
+ ) => {
+ calls.push(call);
+ return Promise.resolve(respond(call)).then(resolve, reject);
+ };
+ return builder;
+ };
+ return { client: { from } as never, calls };
+}
+
+const COMPANY = "company-1";
+const ITEM = { id: "item-uuid-1", readableId: "MAT-AL-PLATE" };
+
+/** Answers the item lookups and the two updates from fixed responses. */
+function respondWith(opts: {
+ byId?: typeof ITEM | null;
+ byReadableId?: (typeof ITEM)[];
+ itemUpdate?: Response;
+ typedUpdate?: Response;
+}) {
+ return (call: Call): Response => {
+ if (call.table === "item" && call.op === "select") {
+ const byUuid = call.filters.some(([, column]) => column === "id");
+ return byUuid
+ ? { data: opts.byId ?? null, error: null }
+ : { data: opts.byReadableId ?? [], error: null };
+ }
+ if (call.op === "update") {
+ return call.table === "item"
+ ? (opts.itemUpdate ?? { data: { id: ITEM.id }, error: null })
+ : (opts.typedUpdate ?? { data: { id: ITEM.readableId }, error: null });
+ }
+ return { data: null, error: null };
+ };
+}
+
+const base = {
+ name: "Aluminum plate",
+ replenishmentSystem: "Buy" as const,
+ defaultMethodType: "Pull from Inventory" as const,
+ itemTrackingType: "Inventory" as const,
+ unitOfMeasureCode: "EA",
+ shelfLifeCalculateFromBom: false,
+ companyId: COMPANY,
+ updatedBy: "user-1"
+};
+
+const updates = (calls: Call[]) => calls.filter((c) => c.op === "update");
+const updateOf = (calls: Call[], table: string) =>
+ updates(calls).find((c) => c.table === table);
+
+describe("typed item updates resolve uuid vs readable id", () => {
+ it("material: by item uuid writes item by uuid and material by readableId + companyId", async () => {
+ const { client, calls } = makeClient(respondWith({ byId: ITEM }));
+ const result = await upsertMaterial(client, {
+ ...base,
+ id: ITEM.id,
+ materialSubstanceId: "aluminum",
+ materialFormId: "plate",
+ gradeId: "aluminum-7075"
+ });
+ expect(result.error).toBeNull();
+
+ const item = updateOf(calls, "item");
+ expect(item?.filters).toEqual(
+ expect.arrayContaining([
+ ["eq", "id", ITEM.id],
+ ["eq", "companyId", COMPANY]
+ ])
+ );
+ expect(item?.payload).not.toHaveProperty("id");
+ expect(item?.payload).toMatchObject({ updatedBy: "user-1" });
+ expect(item?.single).toBe("single");
+
+ const material = updateOf(calls, "material");
+ expect(material?.filters).toEqual(
+ expect.arrayContaining([
+ ["eq", "id", ITEM.readableId],
+ ["eq", "companyId", COMPANY]
+ ])
+ );
+ expect(material?.payload).toMatchObject({
+ materialSubstanceId: "aluminum",
+ materialFormId: "plate",
+ gradeId: "aluminum-7075",
+ updatedBy: "user-1"
+ });
+ expect(material?.single).toBe("single");
+ });
+
+ it("material: by readable id resolves the item uuid first", async () => {
+ const { client, calls } = makeClient(
+ respondWith({ byId: null, byReadableId: [ITEM] })
+ );
+ const result = await upsertMaterial(client, {
+ ...base,
+ id: ITEM.readableId,
+ gradeId: "aluminum-7075"
+ });
+ expect(result.error).toBeNull();
+ expect(updateOf(calls, "item")?.filters).toEqual(
+ expect.arrayContaining([["eq", "id", ITEM.id]])
+ );
+ expect(updateOf(calls, "material")?.filters).toEqual(
+ expect.arrayContaining([["eq", "id", ITEM.readableId]])
+ );
+ });
+
+ it("material: an unknown id is an error and writes nothing", async () => {
+ const { client, calls } = makeClient(
+ respondWith({ byId: null, byReadableId: [] })
+ );
+ const result = await upsertMaterial(client, { ...base, id: "nope" });
+ expect(result.data).toBeNull();
+ expect(result.error).toMatchObject({
+ code: "PGRST116",
+ message: expect.stringContaining("not found")
+ });
+ expect(updates(calls)).toHaveLength(0);
+ });
+
+ it("material: a readable id shared by several revisions is refused", async () => {
+ const { client, calls } = makeClient(
+ respondWith({
+ byId: null,
+ byReadableId: [ITEM, { ...ITEM, id: "item-uuid-2" }]
+ })
+ );
+ const result = await upsertMaterial(client, {
+ ...base,
+ id: ITEM.readableId
+ });
+ expect(result.data).toBeNull();
+ expect(result.error).toMatchObject({
+ message: expect.stringContaining("revisions")
+ });
+ expect(updates(calls)).toHaveLength(0);
+ });
+
+ it("material: a missed material row surfaces as an error", async () => {
+ const { client } = makeClient(
+ respondWith({
+ byId: ITEM,
+ typedUpdate: { data: null, error: { code: "PGRST116" } }
+ })
+ );
+ const result = await upsertMaterial(client, { ...base, id: ITEM.id });
+ expect(result.error).toMatchObject({ code: "PGRST116" });
+ });
+
+ it.each([
+ ["part", upsertPart],
+ ["tool", upsertTool],
+ ["consumable", upsertConsumable],
+ ["service", upsertService]
+ ] as const)(
+ "%s: the typed row is keyed by readableId + companyId",
+ async (table, upsert) => {
+ const { client, calls } = makeClient(respondWith({ byId: ITEM }));
+ // The service validator narrows tracking to Non-Inventory; the payload
+ // has to satisfy all four signatures at once.
+ const result = await upsert(client, {
+ ...base,
+ id: ITEM.id,
+ itemTrackingType: "Non-Inventory" as const,
+ revision: "0",
+ customFields: { colour: "red" }
+ });
+ expect(result.error).toBeNull();
+
+ const typed = updateOf(calls, table);
+ expect(typed?.filters).toEqual(
+ expect.arrayContaining([
+ ["eq", "id", ITEM.readableId],
+ ["eq", "companyId", COMPANY]
+ ])
+ );
+ expect(typed?.payload).toMatchObject({ customFields: { colour: "red" } });
+ expect(typed?.single).toBe("single");
+
+ const item = updateOf(calls, "item");
+ expect(item?.filters).toEqual(
+ expect.arrayContaining([
+ ["eq", "id", ITEM.id],
+ ["eq", "companyId", COMPANY]
+ ])
+ );
+ expect(item?.payload).not.toHaveProperty("id");
+ }
+ );
+});