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
fix(items): block deleting an item with inventory or cost history
sidgaikwadf7050abd37d6
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.mdindex 7a6907d3ea..1a010392f4 100644--- a/apps/erp/app/modules/items/AGENTS.md+++ b/apps/erp/app/modules/items/AGENTS.md@@ -21,7 +21,7 @@ Master data for all item types (Parts, Materials, Tools, Consumables, Services),- MUST use `updateItemMethodAndSourcing` when changing `replenishmentSystem`, `defaultMethodType`, or `sourcingType` — it cascades to Draft method materials.### Ask First-- Deleting items that have inventory, open POs, or active jobs — `item` FK has `ON DELETE RESTRICT` from `trackedEntity`.+- Deleting items that have inventory, open POs, or active jobs — blocked at the DB by FKs to `item`: `trackedEntity` (serial/batch) via `ON DELETE RESTRICT`, and `itemLedger`/`costLedger` (any inventory movement or cost history) via `ON DELETE NO ACTION`. Deactivate the item instead. `NO ACTION` (not `RESTRICT`) is deliberate so whole-company cascade deletes still work.- Changing `itemTrackingType` on items that already have tracked entities — use `cascadeItemTrackingType`.- Modifying Active method versions — create a new version instead.diff --git a/apps/erp/app/routes/x+/items+/delete.$itemId.tsx b/apps/erp/app/routes/x+/items+/delete.$itemId.tsxindex 54c1c0b012..2e17892738 100644--- a/apps/erp/app/routes/x+/items+/delete.$itemId.tsx+++ b/apps/erp/app/routes/x+/items+/delete.$itemId.tsx@@ -19,8 +19,8 @@ export async function action({ request, params }: ActionFunctionArgs) {if (deletion.error) {// Postgres FK violations leak schema names ("violates foreign key// constraint trackedEntity_itemId_fkey on table trackedEntity").- // Map the trackedEntity FK to a clear, actionable user message and- // pass everything else through unchanged.+ // Map the known item FKs (tracked entities, and inventory/cost ledger+ // history) to clear, actionable messages and pass the rest through.const message = friendlyDeleteItemError(deletion.error);throw redirect(requestReferrer(request) ?? path.to.items,@@ -39,6 +39,12 @@ function friendlyDeleteItemError(err: { code?: string; message?: string }) {if (err.message?.includes("trackedEntity_itemId_fkey")) {return "Item has tracked entities linked to it and cannot be deleted. Deactivate the item instead.";}+ if (+ err.message?.includes("itemLedger_itemId_fkey") ||+ err.message?.includes("costLedger_itemId_fkey")+ ) {+ return "Item has inventory transactions or stock on hand and cannot be deleted. Deactivate the item instead.";+ }return "Item is still referenced by other records and cannot be deleted. Remove those references or deactivate the item instead.";}return err.message ?? "Failed to delete item";diff --git a/packages/database/supabase/migrations/20260827112750_prevent-item-delete-with-inventory.sql b/packages/database/supabase/migrations/20260827112750_prevent-item-delete-with-inventory.sqlnew file mode 100644index 0000000000..dcc18c24e6--- /dev/null+++ b/packages/database/supabase/migrations/20260827112750_prevent-item-delete-with-inventory.sql@@ -0,0 +1,67 @@+-- ============================================================================+-- Migration: prevent-item-delete-with-inventory+--+-- Problem:+-- Hard-deleting an "item" that still has inventory history silently destroys+-- and orphans data. The delete path (client.from("item").delete()) does no+-- application-level checks and relies entirely on FK behavior, which is+-- inconsistent across the inventory ledgers:+--+-- * "itemLedger".itemId -> ON DELETE CASCADE (on-hand source of truth):+-- deleting the item CASCADE-deletes every ledger row, destroying the+-- on-hand quantity + movement history with no warning.+-- * "costLedger".itemId -> NO foreign key at all (cost/valuation layers):+-- the rows are left orphaned, pointing at a now-deleted item, so the+-- GL inventory value can no longer be traced back to a part.+--+-- Serial/Batch items are already protected -- "trackedEntity".itemId has an+-- ON DELETE RESTRICT FK (20260426000000_tracked-entity-item-fk.sql) -- but a+-- plain "Inventory" tracking-type item with stock has no such guard.+--+-- Fix:+-- Make an item with inventory history un-deletable, so callers deactivate+-- (item.active = false) instead -- the same "deactivate the item instead"+-- pattern the trackedEntity FK already establishes.+--+-- 1. Repoint "itemLedger".itemId FK from ON DELETE CASCADE to NO ACTION.+-- 2. Add a "costLedger".itemId FK to "item"("id") with ON DELETE NO ACTION+-- (NOT VALID -- pre-existing orphan rows from past deletions must not+-- block the migration; the constraint is still enforced for new/changed+-- rows and for the referential action going forward).+--+-- Why NO ACTION and not RESTRICT:+-- The whole-company delete (settings.service.ts deleteSubsidiary ->+-- DELETE FROM "company") relies on "company" CASCADE-ing to "item",+-- "itemLedger" and "costLedger" together. RESTRICT is checked immediately+-- (mid-cascade) and would abort that delete if the item row is removed before+-- its ledger rows. NO ACTION defers the check to end-of-statement, by which+-- time the company->itemLedger / company->costLedger cascades have emptied the+-- children -- so the company delete still succeeds, while a single-item delete+-- (nothing else removes the ledger rows) is still blocked with SQLSTATE 23503.+-- The bulk wipe (datasets/wipe.ts) and backup restore (company-backup.ts) are+-- unaffected: they delete children before parents / disable RI triggers.+--+-- The route x+/items+/delete.$itemId.tsx maps the resulting 23503 to a friendly+-- "Item has inventory transactions or stock on hand..." message.+-- ============================================================================++-- 1. itemLedger.itemId: CASCADE -> NO ACTION. Re-created under the same name so+-- the app's error mapper keeps matching "itemLedger_itemId_fkey".+ALTER TABLE "itemLedger"+ DROP CONSTRAINT "itemLedger_itemId_fkey";++ALTER TABLE "itemLedger"+ ADD CONSTRAINT "itemLedger_itemId_fkey"+ FOREIGN KEY ("itemId") REFERENCES "item"("id")+ ON DELETE NO ACTION ON UPDATE CASCADE;++-- 2. costLedger.itemId: add the missing FK. NOT VALID skips the scan of+-- existing rows (past deletions left orphans with itemId pointing at a+-- now-deleted item), but the ON DELETE NO ACTION action and the check on+-- new/changed rows are enforced immediately. costLedger.itemId is nullable,+-- so a NULL itemId trivially satisfies the constraint.+ALTER TABLE "costLedger"+ ADD CONSTRAINT "costLedger_itemId_fkey"+ FOREIGN KEY ("itemId") REFERENCES "item"("id")+ ON DELETE NO ACTION ON UPDATE CASCADE+ NOT VALID;