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): ignore a sent name under generated material IDs; share the typed item update

Raul5e9222b6d7e9
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 5eafc72e55..533728c2ec 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2316,3 +2316,38 @@ attacker reads it: `SET LOCAL ROLE anon; SELECT count(*) FROM "view";` must be 0
**Applies to:** `packages/database/supabase/migrations/**`; enforced by the
`no-view-without-invoker` conformance check and the `view-without-security-invoker` invariant.
+
+## A PostgREST update that matches no row reports success
+
+**Context:** Typed item updates (`upsertPart`, `upsertTool`, `upsertConsumable`,
+`upsertService`, `upsertMaterial`) filtered the typed table by the item's uuid,
+but those tables are keyed by the item's readable id plus `companyId`.
+
+**Problem:** `client.from(t).update(...).eq(...)` with no `.select()` returns
+`{ error: null }` when it matches zero rows. Half of every typed update wrote
+nothing, and the API and MCP reported success.
+
+**Rule:** An update whose miss is a bug ends with `.select("id").single()`, so
+a miss comes back as an error. Key each table by its own primary key: `item`
+by uuid, the typed tables by `readableId` + `companyId`
+(`resolveTypedItem` / `updateTypedItem` in `items.service.ts`).
+
+**Applies to:** any supabase-js update in a service, above all one that writes
+a pair of tables keyed differently.
+
+## A Kysely write needs its own RLS gate
+
+**Context:** Material property edits write the material row, every revision's
+item row and `itemCost` in one Kysely transaction.
+
+**Problem:** Kysely connects as the Postgres role and bypasses RLS, so a caller
+without `parts_update` in the company, or naming another company's material,
+would still write.
+
+**Rule:** Before a Kysely transaction on rows a caller names, run one UPDATE
+through the caller's supabase client, filtered by id and `companyId`, with
+`.select().single()`, and stop on its error (`requireMaterialUpdatable`). Pick
+a row whose policy also covers the other rows the transaction writes.
+
+**Applies to:** any service that takes both `client` and `db` and writes with
+`db` on behalf of an API or MCP caller.
diff --git a/.claude/rules/material-tables.md b/.claude/rules/material-tables.md
index 557ffe6dbc..b36fcda0e1 100644
--- a/.claude/rules/material-tables.md
+++ b/.claude/rules/material-tables.md
@@ -103,10 +103,15 @@ the service loads the rows they read and writes what they decide.
an UPDATE through the caller's client (material's policy is parts_update in the company, which
also grants the item and itemCost rows). A taken readable id is refused on rename and on create.
- `upsertMaterial` updates write only the keys present on the payload (a present-but-undefined key,
- a cleared form field, clears); `active` is never touched; `postingGroupId`/`unitCost` go to
+ a cleared form field, clears). The MCP schema requires `name`, `replenishmentSystem`,
+ `defaultMethodType`, `itemTrackingType` and `unitOfMeasureCode`, so those are always sent. With
+ `materialGeneratedIds` on, a sent `name` is ignored (`materialItemUpdateFields`): the name is
+ derived and written to every revision. `active` is never touched; `postingGroupId`/`unitCost` go to
`itemCost`; `readableId` renames when ids are hand-typed; `sizes` adds a revision per new size
via `createRevision` after the transaction, refused before any write while the material is open
- in a change notice.
+ in a change notice. The pick method and shelf life are also written after the transaction, so a
+ failure there leaves the transaction's writes in place. An update by readable id is refused when
+ the material has several revisions (sizes are revisions); pass the item id.
- `materialDimension`, `materialFinish`, `materialGrade` and `materialType` have no audit columns,
so their MCP tools inject only `companyId` (`INJECT_AUTH_OVERRIDES` in
`scripts/lib/service-metadata.ts`). Their update branch filters by `companyId` when given and
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.md
index ce063ff56b..526a4ec452 100644
--- a/apps/erp/app/modules/items/AGENTS.md
+++ b/apps/erp/app/modules/items/AGENTS.md
@@ -62,7 +62,8 @@ pnpm --filter @carbon/erp test
- `getItem` / `getPart` / `getMaterial` / `getConsumable` / `getTool` / `getService` — item reads by type (RPCs `get_part_details`, `get_material_details`, `get_service_details`, etc.)
- `upsertService` — creates/updates a Service item; always `itemTrackingType = 'Non-Inventory'` (never shipped/received/stocked), replenishment `Buy` or `Make` only. The `service` row is keyed by `item.readableId` (like tool/material). Legacy `service.serviceType` is defaulted and no longer read.
-- `upsertMaterial(client, db, material)` — creates/updates material with taxonomy FKs and `item`/`material` linkage; an update writes only the keys sent and never touches `active`
+- `upsertPart` / `upsertTool` / `upsertConsumable` / `upsertService` — an update takes `companyId` and an `id` that is the item uuid or the readable id; it writes the item row by uuid and the typed row by `readableId + companyId` (`updateTypedItem`), and an update that matches no row returns an error. A readable id shared by several revisions is refused.
+- `upsertMaterial(client, db, material)` — creates/updates material with taxonomy FKs and `item`/`material` linkage; an update writes only the keys sent and never touches `active`. Over MCP `name`, `replenishmentSystem`, `defaultMethodType`, `itemTrackingType` and `unitOfMeasureCode` are required, so they are always sent; with generated material IDs a sent `name` is ignored
- `updateMaterialProperties(client, db, material)` — the one path for substance/form/type/finish/grade/dimension changes (properties panel, `upsertMaterial`, MCP): dependent resets, pick-list checks, generated-ID renames in one transaction. See `.claude/rules/material-tables.md`
- `getMakeMethods` / `getMethodMaterials` / `getMethodOperations` / `getMethodTreeArray` — BOM/routing reads
- `copyItem` / `copyMakeMethod` — duplicates via edge function
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index b7eddd5a24..e945842881 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -94,7 +94,7 @@ import {
generateMaterialIdentity,
type MaterialPropertyLookups,
type MaterialPropertyValues,
- materialPropertyFields,
+ materialItemUpdateFields,
noMaterialProperties,
resolveMaterialProperties,
sentFields,
@@ -3321,15 +3321,17 @@ async function cascadeSourcingAndMethodTypeToMethodMaterials(
.execute();
}
+type ServiceError = PostgrestError | { message: string; code?: string };
+
/**
- * 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.
+ * Resolves the typed item (part, material, tool, consumable, service) an
+ * update 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 uuid names one revision; a readable id
+ * names every revision that shares it.
*/
-async function resolveTypedItemForUpdate(
+async function resolveTypedItem(
client: SupabaseClient<Database>,
args: {
id: string;
@@ -3337,8 +3339,8 @@ async function resolveTypedItemForUpdate(
type: Database["public"]["Enums"]["itemType"];
}
): Promise<
- | { data: { id: string; readableId: string }; error: null }
- | { data: null; error: PostgrestError | { message: string; code?: string } }
+ | { data: { readableId: string; itemIds: string[] }; error: null }
+ | { data: null; error: ServiceError }
> {
const byId = await client
.from("item")
@@ -3348,34 +3350,115 @@ async function resolveTypedItemForUpdate(
.eq("type", args.type)
.maybeSingle();
if (byId.error) return { data: null, error: byId.error };
- if (byId.data) return { data: byId.data, error: null };
+ if (byId.data) {
+ return {
+ data: { readableId: byId.data.readableId, itemIds: [byId.data.id] },
+ error: null
+ };
+ }
const byReadableId = await client
.from("item")
- .select("id, readableId")
+ .select("id")
.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 === 0) {
+ return {
+ data: null,
+ error: ruleError(`${args.type} ${args.id} not found`)
+ };
}
- if (byReadableId.data.length > 1) {
+ return {
+ data: {
+ readableId: args.id,
+ itemIds: byReadableId.data.map((item) => item.id)
+ },
+ error: null
+ };
+}
+
+/** resolveTypedItem for a write to one revision's item row. */
+async function resolveTypedItemRevision(
+ client: SupabaseClient<Database>,
+ args: {
+ id: string;
+ companyId: string;
+ type: Database["public"]["Enums"]["itemType"];
+ }
+): Promise<
+ | { data: { id: string; readableId: string }; error: null }
+ | { data: null; error: ServiceError }
+> {
+ const item = await resolveTypedItem(client, args);
+ if (item.error) return item;
+ const { readableId, itemIds } = item.data;
+ if (itemIds.length > 1) {
return {
data: null,
error: ruleError(
- `${args.type} ${args.id} has ${byReadableId.data.length} revisions; pass the item id of the revision to update`
+ `${args.type} ${args.id} has ${itemIds.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` }
- };
+ return { data: { id: itemIds[0], readableId }, error: null };
+}
+
+/**
+ * The update half of upsertPart / upsertTool / upsertConsumable /
+ * upsertService: resolves the item, then writes the item row and the typed
+ * row. Each write selects its row back so a miss fails instead of reporting
+ * success.
+ */
+async function updateTypedItem(
+ client: SupabaseClient<Database>,
+ args: {
+ id: string;
+ companyId: string;
+ updatedBy: string;
+ type: "Part" | "Tool" | "Consumable" | "Service";
+ item: Database["public"]["Tables"]["item"]["Update"];
+ typed: { customFields?: Json };
+ }
+): Promise<
+ | { data: { id: string; readableId: string }; error: null }
+ | { data: null; error: ServiceError }
+> {
+ const resolved = await resolveTypedItemRevision(client, args);
+ if (resolved.error) return resolved;
+ const { id: itemId, readableId } = resolved.data;
+
+ const table = typedItemTables[args.type];
+ const audit = { updatedBy: args.updatedBy, updatedAt: datetime.timestamp() };
+ const [itemWrite, typedWrite] = await Promise.all([
+ client
+ .from("item")
+ .update({ ...sanitize(args.item), ...audit })
+ .eq("id", itemId)
+ .eq("companyId", args.companyId)
+ .select("id")
+ .single(),
+ client
+ .from(table)
+ .update({ ...sanitize(args.typed), ...audit })
+ .eq("id", readableId)
+ .eq("companyId", args.companyId)
+ .select("id")
+ .single()
+ ]);
+ if (itemWrite.error) return { data: null, error: itemWrite.error };
+ if (typedWrite.error) return { data: null, error: typedWrite.error };
+ return resolved;
}
+const typedItemTables = {
+ Part: "part",
+ Tool: "tool",
+ Consumable: "consumable",
+ Service: "service"
+} as const;
+
/**
* 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
@@ -3468,57 +3551,24 @@ export async function upsertConsumable(
return newConsumable;
}
- const item = await resolveTypedItemForUpdate(client, {
+ const updated = await updateTypedItem(client, {
id: consumable.id,
companyId: consumable.companyId,
- type: "Consumable"
+ updatedBy: consumable.updatedBy,
+ type: "Consumable",
+ item: {
+ name: consumable.name,
+ description: consumable.description,
+ replenishmentSystem: consumable.replenishmentSystem,
+ defaultMethodType: consumable.defaultMethodType,
+ itemTrackingType: consumable.itemTrackingType,
+ unitOfMeasureCode: consumable.unitOfMeasureCode,
+ active: true
+ },
+ typed: { customFields: consumable.customFields }
});
- if (item.error) return item;
- const { id: itemId, readableId } = item.data;
-
- const itemUpdate = {
- name: consumable.name,
- description: consumable.description,
- replenishmentSystem: consumable.replenishmentSystem,
- defaultMethodType: consumable.defaultMethodType,
- itemTrackingType: consumable.itemTrackingType,
- unitOfMeasureCode: consumable.unitOfMeasureCode,
- active: true
- };
-
- const consumableUpdate = {
- 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", itemId)
- .eq("companyId", consumable.companyId)
- .select("id")
- .single(),
- client
- .from("consumable")
- .update({
- ...sanitize(consumableUpdate),
- updatedBy: consumable.updatedBy,
- updatedAt: datetime.timestamp()
- })
- .eq("id", readableId)
- .eq("companyId", consumable.companyId)
- .select("id")
- .single()
- ]);
-
- if (updateItem.error) return updateItem;
- if (updateConsumable.error) return updateConsumable;
+ if (updated.error) return updated;
+ const itemId = updated.data.id;
const pickMethod = await upsertItemDefaultPickMethod(client, {
itemId,
@@ -3539,7 +3589,7 @@ export async function upsertConsumable(
});
if (shelfLife.error) return shelfLife;
- return updateItem;
+ return updated;
}
/**
@@ -3793,57 +3843,24 @@ export async function upsertPart(
return newPart;
}
- const item = await resolveTypedItemForUpdate(client, {
+ const updated = await updateTypedItem(client, {
id: part.id,
companyId: part.companyId,
- type: "Part"
+ updatedBy: part.updatedBy,
+ type: "Part",
+ item: {
+ name: part.name,
+ description: part.description,
+ replenishmentSystem: part.replenishmentSystem,
+ defaultMethodType: part.defaultMethodType,
+ itemTrackingType: part.itemTrackingType,
+ unitOfMeasureCode: part.unitOfMeasureCode,
+ active: true
+ },
+ typed: { customFields: part.customFields }
});
- if (item.error) return item;
- const { id: itemId, readableId } = item.data;
-
- const itemUpdate = {
- name: part.name,
- description: part.description,
- replenishmentSystem: part.replenishmentSystem,
- defaultMethodType: part.defaultMethodType,
- itemTrackingType: part.itemTrackingType,
- unitOfMeasureCode: part.unitOfMeasureCode,
- active: true
- };
-
- const partUpdate = {
- 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", itemId)
- .eq("companyId", part.companyId)
- .select("id")
- .single(),
- client
- .from("part")
- .update({
- ...sanitize(partUpdate),
- updatedBy: part.updatedBy,
- updatedAt: datetime.timestamp()
- })
- .eq("id", readableId)
- .eq("companyId", part.companyId)
- .select("id")
- .single()
- ]);
-
- if (updateItem.error) return updateItem;
- if (updatePart.error) return updatePart;
+ if (updated.error) return updated;
+ const itemId = updated.data.id;
const pickMethod = await upsertItemDefaultPickMethod(client, {
itemId,
@@ -3864,7 +3881,7 @@ export async function upsertPart(
});
if (shelfLife.error) return shelfLife;
- return updateItem;
+ return updated;
}
export async function updateItem(
@@ -4911,12 +4928,11 @@ export async function setMethodOperationToolStepLink(
}
type MaterialPropertyPlan = {
+ next: MaterialPropertyValues;
changed: Partial<MaterialPropertyValues>;
generated: { readableId: string; name: string } | null;
};
-type ServiceError = PostgrestError | { message: string; code?: string };
-
async function materialIdsAreGenerated(
client: SupabaseClient<Database>,
companyId: string
@@ -4942,21 +4958,17 @@ async function getMaterialPropertyValues(
> {
const material = await client
.from("material")
- .select(materialPropertyFields.join(", "))
+ .select(
+ "materialSubstanceId, materialFormId, materialTypeId, finishId, gradeId, dimensionId"
+ )
.eq("id", readableId)
.eq("companyId", companyId)
.maybeSingle();
if (material.error) return { data: null, error: material.error };
if (!material.data) {
- return {
- data: null,
- error: { code: "PGRST116", message: `Material ${readableId} not found` }
- };
+ return { data: null, error: ruleError(`Material ${readableId} not found`) };
}
- return {
- data: material.data as unknown as MaterialPropertyValues,
- error: null
- };
+ return { data: material.data, error: null };
}
async function getMaterialPropertyLookups(
@@ -5055,7 +5067,7 @@ async function planMaterialPropertyChanges(
args.changes
);
if (Object.keys(changed).length === 0) {
- return { data: { changed, generated: null }, error: null };
+ return { data: { next, changed, generated: null }, error: null };
}
if (args.generatedIds && clearsSubstanceOrShape(args.current, next)) {
return { data: null, error: ruleError(generatedIdsNeedSubstanceAndShape) };
@@ -5073,6 +5085,7 @@ async function planMaterialPropertyChanges(
return {
data: {
+ next,
changed,
generated: args.generatedIds
? generateMaterialIdentity(next, lookups.data)
@@ -5247,9 +5260,10 @@ async function getNewMaterialSizes(
* Property changes follow updateMaterialProperties: dependents reset, picks
* are checked against their substance and shape, and with generated material
* IDs on the readable id and name are derived from the properties (any `id`
- * or `name` sent for them is replaced). `readableId` renames a material when
+ * or `name` sent for them is ignored). `readableId` renames a material when
* IDs are typed by hand. An update's material, item and item cost writes land
- * together or not at all.
+ * together or not at all; the pick method, shelf life and new sizes are
+ * written after them.
*/
export async function upsertMaterial(
client: SupabaseClient<Database>,
@@ -5447,7 +5461,7 @@ export async function upsertMaterial(
}
const { companyId, updatedBy } = material;
- const item = await resolveTypedItemForUpdate(client, {
+ const item = await resolveTypedItemRevision(client, {
id: material.id,
companyId,
type: "Material"
@@ -5484,16 +5498,10 @@ export async function upsertMaterial(
newSizes = sizes.data;
}
- const itemUpdate = sentFields(material, [
- "name",
- "description",
- "mpn",
- "replenishmentSystem",
- "defaultMethodType",
- "itemTrackingType",
- "unitOfMeasureCode"
- ]);
- if (plan.data.generated) itemUpdate.name = plan.data.generated.name;
+ const itemUpdate = sentFields(
+ material,
+ materialItemUpdateFields(generatedIds.data)
+ );
const costUpdate: { itemPostingGroupId?: string | null; unitCost?: number } =
{};
@@ -5625,15 +5633,13 @@ export async function updateMaterialProperties(
) {
const { companyId, updatedBy } = material;
- const item = await client
- .from("item")
- .select("readableId")
- .eq("id", material.id)
- .eq("companyId", companyId)
- .eq("type", "Material")
- .maybeSingle();
+ const item = await resolveTypedItem(client, {
+ id: material.id,
+ companyId,
+ type: "Material"
+ });
if (item.error) return item;
- let readableId = item.data?.readableId ?? material.id;
+ let readableId = item.data.readableId;
const [current, generatedIds] = await Promise.all([
getMaterialPropertyValues(client, readableId, companyId),
@@ -5681,10 +5687,8 @@ export async function updateMaterialProperties(
.eq("companyId", companyId)
.single();
if (row.error) return row;
- return {
- data: { ...row.data, ...current.data, ...plan.data.changed },
- error: null
- };
+ // The view names finish, grade, dimension and type but has no ids for them.
+ return { data: { ...row.data, ...plan.data.next }, error: null };
}
/**
@@ -6011,58 +6015,23 @@ export async function upsertService(
return newService;
}
- const item = await resolveTypedItemForUpdate(client, {
+ const updated = await updateTypedItem(client, {
id: service.id,
companyId: service.companyId,
- type: "Service"
+ updatedBy: service.updatedBy,
+ type: "Service",
+ item: {
+ name: service.name,
+ description: service.description,
+ replenishmentSystem: service.replenishmentSystem,
+ defaultMethodType: service.defaultMethodType,
+ itemTrackingType: "Non-Inventory",
+ unitOfMeasureCode: service.unitOfMeasureCode,
+ active: true
+ },
+ typed: { customFields: service.customFields }
});
- if (item.error) return item;
- const { id: itemId, readableId } = item.data;
-
- const itemUpdate = {
- name: service.name,
- description: service.description,
- replenishmentSystem: service.replenishmentSystem,
- defaultMethodType: service.defaultMethodType,
- itemTrackingType: "Non-Inventory" as const,
- unitOfMeasureCode: service.unitOfMeasureCode,
- active: true
- };
-
- const serviceUpdate = {
- 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", itemId)
- .eq("companyId", service.companyId)
- .select("id")
- .single(),
- client
- .from("service")
- .update({
- ...sanitize(serviceUpdate),
- updatedBy: service.updatedBy,
- updatedAt: datetime.timestamp()
- })
- .eq("id", readableId)
- .eq("companyId", service.companyId)
- .select("id")
- .single()
- ]);
-
- if (updateItem.error) return updateItem;
- if (updateService.error) return updateService;
- return updateItem;
+ return updated;
}
export async function upsertUnitOfMeasure(
@@ -6189,57 +6158,24 @@ export async function upsertTool(
return newTool;
}
- const item = await resolveTypedItemForUpdate(client, {
+ const updated = await updateTypedItem(client, {
id: tool.id,
companyId: tool.companyId,
- type: "Tool"
+ updatedBy: tool.updatedBy,
+ type: "Tool",
+ item: {
+ name: tool.name,
+ description: tool.description,
+ replenishmentSystem: tool.replenishmentSystem,
+ defaultMethodType: tool.defaultMethodType,
+ itemTrackingType: tool.itemTrackingType,
+ unitOfMeasureCode: tool.unitOfMeasureCode,
+ active: true
+ },
+ typed: { customFields: tool.customFields }
});
- if (item.error) return item;
- const { id: itemId, readableId } = item.data;
-
- const itemUpdate = {
- name: tool.name,
- description: tool.description,
- replenishmentSystem: tool.replenishmentSystem,
- defaultMethodType: tool.defaultMethodType,
- itemTrackingType: tool.itemTrackingType,
- unitOfMeasureCode: tool.unitOfMeasureCode,
- active: true
- };
-
- const toolUpdate = {
- 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", itemId)
- .eq("companyId", tool.companyId)
- .select("id")
- .single(),
- client
- .from("tool")
- .update({
- ...sanitize(toolUpdate),
- updatedBy: tool.updatedBy,
- updatedAt: datetime.timestamp()
- })
- .eq("id", readableId)
- .eq("companyId", tool.companyId)
- .select("id")
- .single()
- ]);
-
- if (updateItem.error) return updateItem;
- if (updateTool.error) return updateTool;
+ if (updated.error) return updated;
+ const itemId = updated.data.id;
const pickMethod = await upsertItemDefaultPickMethod(client, {
itemId,
@@ -6260,7 +6196,7 @@ export async function upsertTool(
});
if (shelfLife.error) return shelfLife;
- return updateItem;
+ return updated;
}
/**
diff --git a/apps/erp/app/modules/items/material-properties.ts b/apps/erp/app/modules/items/material-properties.ts
index 38cb064037..31d828e871 100644
--- a/apps/erp/app/modules/items/material-properties.ts
+++ b/apps/erp/app/modules/items/material-properties.ts
@@ -50,24 +50,49 @@ export const generatedIdsNeedSubstanceAndShape =
* cleared form field) counts as sent and clears; an absent key (an API caller
* editing some fields) is left alone.
*/
-export function sentFields<K extends string>(
- source: object,
+export function sentFields<T extends object, K extends keyof T & string>(
+ source: T,
fields: readonly K[]
-): Partial<Record<K, any>> {
- const sent: Partial<Record<K, any>> = {};
+): SentFields<T, K> {
+ const sent: SentFields<T, K> = {};
for (const field of fields) {
if (field in source) {
- sent[field] = (source as Record<string, unknown>)[field] ?? null;
+ sent[field] = (source[field] ?? null) as SentFields<T, K>[K];
}
}
return sent;
}
+/** A sent field that may be undefined arrives as null, which clears it. */
+export type SentFields<T, K extends keyof T> = {
+ [P in K]?: undefined extends T[P] ? Exclude<T[P], undefined> | null : T[P];
+};
+
+/**
+ * The item columns a material update copies from its payload. With generated
+ * IDs the name is derived from the properties and written to every revision,
+ * so a sent name is ignored.
+ */
+export function materialItemUpdateFields(generatedIds: boolean) {
+ return [
+ ...(generatedIds ? [] : (["name"] as const)),
+ "description",
+ "mpn",
+ "replenishmentSystem",
+ "defaultMethodType",
+ "itemTrackingType",
+ "unitOfMeasureCode"
+ ] as const;
+}
+
/** sentFields for the property ids, where an empty string clears like null. */
export function sentMaterialProperties(
- source: object
+ source: Partial<Record<MaterialPropertyField, string | null>>
): Partial<MaterialPropertyValues> {
- const sent = sentFields(source, materialPropertyFields);
+ const sent: Partial<MaterialPropertyValues> = sentFields(
+ source,
+ materialPropertyFields
+ );
for (const field of materialPropertyFields) {
if (sent[field] === "") sent[field] = null;
}
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 a23e1e65d9..a9f323345e 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
@@ -570,7 +570,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":"40609a62e7f3","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
+ {"name":"items_upsertService","classification":"WRITE","paramCount":19,"schema":"ca47ea7769d4","response":"87c54a97c0fa","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/test/material-properties.test.ts b/apps/erp/test/material-properties.test.ts
index 5d97b20631..989e9e71cf 100644
--- a/apps/erp/test/material-properties.test.ts
+++ b/apps/erp/test/material-properties.test.ts
@@ -3,6 +3,7 @@ import {
checkMaterialProperties,
clearsSubstanceOrShape,
generateMaterialIdentity,
+ materialItemUpdateFields,
type MaterialPropertyLookups,
type MaterialPropertyValues,
noMaterialProperties,
@@ -185,6 +186,11 @@ describe("generated material IDs", () => {
).toBeNull();
});
+ it("ignores a sent name, which is derived instead", () => {
+ expect(materialItemUpdateFields(true)).not.toContain("name");
+ expect(materialItemUpdateFields(false)).toContain("name");
+ });
+
it("refuses clearing a substance or shape that is set, not setting one", () => {
expect(
clearsSubstanceOrShape(ALUMINUM_PLATE, {
@@ -203,15 +209,14 @@ describe("generated material IDs", () => {
describe("sentMaterialProperties", () => {
it("absent keeps, undefined, null and empty string clear", () => {
- expect(
- sentMaterialProperties({
- gradeId: undefined,
- finishId: null,
- dimensionId: "",
- materialFormId: "plate",
- name: "ignored"
- })
- ).toEqual({
+ const payload = {
+ gradeId: undefined,
+ finishId: null,
+ dimensionId: "",
+ materialFormId: "plate",
+ name: "ignored"
+ };
+ expect(sentMaterialProperties(payload)).toEqual({
gradeId: null,
finishId: null,
dimensionId: null,