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): close review findings on material edits

Raul819ba0719431
diff --git a/.claude/rules/material-tables.md b/.claude/rules/material-tables.md
index 394cc36013..557ffe6dbc 100644
--- a/.claude/rules/material-tables.md
+++ b/.claude/rules/material-tables.md
@@ -83,25 +83,34 @@ de-dupes to the latest item per `(readableId, companyId)` and aggregates the rev
`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.
+`upsertMaterial`'s update branch and MCP all go through it. The rules are pure functions in
+`apps/erp/app/modules/items/material-properties.ts` (pinned by `apps/erp/test/material-properties.test.ts`);
+the service loads the rows they read and writes what they decide.
- 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.
+ same call sets them (`resolveMaterialProperties`). This mirrors the panel's cascading pickers;
+ `MaterialForm` clears the same fields on create.
- 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.
+ so an unrelated edit never fails on older data. Refusals are `ruleError`s, so MCP shows them.
+- With `materialGeneratedIds` on, the readable id and name are derived with `getMaterialId` /
+ `getMaterialDescription` once the material has a substance and a form
+ (`generateMaterialIdentity`); until then it keeps its id, so the panel can set them one at a
+ time. Clearing a substance or form that is set is refused. Create requires both.
+- Writes go through Kysely in one transaction (`writeMaterialIdentity`): the material row and, on
+ a rename, every revision's item row; `upsertMaterial` adds the item row, custom fields and
+ itemCost to the same transaction. Kysely bypasses RLS, so `requireMaterialUpdatable` first runs
+ 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
- `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.
+ `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.
- `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`).
+ `scripts/lib/service-metadata.ts`). Their update branch filters by `companyId` when given and
+ never writes it, so an update cannot move a row to another company.
## Code map
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index 418ff6267e..e5ddcecde2 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -343,6 +343,12 @@ dispatcher (`apps/erp/app/routes/api+/inngest.ts`). There is no separate
one. It used to interpolate `JSON.stringify(error)`, which handed a caller the
column, constraint and value out of the PostgREST body, and later an edge
function's own text — CWE-209 either way.
+ - The one exception is a service's own refusal: an error built with
+ `ruleError(message)` (`~/utils/supabase`, code `CARBON_RULE`) is written for
+ the caller, so `isServiceRuleError` lets `callOperation` return its message
+ as an `execution` error. Return one for a broken business rule a caller can
+ fix ("Grade X is not a grade of substance Y"); never wrap a database error
+ in it.
- The **full detail is logged** instead (`logger.error("Operation failed", …)` in
`call.server.ts`) with the operation name, the classification, the raw Supabase
error, and — for an edge function — the message read off the unread `Response`
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 160c80e46a..ae5fa9fecd 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, getMaterialDescription, getMaterialId } from "@carbon/utils";
+import { datetime } from "@carbon/utils";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type { z } from "zod";
@@ -19,7 +19,7 @@ import {
setGenericQueryFilters,
setSearchFilter
} from "~/utils/query";
-import { sanitize } from "~/utils/supabase";
+import { ruleError, sanitize } from "~/utils/supabase";
import type { nonConformancePriority } from "../quality/quality.models";
import type {
operationParameterValidator,
@@ -87,6 +87,19 @@ import {
type toolValidator,
type unitOfMeasureValidator
} from "./items.models";
+import {
+ checkMaterialProperties,
+ clearsSubstanceOrShape,
+ generatedIdsNeedSubstanceAndShape,
+ generateMaterialIdentity,
+ type MaterialPropertyLookups,
+ type MaterialPropertyValues,
+ materialPropertyFields,
+ noMaterialProperties,
+ resolveMaterialProperties,
+ sentFields,
+ sentMaterialProperties
+} from "./material-properties";
import type { InventoryItemType } from "./types";
const PARTS_LIST_COLUMNS =
@@ -3350,9 +3363,9 @@ async function resolveTypedItemForUpdate(
if (byReadableId.data.length > 1) {
return {
data: null,
- error: {
- message: `${args.type} ${args.id} has ${byReadableId.data.length} revisions; pass the item id of the revision to update`
- }
+ error: ruleError(
+ `${args.type} ${args.id} has ${byReadableId.data.length} revisions; pass the item id of the revision to update`
+ )
};
}
// PGRST116 is what a `.single()` miss reports, so the API layer maps this to
@@ -4897,18 +4910,6 @@ 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;
@@ -4916,33 +4917,6 @@ type MaterialPropertyPlan = {
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
@@ -4993,7 +4967,10 @@ async function getMaterialPropertyLookups(
client: SupabaseClient<Database>,
companyId: string,
values: MaterialPropertyValues
-) {
+): Promise<
+ | { data: MaterialPropertyLookups; error: null }
+ | { data: null; error: ServiceError }
+> {
const visible = `companyId.eq.${companyId},companyId.is.null`;
const none = { data: null, error: null };
const [substance, form, type, finish, grade, dimension] = await Promise.all([
@@ -5065,68 +5042,10 @@ async function getMaterialPropertyLookups(
};
}
-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.
+ * Resolves and checks a set of property changes without writing anything (see
+ * material-properties.ts for the rules). With generated material IDs on, also
+ * derives the readable id and name.
*/
async function planMaterialPropertyChanges(
client: SupabaseClient<Database>,
@@ -5140,28 +5059,15 @@ async function planMaterialPropertyChanges(
| { 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]
+ const { next, changed } = resolveMaterialProperties(
+ args.current,
+ args.changes
);
- if (changedFields.length === 0) {
- return {
- data: { changed: {}, generated: null },
- error: null
- };
+ if (Object.keys(changed).length === 0) {
+ return { data: { changed, generated: null }, error: null };
+ }
+ if (args.generatedIds && clearsSubstanceOrShape(args.current, next)) {
+ return { data: null, error: ruleError(generatedIdsNeedSubstanceAndShape) };
}
const lookups = await getMaterialPropertyLookups(
@@ -5171,54 +5077,78 @@ async function planMaterialPropertyChanges(
);
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)
- };
- }
+ const invalid = checkMaterialProperties(args.current, next, lookups.data);
+ if (invalid) return { data: null, error: ruleError(invalid) };
return {
data: {
- changed: Object.fromEntries(changedFields.map((f) => [f, next[f]])),
- generated
+ changed,
+ generated: args.generatedIds
+ ? generateMaterialIdentity(next, lookups.data)
+ : null
},
error: null
};
}
+async function materialIdIsTaken(
+ client: SupabaseClient<Database>,
+ readableId: string,
+ companyId: string
+): Promise<
+ { data: boolean; error: null } | { data: null; error: ServiceError }
+> {
+ const taken = await client
+ .from("item")
+ .select("id")
+ .eq("readableId", readableId)
+ .eq("companyId", companyId)
+ .eq("type", "Material")
+ .limit(1);
+ if (taken.error) return { data: null, error: taken.error };
+ return { data: taken.data.length > 0, error: null };
+}
+
/**
- * 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.
+ * Proves the caller may update the material before a Kysely write, which
+ * bypasses RLS: the same UPDATE through the caller's client has to match the
+ * row. Material's UPDATE policy (parts_update in the company) is the one its
+ * item and itemCost rows also grant. It sets only the audit columns the write
+ * sets anyway.
*/
-async function saveMaterialIdentity(
- db: Kysely<KyselyDatabase>,
+async function requireMaterialUpdatable(
+ client: SupabaseClient<Database>,
+ args: { readableId: string; companyId: string; updatedBy: string }
+): Promise<{ error: ServiceError | null }> {
+ const probe = await client
+ .from("material")
+ .update({ updatedBy: args.updatedBy, updatedAt: datetime.timestamp() })
+ .eq("id", args.readableId)
+ .eq("companyId", args.companyId)
+ .select("id")
+ .single();
+ return { error: probe.error };
+}
+
+/** A refusal raised inside a material transaction, rolled back and reported. */
+class MaterialRuleViolation extends Error {}
+
+function materialWriteError(error: unknown): ServiceError {
+ if (error instanceof MaterialRuleViolation) return ruleError(error.message);
+ const code =
+ error && typeof error === "object" && "code" in error
+ ? String((error as { code: unknown }).code)
+ : undefined;
+ const message = error instanceof Error ? error.message : String(error);
+ return code ? { code, message } : { message };
+}
+
+/**
+ * Inside `trx`: property changes and a new readable id or name on the material
+ * row and every revision's item row. Returns the readable id after.
+ */
+async function writeMaterialIdentity(
+ trx: KyselyTx,
args: {
readableId: string;
newReadableId?: string;
@@ -5227,83 +5157,70 @@ async function saveMaterialIdentity(
updatedBy: string;
changes: Partial<MaterialPropertyValues>;
}
-): Promise<
- | { data: { readableId: string }; error: null }
- | { data: null; error: ServiceError }
-> {
+): Promise<string> {
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" } };
+ throw new MaterialRuleViolation("Material ID cannot be empty");
}
if (!renamed && args.name === undefined && !Object.keys(changes).length) {
- return { data: { readableId }, error: null };
+ return readableId;
}
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) {
+ const taken = await trx
+ .selectFrom("item")
+ .select("id")
+ .where("readableId", "=", newReadableId)
+ .where("companyId", "=", companyId)
+ .where("type", "=", "Material")
+ .executeTakeFirst();
+ if (taken) {
+ throw new MaterialRuleViolation(
+ `Material ${newReadableId} already exists`
+ );
+ }
+ }
- 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)
- }
- };
+ 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 MaterialRuleViolation(`Material ${readableId} not found`);
}
- return { data: { readableId: newReadableId }, error: null };
+ 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();
+ }
+ return newReadableId;
}
/**
- * 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.
+ * The sizes a material lacks, refused while it is open in a change notice as
+ * New Revision is. Runs before any write so a refusal changes nothing.
*/
-async function addMaterialSizes(
+async function getNewMaterialSizes(
client: SupabaseClient<Database>,
args: {
itemId: string;
readableId: string;
companyId: string;
- createdBy: string;
sizes: string[];
}
): Promise<
@@ -5338,36 +5255,23 @@ async function addMaterialSizes(
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.`
- }
+ error: ruleError(
+ `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 };
+ return { data: sizes, 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.
+ * Creates a material or updates one by item id or readable id; an update keeps
+ * any optional field it leaves out, 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.
+ * IDs are typed by hand. An update's material, item and item cost writes land
+ * together or not at all.
*/
export async function upsertMaterial(
client: SupabaseClient<Database>,
@@ -5395,22 +5299,34 @@ export async function upsertMaterial(
const plan = await planMaterialPropertyChanges(client, {
companyId: material.companyId,
current: noMaterialProperties,
- changes: sentFields(material, materialPropertyFields),
+ changes: sentMaterialProperties(material),
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"
- }
+ error: ruleError(generatedIdsNeedSubstanceAndShape)
};
}
const readableId = plan.data.generated?.readableId ?? material.id;
const name = plan.data.generated?.name ?? material.name;
+ // An existing id would take the new item rows as extra revisions and
+ // overwrite its material row; sizes on an update add revisions instead.
+ const taken = await materialIdIsTaken(
+ client,
+ readableId,
+ material.companyId
+ );
+ if (taken.error) return taken;
+ if (taken.data) {
+ return {
+ data: null,
+ error: ruleError(`Material ${readableId} already exists`)
+ };
+ }
+
// Collect every newly-created item id across the sizes / no-sizes
// branches so the shelf-life policy can be applied uniformly.
const newItemIds: string[] = [];
@@ -5560,6 +5476,7 @@ export async function upsertMaterial(
const itemId = item.data.id;
let readableId = item.data.readableId;
+ // Everything that can be refused is checked before the first write.
const current = await getMaterialPropertyValues(
client,
readableId,
@@ -5567,28 +5484,25 @@ export async function upsertMaterial(
);
if (current.error) return current;
- // Everything that can be refused is checked before the first write.
const plan = await planMaterialPropertyChanges(client, {
companyId,
current: current.data,
- changes: sentFields(material, materialPropertyFields),
+ changes: sentMaterialProperties(material),
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;
+ let newSizes: string[] = [];
+ if (material.sizes?.length) {
+ const sizes = await getNewMaterialSizes(client, {
+ itemId,
+ readableId,
+ companyId,
+ sizes: material.sizes
+ });
+ if (sizes.error) return sizes;
+ newSizes = sizes.data;
+ }
const itemUpdate = sentFields(material, [
"name",
@@ -5599,55 +5513,73 @@ export async function upsertMaterial(
"itemTrackingType",
"unitOfMeasureCode"
]);
- // A regenerated name was just written to every revision.
+ // A regenerated name is written to every revision below.
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({
- customFields: material.customFields ?? null,
- updatedBy,
- updatedAt: datetime.timestamp()
- })
- .eq("id", readableId)
- .eq("companyId", companyId)
- .select("id")
- .single();
- if (updateMaterial.error) return updateMaterial;
- }
-
const costUpdate: { itemPostingGroupId?: string | null; unitCost?: number } =
{};
if ("postingGroupId" in material) {
- costUpdate.itemPostingGroupId = material.postingGroupId ?? null;
+ 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 permitted = await requireMaterialUpdatable(client, {
+ readableId,
+ companyId,
+ updatedBy
+ });
+ if (permitted.error) return { data: null, error: permitted.error };
+
+ const updatedAt = datetime.timestamp();
+ try {
+ readableId = await db.transaction().execute(async (trx) => {
+ // Generated IDs follow the properties; hand-typed ones follow
+ // `readableId`.
+ const saved = await writeMaterialIdentity(trx, {
+ readableId,
+ newReadableId: generatedIds.data
+ ? plan.data.generated?.readableId
+ : material.readableId || undefined,
+ name: plan.data.generated?.name,
+ companyId,
+ updatedBy,
+ changes: plan.data.changed
+ });
+
+ await trx
+ .updateTable("item")
+ .set({ ...itemUpdate, updatedBy, updatedAt })
+ .where("id", "=", itemId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ if ("customFields" in material) {
+ await trx
+ .updateTable("material")
+ .set({ customFields: material.customFields ?? null, updatedAt })
+ .where("id", "=", saved)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+
+ // The item insert trigger creates the itemCost row, so this updates it.
+ if (Object.keys(costUpdate).length > 0) {
+ const cost = await trx
+ .updateTable("itemCost")
+ .set({ ...costUpdate, updatedBy, updatedAt })
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (Number(cost.numUpdatedRows) !== 1) {
+ throw new MaterialRuleViolation(`Item cost for ${itemId} not found`);
+ }
+ }
+ return saved;
+ });
+ } catch (error) {
+ return { data: null, error: materialWriteError(error) };
}
const pickMethod = await upsertItemDefaultPickMethod(client, {
@@ -5669,15 +5601,18 @@ export async function upsertMaterial(
});
if (shelfLife.error) return shelfLife;
- if (material.sizes?.length) {
- const sizes = await addMaterialSizes(client, {
- itemId,
- readableId,
- companyId,
- createdBy: updatedBy,
- sizes: material.sizes
- });
- if (sizes.error) return sizes;
+ if (newSizes.length > 0) {
+ // Copied from the updated revision, the way New Revision copies one.
+ const source = await getItem(client, itemId);
+ if (source.error) return source;
+ for (const size of newSizes) {
+ const revision = await createRevision(client, {
+ item: source.data,
+ revision: size,
+ createdBy: updatedBy
+ });
+ if (revision.error) return revision;
+ }
}
return client
@@ -5690,11 +5625,12 @@ export async function upsertMaterial(
/**
* 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.
+ * properties keep their value; null or an empty string 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 once
+ * the material has a substance and a shape.
*/
export async function updateMaterialProperties(
client: SupabaseClient<Database>,
@@ -5723,7 +5659,7 @@ export async function updateMaterialProperties(
.eq("type", "Material")
.maybeSingle();
if (item.error) return item;
- const readableId = item.data?.readableId ?? material.id;
+ let readableId = item.data?.readableId ?? material.id;
const [current, generatedIds] = await Promise.all([
getMaterialPropertyValues(client, readableId, companyId),
@@ -5735,27 +5671,47 @@ export async function updateMaterialProperties(
const plan = await planMaterialPropertyChanges(client, {
companyId,
current: current.data,
- changes: sentFields(material, materialPropertyFields),
+ changes: sentMaterialProperties(material),
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;
+ if (Object.keys(plan.data.changed).length > 0) {
+ const permitted = await requireMaterialUpdatable(client, {
+ readableId,
+ companyId,
+ updatedBy
+ });
+ if (permitted.error) return { data: null, error: permitted.error };
- return client
+ try {
+ readableId = await db.transaction().execute((trx) =>
+ writeMaterialIdentity(trx, {
+ readableId,
+ newReadableId: plan.data.generated?.readableId,
+ name: plan.data.generated?.name,
+ companyId,
+ updatedBy,
+ changes: plan.data.changed
+ })
+ );
+ } catch (error) {
+ return { data: null, error: materialWriteError(error) };
+ }
+ }
+
+ // The view names the grade, finish, dimension and type; add their ids.
+ const row = await client
.from("materials")
.select("*")
- .eq("readableId", saved.data.readableId)
+ .eq("readableId", readableId)
.eq("companyId", companyId)
.single();
+ if (row.error) return row;
+ return {
+ data: { ...row.data, ...current.data, ...plan.data.changed },
+ error: null
+ };
}
/**
@@ -5771,18 +5727,19 @@ export async function upsertMaterialDimension(
})
| (Omit<z.infer<typeof materialDimensionValidator>, "id"> & {
id: string;
+ companyId?: string;
})
) {
if ("id" in materialDimension) {
- return (
- client
- .from("materialDimension")
- .update(sanitize(materialDimension))
- // @ts-ignore
- .eq("id", materialDimension.id)
- .select("id")
- .single()
- );
+ // Never moves the row to another company: companyId only narrows the
+ // match (MCP stamps it on every call; the settings page omits it).
+ const { id, companyId, ...update } = materialDimension;
+ let query = client
+ .from("materialDimension")
+ .update(sanitize(update))
+ .eq("id", id);
+ if (companyId) query = query.eq("companyId", companyId);
+ return query.select("id").single();
}
return client
@@ -5804,18 +5761,19 @@ export async function upsertMaterialFinish(
})
| (Omit<z.infer<typeof materialFinishValidator>, "id"> & {
id: string;
+ companyId?: string;
})
) {
if ("id" in materialFinish) {
- return (
- client
- .from("materialFinish")
- .update(sanitize(materialFinish))
- // @ts-ignore
- .eq("id", materialFinish.id)
- .select("id")
- .single()
- );
+ // Never moves the row to another company: companyId only narrows the
+ // match (MCP stamps it on every call; the settings page omits it).
+ const { id, companyId, ...update } = materialFinish;
+ let query = client
+ .from("materialFinish")
+ .update(sanitize(update))
+ .eq("id", id);
+ if (companyId) query = query.eq("companyId", companyId);
+ return query.select("id").single();
}
return client
.from("materialFinish")
@@ -5868,18 +5826,19 @@ export async function upsertMaterialGrade(
})
| (Omit<z.infer<typeof materialGradeValidator>, "id"> & {
id: string;
+ companyId?: string;
})
) {
if ("id" in materialGrade) {
- return (
- client
- .from("materialGrade")
- .update(sanitize(materialGrade))
- // @ts-ignore
- .eq("id", materialGrade.id)
- .select("id")
- .single()
- );
+ // Never moves the row to another company: companyId only narrows the
+ // match (MCP stamps it on every call; the settings page omits it).
+ const { id, companyId, ...update } = materialGrade;
+ let query = client
+ .from("materialGrade")
+ .update(sanitize(update))
+ .eq("id", id);
+ if (companyId) query = query.eq("companyId", companyId);
+ return query.select("id").single();
}
return client
.from("materialGrade")
@@ -5953,18 +5912,19 @@ export async function upsertMaterialType(
})
| (Omit<z.infer<typeof materialTypeValidator>, "id"> & {
id: string;
+ companyId?: string;
})
) {
if ("id" in materialType) {
- return (
- client
- .from("materialType")
- .update(sanitize(materialType))
- // @ts-ignore
- .eq("id", materialType.id)
- .select("id")
- .single()
- );
+ // Never moves the row to another company: companyId only narrows the
+ // match (MCP stamps it on every call; the settings page omits it).
+ const { id, companyId, ...update } = materialType;
+ let query = client
+ .from("materialType")
+ .update(sanitize(update))
+ .eq("id", id);
+ if (companyId) query = query.eq("companyId", companyId);
+ return query.select("id").single();
}
return client
.from("materialType")
diff --git a/apps/erp/app/modules/items/material-properties.ts b/apps/erp/app/modules/items/material-properties.ts
new file mode 100644
index 0000000000..05e228ffe7
--- /dev/null
+++ b/apps/erp/app/modules/items/material-properties.ts
@@ -0,0 +1,208 @@
+import { getMaterialDescription, getMaterialId } from "@carbon/utils";
+
+// The material properties panel's rules as pure decisions, shared by the
+// panel's route, upsertMaterial and updateMaterialProperties (MCP). The
+// service loads the rows these read and writes what they decide.
+
+export const materialPropertyFields = [
+ "materialSubstanceId",
+ "materialFormId",
+ "materialTypeId",
+ "finishId",
+ "gradeId",
+ "dimensionId"
+] as const;
+
+export type MaterialPropertyField = (typeof materialPropertyFields)[number];
+export type MaterialPropertyValues = Record<
+ MaterialPropertyField,
+ string | null
+>;
+
+export const noMaterialProperties: MaterialPropertyValues = {
+ materialSubstanceId: null,
+ materialFormId: null,
+ materialTypeId: null,
+ finishId: null,
+ gradeId: null,
+ dimensionId: null
+};
+
+/** The name, code and parent of each property a material points at. */
+export type MaterialPropertyLookups = {
+ substance: { name: string; code: string } | null;
+ form: { name: string; code: string } | null;
+ type: {
+ name: string;
+ code: string;
+ materialSubstanceId: string;
+ materialFormId: string;
+ } | null;
+ finish: { name: string; materialSubstanceId: string } | null;
+ grade: { name: string; materialSubstanceId: string } | null;
+ dimension: { name: string; materialFormId: string } | null;
+};
+
+export const generatedIdsNeedSubstanceAndShape =
+ "Generated material IDs need a substance and a shape; set both";
+
+/**
+ * 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.
+ */
+export 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;
+}
+
+/** sentFields for the property ids, where an empty string clears like null. */
+export function sentMaterialProperties(
+ source: object
+): Partial<MaterialPropertyValues> {
+ const sent = sentFields(source, materialPropertyFields);
+ for (const field of materialPropertyFields) {
+ if (sent[field] === "") sent[field] = null;
+ }
+ return sent;
+}
+
+/**
+ * Applies `changes` the way the panel's cascading pickers do: a new substance
+ * clears finish, grade and type, and a new shape clears dimension and type,
+ * unless `changes` sets them too. `changed` holds only the values that differ.
+ */
+export function resolveMaterialProperties(
+ current: MaterialPropertyValues,
+ changes: Partial<MaterialPropertyValues>
+): {
+ next: MaterialPropertyValues;
+ changed: Partial<MaterialPropertyValues>;
+} {
+ 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 changed: Partial<MaterialPropertyValues> = {};
+ for (const field of materialPropertyFields) {
+ if (next[field] !== current[field]) changed[field] = next[field];
+ }
+ return { next, changed };
+}
+
+/**
+ * With generated material IDs, a substance or shape once set cannot be
+ * cleared: the readable id is built from both.
+ */
+export function clearsSubstanceOrShape(
+ current: MaterialPropertyValues,
+ next: MaterialPropertyValues
+): boolean {
+ return (
+ (!!current.materialSubstanceId && !next.materialSubstanceId) ||
+ (!!current.materialFormId && !next.materialFormId)
+ );
+}
+
+/**
+ * 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.
+ */
+export 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);
+ const substance = lookups.substance
+ ? `substance ${lookups.substance.name} (${next.materialSubstanceId})`
+ : "no substance";
+ const shape = lookups.form
+ ? `shape ${lookups.form.name} (${next.materialFormId})`
+ : "no shape";
+
+ 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 ${lookups.grade.name} (${next.gradeId}) is not a grade of ${substance}`;
+ }
+ }
+ if (touched("finishId", substanceChanged)) {
+ if (!lookups.finish) return `Finish ${next.finishId} not found`;
+ if (lookups.finish.materialSubstanceId !== next.materialSubstanceId) {
+ return `Finish ${lookups.finish.name} (${next.finishId}) is not a finish of ${substance}`;
+ }
+ }
+ if (touched("dimensionId", formChanged)) {
+ if (!lookups.dimension) return `Dimension ${next.dimensionId} not found`;
+ if (lookups.dimension.materialFormId !== next.materialFormId) {
+ return `Dimension ${lookups.dimension.name} (${next.dimensionId}) is not a dimension of ${shape}`;
+ }
+ }
+ 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 ${lookups.type.name} (${next.materialTypeId}) is not a type of ${substance} and ${shape}`;
+ }
+ }
+ return null;
+}
+
+/**
+ * The generated readable id and name, once the material has a substance and a
+ * shape; until then it keeps its id, so the panel can set them one at a time.
+ */
+export function generateMaterialIdentity(
+ next: MaterialPropertyValues,
+ lookups: MaterialPropertyLookups
+): { readableId: string; name: string } | null {
+ if (!next.materialSubstanceId || !next.materialFormId) return null;
+ const { substance, form, type, finish, grade, dimension } = lookups;
+ 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
+ };
+ return {
+ readableId: getMaterialId(naming),
+ name: getMaterialDescription(naming)
+ };
+}
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
index db05eedc51..ad945ccc92 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
@@ -1,4 +1,4 @@
-import { ValidatedForm } from "@carbon/form";
+import { useUpdateControlledField, ValidatedForm } from "@carbon/form";
import {
cn,
ModalCard,
@@ -18,7 +18,7 @@ import {
} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useEffect, useState } from "react";
+import { useEffect, useId, useState } from "react";
import { useFetcher } from "react-router";
import type { z } from "zod";
import { TrackingTypeIcon } from "~/components";
@@ -91,6 +91,11 @@ const MaterialForm = ({
const [substanceId, setSubstanceId] = useState<string | undefined>();
const [formId, setFormId] = useState<string | undefined>();
+ // A new substance or shape clears the picks that belong to the old one, as
+ // the properties panel does; their pickers would otherwise hide them.
+ const validatedFormId = useId();
+ const setField = useUpdateControlledField(validatedFormId);
+
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
const currencyDecimals = useCurrencyDecimals(baseCurrency);
@@ -157,6 +162,7 @@ const MaterialForm = ({
<ModalCard onClose={onClose}>
<ModalCardContent>
<ValidatedForm
+ id={validatedFormId}
action={path.to.newMaterial}
method="post"
validator={
@@ -224,9 +230,24 @@ const MaterialForm = ({
name="materialSubstanceId"
label={t`Substance`}
onChange={(value) => {
- setSubstanceId(value?.value as string | undefined);
+ const newSubstanceId = value?.value as string | undefined;
+ const changed = newSubstanceId !== substanceId;
+ if (changed) {
+ setField("gradeId", "");
+ setField("finishId", "");
+ setField("materialTypeId", "");
+ }
+ setSubstanceId(newSubstanceId);
setProperties((prev) => ({
...prev,
+ ...(changed
+ ? {
+ grade: "",
+ finish: "",
+ materialType: "",
+ materialTypeCode: ""
+ }
+ : {}),
substance: (value?.label as string) ?? "",
substanceCode:
substance.find((s) => s.value === value?.value)?.code ??
@@ -249,9 +270,22 @@ const MaterialForm = ({
name="materialFormId"
label={t`Shape`}
onChange={(value) => {
- setFormId(value?.value as string | undefined);
+ const newFormId = value?.value as string | undefined;
+ const changed = newFormId !== formId;
+ if (changed) {
+ setField("dimensionId", "");
+ setField("materialTypeId", "");
+ }
+ setFormId(newFormId);
setProperties((prev) => ({
...prev,
+ ...(changed
+ ? {
+ dimensions: "",
+ materialType: "",
+ materialTypeCode: ""
+ }
+ : {}),
shape: (value?.label as string) ?? "",
shapeCode:
shape.find((s) => s.value === value?.value)?.code ?? ""
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 624395c3c6..a23e1e65d9 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
@@ -534,7 +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_updateMaterialProperties","classification":"WRITE","paramCount":7,"schema":"ba2c8db7ad05","response":"82322ed42796","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},
diff --git a/apps/erp/app/routes/api+/v1+/lib/call.server.ts b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
index a96c9aa2e1..508ffbbb66 100644
--- a/apps/erp/app/routes/api+/v1+/lib/call.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
@@ -12,6 +12,7 @@ import { unwrapArgsEnvelope } from "./args-envelope";
import type { AuthedContext } from "./base.server";
import {
classifyDatabaseFailure,
+ isServiceRuleError,
publicDatabaseError,
type SupabaseFailure
} from "./database-errors";
@@ -103,6 +104,15 @@ export async function callOperation(
err instanceof ORPCError
? (err.data as { supabase?: SupabaseFailure } | undefined)?.supabase
: undefined;
+ // A service's own refusal is written for the caller; only a database
+ // failure is reduced to the fixed public messages below.
+ if (isServiceRuleError(supabase)) {
+ return {
+ success: false,
+ error: supabase.message,
+ errorKind: "execution"
+ };
+ }
if (supabase) {
const edgeMessage = await edgeFunctionMessage(supabase);
logger.error("Operation failed", {
diff --git a/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts b/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
index 18821b5d0f..39c079c13c 100644
--- a/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
@@ -1,8 +1,10 @@
import { FunctionsHttpError, PostgrestError } from "@supabase/supabase-js";
import { describe, expect, it } from "vitest";
+import { ruleError } from "~/utils/supabase";
import {
classifyDatabaseFailure,
DATABASE_ERROR_MESSAGES,
+ isServiceRuleError,
publicDatabaseError
} from "./database-errors";
@@ -106,3 +108,20 @@ describe("publicDatabaseError", () => {
}
});
});
+
+describe("isServiceRuleError", () => {
+ it("recognizes only a service's own refusal", () => {
+ expect(isServiceRuleError(ruleError("Grade X is not a grade of Y"))).toBe(
+ true
+ );
+ for (const error of [
+ postgrestError({ code: "23505", message: "duplicate key" }),
+ postgrestError({ message: "boom" }),
+ edgeFunctionError,
+ null,
+ undefined
+ ]) {
+ expect(isServiceRuleError(error)).toBe(false);
+ }
+ });
+});
diff --git a/apps/erp/app/routes/api+/v1+/lib/database-errors.ts b/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
index 41b4428bfa..00d5880abd 100644
--- a/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
@@ -1,4 +1,5 @@
import type { FunctionsError, PostgrestError } from "@supabase/supabase-js";
+import { SERVICE_RULE_ERROR_CODE } from "~/utils/supabase";
export type SupabaseFailure = PostgrestError | FunctionsError;
@@ -50,3 +51,15 @@ export function publicDatabaseError(
): string {
return DATABASE_ERROR_MESSAGES[classifyDatabaseFailure(error)];
}
+
+/** A service's own refusal (`ruleError`), whose message is safe to show. */
+export function isServiceRuleError(
+ error: unknown
+): error is { code: string; message: string } {
+ return (
+ !!error &&
+ typeof error === "object" &&
+ "code" in error &&
+ error.code === SERVICE_RULE_ERROR_CODE
+ );
+}
diff --git a/apps/erp/app/routes/x+/items+/dimensions.$id.tsx b/apps/erp/app/routes/x+/items+/dimensions.$id.tsx
index 541c331fe5..b6e8ce062c 100644
--- a/apps/erp/app/routes/x+/items+/dimensions.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/dimensions.$id.tsx
@@ -41,7 +41,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
update: "parts"
});
@@ -59,6 +59,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateMaterialDimension = await upsertMaterialDimension(client, {
id: id,
+ companyId,
...validation.data
});
diff --git a/apps/erp/app/routes/x+/items+/finishes.$id.tsx b/apps/erp/app/routes/x+/items+/finishes.$id.tsx
index a28086bef8..f854c1846c 100644
--- a/apps/erp/app/routes/x+/items+/finishes.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/finishes.$id.tsx
@@ -40,7 +40,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
update: "parts"
});
@@ -58,6 +58,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateMaterialFinish = await upsertMaterialFinish(client, {
id: id,
+ companyId,
...validation.data
});
diff --git a/apps/erp/app/routes/x+/items+/grades.$id.tsx b/apps/erp/app/routes/x+/items+/grades.$id.tsx
index 89e9b34a39..72f6bf6f72 100644
--- a/apps/erp/app/routes/x+/items+/grades.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/grades.$id.tsx
@@ -40,7 +40,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
update: "parts"
});
@@ -56,6 +56,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateMaterialGrade = await upsertMaterialGrade(client, {
id: id,
+ companyId,
...validation.data
});
diff --git a/apps/erp/app/routes/x+/items+/types.$id.tsx b/apps/erp/app/routes/x+/items+/types.$id.tsx
index 9cbaef5967..4a58bda097 100644
--- a/apps/erp/app/routes/x+/items+/types.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/types.$id.tsx
@@ -46,7 +46,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
update: "parts"
});
@@ -62,6 +62,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateMaterialType = await upsertMaterialType(client, {
id: id,
+ companyId,
...validation.data
});
diff --git a/apps/erp/app/utils/supabase.ts b/apps/erp/app/utils/supabase.ts
index 5833a66a82..c1eb0463d2 100644
--- a/apps/erp/app/utils/supabase.ts
+++ b/apps/erp/app/utils/supabase.ts
@@ -1,2 +1,13 @@
export { parseJobFilePath } from "@carbon/files/media";
export { sanitize } from "@carbon/utils";
+
+/**
+ * The code on an error a service writes itself: a refused business rule, not
+ * a database failure. API and MCP callers see its message as written, while a
+ * database failure is reduced to a fixed public message.
+ */
+export const SERVICE_RULE_ERROR_CODE = "CARBON_RULE";
+
+export function ruleError(message: string) {
+ return { code: SERVICE_RULE_ERROR_CODE, message };
+}
diff --git a/apps/erp/test/material-properties.test.ts b/apps/erp/test/material-properties.test.ts
index a0ec9c9971..5d97b20631 100644
--- a/apps/erp/test/material-properties.test.ts
+++ b/apps/erp/test/material-properties.test.ts
@@ -1,186 +1,20 @@
-import { describe, expect, it, vi } from "vitest";
+import { describe, expect, it } from "vitest";
+import {
+ checkMaterialProperties,
+ clearsSubstanceOrShape,
+ generateMaterialIdentity,
+ type MaterialPropertyLookups,
+ type MaterialPropertyValues,
+ noMaterialProperties,
+ resolveMaterialProperties,
+ sentMaterialProperties
+} from "~/modules/items/material-properties";
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()
-}));
+// The properties panel's rules for material edits, which upsertMaterial,
+// updateMaterialProperties (MCP) and the panel's own route all apply.
-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 = {
+const ALUMINUM_PLATE: MaterialPropertyValues = {
materialSubstanceId: "aluminum",
materialFormId: "plate",
materialTypeId: "al-pl-cast",
@@ -189,528 +23,200 @@ const ALUMINUM_PLATE = {
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 aluminum = { name: "Aluminum", code: "AL" };
+const plate = { name: "Plate", code: "PL" };
+
+/** Lookups for ALUMINUM_PLATE, overridable per test. */
+function lookupsFor(
+ overrides: Partial<MaterialPropertyLookups> = {}
+): MaterialPropertyLookups {
+ return {
+ substance: aluminum,
+ form: plate,
+ type: {
+ name: "Cast",
+ code: "C",
+ materialSubstanceId: "aluminum",
+ materialFormId: "plate"
+ },
+ finish: { name: "Anodized", materialSubstanceId: "aluminum" },
+ grade: { name: "6061", materialSubstanceId: "aluminum" },
+ dimension: { name: '1/4"', materialFormId: "plate" },
+ ...overrides
};
}
-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,
+describe("resolveMaterialProperties", () => {
+ it("a new substance clears finish, grade and type, not dimension", () => {
+ const { next, changed } = resolveMaterialProperties(ALUMINUM_PLATE, {
materialSubstanceId: "steel"
});
- expect(result.error).toBeNull();
- expect(materialWrite(writes)?.set).toMatchObject({
+ expect(changed).toEqual({
materialSubstanceId: "steel",
finishId: null,
gradeId: null,
- materialTypeId: null,
- id: ITEM.readableId,
- updatedBy: USER
+ materialTypeId: null
});
- expect(materialWrite(writes)?.set).not.toHaveProperty("dimensionId");
- expect(materialWrite(writes)?.where).toEqual(
- expect.arrayContaining([
- ["=", "id", ITEM.readableId],
- ["=", "companyId", COMPANY]
- ])
- );
+ expect(next.dimensionId).toBe("pl-025");
});
- 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,
+ it("keeps a dependent the same change sets", () => {
+ const { changed } = resolveMaterialProperties(ALUMINUM_PLATE, {
materialSubstanceId: "steel",
gradeId: "stl-1018"
});
- expect(result.error).toBeNull();
- expect(materialWrite(writes)?.set).toMatchObject({
- materialSubstanceId: "steel",
- gradeId: "stl-1018",
- finishId: null
- });
+ expect(changed).toMatchObject({ 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,
+ it("a new shape clears dimension and type, not grade", () => {
+ const { changed } = resolveMaterialProperties(ALUMINUM_PLATE, {
materialFormId: "roundBar"
});
- expect(materialWrite(writes)?.set).toMatchObject({
+ expect(changed).toEqual({
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("echoing the current values changes nothing", () => {
+ expect(
+ resolveMaterialProperties(ALUMINUM_PLATE, { ...ALUMINUM_PLATE }).changed
+ ).toEqual({});
});
+});
- 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"]
- ])
- );
- });
+describe("checkMaterialProperties", () => {
+ const check = (
+ changes: Partial<MaterialPropertyValues>,
+ overrides: Partial<MaterialPropertyLookups> = {},
+ current = ALUMINUM_PLATE
+ ) => {
+ const { next } = resolveMaterialProperties(current, changes);
+ return checkMaterialProperties(current, next, lookupsFor(overrides));
+ };
- 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("accepts picks from the substance's and shape's lists", () => {
+ expect(
+ check(
+ { gradeId: "al-7075" },
+ { grade: { name: "7075", materialSubstanceId: "aluminum" } }
+ )
+ ).toBeNull();
});
- 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);
+ it.each([
+ [
+ { gradeId: "stl-1018" },
+ { grade: { name: "1018", materialSubstanceId: "steel" } },
+ "Grade 1018 (stl-1018) is not a grade of substance Aluminum (aluminum)"
+ ],
+ [
+ { finishId: "stl-black" },
+ { finish: { name: "Black oxide", materialSubstanceId: "steel" } },
+ "Finish Black oxide (stl-black) is not a finish of substance Aluminum"
+ ],
+ [
+ { dimensionId: "rb-1" },
+ { dimension: { name: '1"', materialFormId: "roundBar" } },
+ 'Dimension 1" (rb-1) is not a dimension of shape Plate (plate)'
+ ],
+ [
+ { materialFormId: "roundBar", materialTypeId: "al-pl-cast" },
+ { form: { name: "Round Bar", code: "RB" } },
+ "Type Cast (al-pl-cast) is not a type of substance Aluminum (aluminum) and shape Round Bar (roundBar)"
+ ],
+ [{ finishId: "missing" }, { finish: null }, "Finish missing not found"],
+ [
+ { materialSubstanceId: "unobtainium" },
+ { substance: null },
+ "Substance unobtainium not found"
+ ]
+ ] as const)("refuses %o", (changes, overrides, message) => {
+ expect(check(changes, overrides)).toContain(message);
+ });
+
+ it("re-checks a kept dependent against a new parent", () => {
+ expect(
+ check(
+ { materialSubstanceId: "steel", gradeId: "al-6061" },
+ { substance: { name: "Steel", code: "STL" } }
+ )
+ ).toContain("is not a grade of substance Steel (steel)");
+ });
+
+ it("leaves an older inconsistency alone when the change is elsewhere", () => {
+ const current = { ...ALUMINUM_PLATE, gradeId: "stl-1018" };
+ expect(
+ check(
+ { dimensionId: null },
+ { grade: { name: "1018", materialSubstanceId: "steel" } },
+ current
+ )
+ ).toBeNull();
+ });
+
+ it("a grade needs a substance", () => {
+ expect(
+ check(
+ { gradeId: "al-6061" },
+ { substance: null },
+ noMaterialProperties
+ )
+ ).toContain("is not a grade of no substance");
});
});
-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"
+describe("generated material IDs", () => {
+ it("builds the readable id from codes and the name from names", () => {
+ expect(generateMaterialIdentity(ALUMINUM_PLATE, lookupsFor())).toEqual({
+ readableId: '6061-AL-C-PL-1/4"-Anodized',
+ name: '6061 Aluminum Cast Plate 1/4" Anodized'
});
- 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("waits for both a substance and a shape", () => {
+ const substanceOnly = {
+ ...noMaterialProperties,
+ materialSubstanceId: "aluminum"
+ };
+ expect(
+ generateMaterialIdentity(substanceOnly, lookupsFor({ form: null }))
+ ).toBeNull();
});
- 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" }]
+ it("refuses clearing a substance or shape that is set, not setting one", () => {
+ expect(
+ clearsSubstanceOrShape(ALUMINUM_PLATE, {
+ ...ALUMINUM_PLATE,
+ materialFormId: null
})
- );
- 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);
+ ).toBe(true);
+ expect(
+ clearsSubstanceOrShape(noMaterialProperties, {
+ ...noMaterialProperties,
+ materialSubstanceId: "aluminum"
+ })
+ ).toBe(false);
});
});
-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")
+describe("sentMaterialProperties", () => {
+ it("absent keeps, undefined, null and empty string clear", () => {
+ expect(
+ sentMaterialProperties({
+ gradeId: undefined,
+ finishId: null,
+ dimensionId: "",
+ materialFormId: "plate",
+ name: "ignored"
+ })
+ ).toEqual({
+ gradeId: null,
+ finishId: null,
+ dimensionId: null,
+ materialFormId: "plate"
});
- expect(writesTo(calls, "item", "insert")).toHaveLength(0);
});
});
diff --git a/apps/erp/test/upsert-typed-item-keys.test.ts b/apps/erp/test/upsert-typed-item-keys.test.ts
deleted file mode 100644
index 3c335458bc..0000000000
--- a/apps/erp/test/upsert-typed-item-keys.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-
-// The items.service graph transitively loads @carbon/glossary, whose
-// module-load-time Lingui `msg` macro isn't transformed under plain vitest.
-// Stub it; the upserts under test stay the genuine implementation.
-vi.mock("@carbon/glossary", () => ({
- terms: {},
- getEntry: vi.fn(),
- lookupEntry: vi.fn(),
- hasEntry: vi.fn(),
- termSlug: vi.fn()
-}));
-
-const { upsertConsumable, 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/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. Materials are pinned with their
-// property rules in material-properties.test.ts.
-
-type Call = {
- table: string;
- op: "select" | "update" | "insert" | "upsert" | "delete";
- payload?: Record<string, unknown>;
- filters: Array<[string, string, unknown]>;
- single?: "single" | "maybeSingle";
-};
-type Response = { data: unknown; error: unknown };
-
-/** A supabase stub that records every query and answers from `respond`. */
-function makeClient(respond: (call: Call) => Response) {
- const calls: Call[] = [];
- const from = (table: string) => {
- const call: Call = { table, op: "select", filters: [] };
- let started = false;
- const builder: Record<string, unknown> = {};
- builder.select = () => {
- // A select after a write is the "return the row" modifier.
- if (!started) {
- started = true;
- call.op = "select";
- }
- return builder;
- };
- for (const op of ["update", "insert", "upsert", "delete"] as const) {
- builder[op] = (payload?: Record<string, unknown>) => {
- started = true;
- call.op = op;
- call.payload = payload;
- return builder;
- };
- }
- builder.eq = (column: string, value: unknown) => {
- call.filters.push(["eq", column, value]);
- return builder;
- };
- builder.in = (column: string, value: unknown) => {
- call.filters.push(["in", column, value]);
- return builder;
- };
- builder.single = () => {
- call.single = "single";
- return builder;
- };
- builder.maybeSingle = () => {
- call.single = "maybeSingle";
- return builder;
- };
- builder.then = (
- resolve: (value: Response) => unknown,
- reject?: (reason: unknown) => unknown
- ) => {
- calls.push(call);
- return Promise.resolve(respond(call)).then(resolve, reject);
- };
- return builder;
- };
- return { client: { from } as never, calls };
-}
-
-const COMPANY = "company-1";
-const ITEM = { id: "item-uuid-1", readableId: "MAT-AL-PLATE" };
-
-/** Answers the item lookups and the two updates from fixed responses. */
-function respondWith(opts: {
- byId?: typeof ITEM | null;
- byReadableId?: (typeof ITEM)[];
- itemUpdate?: Response;
- typedUpdate?: Response;
-}) {
- return (call: Call): Response => {
- if (call.table === "item" && call.op === "select") {
- const byUuid = call.filters.some(([, column]) => column === "id");
- return byUuid
- ? { data: opts.byId ?? null, error: null }
- : { data: opts.byReadableId ?? [], error: null };
- }
- if (call.op === "update") {
- return call.table === "item"
- ? (opts.itemUpdate ?? { data: { id: ITEM.id }, error: null })
- : (opts.typedUpdate ?? { data: { id: ITEM.readableId }, error: null });
- }
- return { data: null, error: null };
- };
-}
-
-const base = {
- name: "Aluminum plate",
- replenishmentSystem: "Buy" as const,
- defaultMethodType: "Pull from Inventory" as const,
- itemTrackingType: "Inventory" as const,
- unitOfMeasureCode: "EA",
- shelfLifeCalculateFromBom: false,
- companyId: COMPANY,
- updatedBy: "user-1"
-};
-
-const updates = (calls: Call[]) => calls.filter((c) => c.op === "update");
-const updateOf = (calls: Call[], table: string) =>
- updates(calls).find((c) => c.table === table);
-
-describe("typed item updates resolve uuid vs readable id", () => {
- it.each([
- ["part", upsertPart],
- ["tool", upsertTool],
- ["consumable", upsertConsumable],
- ["service", upsertService]
- ] as const)(
- "%s: the typed row is keyed by readableId + companyId",
- async (table, upsert) => {
- const { client, calls } = makeClient(respondWith({ byId: ITEM }));
- // The service validator narrows tracking to Non-Inventory; the payload
- // has to satisfy all four signatures at once.
- const result = await upsert(client, {
- ...base,
- id: ITEM.id,
- itemTrackingType: "Non-Inventory" as const,
- revision: "0",
- customFields: { colour: "red" }
- });
- expect(result.error).toBeNull();
-
- const typed = updateOf(calls, table);
- expect(typed?.filters).toEqual(
- expect.arrayContaining([
- ["eq", "id", ITEM.readableId],
- ["eq", "companyId", COMPANY]
- ])
- );
- expect(typed?.payload).toMatchObject({ customFields: { colour: "red" } });
- expect(typed?.single).toBe("single");
-
- const item = updateOf(calls, "item");
- expect(item?.filters).toEqual(
- expect.arrayContaining([
- ["eq", "id", ITEM.id],
- ["eq", "companyId", COMPANY]
- ])
- );
- expect(item?.payload).not.toHaveProperty("id");
- }
- );
-});