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
Merge remote-tracking branch 'origin/main' into naveenkash/item-master-revision-data-copy
naveenkash0af02a8ce062
diff --cc .claude/rules/revision-system.mdindex 0af5840b93,efcade98de..296da7c2a7--- a/.claude/rules/revision-system.md+++ b/.claude/rules/revision-system.md@@@ -54,65 -54,12 +54,66 @@@ 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 calls the `get-method` server function- (`@carbon/server-functions/get-method`, `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++ revision label. After the commit, if `replenishmentSystem !== "Buy"`, it calls++ the `get-method` server function (`@carbon/server-functions/get-method`,++ `type: "itemToItem"`) to copy the method/BOM from source to the new revision.++ That call runs its own transaction, so it cannot join this one: a failure is++ logged and the revision stands (the method can be copied again). 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` (`requireCompanyPermission`, shared with the+ delete paths below) — 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 deletes its price breaks first.** `supplierPart.itemId`+ cascades from `item`, but `supplierPartPrice → supplierPart` is+ `ON DELETE RESTRICT`, and every revision of an item with price breaks now+ carries them. `deleteItemsWithPriceBreaks(trx, { itemIds, companyId })` deletes+ the price breaks and then the items, scoped to the company, inside the+ caller's Kysely transaction — so an item delete Postgres refuses (ledger+ history, tracked entities) leaves the price breaks in place. Two callers, both+ gated by `assert_company_access(companyId, 'parts_delete')` (the `item` /+ `makeMethod` DELETE rule):+ - `deleteItem(client, db, id, companyId)` — the Item Master delete. A refusal+ keeps its SQLSTATE (`23503`), which the route maps to its message.+ - `discardChangeNoticeDrafts(client, db, drafts, companyId)` — every draft of+ the call (draft items, and Version draft methods) in ONE transaction, and it+ returns the error. `removeChangeNoticeAffectedItem` and `deleteChangeNotice`+ stop on it, so the affected row / notice is never removed while its draft+ survives; `updateChangeNoticeAffectedItemChangeType` checks `parts_delete`+ before it creates the replacement draft, and reports a late failure.+ Deleting a single **supplier part** that has price breaks+ (`deleteSupplierPart`) is still refused by the same constraint.- 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 --cc apps/erp/app/modules/items/AGENTS.mdindex 9a9dcefc5c,4fe8651674..2bf11fa9e9--- a/apps/erp/app/modules/items/AGENTS.md+++ b/apps/erp/app/modules/items/AGENTS.md@@@ -66,8 -66,8 +66,8 @@@ pnpm --filter @carbon/erp tes- `upsertMaterial(client, db, material)` — creates/updates material with taxonomy FKs and `item`/`material` linkage; an update writes only the keys sent and never touches `active`. Over MCP `name`, `replenishmentSystem`, `defaultMethodType`, `itemTrackingType` and `unitOfMeasureCode` are required, so they are always sent; with generated material IDs a sent `name` is ignored- `updateMaterialProperties(client, db, material)` — the one path for substance/form/type/finish/grade/dimension changes (properties panel, `upsertMaterial`, MCP): dependent resets, pick-list checks, generated-ID renames in one transaction. See `.claude/rules/material-tables.md`- `getMakeMethods` / `getMethodMaterials` / `getMethodOperations` / `getMethodTreeArray` — BOM/routing reads- - `copyItem` / `copyMakeMethod` — duplicates via edge function+ - `copyItem` / `copyMakeMethod` — duplicates via the `get-method` server 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 pricingdiff --cc apps/erp/app/modules/items/items.service.test.tsindex aa9e0c174c,17bfb069e9..09056430c0--- a/apps/erp/app/modules/items/items.service.test.ts+++ b/apps/erp/app/modules/items/items.service.test.ts@@@ -2,18 -2,7 +2,18 @@@// 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 { describe, expect, it, vi } from "vitest";+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";++import { beforeEach, describe, expect, it, vi } from "vitest";// diffMethod now lives in items.service. Importing the real module drags in the// items.service graph, which transitively loads @carbon/content/glossary — whose@@@ -28,13 -17,9 +28,21 @@@ vi.mock("@carbon/content/glossary", ()termSlug: vi.fn()}));-const { diffMethod, duplicateMethodOperationStep } = await import(- "./items.service"-);++// The server functions (get-method copies a revision's make method) run their++// own transactions; the boundary here is the call.++const { serverFnInvoke } = vi.hoisted(() => ({ serverFnInvoke: vi.fn() }));++vi.mock("@carbon/server-functions", () => {++ const invoker = { invoke: serverFnInvoke };++ return { serverFns: { system: () => invoker, as: () => invoker } };++});+++const {+ createRevision,+ deleteItem,+ diffMethod,+ duplicateMethodOperationStep,+ removeChangeNoticeAffectedItem+} = await import("./items.service");// A minimal live methodMaterial row (only the fields diffMethod compares + id).function baseMaterial(over: Record<string, unknown> = {}) {@@@ -484,430 -469,6 +492,429 @@@ 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 (`code` is its SQLSTATE).+class RecordingDriver extends DummyDriver {+ readonly sent: CompiledQuery[] = [];+ readonly log: string[] = [];+ constructor(+ private readonly failOn?: string,+ private readonly code?: 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 Object.assign(+ new Error(`failed: ${this.failOn}`),+ this.code ? { code: this.code } : {}+ );+ }+ 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, code?: string) {+ const driver = new RecordingDriver(failOn, code);+ 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.++ beforeEach(() => {++ serverFnInvoke.mockReset().mockResolvedValue({ data: null, error: null });++ });++++ // The caller's supabase client: the permission gate.+ 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 };++ return { client: { rpc } as never, rpc };+ }++ it("inserts the revision and what it inherits in one transaction", async () => {- const { client, rpc, invoke } = revisionClient({ error: null });++ const { client, rpc } = 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"- }++ expect(serverFnInvoke).toHaveBeenCalledWith("get-method", {++ type: "itemToItem",++ sourceId: "item-a",++ targetId: "item-b"+ });+ });++ it("leaves no revision behind when the copy fails", async () => {- const { client, invoke } = revisionClient({ error: null });++ const { client } = 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();++ expect(serverFnInvoke).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 { client } = 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();++ expect(serverFnInvoke).not.toHaveBeenCalled();+ });+});++describe("deleteItem", () => {+ function gateClient(gate: { error: { message: string } | null }) {+ const rpc = vi.fn().mockResolvedValue({ data: null, ...gate });+ return { client: { rpc } as never, rpc };+ }++ it("deletes the item's price breaks and the item in one transaction", async () => {+ const { client, rpc } = gateClient({ error: null });+ const { db, driver } = recordingDatabase();++ const result = await deleteItem(client, db, "item-b", "c1");++ expect(result).toEqual({ data: null, error: null });+ expect(rpc).toHaveBeenCalledWith("assert_company_access", {+ p_company_id: "c1",+ p_permission: "parts_delete"+ });+ // A price break restricts the delete of its supplier part, which the item+ // delete cascades to, so the price breaks go first.+ expect(driver.log).toEqual([+ "BEGIN",+ 'delete from "supplierPartPrice" where "companyId" = $1 and "supplierPartId" in (select "id" from "supplierPart" where "itemId" in ($2) and "companyId" = $3)',+ 'delete from "item" where "id" in ($1) and "companyId" = $2',+ "COMMIT"+ ]);+ expect(driver.sent.map((query) => query.parameters)).toEqual([+ ["c1", "item-b", "c1"],+ ["item-b", "c1"]+ ]);+ });++ it("keeps the price breaks when the item itself cannot be deleted", async () => {+ const { client } = gateClient({ error: null });+ const { db, driver } = recordingDatabase('delete from "item"', "23503");++ const result = await deleteItem(client, db, "item-b", "c1");++ // The route maps a 23503 to its friendly message, so the code survives.+ expect(result).toEqual({+ data: null,+ error: { code: "23503", message: 'failed: delete from "item"' }+ });+ expect(driver.log.at(-1)).toBe("ROLLBACK");+ expect(driver.log).not.toContain("COMMIT");+ });++ it("writes nothing for a caller who cannot delete parts in the company", async () => {+ const denied = { message: "Not authorized for this company" };+ const { client } = gateClient({ error: denied });+ const { db, driver } = recordingDatabase();++ const result = await deleteItem(client, db, "item-b", "c1");++ expect(result).toEqual({ data: null, error: denied });+ expect(driver.log).toEqual([]);+ });+});++describe("removeChangeNoticeAffectedItem", () => {+ // The caller's supabase client: reads the affected row, vouches for the+ // delete, and removes the affected row at the end.+ function affectedItemClient(row: Record<string, unknown>) {+ const deleted: string[] = [];+ const client = {+ rpc: vi.fn().mockResolvedValue({ data: null, error: null }),+ from: (table: string) => {+ const builder = {+ select: () => builder,+ eq: () => builder,+ maybeSingle: () => Promise.resolve({ data: row, error: null }),+ delete: () => {+ deleted.push(table);+ return builder;+ },+ then: (onF: (v: unknown) => unknown) =>+ Promise.resolve({ data: null, error: null }).then(onF)+ };+ return builder;+ }+ };+ return { client: client as never, deleted };+ }++ it("discards a Revision draft, price breaks first, then removes the row", async () => {+ const { client, deleted } = affectedItemClient({+ draftMakeMethodId: "mm-1",+ newItemId: "item-b"+ });+ const { db, driver } = recordingDatabase();++ const result = await removeChangeNoticeAffectedItem(+ client,+ db,+ "aff-1",+ "c1"+ );++ expect(result.error).toBeNull();+ // The draft method goes with its item, so only the item is deleted.+ expect(+ driver.log.map((sql) => sql.match(/^delete from "\w+"|^\w+$/)?.[0])+ ).toEqual([+ "BEGIN",+ 'delete from "supplierPartPrice"',+ 'delete from "item"',+ "COMMIT"+ ]);+ expect(deleted).toEqual(["changeOrderAffectedItem"]);+ });++ it("deletes only the Draft method for a Version", async () => {+ const { client, deleted } = affectedItemClient({+ draftMakeMethodId: "mm-1",+ newItemId: null+ });+ const { db, driver } = recordingDatabase();++ await removeChangeNoticeAffectedItem(client, db, "aff-1", "c1");++ expect(driver.log).toEqual([+ "BEGIN",+ 'delete from "makeMethod" where "id" in ($1) and "companyId" = $2',+ "COMMIT"+ ]);+ expect(deleted).toEqual(["changeOrderAffectedItem"]);+ });++ it("keeps the affected row when its draft cannot be discarded", async () => {+ const { client, deleted } = affectedItemClient({+ draftMakeMethodId: "mm-1",+ newItemId: "item-b"+ });+ const { db, driver } = recordingDatabase('delete from "item"', "23503");++ const result = await removeChangeNoticeAffectedItem(+ client,+ db,+ "aff-1",+ "c1"+ );++ expect(result.error).toEqual({+ code: "23503",+ message: 'failed: delete from "item"'+ });+ expect(driver.log.at(-1)).toBe("ROLLBACK");+ // The row is the only pointer at the draft; it stays with it.+ expect(deleted).toEqual([]);+ });+});+describe("diffMethod — attributes", () => {it("reports one entry per changed attribute column", () => {const { attributes } = diffMethod({diff --cc apps/erp/app/modules/items/items.service.tsindex c464c7d220,a56c549ffa..aeb7a7a8c9--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@@ -416,88 -246,65 +432,95 @@@ 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: the item INSERT policy asks for+ // parts_create in the item's company.+ const permitted = await requireCompanyPermission(+ client,+ companyId,+ "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: {+ const copy = await serverFns- .as({ client, db, companyId: item.companyId!, userId: createdBy })++ .as({ client, db, companyId, userId: createdBy })+ .invoke("get-method", {type: "itemToItem",sourceId: item.id,- targetId: revisionItemId,- targetId: itemInsert.data.id++ targetId: revisionItemId+ });+ // The revision stands either way; its make method can be copied again.+ if (copy.error) {+ logger.error("Failed to copy the make method onto the new revision", {- companyId: item.companyId,+ companyId,- userId: createdBy- }- });+ sourceItemId: item.id,- revisionItemId: itemInsert.data.id,++ revisionItemId,+ error: copy.error+ });+ }}- return itemInsert;+ return { data: { id: revisionItemId }, error: null };}// getNextRevision — numeric → +1, A → …→ Z → AA, AA → AB, etc.diff --cc apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex d64715e0c5,70178007a9..1f5c23bc1c--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@@ -378,7 -378,7 +378,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":"READ","paramCount":1,"schema":"0fdf50a7c7ba","response":"fab3ac9dac53","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_diffMethod","classification":"READ","paramCount":1,"schema":"21d02b3dfd77","response":"945cb97c37b8","injectAuth":"companyId","permission":"parts:view","paginates":false},++ {"name":"items_diffMethod","classification":"READ","paramCount":1,"schema":"2531dd68049b","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},diff --cc apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsxindex a08865682c,438cd311fb..a4ab1977d9--- a/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx@@@ -5,10 -5,10 +5,11 @@@import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+ import { redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";- import { data, redirect } from "react-router";+ import { data } from "react-router";import { deleteChangeNotice } from "~/modules/items";+import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {diff --cc apps/erp/app/routes/x+/items+/delete.$itemId.tsxindex 1c6abb1e1b,c0e2c778b3..2b6582ff5a--- a/apps/erp/app/routes/x+/items+/delete.$itemId.tsx+++ b/apps/erp/app/routes/x+/items+/delete.$itemId.tsx@@@ -5,10 -5,9 +5,10 @@@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+ import { redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";- import { redirect } from "react-router";import { deleteItem } from "~/modules/items";+import { getDatabaseClient } from "~/services/database.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {diff --cc packages/locale/locales/de/erp.poindex 7284931859,3ca770baa1..05d2ed379b--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "Verfolgte Materialien werden namsgid "Tracking"msgstr "Verfolgung"--msgid "Tracking ID"- msgstr "Verfolgungskennung"-msgstr ""--msgid "Tracking method"msgstr "Verfolgungsmethode"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "Unbenannte Zeilemsgid "Untitled step"msgstr "Unbenannter Schritt"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Ungenutzte kommissionierte Materialien werden vom Arbeitsplatz zurück ins Lager geleitet."diff --cc packages/locale/locales/en/erp.poindex e71340a97b,eec6a62ceb..4c2b14b887--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "Tracked material is pre-selectemsgid "Tracking"msgstr "Tracking"--msgid "Tracking ID"--msgstr "Tracking ID"--msgid "Tracking method"msgstr "Tracking method"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "Untitled linemsgid "Untitled step"msgstr "Untitled step"++msgid "Untracked"++msgstr "Untracked"++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Unused picked material flushed back from the work center to the warehouse."diff --cc packages/locale/locales/es/erp.poindex 355e72f7de,7d9db133c5..2a7403746e--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "El material rastreado se preselmsgid "Tracking"msgstr "Seguimiento"--msgid "Tracking ID"- msgstr "ID de Seguimiento"-msgstr ""--msgid "Tracking method"msgstr "Método de seguimiento"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "Línea sin títulomsgid "Untitled step"msgstr "Paso sin título"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Material recogido no utilizado devuelto desde el centro de trabajo al almacén."diff --cc packages/locale/locales/fr/erp.poindex 6e68c79ce4,78a21e81d3..45483a49f2--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "Le matériel suivi est pré-sémsgid "Tracking"msgstr "Suivi"--msgid "Tracking ID"- msgstr "ID de suivi"-msgstr ""--msgid "Tracking method"msgstr "Méthode de suivi"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "Ligne sans titremsgid "Untitled step"msgstr "Étape sans titre"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Matière prélevée inutilisée renvoyée du poste de travail à l'entrepôt."diff --cc packages/locale/locales/hi/erp.poindex 6e13824c94,cb5f4b5910..fcace9b760--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "ट्रैक की गई �msgid "Tracking"msgstr "ट्रैकिंग"--msgid "Tracking ID"- msgstr "ट्रैकिंग आईडी"-msgstr ""--msgid "Tracking method"msgstr "ट्रैकिंग विधि"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "बिना शीर्ष�msgid "Untitled step"msgstr "बिना शीर्षक वाला चरण"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "अप्रयुक्त सामग्री को वर्क सेंटर से गोदाम में वापस भेजा गया।"diff --cc packages/locale/locales/it/erp.poindex 0a329c1087,e9944def61..bb4a450f13--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "Il materiale tracciato è presemsgid "Tracking"msgstr "Tracciamento"--msgid "Tracking ID"- msgstr "ID Tracciamento"-msgstr ""--msgid "Tracking method"msgstr "Metodo di tracciamento"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "Riga senza titolomsgid "Untitled step"msgstr "Passo senza titolo"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Materiale prelevato non utilizzato reso dal centro di lavoro al deposito."diff --cc packages/locale/locales/ja/erp.poindex ef09302147,f994da97de..fdca37ccdc--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "追跡される材料は、ピ�msgid "Tracking"msgstr "追跡"--msgid "Tracking ID"- msgstr "追跡ID"-msgstr ""--msgid "Tracking method"msgstr "追跡方法"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "無題の行msgid "Untitled step"msgstr "無題のステップ"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "未使用のピッキング済み材料が作業区から倉庫に戻されました。"diff --cc packages/locale/locales/ko/erp.poindex 1fa37d909b,b565633448..b21dc4b770--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "추적 자재는 피킹 리스�msgid "Tracking"msgstr "추적"--msgid "Tracking ID"- msgstr "추적 ID"-msgstr ""--msgid "Tracking method"msgstr "추적 방법"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "제목 없는 라인msgid "Untitled step"msgstr "제목 없는 단계"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "작업장에서 창고로 반환된 미사용 선택 재료."diff --cc packages/locale/locales/pl/erp.poindex 60eb88f45c,03c1e30f3c..5c884d946c--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "Materiał śledzony jest wstępmsgid "Tracking"msgstr "Śledzenie"--msgid "Tracking ID"- msgstr "ID śledzenia"-msgstr ""--msgid "Tracking method"msgstr "Metoda śledzenia"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "Linia bez tytułumsgid "Untitled step"msgstr "Krok bez tytułu"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Materiał pobrany, ale nieużywany, zwracany ze stanowiska roboczego do magazynu."diff --cc packages/locale/locales/pt/erp.poindex e9989f946f,68c737bda1..0633349998--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "Material rastreado é pré-selemsgid "Tracking"msgstr "Rastreamento"--msgid "Tracking ID"- msgstr "ID de Rastreamento"-msgstr ""--msgid "Tracking method"msgstr "Método de rastreamento"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "Linha sem títulomsgid "Untitled step"msgstr "Etapa sem título"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Material coletado não utilizado devolvido do centro de trabalho para o armazém."diff --cc packages/locale/locales/ru/erp.poindex 9e16b3eaac,9deed81b4c..30de6f64d6--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "Отслеживаемый маmsgid "Tracking"msgstr "Отслеживание"--msgid "Tracking ID"- msgstr "ID отслеживания"-msgstr ""--msgid "Tracking method"msgstr "Метод отслеживания"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "Безымянная строкmsgid "Untitled step"msgstr "Шаг без названия"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Неиспользованный отобранный материал поступает обратно из рабочего центра на склад."diff --cc packages/locale/locales/tr/erp.poindex af42b1fd9c,873583cef7..49493a7eb1--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "İzlenen malzeme, toplama listemsgid "Tracking"msgstr "Takip"--msgid "Tracking ID"- msgstr "Takip Kimliği"-msgstr ""--msgid "Tracking method"msgstr "İzleme yöntemi"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "Başlıksız satırmsgid "Untitled step"msgstr "Başlıksız Adım"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "İş merkezinden depoya geri gönderilen kullanılmayan alınan malzeme."diff --cc packages/locale/locales/zh/erp.poindex 5d69bcd49f,7d6a79190e..7e2e04fd68--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@@ -19588,9 -19619,9 +19619,6 @@@ msgstr "追踪原材料按拣货顺序�msgid "Tracking"msgstr "追踪"--msgid "Tracking ID"- msgstr "追踪ID"-msgstr ""--msgid "Tracking method"msgstr "跟踪方法"@@@ -19978,6 -20009,6 +20006,9 @@@ msgstr "未命名行msgid "Untitled step"msgstr "未命名步骤"++msgid "Untracked"++msgstr ""++msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "未使用的已拣货物料从工作中心冲回至仓库。"