Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(items): delete price breaks with their item, and stop on a failed draft discard

naveenkash422c19d67d46
diff --git a/.ai/lessons.md b/.ai/lessons.md
index e5c33f5a56..dffdcde260 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2878,16 +2878,18 @@ discards its draft revision by deleting the draft item.
`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.
+path; after it, every revision of an item with price breaks carries the blocker: the Item
+Master delete was refused, and the change notice's draft discard ignored the delete's error,
+so 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.
+delete blocker. Either delete the child first on that path, in the same transaction as the
+parent so a refused parent delete does not lose the child, or change the rule in a migration.
+And a delete whose failure the caller ignores is not a delete: return the error.
**Applies to:** `apps/erp/app/modules/items/items.service.ts` (`createRevision`,
-`discardChangeNoticeDraft`, `deleteItem`, `deleteSupplierPart`), and any copy/duplicate of
-`supplierPart`.
+`deleteItemsWithPriceBreaks`, `deleteItem`, `discardChangeNoticeDrafts`,
+`deleteSupplierPart`), and any copy/duplicate of `supplierPart`.
diff --git a/.claude/rules/revision-system.md b/.claude/rules/revision-system.md
index 9b18a90438..0af5840b93 100644
--- a/.claude/rules/revision-system.md
+++ b/.claude/rules/revision-system.md
@@ -69,7 +69,8 @@ the type-scoped `revisions` array.
(`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
+ 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
@@ -93,11 +94,25 @@ the type-scoped `revisions` array.
`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.
+- **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 in
the 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.md
index 713db6431d..9a9dcefc5c 100644
--- a/apps/erp/app/modules/items/AGENTS.md
+++ b/apps/erp/app/modules/items/AGENTS.md
@@ -102,7 +102,7 @@ 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)`, 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.)
+- **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 (or deleting the notice) discards its draft through `discardChangeNoticeDrafts(client, db, drafts, companyId)`: one Kysely transaction, gated by `parts_delete`, that deletes the draft items' supplier price breaks before the items (`supplierPartPrice → supplierPart` is `ON DELETE RESTRICT` and would otherwise block the item delete) and the Version draft methods. It returns the error, and the callers stop on it rather than remove the affected row or notice and orphan the 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 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.
diff --git a/apps/erp/app/modules/items/items.service.test.ts b/apps/erp/app/modules/items/items.service.test.ts
index 855e6d13bc..aa9e0c174c 100644
--- a/apps/erp/app/modules/items/items.service.test.ts
+++ b/apps/erp/app/modules/items/items.service.test.ts
@@ -28,8 +28,13 @@ vi.mock("@carbon/content/glossary", () => ({
termSlug: vi.fn()
}));
-const { createRevision, diffMethod, duplicateMethodOperationStep } =
- await import("./items.service");
+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> = {}) {
@@ -564,11 +569,14 @@ describe("diffMethod — supplier parts", () => {
// 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.
+// 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) {
+ constructor(
+ private readonly failOn?: string,
+ private readonly code?: string
+ ) {
super();
}
override async acquireConnection(): Promise<DatabaseConnection> {
@@ -577,7 +585,10 @@ class RecordingDriver extends DummyDriver {
query: CompiledQuery
): Promise<QueryResult<R>> => {
if (this.failOn && query.sql.includes(this.failOn)) {
- throw new Error(`failed: ${this.failOn}`);
+ throw Object.assign(
+ new Error(`failed: ${this.failOn}`),
+ this.code ? { code: this.code } : {}
+ );
}
this.sent.push(query);
this.log.push(query.sql);
@@ -603,8 +614,8 @@ class RecordingDriver extends DummyDriver {
}
}
-function recordingDatabase(failOn?: string) {
- const driver = new RecordingDriver(failOn);
+function recordingDatabase(failOn?: string, code?: string) {
+ const driver = new RecordingDriver(failOn, code);
const db = new KyselyClient<KyselyDatabase>({
dialect: {
createAdapter: () => new PostgresAdapter(),
@@ -746,6 +757,157 @@ describe("createRevision", () => {
});
});
+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 --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index b7a5f5b87e..c464c7d220 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -217,6 +217,21 @@ export async function copyItemPostingGroup(
.eq("companyId", args.companyId);
}
+// Kysely bypasses RLS, so before a Kysely write the caller's client vouches for
+// it: the permission the table's RLS policy would have asked for, in that
+// company. A service-role client passes.
+async function requireCompanyPermission(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ permission: string
+): Promise<{ error: ServiceError | null }> {
+ const gate = await client.rpc("assert_company_access", {
+ p_company_id: companyId,
+ p_permission: permission
+ });
+ return { error: gate.error };
+}
+
// 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
@@ -410,13 +425,13 @@ export async function createRevision(
return { data: null, error: { message: "Item has no company" } };
}
- // 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"
- });
+ // 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
@@ -583,9 +598,62 @@ export async function deleteConfigurationParameterGroup(
return client.from("configurationParameterGroup").delete().eq("id", id);
}
+// An item delete cascades to its supplier parts, and a price break restricts
+// the delete of its supplier part, so the price breaks go first. Runs in the
+// caller's transaction: when the item delete is refused (inventory history,
+// tracked entities) the price breaks stay.
+async function deleteItemsWithPriceBreaks(
+ trx: KyselyTx,
+ args: { itemIds: string[]; companyId: string }
+) {
+ const { itemIds, companyId } = args;
+ if (itemIds.length === 0) return;
+
+ await trx
+ .deleteFrom("supplierPartPrice")
+ .where("companyId", "=", companyId)
+ .where("supplierPartId", "in", (eb) =>
+ eb
+ .selectFrom("supplierPart")
+ .select("id")
+ .where("itemId", "in", itemIds)
+ .where("companyId", "=", companyId)
+ )
+ .execute();
+
+ await trx
+ .deleteFrom("item")
+ .where("id", "in", itemIds)
+ .where("companyId", "=", companyId)
+ .execute();
+}
+
/** @mcp delete */
-export async function deleteItem(client: SupabaseClient<Database>, id: string) {
- return client.from("item").delete().eq("id", id);
+export async function deleteItem(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ id: string,
+ companyId: string
+): Promise<{ data: null; error: ServiceError | null }> {
+ // The item DELETE policy asks for parts_delete in the item's company.
+ const permitted = await requireCompanyPermission(
+ client,
+ companyId,
+ "parts_delete"
+ );
+ if (permitted.error) return { data: null, error: permitted.error };
+
+ try {
+ await db
+ .transaction()
+ .execute((trx) =>
+ deleteItemsWithPriceBreaks(trx, { itemIds: [id], companyId })
+ );
+ } catch (error) {
+ logger.error("Failed to delete item", { companyId, itemId: id, error });
+ return { data: null, error: writeError(error) };
+ }
+ return { data: null, error: null };
}
/** @mcp delete */
@@ -6878,6 +6946,7 @@ export async function updateChangeNotice(
/** @mcp delete */
export async function deleteChangeNotice(
client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
changeNoticeId: string,
companyId: string
) {
@@ -6891,11 +6960,17 @@ export async function deleteChangeNotice(
.select("draftMakeMethodId, newItemId")
.eq("changeOrderId", changeNoticeId)
.eq("companyId", companyId);
- if (!affected.error && affected.data) {
- for (const item of affected.data) {
- await discardChangeNoticeDraft(client, item, companyId);
- }
- }
+ if (affected.error) return { data: null, error: affected.error };
+
+ // A draft that cannot be discarded keeps its change notice: deleting the
+ // notice anyway would leave the draft with nothing pointing at it.
+ const discarded = await discardChangeNoticeDrafts(
+ client,
+ db,
+ affected.data,
+ companyId
+ );
+ if (discarded.error) return { data: null, error: discarded.error };
// Remaining children (affected items, action tasks) cascade via ON DELETE CASCADE.
return client
@@ -7640,62 +7715,60 @@ export async function createChangeNoticeDraftMethod(
};
}
-// Discard an affected item's CO-owned Draft (used on change-type switch + when
-// removing the affected item). Deletes the new item for Revision/New Part
-// (cascades its method rows) or the Draft method for Version.
-async function discardChangeNoticeDraft(
+// Discard affected items' CO-owned Drafts (on a change-type switch, and when an
+// affected item or its change notice is removed): the new item for a
+// Revision / Replacement Part / New Part, which cascades its method rows, or
+// the Draft method for a Version. One transaction, so a failure leaves every
+// draft in place and the caller can stop instead of orphaning one.
+async function discardChangeNoticeDrafts(
client: SupabaseClient<Database>,
- affected: {
+ db: Kysely<KyselyDatabase>,
+ drafts: {
draftMakeMethodId: string | null;
newItemId: string | null;
- },
+ }[],
companyId: string
-): Promise<void> {
- if (affected.newItemId) {
- // 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;
+): Promise<{ error: ServiceError | null }> {
+ const itemIds = drafts.flatMap((draft) =>
+ draft.newItemId ? [draft.newItemId] : []
+ );
+ const makeMethodIds = drafts.flatMap((draft) =>
+ !draft.newItemId && draft.draftMakeMethodId ? [draft.draftMakeMethodId] : []
+ );
+ if (itemIds.length === 0 && makeMethodIds.length === 0) {
+ return { error: null };
}
- if (affected.draftMakeMethodId) {
- await client
- .from("makeMethod")
- .delete()
- .eq("id", affected.draftMakeMethodId)
- .eq("companyId", companyId);
+
+ // The item and makeMethod DELETE policies both ask for parts_delete.
+ const permitted = await requireCompanyPermission(
+ client,
+ companyId,
+ "parts_delete"
+ );
+ if (permitted.error) return permitted;
+
+ try {
+ await db.transaction().execute(async (trx) => {
+ // A Revision draft inherits its source's price breaks.
+ await deleteItemsWithPriceBreaks(trx, { itemIds, companyId });
+ if (makeMethodIds.length > 0) {
+ await trx
+ .deleteFrom("makeMethod")
+ .where("id", "in", makeMethodIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ });
+ } catch (error) {
+ logger.error("Failed to discard change notice drafts", {
+ companyId,
+ itemIds,
+ makeMethodIds,
+ error
+ });
+ return { error: writeError(error) };
}
+ return { error: null };
}
// Add an affected item to a CO: insert the row, then spin its CO-owned Draft
@@ -7902,6 +7975,15 @@ export async function updateChangeNoticeAffectedItemChangeType(
return { data: { id }, error: null };
}
+ // The current Draft is deleted at the end, which takes parts_delete. Refuse
+ // now rather than after the swap, when the old draft could only be orphaned.
+ const canDiscard = await requireCompanyPermission(
+ client,
+ companyId,
+ "parts_delete"
+ );
+ if (canDiscard.error) return { data: null, error: canDiscard.error };
+
// Create the replacement Draft BEFORE destroying the current one, so a failure
// in creation or the ref swap leaves the affected row still pointing at a valid
// (undeleted) draft instead of a dangling reference. The old draft is discarded
@@ -7936,8 +8018,15 @@ export async function updateChangeNoticeAffectedItemChangeType(
.eq("companyId", companyId);
if (updated.error) return { data: null, error: updated.error };
- // Swap succeeded — now safe to discard the superseded draft.
- await discardChangeNoticeDraft(client, previousDraft, companyId);
+ // Swap succeeded — now safe to discard the superseded draft. The type has
+ // changed either way; a draft that could not be removed is reported.
+ const discarded = await discardChangeNoticeDrafts(
+ client,
+ db,
+ [previousDraft],
+ companyId
+ );
+ if (discarded.error) return { data: null, error: discarded.error };
return { data: { id }, error: null };
}
@@ -8060,6 +8149,7 @@ export async function getChangeNoticeAffectedItems(
/** @mcp action destructive */
export async function removeChangeNoticeAffectedItem(
client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
id: string,
companyId: string
) {
@@ -8069,8 +8159,17 @@ export async function removeChangeNoticeAffectedItem(
.eq("id", id)
.eq("companyId", companyId)
.maybeSingle();
- if (!affected.error && affected.data) {
- await discardChangeNoticeDraft(client, affected.data, companyId);
+ if (affected.error) return { data: null, error: affected.error };
+ if (affected.data) {
+ // The affected row is the only pointer at its draft, so it stays until the
+ // draft is gone.
+ const discarded = await discardChangeNoticeDrafts(
+ client,
+ db,
+ [affected.data],
+ companyId
+ );
+ if (discarded.error) return { data: null, error: discarded.error };
}
return client
.from("changeOrderAffectedItem")
diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.delete.$affectedId.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.delete.$affectedId.tsx
index f06e76462d..a5884b359f 100644
--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.delete.$affectedId.tsx
+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.affected.delete.$affectedId.tsx
@@ -12,6 +12,7 @@ import {
requireChangeNoticeChildRoute,
requireEditableChangeNoticeRoute
} from "~/modules/items/items.server";
+import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -41,6 +42,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const remove = await removeChangeNoticeAffectedItem(
client,
+ getDatabaseClient(),
affectedId,
companyId
);
diff --git a/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx b/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx
index fdda4784da..a08865682c 100644
--- a/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/change-notice+/delete.$id.tsx
@@ -8,6 +8,7 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { data, redirect } 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) {
@@ -18,7 +19,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id } = params;
if (!id) throw new Error("id is not found");
- const mutation = await deleteChangeNotice(client, id, companyId);
+ const mutation = await deleteChangeNotice(
+ client,
+ getDatabaseClient(),
+ id,
+ companyId
+ );
if (mutation.error) {
return data(
{ success: false },
diff --git a/apps/erp/app/routes/x+/items+/delete.$itemId.tsx b/apps/erp/app/routes/x+/items+/delete.$itemId.tsx
index f9d9e930ce..1c6abb1e1b 100644
--- a/apps/erp/app/routes/x+/items+/delete.$itemId.tsx
+++ b/apps/erp/app/routes/x+/items+/delete.$itemId.tsx
@@ -8,18 +8,24 @@ import { flash } from "@carbon/auth/session.server";
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) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
delete: "parts"
});
const { itemId } = params;
if (!itemId) throw new Error("Could not find itemId");
- const deletion = await deleteItem(client, itemId);
+ const deletion = await deleteItem(
+ client,
+ getDatabaseClient(),
+ itemId,
+ companyId
+ );
if (deletion.error) {
// Postgres FK violations leak schema names ("violates foreign key
// constraint trackedEntity_itemId_fkey on table trackedEntity").