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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(items): new revisions inherit planning, purchasing and supplier parts
naveenkashc44f07217688
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex cf60f1e01e..ae9de6734b 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -2706,3 +2706,27 @@ awaited.drawer (`foo.tsx` + `foo.new.tsx`). A list loader reads the whole query string, so it passes`search: "all"`. A loader that reads the pathname, a cookie or a header must not use thehelper.++## 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 --git a/.claude/rules/revision-system.md b/.claude/rules/revision-system.mdindex 799512902f..9b18a90438 100644--- a/.claude/rules/revision-system.md+++ b/.claude/rules/revision-system.md@@ -54,12 +54,50 @@ the type-scoped `revisions` array.— `{ id?, type, copyFromId?, revision }`; requires `id` **or** `copyFromId`.- Route: `apps/erp/app/routes/x+/items+/revisions.new.tsx` (action). For a **new**revision it requires `copyFromId`, loads that item via `getItem`, then calls- `createRevision(getCarbonServiceRole(), { item, revision, createdBy })`. Redirects- to the new revision's detail page by type. URL: `path.to.newRevision`.-- Service: `createRevision` (`items.service.ts`) inserts a new `item` row copying- the source's core fields (same `readableId`, new `revision`, `active: true`).- If `replenishmentSystem !== "Buy"`, it invokes the `get-method` edge function- (`type: "itemToItem"`) to copy the method/BOM from source to the new revision.+ `createRevision(getCarbonServiceRole(), getDatabaseClient(), { item, revision, createdBy })`.+ Redirects to the new revision's detail page by type. URL: `path.to.newRevision`.+- Service: `createRevision(client, db, args)` (`items.service.ts`). In ONE Kysely+ transaction it inserts a new `item` row copying the source's core fields (same+ `readableId`, new `revision`, `active: true`) and copies the source's planning+ and purchasing setup onto it (next bullet), so a revision with default planning+ and no suppliers is never visible and a failure leaves no row holding the+ revision label. After the commit, if `replenishmentSystem !== "Buy"`, it invokes+ the `get-method` edge function (`type: "itemToItem"`) to copy the method/BOM+ from source to the new revision — that call cannot join the transaction, and+ its result is still ignored. Three callers, one behaviour: the New Revision+ route, material sizes (`upsertMaterial`), and a change notice's Revision draft+ (`createChangeNoticeDraftMethod`, `active: false`).+- **Authorization.** Kysely bypasses RLS, so before the transaction+ `createRevision` calls `assert_company_access(companyId, 'parts_create')`+ through the caller's `client` — the same predicate as the `item` INSERT policy+ (`inCompany("companyId", "parts_create")`), and a no-op for a service-role+ client. It matters: two change-notice routes (`$id.affected`,+ `…change-type`) only require `parts_update`, so without the gate a user who+ cannot create parts could mint a revision there. A refused caller gets the+ function's error and nothing is written. A taken revision label comes back as+ `{ code: "23505" }`.+- **What a revision inherits** (`copyItemPlanningAndPurchasing(trx, …)`, inside+ that transaction, every statement scoped to the company on both sides). The+ item interceptor runs with the insert, so the new item's `itemReplenishment` /+ `itemPlanning` / `itemCost` rows already exist with defaults and are updated+ in place:+ - `itemReplenishment`: `lotSize` (Batch Size), `scrapPercentage`, `leadTime`,+ `preferredSupplierId`, and with it `purchasingUnitOfMeasureCode` ++ `conversionFactor` (both derived from the preferred supplier's supplier part).+ - `itemPlanning`, per location: `reorderingPolicy` and every parameter the+ planning form edits (accumulation period, safety stock, reorder point and+ quantity, maximum inventory, min/max order quantity, order multiple). A policy+ without its parameters is invalid, so they travel together.+ - `itemCost.itemPostingGroupId` (the item group).+ - `supplierPart` rows and their `supplierPartPrice` price breaks, paired by+ `supplierId` (unique per item).+ NOT copied: costs, `itemUnitSalePrice`, `requiresConfiguration` and the+ blocked flags, `minimumReserveQuantity`, supersession, pick method, shelf life.+- **Deleting an item that has price breaks fails** unless the price breaks go+ first: `supplierPart.itemId` cascades from `item`, but+ `supplierPartPrice → supplierPart` is `ON DELETE RESTRICT`. Every revision of+ an item with price breaks now carries them, so `discardChangeNoticeDraft`+ deletes the draft item's `supplierPartPrice` rows before the item.- UI form: `RevisionForm.tsx`; version switcher menus ("Versions" submenu) live inthe type tables (`PartsTable.tsx`, etc.), shown only when `revisions.length > 1`,linking each sibling by its item id. Badge component: `ItemWithRevision.tsx`.diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.mdindex 526a4ec452..713db6431d 100644--- a/apps/erp/app/modules/items/AGENTS.md+++ b/apps/erp/app/modules/items/AGENTS.md@@ -67,7 +67,7 @@ pnpm --filter @carbon/erp test- `updateMaterialProperties(client, db, material)` — the one path for substance/form/type/finish/grade/dimension changes (properties panel, `upsertMaterial`, MCP): dependent resets, pick-list checks, generated-ID renames in one transaction. See `.claude/rules/material-tables.md`- `getMakeMethods` / `getMethodMaterials` / `getMethodOperations` / `getMethodTreeArray` — BOM/routing reads- `copyItem` / `copyMakeMethod` — duplicates via edge function-- `createRevision` / `activateMethodVersion` — revision and version management+- `createRevision(client, db, args)` / `activateMethodVersion` — revision and version management; the revision's item row and the planning and purchasing setup it inherits from the source are written in one Kysely transaction, gated by `assert_company_access(companyId, 'parts_create')` through the caller's client- `updateItemMethodAndSourcing` — cascades replenishment/sourcing changes to Draft method materials- `getItemCost` / `getItemQuantities` / `getItemDemand` / `getItemSupply` — cost and planning reads- `getSupplierParts` / `getSupplierPriceBreaksForItems` / `lookupBuyPrice` — vendor pricing@@ -102,8 +102,8 @@ Change-order code follows the one-service/models/server-per-module convention- `Replacement Part` — a new part **number** derived from the affected part, BoM/BoP **and** attributes (embedded `PartProperties`); auto affected→new supersession at release. The 1:1 replacement (renamed from the old "New Part"). Restricted to Parts. Embedded attribute editing is currently wired for **Parts** only.- `New Part` — a **net-new** part (no predecessor, **no supersession**) minted + released under the CO (Make or Buy). Used to introduce a part under change control, including the consolidated "1" in an N→1 assembly BOM change. Added via the "Add Affected Item" modal's change-type Select → create-new-part mini-form (`changeNoticeNewPartValidator` — Part Number, Name, Replenishment System, Tracking Type; **no Part/Tool choice — always a Part**; `addChangeNoticeAffectedItem`'s `newPart` path mints the item with the chosen `itemTrackingType`). Its type **cannot** be switched (net-new by construction), and it shows no cutover card. Restricted to Parts.- **Buy (purchased) items have no BoM/BoP** — `isManufactured = replenishmentSystem !== "Buy"` gates the embedded editors (mirrors the part page). `Version` is hidden from the change-type picker for Buy items, and `addChangeNoticeAffectedItem` coerces a Buy item's default `Version` → `Revision` on add. Complementarily, the Add Affected Item item picker restricts to **Make parts** (`Item` `replenishmentSystem="Make"` → `Make` or `Buy and Make`) whenever the selected change type is `Version`, so a Buy part can't be picked for a Version in the first place; other change types show all Parts.-- **Draft creation (`createChangeNoticeDraftMethod`, called by `addChangeNoticeAffectedItem`)** — per change type: `Version` → `upsertMakeMethodVersion` + `copyMakeMethod` on the same item; `Revision` → `createRevision(active:false)`; `Replacement Part` → mint a new numeric `readableId` derived from the source (`getNextItemIdFromSource`) + `copyItem`; `New Part` → the item is minted by `addChangeNoticeAffectedItem`'s `newPart` path (net-new, no source copy), and this just stamps its trigger-created Draft method CO-owned (`baseMakeMethodId` null). The resulting Draft method's `changeOrderId` is stamped to the CO (and the new item's, for Revision/Replacement Part/New Part). The draft refs (`draftMakeMethodId`, `baseMakeMethodId`, `newItemId`) are written back onto the affected-item row. **The Version draft is numbered `max(all versions)+1`, not `active+1`** (with a unique-violation retry) so parallel COs on the same part get distinct versions instead of colliding on `makeMethod (itemId, version)`. **Switching change type discards + recreates the draft** (`updateChangeNoticeAffectedItemChangeType`), resetting edits — but a `New Part` cannot be switched to/from. Removing an affected item discards its draft. (`mintPlaceholderPart` exists but is **not wired** into any current path — the old G3 forward-reference claim is stale.)-- **Authoring diff (git-style end-state)** — `getChangeNoticeDiff` + pure `diffMethod` (unit-tested in `items.service.test.ts`) diffs the CO-owned Draft method against the **base Active method** the draft was copied from (both real methods), correlating rows by natural key (material → component `itemId`, operation → `order`, operation children → `name`/`key`/`toolId`) since the copied draft carries no back-pointer ids. Classifies each material/operation/attribute added/removed/modified/unchanged. For a Revision/Replacement Part/New Part draft item it also surfaces the draft's **supplier parts** as additions — the source item's suppliers are NOT copied to the draft, so `getChangeNoticeDiff` (via `readDraftSupplierParts`) emits each `supplierPart` row as `added`; a `Version` shares the live item's suppliers and shows none. Rendered **read-only** by `ChangeNoticeDiffViewer` — the single diff renderer, reused by the affected-item "Changes" card (`AffectedItemDetail`), the CO-wide `ChangeNoticeChanges` rollup on the overview, and the release dialog (shown during authoring, not just at release).+- **Draft creation (`createChangeNoticeDraftMethod`, called by `addChangeNoticeAffectedItem`)** — per change type: `Version` → `upsertMakeMethodVersion` + `copyMakeMethod` on the same item; `Revision` → `createRevision(active:false)`, which also copies the source revision's planning and purchasing setup (batch size, scrap, lead time, per-location reorder policy, item group, preferred supplier, supplier parts + price breaks — see `.claude/rules/revision-system.md`); `Replacement Part` → mint a new numeric `readableId` derived from the source (`getNextItemIdFromSource`) + `copyItem`; `New Part` → the item is minted by `addChangeNoticeAffectedItem`'s `newPart` path (net-new, no source copy), and this just stamps its trigger-created Draft method CO-owned (`baseMakeMethodId` null). The resulting Draft method's `changeOrderId` is stamped to the CO (and the new item's, for Revision/Replacement Part/New Part). The draft refs (`draftMakeMethodId`, `baseMakeMethodId`, `newItemId`) are written back onto the affected-item row. **The Version draft is numbered `max(all versions)+1`, not `active+1`** (with a unique-violation retry) so parallel COs on the same part get distinct versions instead of colliding on `makeMethod (itemId, version)`. **Switching change type discards + recreates the draft** (`updateChangeNoticeAffectedItemChangeType`), resetting edits — but a `New Part` cannot be switched to/from. Removing an affected item discards its draft; `discardChangeNoticeDraft` deletes the draft item's supplier price breaks first, because `supplierPartPrice → supplierPart` is `ON DELETE RESTRICT` and would otherwise block the item delete. (`mintPlaceholderPart` exists but is **not wired** into any current path — the old G3 forward-reference claim is stale.)+- **Authoring diff (git-style end-state)** — `getChangeNoticeDiff` + pure `diffMethod` (unit-tested in `items.service.test.ts`) diffs the CO-owned Draft method against the **base Active method** the draft was copied from (both real methods), correlating rows by natural key (material → component `itemId`, operation → `order`, operation children → `name`/`key`/`toolId`) since the copied draft carries no back-pointer ids. Classifies each material/operation/attribute added/removed/modified/unchanged. For a Revision/Replacement Part/New Part draft item it also diffs the draft's **supplier parts** (`diffMethod`'s `baseSupplierParts`/`targetSupplierParts`, paired by `supplierId`). A **Revision** draft starts with a copy of its source revision's supplier parts, so it is diffed against the source item's and shows only what was added, changed or removed on the CO line. A Replacement Part / New Part draft starts with none (the source's suppliers are NOT copied by `copyItem`), so the base is null and every `supplierPart` row is `added`; a `Version` shares the live item's suppliers and shows none. Rendered **read-only** by `ChangeNoticeDiffViewer` — the single diff renderer, reused by the affected-item "Changes" card (`AffectedItemDetail`), the CO-wide `ChangeNoticeChanges` rollup on the overview, and the release dialog (shown during authoring, not just at release).- **Release confirmation** — `ChangeNoticeReleaseMerge` (properties panel, at Implementation) is a plain review-then-confirm dialog: it shows each affected item's authoring diff (`getChangeNoticeDiff`) and posts Implementation → Done. **No merge/conflict step** — releasing a Version just appends a new Active version and archives the prior one, so a same-part parallel CO that released first is not clobbered (its version stays as method history). The old 2-way merge / conflict-resolver UI + `getChangeNoticeReleaseDiff` / `reconcileDraftWithLive` were removed.- **Release (`applyChangeNotice` → `releaseAffectedItem`)** — the Implementation → Done action. Dispatch by change type per affected item: `Version` activates the Draft (prior Active → Archived), no new item, no supersession; `Revision`/`Replacement Part` activate the Draft, reveal the new item (`item.active = true`, stamp `item.changeOrderId`), and auto-write the affected→new `itemSupersession`; `New Part` activates the Draft + reveals the net-new item but writes **no** supersession (no predecessor). `applyChangeNotice` releases **New Part items first** (stable sort) so a parent assembly's BOM line resolves to an already-active new part. Final Kysely CAS flip to Done. Idempotent: a released draft has its `makeMethod.changeOrderId` cleared, so a re-run skips it.- **Supersession propagation (no parent cascade)** — changing a component does **not** re-BOM its parents. Propagation is via supersession chains (`itemSupersession`): the auto affected→new cutover per Revision/Replacement Part affected item (a net-new New Part has no predecessor, so no supersession). **N→1 consolidation** ("3 parts become 1") is modeled as a parent-assembly `Version`/`Revision` change whose draft BOM removes the old component lines and adds a `New Part` line — surfaced by `diffMethod` as removed + added, **not** as supersessions. `item.changeOrderId` is the revision→CO back-link powering the "Created by CO-…" chip and part-side change history.diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex 03bb91eac0..ba87d0e46b 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -1319,8 +1319,9 @@ export type ChangeNoticeItemDiff = {// read-only diff viewer can render the BOP as a tree.operations: OperationDiffEntry[];attributes: MethodDiffEntry<Record<string, unknown>>[];- // Supplier parts on a Revision/New Part draft item. Drafts start with none- // (the source's suppliers aren't copied), so these surface as `added` entries.+ // Supplier parts on a draft item. A Revision draft starts with a copy of its+ // source revision's, so its entries are a real diff against the source; a+ // Replacement Part / New Part draft starts with none, so its are all `added`.supplierParts: MethodDiffEntry<Record<string, unknown>>[];};diff --git a/apps/erp/app/modules/items/items.service.test.ts b/apps/erp/app/modules/items/items.service.test.tsindex faf7385aff..6eb320ba49 100644--- a/apps/erp/app/modules/items/items.service.test.ts+++ b/apps/erp/app/modules/items/items.service.test.ts@@ -2,6 +2,17 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import {+ type CompiledQuery,+ type DatabaseConnection,+ DummyDriver,+ Kysely as KyselyClient,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler,+ type QueryResult+} from "kysely";import { describe, expect, it, vi } from "vitest";// diffMethod now lives in items.service. Importing the real module drags in the@@ -17,9 +28,8 @@ vi.mock("@carbon/content/glossary", () => ({termSlug: vi.fn()}));-const { diffMethod, duplicateMethodOperationStep } = await import(- "./items.service"-);+const { createRevision, diffMethod, duplicateMethodOperationStep } =+ await import("./items.service");// A minimal live methodMaterial row (only the fields diffMethod compares + id).function baseMaterial(over: Record<string, unknown> = {}) {@@ -469,6 +479,273 @@ describe("duplicateMethodOperationStep", () => {});});+// A supplierPart row as the diff reads it (every column, as `select("*")`).+function supplierPart(over: Record<string, unknown> = {}) {+ return {+ id: "sp-1",+ itemId: "item-a",+ supplierId: "sup-1",+ supplierPartId: "ACME-100",+ supplierUnitOfMeasureCode: "BOX",+ minimumOrderQuantity: 10,+ orderMultiple: 5,+ conversionFactor: 12,+ unitPrice: 4.5,+ active: true,+ customFields: null,+ tags: null,+ companyId: "c1",+ createdBy: "u1",+ createdAt: "2026-01-01T00:00:00Z",+ updatedBy: null,+ updatedAt: null,+ ...over+ };+}++describe("diffMethod — supplier parts", () => {+ it("reads a revision's copied supplier parts as unchanged", () => {+ const { supplierParts } = diffMethod({+ ...EMPTY,+ baseSupplierParts: [+ supplierPart(),+ supplierPart({ id: "sp-2", supplierId: "sup-2" })+ ],+ // The copy is a different row on a different item, created later.+ targetSupplierParts: [+ supplierPart({+ id: "sp-9",+ itemId: "item-b",+ createdBy: "u2",+ createdAt: "2026-02-01T00:00:00Z"+ }),+ supplierPart({ id: "sp-10", itemId: "item-b", supplierId: "sup-2" })+ ]+ });+ expect(supplierParts.map((e) => e.status)).toEqual([+ "unchanged",+ "unchanged"+ ]);+ });++ it("reports an edited, a dropped and a new supplier on the draft", () => {+ const { supplierParts } = diffMethod({+ ...EMPTY,+ baseSupplierParts: [+ supplierPart(),+ supplierPart({ id: "sp-2", supplierId: "sup-2" })+ ],+ targetSupplierParts: [+ supplierPart({ id: "sp-9", itemId: "item-b", unitPrice: 5 }),+ supplierPart({ id: "sp-11", itemId: "item-b", supplierId: "sup-3" })+ ]+ });+ expect(+ supplierParts.map((e) => [e.status, (e.after ?? e.before)?.supplierId])+ ).toEqual([+ ["modified", "sup-1"],+ ["added", "sup-3"],+ ["removed", "sup-2"]+ ]);+ expect(supplierParts[0].changedFields).toEqual({+ unitPrice: { before: 4.5, after: 5 }+ });+ });++ it("reads every supplier part as added when the draft has no source", () => {+ const { supplierParts } = diffMethod({+ ...EMPTY,+ targetSupplierParts: [supplierPart({ id: "sp-9", itemId: "item-b" })]+ });+ expect(supplierParts.map((e) => e.status)).toEqual(["added"]);+ });+});++// The boundary is the Postgres wire: a driver that records what Kysely sends+// and answers the item insert with the id the database would have generated.+// `failOn` makes the first statement containing that text throw, as the+// database would on a constraint violation.+class RecordingDriver extends DummyDriver {+ readonly sent: CompiledQuery[] = [];+ readonly log: string[] = [];+ constructor(private readonly failOn?: string) {+ super();+ }+ override async acquireConnection(): Promise<DatabaseConnection> {+ return {+ executeQuery: async <R>(+ query: CompiledQuery+ ): Promise<QueryResult<R>> => {+ if (this.failOn && query.sql.includes(this.failOn)) {+ throw new Error(`failed: ${this.failOn}`);+ }+ this.sent.push(query);+ this.log.push(query.sql);+ const rows = query.sql.startsWith('insert into "item"')+ ? [{ id: "item-b" }]+ : [];+ return { rows: rows as R[] };+ },+ // biome-ignore lint/correctness/useYield: never streamed+ streamQuery: async function* () {+ throw new Error("not streamed");+ }+ };+ }+ override async beginTransaction() {+ this.log.push("BEGIN");+ }+ override async commitTransaction() {+ this.log.push("COMMIT");+ }+ override async rollbackTransaction() {+ this.log.push("ROLLBACK");+ }+}++function recordingDatabase(failOn?: string) {+ const driver = new RecordingDriver(failOn);+ const db = new KyselyClient<KyselyDatabase>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => driver,+ createIntrospector: (k) => new PostgresIntrospector(k),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+ }) as unknown as Kysely<KyselyDatabase>;+ return { db, driver };+}++describe("createRevision", () => {+ const item = {+ id: "item-a",+ readableId: "P-100",+ revision: "A",+ name: "Bracket",+ type: "Part",+ replenishmentSystem: "Make",+ defaultMethodType: "Make to Order",+ itemTrackingType: "Inventory",+ unitOfMeasureCode: "EA",+ description: null,+ sourcingType: "Specified",+ thumbnailPath: null,+ mpn: null,+ modelUploadId: null,+ companyId: "c1"+ } as never;++ // The caller's supabase client: the permission gate and the method copy.+ function revisionClient(gate: { error: { message: string } | null }) {+ const rpc = vi.fn().mockResolvedValue({ data: null, ...gate });+ const invoke = vi.fn().mockResolvedValue({ data: null, error: null });+ return { client: { rpc, functions: { invoke } } as never, rpc, invoke };+ }++ it("inserts the revision and what it inherits in one transaction", async () => {+ const { client, rpc, invoke } = revisionClient({ error: null });+ const { db, driver } = recordingDatabase();++ const result = await createRevision(client, db, {+ item,+ revision: "B",+ createdBy: "u1"+ });++ expect(result).toEqual({ data: { id: "item-b" }, error: null });+ expect(rpc).toHaveBeenCalledWith("assert_company_access", {+ p_company_id: "c1",+ p_permission: "parts_create"+ });++ // The item first (its interceptor creates the rows the updates land on),+ // and the price breaks after the supplier parts they hang off.+ expect(+ driver.log.map((sql) => sql.match(/^\w+( into)? "\w+"|^\w+$/)?.[0])+ ).toEqual([+ "BEGIN",+ 'insert into "item"',+ 'update "itemReplenishment"',+ 'update "itemPlanning"',+ 'update "itemCost"',+ 'insert into "supplierPart"',+ 'insert into "supplierPartPrice"',+ "COMMIT"+ ]);++ const [insert, ...copies] = driver.sent;+ expect(insert.parameters).toEqual(+ expect.arrayContaining(["P-100", "B", "Bracket", "c1", "u1", true])+ );+ // Kysely bypasses RLS: both sides of every statement name the company,+ // and the rows move from the source revision to the new one only.+ for (const query of copies) {+ expect(query.parameters).toContain("c1");+ expect(query.parameters).toContain("item-a");+ expect(query.parameters).toContain("item-b");+ }+ const [replenishment, planning, , supplierParts, prices] = copies.map(+ (query) => query.sql+ );+ expect(replenishment).toContain(+ 'where "target"."itemId" = $3 and "target"."companyId" = $4 and "source"."itemId" = $5 and "source"."companyId" = $6'+ );+ expect(planning).toContain('"target"."locationId" = "source"."locationId"');+ expect(supplierParts).toContain('where "itemId" = $3 and "companyId" = $4');+ expect(prices).toContain(+ '"target"."supplierId" = "source"."supplierId" and "target"."companyId" = "source"."companyId"'+ );++ // The method is copied once the revision is committed.+ expect(invoke).toHaveBeenCalledWith("get-method", {+ body: {+ type: "itemToItem",+ sourceId: "item-a",+ targetId: "item-b",+ companyId: "c1",+ userId: "u1"+ }+ });+ });++ it("leaves no revision behind when the copy fails", async () => {+ const { client, invoke } = revisionClient({ error: null });+ const { db, driver } = recordingDatabase('insert into "supplierPart"');++ const result = await createRevision(client, db, {+ item,+ revision: "B",+ createdBy: "u1"+ });++ expect(result).toEqual({+ data: null,+ error: { message: 'failed: insert into "supplierPart"' }+ });+ // The item insert rolls back with the copy; there is nothing to clean up.+ expect(driver.log.at(-1)).toBe("ROLLBACK");+ expect(driver.log).not.toContain("COMMIT");+ expect(driver.log.some((sql) => sql.startsWith("delete"))).toBe(false);+ expect(invoke).not.toHaveBeenCalled();+ });++ it("writes nothing for a caller who cannot create parts in the company", async () => {+ const denied = { message: "Not authorized for this company" };+ const { client, invoke } = revisionClient({ error: denied });+ const { db, driver } = recordingDatabase();++ const result = await createRevision(client, db, {+ item,+ revision: "B",+ createdBy: "u1"+ });++ expect(result).toEqual({ data: null, error: denied });+ expect(driver.log).toEqual([]);+ expect(invoke).not.toHaveBeenCalled();+ });+});+describe("diffMethod — attributes", () => {it("reports one entry per changed attribute column", () => {const { attributes } = diffMethod({diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex a3853b7016..accbe0416f 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -214,8 +214,180 @@ export async function copyItemPostingGroup(.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();+}+export async function createRevision(client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,args: {item: NonNullable<Awaited<ReturnType<typeof getItem>>["data"]>;revision: string;@@ -225,58 +397,88 @@ export async function createRevision(// "New Revision" keeps the default (active).active?: boolean;}-) {+): Promise<+ { data: { id: string }; error: null } | { data: null; error: ServiceError }+> {const { item, revision, createdBy, active = true } = args;- const itemInsert = await client- .from("item")- .insert({- readableId: item.readableId,- revision: revision,- name: item.name,- type: item.type,- replenishmentSystem: item.replenishmentSystem,- defaultMethodType: item.defaultMethodType,- itemTrackingType: item.itemTrackingType,- unitOfMeasureCode: item.unitOfMeasureCode,- // A revision starts as a faithful copy of the source's attributes so the- // only differences the user (and the CO diff) sees are ones they made.- description: item.description,- sourcingType: item.sourcingType,- thumbnailPath: item.thumbnailPath,- mpn: item.mpn,- active,- modelUploadId: item.modelUploadId,- companyId: item.companyId,- createdBy: createdBy- })- .select("id")- .single();-- if (itemInsert.error) {- return itemInsert;+ const companyId = item.companyId;+ if (!companyId) {+ return { data: null, error: { message: "Item has no company" } };}- // Carry the source's item group (itemPostingGroupId lives on itemCost, which- // the item-insert trigger auto-creates with defaults) onto the new revision.- await copyItemPostingGroup(client, {- sourceItemId: item.id,- targetItemId: itemInsert.data.id,- companyId: item.companyId+ // The revision is written with Kysely, which bypasses RLS, so the caller's+ // client vouches for it first: the same rule as the item INSERT policy+ // (parts_create in the item's company). A service-role client passes.+ const permitted = await client.rpc("assert_company_access", {+ p_company_id: companyId,+ p_permission: "parts_create"});+ if (permitted.error) return { data: null, error: permitted.error };++ // The item and what it inherits land together or not at all: a revision+ // with default planning and no suppliers is never visible, and a failure+ // leaves nothing holding the revision label against a retry.+ let revisionItemId: string;+ try {+ revisionItemId = await db.transaction().execute(async (trx) => {+ const inserted = await trx+ .insertInto("item")+ .values({+ readableId: item.readableId,+ revision,+ name: item.name,+ type: item.type,+ replenishmentSystem: item.replenishmentSystem,+ defaultMethodType: item.defaultMethodType,+ itemTrackingType: item.itemTrackingType,+ unitOfMeasureCode: item.unitOfMeasureCode,+ // A revision starts as a faithful copy of the source's attributes so+ // the only differences the user (and the CO diff) sees are ones they+ // made.+ description: item.description,+ sourcingType: item.sourcingType,+ thumbnailPath: item.thumbnailPath,+ mpn: item.mpn,+ active,+ modelUploadId: item.modelUploadId,+ companyId,+ createdBy+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ await copyItemPlanningAndPurchasing(trx, {+ sourceItemId: item.id,+ targetItemId: inserted.id,+ companyId,+ userId: createdBy+ });++ return inserted.id;+ });+ } catch (error) {+ logger.error("Failed to create revision", {+ companyId,+ sourceItemId: item.id,+ revision,+ error+ });+ return { data: null, error: writeError(error) };+ }if (item.replenishmentSystem !== "Buy") {await client.functions.invoke("get-method", {body: {type: "itemToItem",sourceId: item.id,- targetId: itemInsert.data.id,- companyId: item.companyId,+ targetId: revisionItemId,+ companyId,userId: createdBy}});}- return itemInsert;+ return { data: { id: revisionItemId }, error: null };}// getNextRevision — numeric → +1, A → …→ Z → AA, AA → AB, etc.@@ -5145,8 +5347,9 @@ async function requireMaterialUpdatable(class MaterialRuleViolation extends Error {}-function materialWriteError(error: unknown): ServiceError {- if (error instanceof MaterialRuleViolation) return ruleError(error.message);+// A thrown Kysely/Postgres error in the { message, code } shape services+// return. The code is the SQLSTATE (23505 for a taken revision label).+function writeError(error: unknown): ServiceError {const code =error && typeof error === "object" && "code" in error? String((error as { code: unknown }).code)@@ -5155,6 +5358,11 @@ function materialWriteError(error: unknown): ServiceError {return code ? { code, message } : { message };}+function materialWriteError(error: unknown): ServiceError {+ if (error instanceof MaterialRuleViolation) return ruleError(error.message);+ return writeError(error);+}+async function writeMaterialIdentity(trx: KyselyTx,args: {@@ -5599,7 +5807,7 @@ export async function upsertMaterial(const source = await getItem(client, itemId);if (source.error) return source;for (const size of newSizes) {- const revision = await createRevision(client, {+ const revision = await createRevision(client, db, {item: source.data,revision: size,createdBy: updatedBy@@ -6934,6 +7142,7 @@ type DraftMethodResult = {// Create the CO-owned Draft make method for an affected item per its change type.export async function createChangeNoticeDraftMethod(client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,input: {changeNoticeId: string;itemId: string;@@ -7051,7 +7260,7 @@ export async function createChangeNoticeDraftMethod(nextRevision = getNextRevision(maxRevision);}- const created = await createRevision(client, {+ const created = await createRevision(client, db, {item: source.data,revision: nextRevision,createdBy: userId,@@ -7228,11 +7437,41 @@ async function discardChangeNoticeDraft(companyId: string): Promise<void> {if (affected.newItemId) {- await client+ // The item delete cascades to its supplier parts, and a price break+ // restricts the delete of its supplier part. A Revision draft inherits its+ // source's price breaks, so they have to go first or the draft survives.+ const supplierParts = await client+ .from("supplierPart")+ .select("id")+ .eq("itemId", affected.newItemId)+ .eq("companyId", companyId);+ const supplierPartIds = (supplierParts.data ?? []).map((part) => part.id);+ if (supplierPartIds.length > 0) {+ const prices = await client+ .from("supplierPartPrice")+ .delete()+ .in("supplierPartId", supplierPartIds)+ .eq("companyId", companyId);+ if (prices.error) {+ logger.error("Failed to delete a draft item's supplier price breaks", {+ companyId,+ itemId: affected.newItemId,+ error: prices.error+ });+ }+ }+ const item = await client.from("item").delete().eq("id", affected.newItemId).eq("companyId", companyId);+ if (supplierParts.error || item.error) {+ logger.error("Failed to discard a change notice draft item", {+ companyId,+ itemId: affected.newItemId,+ error: supplierParts.error ?? item.error+ });+ }return;}if (affected.draftMakeMethodId) {@@ -7249,6 +7488,7 @@ async function discardChangeNoticeDraft(// back if draft creation fails (edge-fn calls can't share one txn — G2).export async function addChangeNoticeAffectedItem(client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,input: {changeNoticeId: string;// The existing affected item (Version / Revision / Replacement Part). Omitted@@ -7371,7 +7611,7 @@ export async function addChangeNoticeAffectedItem(}const affectedItemId = inserted.data.id;- const draft = await createChangeNoticeDraftMethod(client, {+ const draft = await createChangeNoticeDraftMethod(client, db, {changeNoticeId,itemId,changeType: effectiveChangeType,@@ -7412,6 +7652,7 @@ export async function addChangeNoticeAffectedItem(// for the new type (Q2 — the editable surface differs per type, so edits reset).export async function updateChangeNoticeAffectedItemChangeType(client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,input: {id: string;changeType: ChangeNoticeChangeType;@@ -7454,7 +7695,7 @@ export async function updateChangeNoticeAffectedItemChangeType(newItemId: affected.data.newItemId};- const draft = await createChangeNoticeDraftMethod(client, {+ const draft = await createChangeNoticeDraftMethod(client, db, {changeNoticeId: affected.data.changeOrderId,itemId: affected.data.itemId,changeType,@@ -8369,6 +8610,24 @@ function diffAttributes(return entries;}+// Supplier parts of a draft item against the item it was drafted from. A+// Revision draft starts with a copy of the source revision's supplier parts+// (createRevision), so only what the user changed on the CO line shows: a+// supplier has at most one supplier part per item, so the supplier pairs the+// two sides. A Replacement Part or New Part draft starts with none — a null+// base — and every supplier part is an addition.+function diffSupplierParts(+ base: Row[] | null,+ target: Row[]+): MethodDiffEntry<Row>[] {+ // The two sides are different items by construction; that is not a change.+ const withoutItem = ({ itemId: _itemId, ...row }: Row): Row => row;+ const baseRows = (base ?? []).map(withoutItem);+ const targetRows = target.map(withoutItem);+ correlate(baseRows, targetRows, "supplierId", CHILD_SOURCE_KEY);+ return diffRows(baseRows, targetRows, CHILD_SOURCE_KEY);+}+// -----------------------------------------------------------------------------// The pure diff engine// -----------------------------------------------------------------------------@@ -8386,6 +8645,11 @@ export type DiffMethodInput = {// shape.baseOperationChildren?: ChildrenByOperationId;targetOperationChildren?: ChildrenByOperationId;+ // Optional supplier parts of the draft item (target) and of the item it was+ // drafted from (base). A null/omitted base means the draft started with none,+ // so every target supplier part is an addition.+ baseSupplierParts?: Row[] | null;+ targetSupplierParts?: Row[];};export type DiffMethodResult = {@@ -8395,11 +8659,13 @@ export type DiffMethodResult = {// against MethodDiffEntry<Row>[] keep working.operations: OperationDiffEntry[];attributes: MethodDiffEntry<Row>[];+ supplierParts: MethodDiffEntry<Row>[];};// 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.export function diffMethod(input: DiffMethodInput): DiffMethodResult {return {materials: diffRows(@@ -8416,6 +8682,10 @@ export function diffMethod(input: DiffMethodInput): DiffMethodResult {attributes: diffAttributes(input.baseAttributes ?? null,input.targetAttributes ?? null+ ),+ supplierParts: diffSupplierParts(+ input.baseSupplierParts ?? null,+ input.targetSupplierParts ?? [])};}@@ -8577,17 +8847,13 @@ async function readItemAttributes(};}-// A Revision/New Part draft item starts with no supplier parts (the source's-// aren't copied); the ones the user sets up on the CO line are surfaced as `added`-// entries. Mirrors getSupplierParts (items.service) — active rows for the item.-async function readDraftSupplierParts(+// One item's supplier parts for the diff. Mirrors getSupplierParts+// (items.service) — active rows for the item.+async function readSupplierPartRows(client: SupabaseClient<Database>,itemId: string,companyId: string-): Promise<{- data: MethodDiffEntry<Row>[];- error: { message: string } | null;-}> {+): Promise<{ data: Row[]; error: { message: string } | null }> {const res = await client.from("supplierPart").select("*")@@ -8595,14 +8861,7 @@ async function readDraftSupplierParts(.eq("companyId", companyId).eq("active", true);if (res.error) return { data: [], error: res.error };- return {- data: (res.data ?? []).map((row) => ({- status: "added" as const,- before: null,- after: row as Row- })),- error: null- };+ return { data: (res.data ?? []) as Row[], error: null };}// Resolve item-group ids → their names for readable diff display.@@ -8889,14 +9148,34 @@ export async function getChangeNoticeDiff(: await readItemAttributes(client, draftItemId, companyId);// Supplier parts on the draft item (Revision/Replacement Part/New Part; a- // Version shares the live item's suppliers, which are not a CO change).- // Surfaced as additions. A New Part's draft item IS its own item- // (draftItemId === itemId), so gate on the change type too.- let supplierParts: MethodDiffEntry<Row>[] = [];+ // Version shares the live item's suppliers, which are not a CO change). A+ // Revision is diffed against the source revision it was copied from; the+ // other two start with none, so theirs are all additions. A New Part's+ // draft item IS its own item (draftItemId === itemId), so gate on the+ // change type too.+ let draftSupplierParts: Row[] = [];+ let sourceSupplierParts: Row[] | null = null;if (draftItemId !== affectedItem.itemId || isNewPart) {- const sp = await readDraftSupplierParts(client, draftItemId, companyId);- if (sp.error) return { data: { items: [] }, error: sp.error };- supplierParts = sp.data;+ const draftParts = await readSupplierPartRows(+ client,+ draftItemId,+ companyId+ );+ if (draftParts.error) {+ return { data: { items: [] }, error: draftParts.error };+ }+ draftSupplierParts = draftParts.data;+ if (affectedItem.changeType === "Revision") {+ const sourceParts = await readSupplierPartRows(+ client,+ affectedItem.itemId,+ companyId+ );+ if (sourceParts.error) {+ return { data: { items: [] }, error: sourceParts.error };+ }+ sourceSupplierParts = sourceParts.data;+ }}const diff = diffMethod({@@ -8907,7 +9186,9 @@ export async function getChangeNoticeDiff(baseAttributes: isNewPart ? null : baseAttributes,targetAttributes,baseOperationChildren: base.children,- targetOperationChildren: target.children+ targetOperationChildren: target.children,+ baseSupplierParts: sourceSupplierParts,+ targetSupplierParts: draftSupplierParts});// Label BOM lines by their component's readable id and BOP tools by the tool@@ -8975,7 +9256,7 @@ export async function getChangeNoticeDiff(materials: diff.materials,operations: diff.operations,attributes: diff.attributes,- supplierParts+ supplierParts: diff.supplierParts});}diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeDiffViewer.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeDiffViewer.tsxindex b83971e4bb..1f441fb4e7 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeDiffViewer.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeDiffViewer.tsx@@ -669,9 +669,13 @@ export default function ChangeNoticeDiffViewer({// non-hidden field to show.return entryHasBody(a, skip);});- const supplierParts = (diff?.supplierParts ?? []).filter(- (s) => s.status !== "unchanged"- );+ const supplierParts = (diff?.supplierParts ?? []).filter((s) => {+ if (s.status === "unchanged") return false;+ // As with materials: a modified row whose only change is a hidden field+ // reads as unchanged.+ if (s.status !== "modified") return true;+ return entryHasBody(s, SUPPLIER_PART_LABEL_FIELDS);+ });const isEmpty =materials.length === 0 &&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.jsonindex e3ecba59b9..8f5152b752 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@@ -408,7 +408,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":"8e916e7918fd","response":"945cb97c37b8","injectAuth":"companyId","permission":"parts:update","paginates":false},+ {"name":"items_diffMethod","classification":"WRITE","paramCount":1,"schema":"0fdf50a7c7ba","response":"fab3ac9dac53","injectAuth":"companyId","permission":"parts:update","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},diff --git a/apps/erp/app/routes/x+/change-notice+/new.tsx b/apps/erp/app/routes/x+/change-notice+/new.tsxindex b6819cd592..8ce70b9574 100644--- a/apps/erp/app/routes/x+/change-notice+/new.tsx+++ b/apps/erp/app/routes/x+/change-notice+/new.tsx@@ -20,6 +20,7 @@ import {} from "~/modules/items";import { ChangeNoticeForm } from "~/modules/items/ui/ChangeNotice";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";+import { getDatabaseClient } from "~/services/database.server";import { setCustomFields } from "~/utils/form";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -133,7 +134,7 @@ export async function action({ request }: ActionFunctionArgs) {let affectedError: Parameters<typeof error>[0] =submittedItems?.error ?? null;for (const itemId of affectedItemIds) {- const add = await addChangeNoticeAffectedItem(client, {+ const add = await addChangeNoticeAffectedItem(client, getDatabaseClient(), {changeNoticeId: createResult.data.id,itemId,changeType: "Version",diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.$affectedId.change-type.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.$affectedId.change-type.tsxindex 0c34c7a575..94928d518a 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.$affectedId.change-type.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.$affectedId.change-type.tsx@@ -16,6 +16,7 @@ import {requireChangeNoticeChildRoute,requireEditableChangeNoticeRoute} from "~/modules/items/items.server";+import { getDatabaseClient } from "~/services/database.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -66,12 +67,16 @@ export async function action({ request, params }: ActionFunctionArgs) {});if (owned) return owned;- const update = await updateChangeNoticeAffectedItemChangeType(client, {- id,- changeType,- companyId,- userId- });+ const update = await updateChangeNoticeAffectedItemChangeType(+ client,+ getDatabaseClient(),+ {+ id,+ changeType,+ companyId,+ userId+ }+ );if (update.error) {return data(diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.tsxindex 86b6c9cb96..63af9653b3 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.tsx@@ -14,6 +14,7 @@ import {changeNoticeNewPartValidator} from "~/modules/items";import { requireEditableChangeNoticeRoute } from "~/modules/items/items.server";+import { getDatabaseClient } from "~/services/database.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -57,7 +58,7 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, error(null, "Invalid change notice")));}- const add = await addChangeNoticeAffectedItem(client, {+ const add = await addChangeNoticeAffectedItem(client, getDatabaseClient(), {changeNoticeId: changeOrderId,changeType: "New Part",// A net-new affected item is always a Part.@@ -100,7 +101,7 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- const add = await addChangeNoticeAffectedItem(client, {+ const add = await addChangeNoticeAffectedItem(client, getDatabaseClient(), {changeNoticeId: changeOrderId,itemId,changeType,diff --git a/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx b/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsxindex c893a02ff0..208bc379cb 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/new-from-item.$itemId.tsx@@ -16,6 +16,7 @@ import {insertChangeNotice} from "~/modules/items";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";+import { getDatabaseClient } from "~/services/database.server";import { path, requestReferrer } from "~/utils/path";// One-click "Create Change Notice" for a part/tool: mint a CO and attach the item@@ -70,7 +71,7 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- const add = await addChangeNoticeAffectedItem(client, {+ const add = await addChangeNoticeAffectedItem(client, getDatabaseClient(), {changeNoticeId: co.data.id,itemId,changeType,diff --git a/apps/erp/app/routes/x+/items+/revisions.new.tsx b/apps/erp/app/routes/x+/items+/revisions.new.tsxindex f95ad24f67..e1cad9c69f 100644--- a/apps/erp/app/routes/x+/items+/revisions.new.tsx+++ b/apps/erp/app/routes/x+/items+/revisions.new.tsx@@ -11,6 +11,7 @@ import type { ActionFunctionArgs } from "react-router";import { revisionValidator } from "~/modules/items/items.models";import { requireItemChangeNoticeUnlocked } from "~/modules/items/items.server";import { createRevision, getItem } from "~/modules/items/items.service";+import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";const logger = getLogger("erp", "items-revisions-new");@@ -25,13 +26,13 @@ export async function action({ request }: ActionFunctionArgs) {const validation = await validator(revisionValidator).validate(formData);if (validation.error) {- return { success: false, error: "Invalid form data" };+ return { success: false, message: "Invalid form data" };}if (!validation.data.copyFromId) {return {success: false,- error: "Copy from ID is required for a new revision"+ message: "Copy from ID is required for a new revision"};}@@ -41,13 +42,13 @@ export async function action({ request }: ActionFunctionArgs) {});if (changeNoticeLock) {- return { success: false, error: changeNoticeLock.error.message };+ return { success: false, message: changeNoticeLock.error.message };}const currentItem = await getItem(client, validation.data.copyFromId);if (currentItem.error) {- return { success: false, error: "Failed to get current item" };+ return { success: false, message: "Failed to get current item" };}// createRevision writes through the service role with the SOURCE item's@@ -57,17 +58,26 @@ export async function action({ request }: ActionFunctionArgs) {companyId,itemId: validation.data.copyFromId});- return { success: false, error: "Failed to get current item" };+ return { success: false, message: "Failed to get current item" };}- const result = await createRevision(getCarbonServiceRole(), {- item: currentItem.data,- revision: validation.data.revision,- createdBy: userId- });+ const result = await createRevision(+ getCarbonServiceRole(),+ getDatabaseClient(),+ {+ item: currentItem.data,+ revision: validation.data.revision,+ createdBy: userId+ }+ );if (result.error) {- return { success: false, error: "Failed to create revision" };+ logger.error("Failed to create revision", {+ companyId,+ itemId: validation.data.copyFromId,+ error: result.error+ });+ return { success: false, message: "Failed to create revision" };}const link = (() => {diff --git a/docs/content/docs/reference/change-orders/change-types.mdx b/docs/content/docs/reference/change-orders/change-types.mdxindex d829ff84ef..7d721a9ff0 100644--- a/docs/content/docs/reference/change-orders/change-types.mdx+++ b/docs/content/docs/reference/change-orders/change-types.mdx@@ -86,12 +86,17 @@ how the new part or revision is bought: **Supplier**, **Supplier ID** (the supplPrice**, **Unit of Measure**, **Minimum Order Quantity**, and **Conversion Factor**. Add, edit, and delete rowshere the same way you would on a live part.-<Callout type="warning" title="Set suppliers up before you release, or the released part can't be bought.">-A draft item starts with **no** supplier parts — the source item's suppliers aren't copied onto the draft. If a-purchased Revision, Replacement Part, or New Part releases with an empty grid, the new part is stocked but has-no way to buy it, so a purchase order can't reference it. Fill the grid on the line first. The suppliers you add-show up in the change notice's [changes](/docs/reference/change-orders/lifecycle#review-the-changes-then-release)-as additions.+A **Revision** draft starts with the source revision's supplier parts and their price breaks, along with its+batch size, scrap percent, lead time, reordering policy, preferred supplier, and item group. It releases ready+to plan and buy, so edit the grid only where the new revision differs. The change notice's+[changes](/docs/reference/change-orders/lifecycle#review-the-changes-then-release) list only the suppliers you+added, changed, or removed.++<Callout type="warning" title="Set suppliers up on a Replacement Part or New Part before you release.">+These two drafts start with **no** supplier parts. A Replacement Part does not inherit the source item's+suppliers, and a New Part has no source to inherit from. If a purchased one releases with an empty grid, the+new part is stocked but has no way to buy it, so a purchase order can't reference it. Fill the grid on the line+first. The suppliers you add show up in the change notice's changes as additions.</Callout>## Relateddiff --git a/docs/content/docs/reference/change-orders/lifecycle.mdx b/docs/content/docs/reference/change-orders/lifecycle.mdxindex 747cb60a34..4c10b98901 100644--- a/docs/content/docs/reference/change-orders/lifecycle.mdx+++ b/docs/content/docs/reference/change-orders/lifecycle.mdx@@ -99,10 +99,11 @@ Each item's diff compares its edited draft against the method it was snapshotted- **Bill of Process** — added, removed, and modified operations and their steps, parameters, and tools.- **Properties** — changed item fields (name, description, unit of measure, tracking type, replenishmentsystem, and the rest), one row per changed column.-- **Supplier Parts** — for a purchased Revision, Replacement Part, or New Part, the [suppliers you set up on the- line](/docs/reference/change-orders/change-types#supplier-parts-on-a-purchased-line), each listed as an- addition with its part number, unit price, min order qty, order multiple, conversion factor, and purchasing- unit. A draft starts with none, so every supplier you add shows here.+- **Supplier Parts** — for a purchased Revision, Replacement Part, or New Part, the [suppliers on the+ line](/docs/reference/change-orders/change-types#supplier-parts-on-a-purchased-line), with their part number,+ unit price, min order qty, order multiple, conversion factor, and purchasing unit. A Revision starts with its+ source revision's suppliers, so only the ones you added, changed, or removed show here. A Replacement Part or+ New Part starts with none, so every supplier you add shows as an addition.<Callout type="info" title="The diff is exact because the draft is real.">There's no shadow copy of your edits to drift out of sync. You edited an actual draft method, so the diff isdiff --git a/docs/content/docs/reference/items.mdx b/docs/content/docs/reference/items.mdxindex 004175f2ba..dadeef54d7 100644--- a/docs/content/docs/reference/items.mdx+++ b/docs/content/docs/reference/items.mdx@@ -31,6 +31,15 @@ The tracking type sets how units are counted. *Inventory* items are quantity-traEach revision of a part is its **own item record**, sharing the same part number but a different revision. A design change creates a new revision rather than rewriting the old one, so jobs built against an earlier revision keep their history.+A new revision starts as a copy of the revision you created it from, so you don't set it up again. Along with the item's properties and its method, it carries over:++- **Batch Size**, **Scrap Percent**, and <Term id="lead-time">lead time</Term>+- each location's <Term id="reordering-policy">reordering policy</Term> with its parameters, such as the accumulation period and safety stock+- the <Term id="item-group">item group</Term>+- the preferred supplier, and every supplier part with its price breaks++Costs, the sale price, and stock are not copied. They belong to the revision they were recorded against. Change anything on the new revision and the old one is left as it was.+<Callout type="info">An item's <Term>costing method</Term>, one of *Standard*, *Average*, *FIFO*, or *LIFO*, lives on its cost record, not the item itself, and decides how consumption is valued.</Callout>diff --git a/docs/content/guides/change-order.mdx b/docs/content/guides/change-order.mdxindex 666dc95feb..97dcd17bd8 100644--- a/docs/content/guides/change-order.mdx+++ b/docs/content/guides/change-order.mdx@@ -80,11 +80,12 @@ For the bracket we want the wall change to carry a new drawing revision and phas**Revision**. You thicken the wall in the attributes, drop the extra fastener line from the BoM, and attachthe updated drawing — all on the draft.-<Callout tone="amber" badge="PURCHASED PARTS NEED A SUPPLIER" title="A bought revision releases un-buyable unless you set its supplier up first.">-If the revised part were purchased instead of made, its line would carry a **Supplier Parts** grid. The draft-starts with none, because the old revision's suppliers aren't copied over. Leave it empty and the new part-releases with nowhere to buy it — no purchase order can reference it. So for a **Buy** revision you add the-supplier, part number, price, and order quantities on the line before you release.+<Callout tone="green" badge="PURCHASED PARTS KEEP THEIR SUPPLIERS" title="A bought revision inherits the old revision's suppliers.">+If the revised part were purchased instead of made, its line would carry a **Supplier Parts** grid. A Revision+draft starts with the old revision's supplier parts and price breaks, along with its lead time, batch size, and+reordering policy, so it releases ready to buy. You change the grid only where the new revision differs, such+as a new supplier part number. A **Replacement Part** or **New Part** starts with an empty grid, and that one+you fill in before you release.</Callout>## Review the diff