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.

Merge remote-tracking branch 'origin/main' into naveenkash/item-master-revision-data-copy

naveenkashc82a3f47970e
diff --cc .ai/lessons.md
index ae9de6734b,e93b072089..0810e446e1
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@@ -2707,26 -2740,86 +2740,110 @@@ drawer (`foo.tsx` + `foo.new.tsx`). A l
`search: "all"`. A loader that reads the pathname, a cookie or a header must not use the
helper.
+ ## A write that changes nothing still costs a queue message, an Inngest event and a function run
+
+ **Context:** `/api/inngest` was the largest consumer on the ERP deployment (2026-10-01
+ traces). The audit handler's log was mostly "Skipping: no meaningful diff for UPDATE on
+ jobOperation".
+
+ **Problem:** The scheduler's `persistChanges` issued one `UPDATE jobOperation` per operation on
+ every regen, always setting `updatedAt`, and re-stamped `status = 'Ready'` on operations that
+ were already Ready. `dispatch_event_batch()` queued every one of those updates, the drainer
+ sent them to Inngest ten at a time, and the audit, search and embedding handlers then threw
+ them away. Nothing was wrong in any single place; the waste was the sum.
+
+ **Rule:** A bulk writer guards its UPDATE on the values it writes (`isDistinctFromAny` in
+ `scheduling-engine.ts` compares in Postgres, so DATE and timestamptz are matched in their own
+ type) rather than writing every row and bumping `updatedAt`. The trigger is the backstop: an
+ UPDATE that changes only `updatedAt` / `updatedBy` / `embedding` is not queued for AUDIT,
+ SEARCH or EMBEDDING (`20261001195204`). When forking `dispatch_event_batch()` into a new
+ migration, fork the NEWEST definition; `packages/database/src/event-dispatch.test.ts` fails
+ if the filter is lost.
+
+ **Applies to:** `packages/planning/src/scheduling/`, any job or route that rewrites many rows
+ of a table with event subscriptions, and every migration that redefines
+ `dispatch_event_batch()`.
+
+ ## A cached generator's inputs are everything it executes, not everything it parses
+
+ **Context:** The MCP manifest generator was made a cached Turborepo task with `inputs`
+ listing the service, models and `types.ts` files it parses.
+
+ **Problem:** It also EXECUTES every `*.models.ts` to convert the zod validators, so the
+ schemas depend on whatever those files import: `sales.utils.ts`, `accounting.utils.ts`,
+ `samplingStandards`, `@carbon/utils`. A change to one of those was a cache hit; turbo
+ restored the old manifest (and the old committed digest) over the working tree, and the
+ build bundled it. Uncached, this could not happen.
+
+ **Rule:** Before caching a task, list what it loads and runs, not only what it reads on
+ purpose, and pin that list with a test against the task's real imports. If the true set
+ cannot be named, leave the task uncached.
+
+ **Applies to:** `//#generate:mcp` in `turbo.json` (pinned by
+ `apps/erp/test/mcp-manifest-cache-inputs.test.ts`), and any task given `inputs`.
+
+ ## A key looked up "anywhere in the payload" finds the wrong one
+
+ **Context:** The API dispatcher decides whether an upsert creates or updates from the
+ record's `id`. It looked for `id` at the top level and then inside any nested object, to
+ support `{ job: { id } }`.
+
+ **Problem:** `{ name: "x", customFields: { id: "z" } }` matched the nested `id`, so a
+ create was stamped as an update and went down the service's update branch.
+
+ **Rule:** Read a record's key only where the record can be: the body itself or the wrapper
+ named by the service's payload parameter. A search that descends into arbitrary objects
+ will eventually match user data.
+
+ **Applies to:** `resolveUpsertOperation` / `recordField` in
+ `apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts`.
+
+ ## A git merge can move a doc comment onto a different function
+
+ **Context:** Every API tool is declared by an `@mcp` line in its function's doc comment.
+ Main inserted a new function directly under an existing doc block.
+
+ **Problem:** The merge was clean, but the doc block (and its `@mcp` line) now sat above
+ the NEW function, and the function it described had none. That function silently stopped
+ being a tool. Nothing fails: an untagged export is simply not exposed.
+
+ **Rule:** After merging into a branch that touches service files, regenerate the manifest
+ and diff the tool NAMES against the pre-merge list. A name that disappears is a displaced
+ tag until proven otherwise.
+
+ **Applies to:** `apps/erp/app/modules/*/*.service.ts`, `pnpm run generate:mcp`.
+
+
+ ## A cast that silences excess-property errors hides failed writes
+
+ **Context:** supabase-js 2.117 types reject keys a table does not have (`RejectExcessProperties`). The upgrade wrapped ~75 failing write payloads in `unchecked()` (a cast to `never`) to get typecheck green.
+
+ **Problem:** About 30 of those were typed payloads (a zod validator spread into an insert/update) carrying fields the table lacks: `item.shelfLifeCalculateFromBom`, `ability.name`, `quote.notes`, `salesOrder.promisedDate`, `batchProperty.batchPropertyGroupId`, and more. PostgREST rejects any unknown column with PGRST204, so every such write failed whenever the field was present, and `itemValidator`'s always-present checkbox made the BoM explorer's item edit (`api+/item.$type.ts` → `updateItem`) fail on every save. The cast had removed the only warning. The 2.80 types never rejected excess keys, so these were latent all along.
+
+ **Rule:** Never cast a typed payload past the table's type. When the compiler names an extra key, destructure it out at the write, where every caller is covered, and say where the value actually lives. `unchecked()` is only for a column or table chosen at runtime (`{ [field]: value }`, `.from(table)`). To list every extra key at once rather than one per error, probe with `Exclude<keyof Payload, keyof Database["public"]["Tables"][T]["Update"]>`.
+
+ **Applies to:** every `{module}.service.ts` write, MES `services/*.service.ts`, `packages/utils/src/object.ts` (`unchecked`).
++
+## Copying child rows onto a new record can make that record undeletable
+
+**Context:** A new item revision now inherits the source revision's supplier parts and their
+price breaks (`copyItemPlanningAndPurchasing`, called by `createRevision`). A change notice
+discards its draft revision by deleting the draft item.
+
+**Problem:** `supplierPart.itemId → item` is `ON DELETE CASCADE`, but
+`supplierPartPrice → supplierPart` is `ON DELETE RESTRICT`. An item delete therefore cascades
+into a supplier part that a price break refuses to let go, and the whole delete fails with
+`23503`. Before the copy, a fresh revision had no supplier parts, so nothing exercised that
+path; after it, every revision of an item with price breaks carries the blocker, and
+`discardChangeNoticeDraft` ignores the delete's error — the draft would have survived
+silently. Reading the migrations for the table being copied was not enough; the constraint
+that mattered sat on its child.
+
+**Rule:** Before copying rows onto a record, list the delete rule of every FK that points at
+the copied tables (`pg_constraint.confdeltype`, or `grep REFERENCES` for the table name) and
+walk every path that deletes the parent. A `RESTRICT`/`NO ACTION` child turns a copy into a
+delete blocker. Either delete the child first on that path, or change the rule in a migration.
+
+**Applies to:** `apps/erp/app/modules/items/items.service.ts` (`createRevision`,
+`discardChangeNoticeDraft`, `deleteItem`, `deleteSupplierPart`), and any copy/duplicate of
+`supplierPart`.
diff --cc apps/erp/app/modules/items/items.service.ts
index accbe0416f,01186fc435..b7a5f5b87e
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@@ -214,180 -217,9 +217,181 @@@ export async function copyItemPostingGr
.eq("companyId", args.companyId);
}
+// What a new revision inherits from the revision it was copied from, beyond the
+// item row and the method: replenishment (batch size, scrap percent, lead time,
+// the preferred supplier and its purchasing unit), each location's reorder
+// policy with its parameters, the item group, and the supplier parts with their
+// price breaks. Runs in the transaction that inserted the target item: the item
+// interceptor has by then created the target's itemReplenishment / itemPlanning
+// / itemCost rows with defaults, and it has no supplier parts, so this updates
+// those rows in place and inserts the rest. Both sides of every statement are
+// scoped to the company.
+async function copyItemPlanningAndPurchasing(
+ trx: KyselyTx,
+ args: {
+ sourceItemId: string;
+ targetItemId: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ const { sourceItemId, targetItemId, companyId, userId } = args;
+ const updatedAt = datetime.timestamp();
+
+ await trx
+ .updateTable("itemReplenishment as target")
+ .from("itemReplenishment as source")
+ .set((eb) => ({
+ lotSize: eb.ref("source.lotSize"),
+ scrapPercentage: eb.ref("source.scrapPercentage"),
+ leadTime: eb.ref("source.leadTime"),
+ // The purchasing unit and conversion factor are properties of the
+ // preferred supplier's supplier part (see upsertItemPurchasing), which
+ // is copied below, so the three travel together.
+ preferredSupplierId: eb.ref("source.preferredSupplierId"),
+ purchasingUnitOfMeasureCode: eb.ref("source.purchasingUnitOfMeasureCode"),
+ conversionFactor: eb.ref("source.conversionFactor"),
+ updatedBy: userId,
+ updatedAt
+ }))
+ .where("target.itemId", "=", targetItemId)
+ .where("target.companyId", "=", companyId)
+ .where("source.itemId", "=", sourceItemId)
+ .where("source.companyId", "=", companyId)
+ .execute();
+
+ // A reorder policy is only meaningful with its parameters (Maximum
+ // Quantity needs a reorder point and a maximum, and so on), so the whole
+ // planning form is copied, location by location. A location the source has
+ // no planning row for keeps the defaults.
+ await trx
+ .updateTable("itemPlanning as target")
+ .from("itemPlanning as source")
+ .set((eb) => ({
+ reorderingPolicy: eb.ref("source.reorderingPolicy"),
+ demandAccumulationPeriod: eb.ref("source.demandAccumulationPeriod"),
+ demandAccumulationSafetyStock: eb.ref(
+ "source.demandAccumulationSafetyStock"
+ ),
+ reorderPoint: eb.ref("source.reorderPoint"),
+ reorderQuantity: eb.ref("source.reorderQuantity"),
+ maximumInventoryQuantity: eb.ref("source.maximumInventoryQuantity"),
+ minimumOrderQuantity: eb.ref("source.minimumOrderQuantity"),
+ maximumOrderQuantity: eb.ref("source.maximumOrderQuantity"),
+ orderMultiple: eb.ref("source.orderMultiple"),
+ updatedBy: userId,
+ updatedAt
+ }))
+ .whereRef("target.locationId", "=", "source.locationId")
+ .where("target.itemId", "=", targetItemId)
+ .where("target.companyId", "=", companyId)
+ .where("source.itemId", "=", sourceItemId)
+ .where("source.companyId", "=", companyId)
+ .execute();
+
+ await trx
+ .updateTable("itemCost as target")
+ .from("itemCost as source")
+ .set((eb) => ({
+ itemPostingGroupId: eb.ref("source.itemPostingGroupId"),
+ updatedBy: userId,
+ updatedAt
+ }))
+ .where("target.itemId", "=", targetItemId)
+ .where("target.companyId", "=", companyId)
+ .where("source.itemId", "=", sourceItemId)
+ .where("source.companyId", "=", companyId)
+ .execute();
+
+ await trx
+ .insertInto("supplierPart")
+ .columns([
+ "itemId",
+ "supplierId",
+ "supplierPartId",
+ "supplierUnitOfMeasureCode",
+ "minimumOrderQuantity",
+ "orderMultiple",
+ "conversionFactor",
+ "unitPrice",
+ "active",
+ "customFields",
+ "tags",
+ "companyId",
+ "createdBy"
+ ])
+ .expression((eb) =>
+ eb
+ .selectFrom("supplierPart")
+ .select((eb) => [
+ eb.val(targetItemId).as("itemId"),
+ "supplierId",
+ "supplierPartId",
+ "supplierUnitOfMeasureCode",
+ "minimumOrderQuantity",
+ "orderMultiple",
+ "conversionFactor",
+ "unitPrice",
+ "active",
+ "customFields",
+ "tags",
+ "companyId",
+ eb.val(userId).as("createdBy")
+ ])
+ .where("itemId", "=", sourceItemId)
+ .where("companyId", "=", companyId)
+ )
+ .execute();
+
+ // Price breaks hang off the supplier part, not the item. A supplier has at
+ // most one supplier part per item, so the supplier pairs each source part
+ // with the copy just inserted.
+ await trx
+ .insertInto("supplierPartPrice")
+ .columns([
+ "supplierPartId",
+ "quantity",
+ "unitPrice",
+ "leadTime",
+ "sourceType",
+ "sourceDocumentId",
+ "companyId",
+ "createdBy"
+ ])
+ .expression((eb) =>
+ eb
+ .selectFrom("supplierPartPrice as price")
+ .innerJoin("supplierPart as source", (join) =>
+ join
+ .onRef("source.id", "=", "price.supplierPartId")
+ .onRef("source.companyId", "=", "price.companyId")
+ )
+ .innerJoin("supplierPart as target", (join) =>
+ join
+ .onRef("target.supplierId", "=", "source.supplierId")
+ .onRef("target.companyId", "=", "source.companyId")
+ )
+ .select((eb) => [
+ "target.id as supplierPartId",
+ "price.quantity",
+ "price.unitPrice",
+ "price.leadTime",
+ "price.sourceType",
+ "price.sourceDocumentId",
+ "price.companyId",
+ eb.val(userId).as("createdBy")
+ ])
+ .where("source.itemId", "=", sourceItemId)
+ .where("target.itemId", "=", targetItemId)
+ .where("price.companyId", "=", companyId)
+ )
+ .execute();
+}
+
+ /** @mcp create */
export async function createRevision(
client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
args: {
item: NonNullable<Awaited<ReturnType<typeof getItem>>["data"]>;
revision: string;
@@@ -7486,9 -7462,9 +7701,10 @@@ async function discardChangeNoticeDraft
// Add an affected item to a CO: insert the row, then spin its CO-owned Draft
// make method per the change type and write the draft refs back. Rolls the row
// back if draft creation fails (edge-fn calls can't share one txn — G2).
+ /** @mcp create destructive */
export async function addChangeNoticeAffectedItem(
client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
input: {
changeNoticeId: string;
// The existing affected item (Version / Revision / Replacement Part). Omitted
@@@ -7650,9 -7626,9 +7866,10 @@@
// Switch an affected item's change type: discard its current draft and rebuild
// for the new type (Q2 — the editable surface differs per type, so edits reset).
+ /** @mcp update */
export async function updateChangeNoticeAffectedItemChangeType(
client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
input: {
id: string;
changeType: ChangeNoticeChangeType;
@@@ -8664,8 -8633,10 +8898,11 @@@ export type DiffMethodResult =
// PURE. Compares two method snapshots. No DB access — the caller supplies plain
// rows (live method rows as `base`, CO-staged rows as `target`), and optionally
-// the per-operation child buckets to also diff steps/parameters/tools.
+// the per-operation child buckets to also diff steps/parameters/tools, and the
+// two items' supplier parts.
+ /**
+ * @mcp read
+ */
export function diffMethod(input: DiffMethodInput): DiffMethodResult {
return {
materials: diffRows(
diff --cc apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 8f5152b752,26530619dc..9203e10459
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@@ -408,7 -377,7 +377,7 @@@
{"name":"items_deleteMethodOperationTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},
{"name":"items_deleteSupplierPart","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},
{"name":"items_deleteUnitOfMeasure","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},
- {"name":"items_diffMethod","classification":"WRITE","paramCount":1,"schema":"0fdf50a7c7ba","response":"fab3ac9dac53","injectAuth":"companyId","permission":"parts:update","paginates":false},
- {"name":"items_diffMethod","classification":"READ","paramCount":1,"schema":"8e916e7918fd","response":"945cb97c37b8","injectAuth":"companyId","permission":"parts:view","paginates":false},
++ {"name":"items_diffMethod","classification":"READ","paramCount":1,"schema":"0fdf50a7c7ba","response":"fab3ac9dac53","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_duplicateMethodOperationStep","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},
{"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},