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): material edits over MCP follow the properties panel's rules

Raul8d11c46344fd
diff --git a/.claude/rules/material-tables.md b/.claude/rules/material-tables.md
index 5edc35f170..394cc36013 100644
--- a/.claude/rules/material-tables.md
+++ b/.claude/rules/material-tables.md
@@ -69,8 +69,9 @@ RLS lets authenticated users read global rows and employees read their company's
A material is an `item` of `type = 'Material'`. `material.id` is set to the item's `readableId`,
**not** the item's `id`. Creating a material inserts the `item` row(s) first then the `material` row
with the shared id — see `upsertMaterial` in
-`apps/erp/app/modules/items/items.service.ts` (`readableId: material.id`, then
-`client.from("material").upsert({ id: material.id, ... })`). Because the join is on `readableId`,
+`apps/erp/app/modules/items/items.service.ts` (the readable id is `material.id`, or the id derived
+from the properties when `companySettings.materialGeneratedIds` is on, then
+`client.from("material").upsert({ id: readableId, ... })`). Because the join is on `readableId`,
one material can have multiple item **revisions** (and per-size item rows); the `materials` view
de-dupes to the latest item per `(readableId, companyId)` and aggregates the revisions.
@@ -78,6 +79,30 @@ de-dupes to the latest item per `(readableId, companyId)` and aggregates the rev
`20250721101110` and `20250725140205_material-details.sql` migrations). There is also
`get_material_naming_details(readable_id)` (builds the readable name/code from the taxonomy).
+## Editing properties
+
+`updateMaterialProperties(client, db, material)` is the one path for substance, form, type,
+finish, grade and dimension changes: the properties panel (`x+/items+/update.tsx`),
+`upsertMaterial`'s update branch and MCP all go through its helpers.
+
+- A new substance clears finish, grade and type; a new form clears dimension and type; unless the
+ same call sets them. This mirrors the panel's cascading pickers.
+- Grade and finish must belong to the substance, dimension to the form, type to both
+ (`checkMaterialProperties`). Only a value the call changes, or whose parent changed, is checked,
+ so an unrelated edit never fails on older data.
+- With `materialGeneratedIds` on, substance and form are required and the readable id and name are
+ derived with `getMaterialId` / `getMaterialDescription` (`@carbon/utils`) from the resolved
+ properties, on create and on every property change. The rename of the material row and every
+ revision's item row runs in one Kysely transaction (`saveMaterialIdentity`), which refuses an id
+ another material already has.
+- `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
+ `itemCost`; `readableId` renames when ids are hand-typed; `sizes` adds a revision per new size via
+ `createRevision`, refused while the material is open in a change notice.
+- `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`).
+
## Code map
- Service: `apps/erp/app/modules/items/items.service.ts` — `getMaterial`, `getMaterials`
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.md
index 193554328b..ce063ff56b 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` — creates/updates material with taxonomy FKs and `item`/`material` linkage
+- `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`
+- `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
- `createRevision` / `activateMethodVersion` — revision and version management
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 693d7c951b..160c80e46a 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -8,7 +8,7 @@ import type {
} from "@carbon/database/client";
import { storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
-import { datetime } from "@carbon/utils";
+import { datetime, getMaterialDescription, getMaterialId } from "@carbon/utils";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type { z } from "zod";
@@ -4897,13 +4897,481 @@ export async function setMethodOperationToolStepLink(
.eq("methodOperationStepId", args.methodOperationStepId);
}
+const materialPropertyFields = [
+ "materialSubstanceId",
+ "materialFormId",
+ "materialTypeId",
+ "finishId",
+ "gradeId",
+ "dimensionId"
+] as const;
+
+type MaterialPropertyField = (typeof materialPropertyFields)[number];
+type MaterialPropertyValues = Record<MaterialPropertyField, string | null>;
+
+type MaterialPropertyPlan = {
+ changed: Partial<MaterialPropertyValues>;
+ generated: { readableId: string; name: string } | null;
+};
+
+type ServiceError = PostgrestError | { message: string; code?: string };
+
+const noMaterialProperties: MaterialPropertyValues = {
+ materialSubstanceId: null,
+ materialFormId: null,
+ materialTypeId: null,
+ finishId: null,
+ gradeId: null,
+ dimensionId: null
+};
+
+/**
+ * The `fields` present on `source`. A present key holding undefined (a
+ * cleared form field) counts as sent and clears; an absent key (an API caller
+ * editing some fields) is left alone.
+ */
+function sentFields<K extends string>(
+ source: object,
+ fields: readonly K[]
+): Partial<Record<K, any>> {
+ const sent: Partial<Record<K, any>> = {};
+ for (const field of fields) {
+ if (field in source) {
+ sent[field] = (source as Record<string, unknown>)[field] ?? null;
+ }
+ }
+ return sent;
+}
+
+async function materialIdsAreGenerated(
+ client: SupabaseClient<Database>,
+ companyId: string
+): Promise<
+ { data: boolean; error: null } | { data: null; error: ServiceError }
+> {
+ const settings = await client
+ .from("companySettings")
+ .select("materialGeneratedIds")
+ .eq("id", companyId)
+ .single();
+ if (settings.error) return { data: null, error: settings.error };
+ return { data: settings.data.materialGeneratedIds === true, error: null };
+}
+
+async function getMaterialPropertyValues(
+ client: SupabaseClient<Database>,
+ readableId: string,
+ companyId: string
+): Promise<
+ | { data: MaterialPropertyValues; error: null }
+ | { data: null; error: ServiceError }
+> {
+ const material = await client
+ .from("material")
+ .select(materialPropertyFields.join(", "))
+ .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: material.data as unknown as MaterialPropertyValues,
+ error: null
+ };
+}
+
+/**
+ * Loads the name, code and parent of each property value set on a material.
+ * System rows (companyId null) count alongside the company's own.
+ */
+async function getMaterialPropertyLookups(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ values: MaterialPropertyValues
+) {
+ const visible = `companyId.eq.${companyId},companyId.is.null`;
+ const none = { data: null, error: null };
+ const [substance, form, type, finish, grade, dimension] = await Promise.all([
+ values.materialSubstanceId
+ ? client
+ .from("materialSubstance")
+ .select("name, code")
+ .eq("id", values.materialSubstanceId)
+ .or(visible)
+ .maybeSingle()
+ : none,
+ values.materialFormId
+ ? client
+ .from("materialForm")
+ .select("name, code")
+ .eq("id", values.materialFormId)
+ .or(visible)
+ .maybeSingle()
+ : none,
+ values.materialTypeId
+ ? client
+ .from("materialType")
+ .select("name, code, materialSubstanceId, materialFormId")
+ .eq("id", values.materialTypeId)
+ .or(visible)
+ .maybeSingle()
+ : none,
+ values.finishId
+ ? client
+ .from("materialFinish")
+ .select("name, materialSubstanceId")
+ .eq("id", values.finishId)
+ .or(visible)
+ .maybeSingle()
+ : none,
+ values.gradeId
+ ? client
+ .from("materialGrade")
+ .select("name, materialSubstanceId")
+ .eq("id", values.gradeId)
+ .or(visible)
+ .maybeSingle()
+ : none,
+ values.dimensionId
+ ? client
+ .from("materialDimension")
+ .select("name, materialFormId")
+ .eq("id", values.dimensionId)
+ .or(visible)
+ .maybeSingle()
+ : none
+ ]);
+
+ const error = [substance, form, type, finish, grade, dimension].find(
+ (result) => result.error
+ )?.error;
+ if (error) return { data: null, error };
+
+ return {
+ data: {
+ substance: substance.data,
+ form: form.data,
+ type: type.data,
+ finish: finish.data,
+ grade: grade.data,
+ dimension: dimension.data
+ },
+ error: null
+ };
+}
+
+type MaterialPropertyLookups = NonNullable<
+ Awaited<ReturnType<typeof getMaterialPropertyLookups>>["data"]
+>;
+
+/**
+ * The property panel's pickers as rules: grade and finish come from the
+ * substance's list, dimension from the shape's, and type from the pair's.
+ * Only checks a value that is new or whose parent changed, so an unrelated
+ * edit never trips over an older inconsistency.
+ */
+function checkMaterialProperties(
+ current: MaterialPropertyValues,
+ next: MaterialPropertyValues,
+ lookups: MaterialPropertyLookups
+): string | null {
+ const substanceChanged =
+ next.materialSubstanceId !== current.materialSubstanceId;
+ const formChanged = next.materialFormId !== current.materialFormId;
+ const touched = (field: MaterialPropertyField, parentChanged: boolean) =>
+ next[field] !== null && (next[field] !== current[field] || parentChanged);
+
+ if (touched("materialSubstanceId", false) && !lookups.substance) {
+ return `Substance ${next.materialSubstanceId} not found`;
+ }
+ if (touched("materialFormId", false) && !lookups.form) {
+ return `Shape ${next.materialFormId} not found`;
+ }
+ if (touched("gradeId", substanceChanged)) {
+ if (!lookups.grade) return `Grade ${next.gradeId} not found`;
+ if (lookups.grade.materialSubstanceId !== next.materialSubstanceId) {
+ return `Grade ${next.gradeId} is not a grade of substance ${next.materialSubstanceId ?? "(none)"}`;
+ }
+ }
+ if (touched("finishId", substanceChanged)) {
+ if (!lookups.finish) return `Finish ${next.finishId} not found`;
+ if (lookups.finish.materialSubstanceId !== next.materialSubstanceId) {
+ return `Finish ${next.finishId} is not a finish of substance ${next.materialSubstanceId ?? "(none)"}`;
+ }
+ }
+ if (touched("dimensionId", formChanged)) {
+ if (!lookups.dimension) return `Dimension ${next.dimensionId} not found`;
+ if (lookups.dimension.materialFormId !== next.materialFormId) {
+ return `Dimension ${next.dimensionId} is not a dimension of shape ${next.materialFormId ?? "(none)"}`;
+ }
+ }
+ if (touched("materialTypeId", substanceChanged || formChanged)) {
+ if (!lookups.type) return `Type ${next.materialTypeId} not found`;
+ if (
+ lookups.type.materialSubstanceId !== next.materialSubstanceId ||
+ lookups.type.materialFormId !== next.materialFormId
+ ) {
+ return `Type ${next.materialTypeId} is not a type of substance ${next.materialSubstanceId ?? "(none)"} and shape ${next.materialFormId ?? "(none)"}`;
+ }
+ }
+ return null;
+}
+
+/**
+ * Resolves and checks a set of property changes without writing anything.
+ * Mirrors the properties panel: a new substance clears finish, grade and type,
+ * and a new shape clears dimension and type, unless `changes` sets them too.
+ * With generated material IDs on, also derives the readable id and name.
+ */
+async function planMaterialPropertyChanges(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ current: MaterialPropertyValues;
+ changes: Partial<MaterialPropertyValues>;
+ generatedIds: boolean;
+ }
+): Promise<
+ | { data: MaterialPropertyPlan; error: null }
+ | { data: null; error: ServiceError }
+> {
+ const { current, changes } = args;
+ const next: MaterialPropertyValues = { ...current, ...changes };
+
+ if (next.materialSubstanceId !== current.materialSubstanceId) {
+ for (const field of ["finishId", "gradeId", "materialTypeId"] as const) {
+ if (!(field in changes)) next[field] = null;
+ }
+ }
+ if (next.materialFormId !== current.materialFormId) {
+ for (const field of ["dimensionId", "materialTypeId"] as const) {
+ if (!(field in changes)) next[field] = null;
+ }
+ }
+
+ const changedFields = materialPropertyFields.filter(
+ (field) => next[field] !== current[field]
+ );
+ if (changedFields.length === 0) {
+ return {
+ data: { changed: {}, generated: null },
+ error: null
+ };
+ }
+
+ const lookups = await getMaterialPropertyLookups(
+ client,
+ args.companyId,
+ next
+ );
+ if (lookups.error) return { data: null, error: lookups.error };
+
+ const invalid = checkMaterialProperties(current, next, lookups.data);
+ if (invalid) return { data: null, error: { message: invalid } };
+
+ let generated: MaterialPropertyPlan["generated"] = null;
+ if (args.generatedIds) {
+ if (!next.materialSubstanceId || !next.materialFormId) {
+ return {
+ data: null,
+ error: {
+ message:
+ "Generated material IDs need a substance and a shape; set both"
+ }
+ };
+ }
+ const { substance, form, type, finish, grade, dimension } = lookups.data;
+ const naming = {
+ substance: substance?.name,
+ substanceCode: substance?.code,
+ shape: form?.name,
+ shapeCode: form?.code,
+ materialType: type?.name,
+ materialTypeCode: type?.code,
+ finish: finish?.name,
+ grade: grade?.name,
+ dimensions: dimension?.name
+ };
+ generated = {
+ readableId: getMaterialId(naming),
+ name: getMaterialDescription(naming)
+ };
+ }
+
+ return {
+ data: {
+ changed: Object.fromEntries(changedFields.map((f) => [f, next[f]])),
+ generated
+ },
+ error: null
+ };
+}
+
/**
- * 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.
+ * Writes property changes and a new readable id or name in one transaction:
+ * the material row, and every revision's item row when the readable id or
+ * name changes. An id already taken is refused. Returns the readable id after.
+ */
+async function saveMaterialIdentity(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ readableId: string;
+ newReadableId?: string;
+ name?: string;
+ companyId: string;
+ updatedBy: string;
+ changes: Partial<MaterialPropertyValues>;
+ }
+): Promise<
+ | { data: { readableId: string }; error: null }
+ | { data: null; error: ServiceError }
+> {
+ const { readableId, companyId, updatedBy, changes } = args;
+ const newReadableId = args.newReadableId ?? readableId;
+ const renamed = newReadableId !== readableId;
+ if (!newReadableId) {
+ return { data: null, error: { message: "Material ID cannot be empty" } };
+ }
+ if (!renamed && args.name === undefined && !Object.keys(changes).length) {
+ return { data: { readableId }, error: null };
+ }
+
+ const updatedAt = datetime.timestamp();
+ try {
+ await db.transaction().execute(async (trx) => {
+ if (renamed) {
+ const taken = await trx
+ .selectFrom("item")
+ .select("id")
+ .where("readableId", "=", newReadableId)
+ .where("companyId", "=", companyId)
+ .where("type", "=", "Material")
+ .executeTakeFirst();
+ if (taken) throw new Error(`Material ${newReadableId} already exists`);
+ }
+
+ const material = await trx
+ .updateTable("material")
+ .set({ ...changes, id: newReadableId, updatedBy, updatedAt })
+ .where("id", "=", readableId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (Number(material.numUpdatedRows) !== 1) {
+ throw new Error(`Material ${readableId} not found`);
+ }
+
+ if (renamed || args.name !== undefined) {
+ await trx
+ .updateTable("item")
+ .set({
+ readableId: newReadableId,
+ ...(args.name !== undefined ? { name: args.name } : {}),
+ updatedBy,
+ updatedAt
+ })
+ .where("readableId", "=", readableId)
+ .where("companyId", "=", companyId)
+ .where("type", "=", "Material")
+ .execute();
+ }
+ });
+ } catch (error) {
+ return {
+ data: null,
+ error: {
+ message: error instanceof Error ? error.message : String(error)
+ }
+ };
+ }
+
+ return { data: { readableId: newReadableId }, error: null };
+}
+
+/**
+ * Adds a revision for each size the material lacks, copied from `itemId` the
+ * way New Revision copies one. Refused while the material is open in a change
+ * notice, as New Revision is.
+ */
+async function addMaterialSizes(
+ client: SupabaseClient<Database>,
+ args: {
+ itemId: string;
+ readableId: string;
+ companyId: string;
+ createdBy: string;
+ sizes: string[];
+ }
+): Promise<
+ { data: string[]; error: null } | { data: null; error: ServiceError }
+> {
+ const existing = await client
+ .from("item")
+ .select("revision")
+ .eq("readableId", args.readableId)
+ .eq("companyId", args.companyId)
+ .eq("type", "Material");
+ if (existing.error) return { data: null, error: existing.error };
+
+ const revisions = new Set(existing.data.map((item) => item.revision));
+ const sizes = [...new Set(args.sizes)].filter(
+ (size) => size && !revisions.has(size)
+ );
+ if (sizes.length === 0) return { data: [], error: null };
+
+ const open = await findChangeNoticesForItem(client, {
+ itemId: args.itemId,
+ companyId: args.companyId,
+ statuses: changeNoticeOpenStatuses
+ });
+ if (open.error) {
+ return {
+ data: null,
+ error: { message: "Could not check open change notices for this item" }
+ };
+ }
+ if (open.data.length > 0) {
+ const ids = open.data.map((co) => co.changeOrderId).join(", ");
+ return {
+ data: null,
+ error: {
+ message: `This item is open in change notice ${ids}. Release it to create new revisions.`
+ }
+ };
+ }
+
+ const source = await getItem(client, args.itemId);
+ if (source.error) return { data: null, error: source.error };
+
+ const created: string[] = [];
+ for (const size of sizes) {
+ const revision = await createRevision(client, {
+ item: source.data,
+ revision: size,
+ createdBy: args.createdBy
+ });
+ if (revision.error) return { data: null, error: revision.error };
+ created.push(revision.data.id);
+ }
+ return { data: created, error: null };
+}
+
+/**
+ * Creates a material or updates one by item id or readable id; an update
+ * writes only the fields sent, and `sizes` adds a revision per new size.
+ * 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
+ * IDs are typed by hand.
*/
export async function upsertMaterial(
client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
material:
| (z.infer<typeof materialValidator> & {
companyId: string;
@@ -4917,7 +5385,32 @@ export async function upsertMaterial(
customFields?: Json;
})
) {
+ const generatedIds = await materialIdsAreGenerated(
+ client,
+ material.companyId
+ );
+ if (generatedIds.error) return generatedIds;
+
if ("createdBy" in material) {
+ const plan = await planMaterialPropertyChanges(client, {
+ companyId: material.companyId,
+ current: noMaterialProperties,
+ changes: sentFields(material, materialPropertyFields),
+ generatedIds: generatedIds.data
+ });
+ if (plan.error) return plan;
+ if (generatedIds.data && !plan.data.generated) {
+ return {
+ data: null,
+ error: {
+ message:
+ "Generated material IDs need a substance and a shape; set both"
+ }
+ };
+ }
+ const readableId = plan.data.generated?.readableId ?? material.id;
+ const name = plan.data.generated?.name ?? material.name;
+
// Collect every newly-created item id across the sizes / no-sizes
// branches so the shelf-life policy can be applied uniformly.
const newItemIds: string[] = [];
@@ -4928,8 +5421,8 @@ export async function upsertMaterial(
client
.from("item")
.insert({
- readableId: material.id,
- name: material.name,
+ readableId,
+ name,
description: material.description,
type: "Material",
replenishmentSystem: material.replenishmentSystem,
@@ -4976,8 +5469,8 @@ export async function upsertMaterial(
const itemInsert = await client
.from("item")
.insert({
- readableId: material.id,
- name: material.name,
+ readableId,
+ name,
description: material.description,
type: "Material",
replenishmentSystem: material.replenishmentSystem,
@@ -5031,7 +5524,7 @@ export async function upsertMaterial(
}
const materialInsert = await client.from("material").upsert({
- id: material.id,
+ id: readableId,
materialFormId: material.materialFormId,
materialSubstanceId: material.materialSubstanceId,
finishId: material.finishId,
@@ -5048,7 +5541,7 @@ export async function upsertMaterial(
const newMaterial = await client
.from("materials")
.select("*")
- .eq("readableId", material.id)
+ .eq("readableId", readableId)
.eq("companyId", material.companyId);
return {
@@ -5057,75 +5550,117 @@ export async function upsertMaterial(
};
}
+ const { companyId, updatedBy } = material;
const item = await resolveTypedItemForUpdate(client, {
id: material.id,
- companyId: material.companyId,
+ companyId,
type: "Material"
});
if (item.error) return item;
- const { id: itemId, readableId } = item.data;
+ const itemId = item.data.id;
+ let readableId = item.data.readableId;
- const itemUpdate = {
- name: material.name,
- description: material.description,
- replenishmentSystem: material.replenishmentSystem,
- defaultMethodType: material.defaultMethodType,
- itemTrackingType: material.itemTrackingType,
- unitOfMeasureCode: material.unitOfMeasureCode,
- active: true
- };
+ const current = await getMaterialPropertyValues(
+ client,
+ readableId,
+ companyId
+ );
+ if (current.error) return current;
- const materialUpdate = {
- materialFormId: material.materialFormId,
- materialSubstanceId: material.materialSubstanceId,
- finishId: material.finishId,
- gradeId: material.gradeId,
- dimensionId: material.dimensionId,
- materialTypeId: material.materialTypeId,
- customFields: material.customFields
- };
+ // Everything that can be refused is checked before the first write.
+ const plan = await planMaterialPropertyChanges(client, {
+ companyId,
+ current: current.data,
+ changes: sentFields(material, materialPropertyFields),
+ generatedIds: generatedIds.data
+ });
+ if (plan.error) return plan;
+
+ // Generated IDs follow the properties; hand-typed ones follow `readableId`.
+ const saved = await saveMaterialIdentity(db, {
+ readableId,
+ newReadableId: generatedIds.data
+ ? plan.data.generated?.readableId
+ : material.readableId || undefined,
+ name: plan.data.generated?.name,
+ companyId,
+ updatedBy,
+ changes: plan.data.changed
+ });
+ if (saved.error) return saved;
+ readableId = saved.data.readableId;
- // 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", itemId)
- .eq("companyId", material.companyId)
- .select("id")
- .single(),
- client
+ const itemUpdate = sentFields(material, [
+ "name",
+ "description",
+ "mpn",
+ "replenishmentSystem",
+ "defaultMethodType",
+ "itemTrackingType",
+ "unitOfMeasureCode"
+ ]);
+ // A regenerated name was just written to every revision.
+ if (plan.data.generated) itemUpdate.name = plan.data.generated.name;
+
+ const updateItem = await client
+ .from("item")
+ .update({
+ ...itemUpdate,
+ updatedBy,
+ updatedAt: datetime.timestamp()
+ })
+ .eq("id", itemId)
+ .eq("companyId", companyId)
+ .select("id")
+ .single();
+ if (updateItem.error) return updateItem;
+
+ if ("customFields" in material) {
+ const updateMaterial = await client
.from("material")
.update({
- ...sanitize(materialUpdate),
- updatedBy: material.updatedBy,
+ customFields: material.customFields ?? null,
+ updatedBy,
updatedAt: datetime.timestamp()
})
.eq("id", readableId)
- .eq("companyId", material.companyId)
+ .eq("companyId", companyId)
.select("id")
- .single()
- ]);
+ .single();
+ if (updateMaterial.error) return updateMaterial;
+ }
- if (updateItem.error) return updateItem;
- if (updateMaterial.error) return updateMaterial;
+ const costUpdate: { itemPostingGroupId?: string | null; unitCost?: number } =
+ {};
+ if ("postingGroupId" in material) {
+ costUpdate.itemPostingGroupId = material.postingGroupId ?? null;
+ }
+ if (typeof material.unitCost === "number") {
+ costUpdate.unitCost = material.unitCost;
+ }
+ if (Object.keys(costUpdate).length > 0) {
+ // The item insert trigger creates the itemCost row, so this updates it.
+ const itemCost = await client
+ .from("itemCost")
+ .update({ ...costUpdate, updatedBy, updatedAt: datetime.timestamp() })
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .select("itemId")
+ .single();
+ if (itemCost.error) return itemCost;
+ }
const pickMethod = await upsertItemDefaultPickMethod(client, {
itemId,
- userId: material.updatedBy,
+ userId: updatedBy,
storageUnitId: material.defaultStorageUnitId
});
if (pickMethod.error) return pickMethod;
const shelfLife = await upsertItemShelfLife(client, {
itemId,
- userId: material.updatedBy,
- companyId: material.companyId,
+ userId: updatedBy,
+ companyId,
mode: material.shelfLifeMode,
days: material.shelfLifeDays,
triggerProcessId: material.shelfLifeTriggerProcessId,
@@ -5134,9 +5669,99 @@ export async function upsertMaterial(
});
if (shelfLife.error) return shelfLife;
- return updateItem;
+ if (material.sizes?.length) {
+ const sizes = await addMaterialSizes(client, {
+ itemId,
+ readableId,
+ companyId,
+ createdBy: updatedBy,
+ sizes: material.sizes
+ });
+ if (sizes.error) return sizes;
+ }
+
+ return client
+ .from("item")
+ .select("id, readableId, readableIdWithRevision, revision, name")
+ .eq("id", itemId)
+ .single();
+}
+
+/**
+ * Changes a material's substance, shape, type, finish, grade or dimension by
+ * item id or readable id, as the item properties panel does. Omitted
+ * properties keep their value and null clears one. A new substance clears
+ * finish, grade and type, and a new shape clears dimension and type, unless
+ * the same call sets them. Grade and finish must belong to the substance,
+ * dimension to the shape, and type to both. With generated material IDs on,
+ * every revision's readable id and name are regenerated.
+ */
+export async function updateMaterialProperties(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ material: {
+ id: string;
+ companyId: string;
+ updatedBy: string;
+ materialSubstanceId?: string | null;
+ materialFormId?: string | null;
+ materialTypeId?: string | null;
+ finishId?: string | null;
+ gradeId?: string | null;
+ dimensionId?: string | null;
+ }
+) {
+ const { companyId, updatedBy } = material;
+
+ // Properties live on the material row every revision shares, so any
+ // revision's item id or the readable id itself identifies it.
+ const item = await client
+ .from("item")
+ .select("readableId")
+ .eq("id", material.id)
+ .eq("companyId", companyId)
+ .eq("type", "Material")
+ .maybeSingle();
+ if (item.error) return item;
+ const readableId = item.data?.readableId ?? material.id;
+
+ const [current, generatedIds] = await Promise.all([
+ getMaterialPropertyValues(client, readableId, companyId),
+ materialIdsAreGenerated(client, companyId)
+ ]);
+ if (current.error) return current;
+ if (generatedIds.error) return generatedIds;
+
+ const plan = await planMaterialPropertyChanges(client, {
+ companyId,
+ current: current.data,
+ changes: sentFields(material, materialPropertyFields),
+ generatedIds: generatedIds.data
+ });
+ if (plan.error) return plan;
+
+ const saved = await saveMaterialIdentity(db, {
+ readableId,
+ newReadableId: plan.data.generated?.readableId,
+ name: plan.data.generated?.name,
+ companyId,
+ updatedBy,
+ changes: plan.data.changed
+ });
+ if (saved.error) return saved;
+
+ return client
+ .from("materials")
+ .select("*")
+ .eq("readableId", saved.data.readableId)
+ .eq("companyId", companyId)
+ .single();
}
+/**
+ * Creates a dimension (a named size) for a material shape, or updates the one
+ * whose `id` is sent; a new dimension's id is generated.
+ */
export async function upsertMaterialDimension(
client: SupabaseClient<Database>,
materialDimension:
@@ -5167,6 +5792,10 @@ export async function upsertMaterialDimension(
.single();
}
+/**
+ * Creates a finish for a material substance, or updates the one whose `id` is
+ * sent; a new finish's id is generated.
+ */
export async function upsertMaterialFinish(
client: SupabaseClient<Database>,
materialFinish:
@@ -5227,6 +5856,10 @@ export async function upsertMaterialForm(
);
}
+/**
+ * Creates a grade for a material substance, or updates the one whose `id` is
+ * sent; a new grade's id is generated.
+ */
export async function upsertMaterialGrade(
client: SupabaseClient<Database>,
materialGrade:
@@ -5308,6 +5941,10 @@ export async function getMaterialTypeList(
.or(`companyId.eq.${companyId},companyId.is.null`);
}
+/**
+ * Creates a material type for a substance and shape pair, or updates the one
+ * whose `id` is sent; a new type's id is generated.
+ */
export async function upsertMaterialType(
client: SupabaseClient<Database>,
materialType:
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 f82180da6a..624395c3c6 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
@@ -1,5 +1,5 @@
{
- "totalTools": 1547,
+ "totalTools": 1548,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},
@@ -534,6 +534,7 @@
{"name":"items_updateItemCost","classification":"WRITE","paramCount":2,"schema":"c55de757a7e4","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},
{"name":"items_updateItemMethodAndSourcing","classification":"WRITE","paramCount":3,"schema":"1165eb54378a","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},
{"name":"items_updateMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},
+ {"name":"items_updateMaterialProperties","classification":"WRITE","paramCount":7,"schema":"ba2c8db7ad05","response":"e30f0104d9ce","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},
{"name":"items_updateOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},
{"name":"items_updateRevision","classification":"WRITE","paramCount":2,"schema":"25c295d358ea","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},
{"name":"items_upsertChangeNoticeRequiredAction","classification":"WRITE","paramCount":3,"schema":"e790518da1ff","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},
@@ -554,12 +555,12 @@
{"name":"items_upsertItemUnitSalePrice","classification":"WRITE","paramCount":3,"schema":"fafa19d3d976","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMakeMethodVersion","classification":"WRITE","paramCount":3,"schema":"068ef4e9b168","response":"83e06908ebb7","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMaterial","classification":"WRITE","paramCount":25,"schema":"4b81671162f9","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
- {"name":"items_upsertMaterialDimension","classification":"WRITE","paramCount":4,"schema":"cd59518ed575","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
- {"name":"items_upsertMaterialFinish","classification":"WRITE","paramCount":3,"schema":"d23a9b1a2253","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
+ {"name":"items_upsertMaterialDimension","classification":"WRITE","paramCount":4,"schema":"cd59518ed575","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},
+ {"name":"items_upsertMaterialFinish","classification":"WRITE","paramCount":3,"schema":"d23a9b1a2253","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMaterialForm","classification":"WRITE","paramCount":4,"schema":"50ac0c460dd0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
- {"name":"items_upsertMaterialGrade","classification":"WRITE","paramCount":3,"schema":"d23a9b1a2253","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
+ {"name":"items_upsertMaterialGrade","classification":"WRITE","paramCount":3,"schema":"d23a9b1a2253","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMaterialSubstance","classification":"WRITE","paramCount":4,"schema":"50ac0c460dd0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
- {"name":"items_upsertMaterialType","classification":"WRITE","paramCount":5,"schema":"c033d56db90c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
+ {"name":"items_upsertMaterialType","classification":"WRITE","paramCount":5,"schema":"c033d56db90c","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMethodMaterial","classification":"WRITE","paramCount":13,"schema":"d52e20f3488d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMethodOperation","classification":"WRITE","paramCount":22,"schema":"1bab96040db4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMethodOperationParameter","classification":"WRITE","paramCount":5,"schema":"7886eea4515f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsx
index c189b793d1..4c70113c4d 100644
--- a/apps/erp/app/routes/x+/items+/update.tsx
+++ b/apps/erp/app/routes/x+/items+/update.tsx
@@ -1,8 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import type { Database } from "@carbon/database";
import { getLogger } from "@carbon/logger";
-import { getMaterialDescription, getMaterialId } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import type { InventoryItemType } from "~/modules/items";
import { deriveItemMethodUpdate } from "~/modules/items";
@@ -12,9 +10,9 @@ import {
} from "~/modules/items/items.server";
import {
cascadeItemTrackingType,
- updateItemMethodAndSourcing
+ updateItemMethodAndSourcing,
+ updateMaterialProperties
} from "~/modules/items/items.service";
-import { getCompanySettings } from "~/modules/settings";
import { getDatabaseClient } from "~/services/database.server";
const logger = getLogger("erp", "update");
@@ -114,209 +112,41 @@ export async function action({ request }: ActionFunctionArgs) {
case "finishId":
case "materialFormId":
case "materialSubstanceId":
- case "materialTypeId":
- const settings = await getCompanySettings(client, companyId);
-
- if (settings.data?.materialGeneratedIds) {
- let name = "";
- let code = "";
- if (field === "materialSubstanceId") {
- const materialSubstance = await client
- .from("materialSubstance")
- .select("name, code")
- .eq("id", value)
- .single();
- name = materialSubstance.data?.name ?? "";
- code = materialSubstance.data?.code ?? "";
- }
- if (field === "materialFormId") {
- const materialForm = await client
- .from("materialForm")
- .select("name, code")
- .eq("id", value)
- .single();
- name = materialForm.data?.name ?? "";
- code = materialForm.data?.code ?? "";
- }
- if (field === "materialTypeId") {
- const materialType = await client
- .from("materialType")
- .select("name, code")
- .eq("id", value)
- .single();
- name = materialType.data?.name ?? "";
- code = materialType.data?.code ?? "";
- }
- if (field === "finishId") {
- const finish = await client
- .from("materialFinish")
- .select("name")
- .eq("id", value)
- .single();
- name = finish.data?.name ?? "";
- }
- if (field === "gradeId") {
- const grade = await client
- .from("materialGrade")
- .select("name")
- .eq("id", value)
- .single();
-
- name = grade.data?.name ?? "";
- }
- if (field === "dimensionId") {
- const dimension = await client
- .from("materialDimension")
- .select("name")
- .eq("id", value)
- .single();
- name = dimension.data?.name ?? "";
- }
-
- for await (const id of items as string[]) {
- const item = await client
- .from("item")
- .select("readableId")
- .eq("id", id)
- .eq("companyId", companyId)
- .single();
+ case "materialTypeId": {
+ const materialItems = await client
+ .from("item")
+ .select("readableId")
+ .in("id", items as string[])
+ .eq("companyId", companyId);
+ if (materialItems.error) return materialItems;
+ const materialIds = [
+ ...new Set(materialItems.data.map((item) => item.readableId))
+ ];
+ if (materialIds.length === 0) {
+ return { error: { message: "No materials found" }, data: null };
+ }
- const readableId = item.data?.readableId;
-
- if (readableId) {
- const [materialDetails, relatedItems] = await Promise.all([
- client
- .rpc("get_material_naming_details", { readable_id: readableId })
- .single(),
- client
- .from("item")
- .select("id")
- .eq("readableId", readableId)
- .eq("type", "Material")
- .eq("companyId", companyId)
- ]);
-
- if (materialDetails.data) {
- const namingDetails = materialDetails.data;
-
- if (field === "materialSubstanceId") {
- namingDetails.substance = name;
- namingDetails.substanceCode = code;
- }
- if (field === "materialFormId") {
- namingDetails.shape = name;
- namingDetails.shapeCode = code;
- }
- if (field === "materialTypeId") {
- namingDetails.materialType = name;
- namingDetails.materialTypeCode = code;
- }
- if (field === "finishId") {
- namingDetails.finish = name;
- }
- if (field === "gradeId") {
- namingDetails.grade = name;
- }
- if (field === "dimensionId") {
- namingDetails.dimensions = name;
- }
-
- const newMaterialId = getMaterialId(namingDetails);
- const newDescription = getMaterialDescription(namingDetails);
-
- const relatedItemIds = relatedItems.data?.map((item) => item.id);
-
- if (relatedItemIds) {
- const itemUpdateResult = await client
- .from("item")
- .update({ readableId: newMaterialId, name: newDescription })
- .in("id", relatedItemIds as string[])
- .eq("companyId", companyId);
-
- if (itemUpdateResult.error) {
- return itemUpdateResult;
- }
- }
-
- let updateData: Database["public"]["Tables"]["material"]["Update"] =
- {
- [field]: value || null,
- id: newMaterialId,
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- };
-
- // If substance changes, reset finishId, gradeId, and materialTypeId
- if (field === "materialSubstanceId") {
- updateData.finishId = null;
- updateData.gradeId = null;
- updateData.materialTypeId = null;
- }
-
- // If form changes, reset dimensionId and materialTypeId
- if (field === "materialFormId") {
- updateData.dimensionId = null;
- updateData.materialTypeId = null;
- }
-
- const update = await client
- .from("material")
- .update(updateData)
- .eq("id", readableId)
- .eq("companyId", companyId);
-
- if (update.error) {
- return {
- error: { message: update.error.message },
- data: null
- };
- }
- }
+ // One material row per readable id, shared by its revisions. The
+ // service applies the dependent resets and, with generated material
+ // IDs on, regenerates each material's readable id and name.
+ for (const materialId of materialIds) {
+ const update = await updateMaterialProperties(
+ client,
+ getDatabaseClient(),
+ {
+ id: materialId,
+ companyId,
+ updatedBy: userId,
+ [field]: value || null
}
+ );
+ if (update.error) {
+ return { error: { message: update.error.message }, data: null };
}
-
- return {
- data: null,
- error: null
- };
- } else {
- const materialItems = await client
- .from("item")
- .select("readableId")
- .in("id", items as string[])
- .eq("companyId", companyId);
- const materialIds = [
- ...new Set(materialItems.data?.map((item) => item.readableId) ?? [])
- ];
- if (materialIds.length === 0) {
- return { error: { message: "No materials found" }, data: null };
- }
-
- let updateData: Database["public"]["Tables"]["material"]["Update"] = {
- [field]: value || null,
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- };
-
- // If substance changes, reset finishId, gradeId, and materialTypeId
- if (field === "materialSubstanceId") {
- updateData.finishId = null;
- updateData.gradeId = null;
- updateData.materialTypeId = null;
- }
-
- // If form changes, reset dimensionId and materialTypeId
- if (field === "materialFormId") {
- updateData.dimensionId = null;
- updateData.materialTypeId = null;
- }
-
- return await client
- .from("material")
- .update(updateData)
- .in("id", materialIds as string[])
- .eq("companyId", companyId);
}
+
+ return { data: null, error: null };
+ }
case "active": {
// Activating is the change notice's job: applyChangeNotice flips the
// revisions and parts it minted when it reaches Done. Switching one on by
diff --git a/apps/erp/app/routes/x+/material+/$itemId.details.tsx b/apps/erp/app/routes/x+/material+/$itemId.details.tsx
index 96c2826019..b7bab3d637 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.details.tsx
@@ -15,6 +15,7 @@ import {
ItemNotes,
ItemRiskRegister
} from "~/modules/items/ui/Item";
+import { getDatabaseClient } from "~/services/database.server";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -34,7 +35,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const updateMaterial = await upsertMaterial(client, {
+ const updateMaterial = await upsertMaterial(client, getDatabaseClient(), {
...validation.data,
id: itemId,
companyId,
diff --git a/apps/erp/app/routes/x+/material+/new.tsx b/apps/erp/app/routes/x+/material+/new.tsx
index 2322960410..739ba76b59 100644
--- a/apps/erp/app/routes/x+/material+/new.tsx
+++ b/apps/erp/app/routes/x+/material+/new.tsx
@@ -7,6 +7,7 @@ import type { ActionFunctionArgs } from "react-router";
import { data, redirect } from "react-router";
import { materialValidator, upsertMaterial } from "~/modules/items";
import { MaterialForm } from "~/modules/items/ui/Materials";
+import { getDatabaseClient } from "~/services/database.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -32,7 +33,7 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const createMaterial = await upsertMaterial(client, {
+ const createMaterial = await upsertMaterial(client, getDatabaseClient(), {
...validation.data,
companyId,
customFields: setCustomFields(formData),
diff --git a/apps/erp/test/material-properties.test.ts b/apps/erp/test/material-properties.test.ts
new file mode 100644
index 0000000000..a0ec9c9971
--- /dev/null
+++ b/apps/erp/test/material-properties.test.ts
@@ -0,0 +1,741 @@
+import { describe, expect, it, vi } from "vitest";
+import toolMetadataJson from "../app/routes/api+/mcp+/lib/tool-metadata.json";
+
+// The items.service graph transitively loads @carbon/glossary, whose
+// module-load-time Lingui `msg` macro isn't transformed under plain vitest.
+// Stub it; the services under test stay the genuine implementation.
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn()
+}));
+
+const { updateMaterialProperties, upsertMaterial } = await import(
+ "~/modules/items/items.service"
+);
+
+// Pins material edits over the API and MCP: the properties panel's rules
+// (dependent resets, pick lists, generated IDs) in the service, updates that
+// write only the fields sent, sizes on update, and the lookup-table writes
+// the MCP layer used to break by stamping audit columns those tables lack.
+
+type Filter = [string, string, unknown];
+type Call = {
+ table: string;
+ op: "select" | "update" | "insert" | "upsert" | "delete";
+ columns?: string;
+ payload?: Record<string, unknown>;
+ filters: Filter[];
+ 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 = (columns?: string) => {
+ // A select after a write is the "return the row" modifier.
+ if (!started) {
+ started = true;
+ call.op = "select";
+ call.columns = columns;
+ }
+ 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;
+ };
+ }
+ for (const op of ["eq", "in", "or", "not"] as const) {
+ builder[op] = (column: string, value: unknown) => {
+ call.filters.push([op, column, value]);
+ return builder;
+ };
+ }
+ builder.order = () => builder;
+ builder.limit = () => 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 };
+}
+
+type Write = {
+ table: string;
+ set: Record<string, unknown>;
+ where: Filter[];
+};
+
+/**
+ * A Kysely stub for saveMaterialIdentity's transaction. `writes` holds only
+ * committed statements: a throw inside the callback drops what it staged.
+ */
+function makeDb(opts: { taken?: boolean; materialRows?: number } = {}) {
+ const writes: Write[] = [];
+ let staged: Write[] = [];
+ const trx = {
+ selectFrom: () => {
+ const query = {
+ select: () => query,
+ where: () => query,
+ executeTakeFirst: async () => (opts.taken ? { id: "other" } : undefined)
+ };
+ return query;
+ },
+ updateTable: (table: string) => {
+ const write: Write = { table, set: {}, where: [] };
+ const query = {
+ set: (values: Record<string, unknown>) => {
+ write.set = values;
+ return query;
+ },
+ where: (column: string, op: string, value: unknown) => {
+ write.where.push([op, column, value]);
+ return query;
+ },
+ executeTakeFirst: async () => {
+ staged.push(write);
+ return {
+ numUpdatedRows: BigInt(
+ table === "material" ? (opts.materialRows ?? 1) : 1
+ )
+ };
+ },
+ execute: async () => {
+ staged.push(write);
+ return [];
+ }
+ };
+ return query;
+ }
+ };
+ const db = {
+ transaction: () => ({
+ execute: async (callback: (tx: typeof trx) => Promise<unknown>) => {
+ staged = [];
+ const result = await callback(trx);
+ writes.push(...staged);
+ return result;
+ }
+ })
+ };
+ return { db: db as never, writes };
+}
+
+const COMPANY = "company-1";
+const USER = "user-1";
+
+const lookups: Record<string, Record<string, Record<string, unknown>>> = {
+ materialSubstance: {
+ aluminum: { name: "Aluminum", code: "AL" },
+ steel: { name: "Steel", code: "STL" }
+ },
+ materialForm: {
+ plate: { name: "Plate", code: "PL" },
+ roundBar: { name: "Round Bar", code: "RB" }
+ },
+ materialGrade: {
+ "al-6061": { name: "6061", materialSubstanceId: "aluminum" },
+ "al-7075": { name: "7075", materialSubstanceId: "aluminum" },
+ "stl-1018": { name: "1018", materialSubstanceId: "steel" }
+ },
+ materialFinish: {
+ "al-anodized": { name: "Anodized", materialSubstanceId: "aluminum" }
+ },
+ materialDimension: {
+ "pl-025": { name: '1/4"', materialFormId: "plate" },
+ "rb-1": { name: '1"', materialFormId: "roundBar" }
+ },
+ materialType: {
+ "al-pl-cast": {
+ name: "Cast",
+ code: "C",
+ materialSubstanceId: "aluminum",
+ materialFormId: "plate"
+ }
+ }
+};
+
+const ALUMINUM_PLATE = {
+ materialSubstanceId: "aluminum",
+ materialFormId: "plate",
+ materialTypeId: "al-pl-cast",
+ finishId: "al-anodized",
+ gradeId: "al-6061",
+ dimensionId: "pl-025"
+};
+
+const ITEM = { id: "item-uuid-1", readableId: "MAT-AL-PLATE" };
+
+const idOf = (call: Call) =>
+ call.filters.find(([op, column]) => op === "eq" && column === "id")?.[2];
+
+type Scenario = {
+ generated?: boolean;
+ material?: Record<string, string | null> | null;
+ itemById?: typeof ITEM | null;
+ itemsByReadableId?: (typeof ITEM)[];
+ revisions?: string[];
+ changeNotice?: string;
+};
+
+/** Answers every read the material paths make from one scenario. */
+function respondTo(scenario: Scenario) {
+ return (call: Call): Response => {
+ const { table, op } = call;
+ if (op === "select" && table === "companySettings") {
+ return {
+ data: { materialGeneratedIds: scenario.generated ?? false },
+ error: null
+ };
+ }
+ if (op === "select" && table === "material") {
+ return {
+ data: scenario.material === undefined ? ALUMINUM_PLATE : scenario.material,
+ error: null
+ };
+ }
+ if (op === "select" && table in lookups) {
+ return {
+ data: lookups[table][idOf(call) as string] ?? null,
+ error: null
+ };
+ }
+ if (op === "select" && table === "item") {
+ if (call.columns === "revision") {
+ return {
+ data: (scenario.revisions ?? ["0"]).map((revision) => ({ revision })),
+ error: null
+ };
+ }
+ if (call.columns === "id, changeOrderId") {
+ return {
+ data: [{ id: ITEM.id, changeOrderId: scenario.changeNotice ?? null }],
+ error: null
+ };
+ }
+ if (call.columns === "*") {
+ return {
+ data: {
+ ...ITEM,
+ name: "Aluminum plate",
+ type: "Material",
+ replenishmentSystem: "Buy",
+ companyId: COMPANY
+ },
+ error: null
+ };
+ }
+ const byUuid = idOf(call) !== undefined;
+ if (byUuid) {
+ const item =
+ scenario.itemById === undefined ? ITEM : scenario.itemById;
+ return { data: item, error: null };
+ }
+ return { data: scenario.itemsByReadableId ?? [], error: null };
+ }
+ if (op === "select" && table === "changeOrder") {
+ return {
+ data: scenario.changeNotice
+ ? [{ id: "co-1", changeOrderId: scenario.changeNotice }]
+ : [],
+ error: null
+ };
+ }
+ if (op === "select" && table === "materials") {
+ return { data: { readableId: ITEM.readableId }, error: null };
+ }
+ if (op === "insert" && table === "item") {
+ return { data: { id: "item-uuid-new" }, error: null };
+ }
+ if (op === "update" && table === "item") {
+ return { data: { id: ITEM.id }, error: null };
+ }
+ if (op === "update" && table === "itemCost") {
+ return { data: { itemId: ITEM.id }, error: null };
+ }
+ if (op === "select") return { data: [], error: null };
+ return { data: null, error: null };
+ };
+}
+
+const writesTo = (calls: Call[], table: string, op: Call["op"]) =>
+ calls.filter((c) => c.table === table && c.op === op);
+
+const materialWrite = (writes: Write[]) =>
+ writes.find((w) => w.table === "material");
+
+describe("updateMaterialProperties", () => {
+ it("a new substance clears finish, grade and type", async () => {
+ const { client } = makeClient(respondTo({}));
+ const { db, writes } = makeDb();
+ const result = await updateMaterialProperties(client, db, {
+ id: ITEM.id,
+ companyId: COMPANY,
+ updatedBy: USER,
+ materialSubstanceId: "steel"
+ });
+ expect(result.error).toBeNull();
+ expect(materialWrite(writes)?.set).toMatchObject({
+ materialSubstanceId: "steel",
+ finishId: null,
+ gradeId: null,
+ materialTypeId: null,
+ id: ITEM.readableId,
+ updatedBy: USER
+ });
+ expect(materialWrite(writes)?.set).not.toHaveProperty("dimensionId");
+ expect(materialWrite(writes)?.where).toEqual(
+ expect.arrayContaining([
+ ["=", "id", ITEM.readableId],
+ ["=", "companyId", COMPANY]
+ ])
+ );
+ });
+
+ it("keeps a dependent the same call sets", async () => {
+ const { client } = makeClient(respondTo({}));
+ const { db, writes } = makeDb();
+ const result = await updateMaterialProperties(client, db, {
+ id: ITEM.readableId,
+ companyId: COMPANY,
+ updatedBy: USER,
+ materialSubstanceId: "steel",
+ gradeId: "stl-1018"
+ });
+ expect(result.error).toBeNull();
+ expect(materialWrite(writes)?.set).toMatchObject({
+ materialSubstanceId: "steel",
+ gradeId: "stl-1018",
+ finishId: null
+ });
+ });
+
+ it("a new shape clears dimension and type", async () => {
+ const { client } = makeClient(respondTo({}));
+ const { db, writes } = makeDb();
+ await updateMaterialProperties(client, db, {
+ id: ITEM.id,
+ companyId: COMPANY,
+ updatedBy: USER,
+ materialFormId: "roundBar"
+ });
+ expect(materialWrite(writes)?.set).toMatchObject({
+ materialFormId: "roundBar",
+ dimensionId: null,
+ materialTypeId: null
+ });
+ expect(materialWrite(writes)?.set).not.toHaveProperty("gradeId");
+ });
+
+ it.each([
+ [{ gradeId: "stl-1018" }, "not a grade of substance aluminum"],
+ [{ finishId: "missing" }, "Finish missing not found"],
+ [{ dimensionId: "rb-1" }, "not a dimension of shape plate"],
+ [
+ { materialFormId: "roundBar", materialTypeId: "al-pl-cast" },
+ "not a type of substance aluminum and shape roundBar"
+ ],
+ [{ materialSubstanceId: "unobtainium" }, "Substance unobtainium not found"]
+ ])("refuses %o", async (change, message) => {
+ const { client } = makeClient(respondTo({}));
+ const { db, writes } = makeDb();
+ const result = await updateMaterialProperties(client, db, {
+ id: ITEM.id,
+ companyId: COMPANY,
+ updatedBy: USER,
+ ...change
+ });
+ expect(result.data).toBeNull();
+ expect(result.error).toMatchObject({
+ message: expect.stringContaining(message)
+ });
+ expect(writes).toHaveLength(0);
+ });
+
+ it("does not re-check an older inconsistency the call leaves alone", async () => {
+ const { client } = makeClient(
+ respondTo({ material: { ...ALUMINUM_PLATE, gradeId: "stl-1018" } })
+ );
+ const { db, writes } = makeDb();
+ const result = await updateMaterialProperties(client, db, {
+ id: ITEM.id,
+ companyId: COMPANY,
+ updatedBy: USER,
+ dimensionId: null
+ });
+ expect(result.error).toBeNull();
+ expect(materialWrite(writes)?.set).toMatchObject({ dimensionId: null });
+ expect(materialWrite(writes)?.set).not.toHaveProperty("gradeId");
+ });
+
+ it("an unknown material is an error and writes nothing", async () => {
+ const { client } = makeClient(
+ respondTo({ itemById: null, material: null })
+ );
+ const { db, writes } = makeDb();
+ const result = await updateMaterialProperties(client, db, {
+ id: "nope",
+ companyId: COMPANY,
+ updatedBy: USER,
+ gradeId: "al-7075"
+ });
+ expect(result.error).toMatchObject({ code: "PGRST116" });
+ expect(writes).toHaveLength(0);
+ });
+
+ it("with generated IDs, renames the material and every revision in one transaction", async () => {
+ const { client } = makeClient(respondTo({ generated: true }));
+ const { db, writes } = makeDb();
+ const result = await updateMaterialProperties(client, db, {
+ id: ITEM.id,
+ companyId: COMPANY,
+ updatedBy: USER,
+ gradeId: "al-7075"
+ });
+ expect(result.error).toBeNull();
+
+ const newId = '7075-AL-C-PL-1/4"-Anodized';
+ expect(materialWrite(writes)?.set).toMatchObject({
+ gradeId: "al-7075",
+ id: newId
+ });
+ const items = writes.find((w) => w.table === "item");
+ expect(items?.set).toMatchObject({
+ readableId: newId,
+ name: '7075 Aluminum Cast Plate 1/4" Anodized',
+ updatedBy: USER
+ });
+ expect(items?.where).toEqual(
+ expect.arrayContaining([
+ ["=", "readableId", ITEM.readableId],
+ ["=", "companyId", COMPANY],
+ ["=", "type", "Material"]
+ ])
+ );
+ });
+
+ it("with generated IDs, refuses an id another material has", async () => {
+ const { client } = makeClient(respondTo({ generated: true }));
+ const { db, writes } = makeDb({ taken: true });
+ const result = await updateMaterialProperties(client, db, {
+ id: ITEM.id,
+ companyId: COMPANY,
+ updatedBy: USER,
+ gradeId: "al-7075"
+ });
+ expect(result.error).toMatchObject({
+ message: expect.stringContaining("already exists")
+ });
+ expect(writes).toHaveLength(0);
+ });
+
+ it("with generated IDs, needs a substance and a shape", async () => {
+ const { client } = makeClient(respondTo({ generated: true }));
+ const { db, writes } = makeDb();
+ const result = await updateMaterialProperties(client, db, {
+ id: ITEM.id,
+ companyId: COMPANY,
+ updatedBy: USER,
+ materialFormId: null
+ });
+ expect(result.error).toMatchObject({
+ message: expect.stringContaining("substance and a shape")
+ });
+ expect(writes).toHaveLength(0);
+ });
+});
+
+const required = {
+ name: "Aluminum plate",
+ replenishmentSystem: "Buy" as const,
+ defaultMethodType: "Pull from Inventory" as const,
+ itemTrackingType: "Inventory" as const,
+ unitOfMeasureCode: "EA",
+ shelfLifeCalculateFromBom: false,
+ companyId: COMPANY
+};
+
+describe("upsertMaterial update", () => {
+ it("writes only the fields sent and leaves active alone", async () => {
+ const { client, calls } = makeClient(respondTo({}));
+ const { db, writes } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.id,
+ updatedBy: USER,
+ mpn: "MPN-1"
+ });
+ expect(result.error).toBeNull();
+
+ const [item] = writesTo(calls, "item", "update");
+ expect(item.payload).toMatchObject({ name: "Aluminum plate", mpn: "MPN-1" });
+ expect(item.payload).not.toHaveProperty("description");
+ expect(item.payload).not.toHaveProperty("active");
+ expect(item.filters).toEqual(
+ expect.arrayContaining([
+ ["eq", "id", ITEM.id],
+ ["eq", "companyId", COMPANY]
+ ])
+ );
+ // No property or custom field sent, so the material row is untouched.
+ expect(writes).toHaveLength(0);
+ expect(writesTo(calls, "material", "update")).toHaveLength(0);
+ });
+
+ it("a readable id resolves to the item uuid", async () => {
+ const { client, calls } = makeClient(
+ respondTo({ itemById: null, itemsByReadableId: [ITEM] })
+ );
+ const { db } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.readableId,
+ updatedBy: USER
+ });
+ expect(result.error).toBeNull();
+ expect(writesTo(calls, "item", "update")[0].filters).toEqual(
+ expect.arrayContaining([["eq", "id", ITEM.id]])
+ );
+ });
+
+ it("a readable id shared by several revisions is refused", async () => {
+ const { client, calls } = makeClient(
+ respondTo({
+ itemById: null,
+ itemsByReadableId: [ITEM, { ...ITEM, id: "item-uuid-2" }]
+ })
+ );
+ const { db, writes } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.readableId,
+ updatedBy: USER
+ });
+ expect(result.error).toMatchObject({
+ message: expect.stringContaining("revisions")
+ });
+ expect(writesTo(calls, "item", "update")).toHaveLength(0);
+ expect(writes).toHaveLength(0);
+ });
+
+ it("sends item group and unit cost to itemCost", async () => {
+ const { client, calls } = makeClient(respondTo({}));
+ const { db } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.id,
+ updatedBy: USER,
+ postingGroupId: "group-1",
+ unitCost: 12.5
+ });
+ expect(result.error).toBeNull();
+ const [cost] = writesTo(calls, "itemCost", "update");
+ expect(cost.payload).toMatchObject({
+ itemPostingGroupId: "group-1",
+ unitCost: 12.5,
+ updatedBy: USER
+ });
+ expect(cost.filters).toEqual(
+ expect.arrayContaining([
+ ["eq", "itemId", ITEM.id],
+ ["eq", "companyId", COMPANY]
+ ])
+ );
+ expect(cost.single).toBe("single");
+ });
+
+ it("checks property changes before any write", async () => {
+ const { client, calls } = makeClient(respondTo({}));
+ const { db, writes } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.id,
+ updatedBy: USER,
+ gradeId: "stl-1018"
+ });
+ expect(result.error).toMatchObject({
+ message: expect.stringContaining("not a grade of substance aluminum")
+ });
+ expect(writesTo(calls, "item", "update")).toHaveLength(0);
+ expect(writes).toHaveLength(0);
+ });
+
+ it("echoing unchanged properties writes none of them", async () => {
+ const { client } = makeClient(respondTo({}));
+ const { db, writes } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.id,
+ updatedBy: USER,
+ ...ALUMINUM_PLATE
+ });
+ expect(result.error).toBeNull();
+ expect(writes).toHaveLength(0);
+ });
+
+ it("with generated IDs, a property change renames and replaces the sent name", async () => {
+ const { client, calls } = makeClient(respondTo({ generated: true }));
+ const { db, writes } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.id,
+ updatedBy: USER,
+ readableId: ITEM.readableId,
+ gradeId: "al-7075"
+ });
+ expect(result.error).toBeNull();
+ const name = '7075 Aluminum Cast Plate 1/4" Anodized';
+ expect(writes.find((w) => w.table === "item")?.set).toMatchObject({
+ name
+ });
+ expect(writesTo(calls, "item", "update")[0].payload).toMatchObject({
+ name
+ });
+ });
+
+ it("with hand-typed IDs, readableId renames the material", async () => {
+ const { client } = makeClient(respondTo({}));
+ const { db, writes } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.id,
+ updatedBy: USER,
+ readableId: "MAT-AL-PLATE-2"
+ });
+ expect(result.error).toBeNull();
+ expect(materialWrite(writes)?.set).toMatchObject({ id: "MAT-AL-PLATE-2" });
+ expect(writes.find((w) => w.table === "item")?.set).toMatchObject({
+ readableId: "MAT-AL-PLATE-2"
+ });
+ });
+
+ it("sizes add a revision per size the material lacks", async () => {
+ const { client, calls } = makeClient(
+ respondTo({ revisions: ["0", '1"'] })
+ );
+ const { db } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.id,
+ updatedBy: USER,
+ sizes: ['1"', '2"', '2"']
+ });
+ expect(result.error).toBeNull();
+ const inserts = writesTo(calls, "item", "insert");
+ expect(inserts).toHaveLength(1);
+ expect(inserts[0].payload).toMatchObject({
+ readableId: ITEM.readableId,
+ revision: '2"',
+ type: "Material",
+ createdBy: USER
+ });
+ });
+
+ it("sizes are refused while the material is open in a change notice", async () => {
+ const { client, calls } = makeClient(
+ respondTo({ changeNotice: "ECN-0001" })
+ );
+ const { db } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: ITEM.id,
+ updatedBy: USER,
+ sizes: ['2"']
+ });
+ expect(result.error).toMatchObject({
+ message: expect.stringContaining("ECN-0001")
+ });
+ expect(writesTo(calls, "item", "insert")).toHaveLength(0);
+ });
+});
+
+describe("upsertMaterial create", () => {
+ it("with generated IDs, derives the readable id and name from the properties", async () => {
+ const { client, calls } = makeClient(respondTo({ generated: true }));
+ const { db } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: "anything",
+ name: "anything",
+ createdBy: USER,
+ materialSubstanceId: "aluminum",
+ materialFormId: "plate",
+ gradeId: "al-7075"
+ });
+ expect(result.error).toBeNull();
+ expect(writesTo(calls, "item", "insert")[0].payload).toMatchObject({
+ readableId: "7075-AL-PL",
+ name: "7075 Aluminum Plate"
+ });
+ expect(writesTo(calls, "material", "upsert")[0].payload).toMatchObject({
+ id: "7075-AL-PL"
+ });
+ });
+
+ it("refuses a grade that is not of the substance", async () => {
+ const { client, calls } = makeClient(respondTo({}));
+ const { db } = makeDb();
+ const result = await upsertMaterial(client, db, {
+ ...required,
+ id: "MAT-1",
+ createdBy: USER,
+ materialSubstanceId: "aluminum",
+ gradeId: "stl-1018"
+ });
+ expect(result.error).toMatchObject({
+ message: expect.stringContaining("not a grade of substance aluminum")
+ });
+ expect(writesTo(calls, "item", "insert")).toHaveLength(0);
+ });
+});
+
+describe("material tools over MCP", () => {
+ const tools = (
+ toolMetadataJson as unknown as {
+ tools: { name: string; injectAuth: string[]; serviceParams: string[] }[];
+ }
+ ).tools;
+ const tool = (name: string) => tools.find((t) => t.name === name);
+
+ it.each([
+ "items_upsertMaterialDimension",
+ "items_upsertMaterialFinish",
+ "items_upsertMaterialGrade",
+ "items_upsertMaterialType"
+ ])("%s stamps no audit columns its table lacks", (name) => {
+ expect(tool(name)?.injectAuth).toEqual(["companyId"]);
+ });
+
+ it("items_updateMaterialProperties is reachable with a database client", () => {
+ const update = tool("items_updateMaterialProperties");
+ expect(update?.serviceParams).toEqual(["client", "db", "material"]);
+ expect(update?.injectAuth).toEqual(
+ expect.arrayContaining(["companyId", "updatedBy"])
+ );
+ });
+});
diff --git a/apps/erp/test/upsert-typed-item-keys.test.ts b/apps/erp/test/upsert-typed-item-keys.test.ts
index 5c57bc4c39..3c335458bc 100644
--- a/apps/erp/test/upsert-typed-item-keys.test.ts
+++ b/apps/erp/test/upsert-typed-item-keys.test.ts
@@ -11,15 +11,16 @@ vi.mock("@carbon/glossary", () => ({
termSlug: vi.fn()
}));
-const { upsertConsumable, upsertMaterial, upsertPart, upsertService, upsertTool } =
+const { upsertConsumable, 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
+// by uuid; part/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.
+// over MCP the typed fields never saved. Materials are pinned with their
+// property rules in material-properties.test.ts.
type Call = {
table: string;
@@ -123,104 +124,6 @@ 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],
diff --git a/scripts/lib/service-metadata.ts b/scripts/lib/service-metadata.ts
index 6040534e93..1a16a2ad96 100644
--- a/scripts/lib/service-metadata.ts
+++ b/scripts/lib/service-metadata.ts
@@ -97,11 +97,17 @@ const DESCRIPTION_OVERRIDES: Record<string, string> = {
// - accounting_upsertFixedAssetUsageLog → fixedAssetUsageLog
// account_upsertNotificationPreference spreads its argument into an upsert on
// notificationPreference, which (like userModulePreference) carries no
-// createdBy/updatedBy columns at all — injecting them breaks the write.
+// createdBy/updatedBy columns at all — injecting them breaks the write. The
+// four lean material lookups (dimension, finish, grade, type) are the same:
+// no audit columns, argument spread into the row.
const INJECT_AUTH_OVERRIDES: Record<string, AuthField[]> = {
inventory_insertManualInventoryAdjustment: ["companyId", "createdBy"],
accounting_upsertFixedAssetUsageLog: ["companyId", "createdBy"],
account_upsertNotificationPreference: ["companyId"],
+ items_upsertMaterialDimension: ["companyId"],
+ items_upsertMaterialFinish: ["companyId"],
+ items_upsertMaterialGrade: ["companyId"],
+ items_upsertMaterialType: ["companyId"],
// Both operations replace settlement rows in a transaction. Their verbs do
// not imply INSERT to the name-based rule, but the service requires the
// authenticated creator for every replacement row.