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): refuse to delete a unit of measure that is still in use (#1394)

BettrCallRaulfbdffd307dd0
diff --git a/apps/erp/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx b/apps/erp/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
index 7e05891fc0..2872dee62e 100644
--- a/apps/erp/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
+++ b/apps/erp/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx
@@ -27,6 +27,8 @@ type ConfirmDeleteProps = {
* a URL-addressable delete route. Array values render one input per entry.
*/
fields?: Record<string, string | string[]>;
+ /** Blocks the delete while still explaining why in `text`. */
+ isDisabled?: boolean;
onCancel: () => void;
onSubmit?: () => void;
};
@@ -39,6 +41,7 @@ const ConfirmDelete = ({
deleteText = "Delete",
title,
fields,
+ isDisabled = false,
onCancel,
onSubmit
}: ConfirmDeleteProps) => {
@@ -95,8 +98,8 @@ const ConfirmDelete = ({
)}
<Button
variant="destructive"
- isLoading={fetcher.state !== "idle"}
- isDisabled={fetcher.state !== "idle"}
+ isLoading={!isDisabled && fetcher.state !== "idle"}
+ isDisabled={isDisabled || fetcher.state !== "idle"}
type="submit"
shortcut={SHORTCUTS.confirm}
>
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.md
index 1a010392f4..93af6a30c6 100644
--- a/apps/erp/app/modules/items/AGENTS.md
+++ b/apps/erp/app/modules/items/AGENTS.md
@@ -22,6 +22,7 @@ Master data for all item types (Parts, Materials, Tools, Consumables, Services),
### Ask First
- 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 how a unit of measure is deleted — `prevent_unit_of_measure_deletion_when_in_use_trigger` refuses any delete whose code is still referenced, across all 33 UoM columns including the ten that have no foreign key. It reads the referencing columns from `information_schema` at runtime, so a new table is covered without a migration. For those ten columns the guarantee is not concurrency-safe: a write takes no lock on the `unitOfMeasure` row, so one that commits between the trigger's check and the delete's commit can still leave a dangling code.
- 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/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index cbee52079a..1b9e95705b 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -2254,6 +2254,18 @@ export async function getUnitOfMeasure(
.single();
}
+/**
+ * Which tables still reference a unit of measure, and how many rows each;
+ * empty means safe to delete (or id not visible to the caller). RPC-backed so
+ * the answer doesn't depend on the caller's module permissions.
+ */
+export async function getUnitOfMeasureUsage(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.rpc("get_unit_of_measure_usage", { p_id: id });
+}
+
export async function getUnitOfMeasures(
client: SupabaseClient<Database>,
companyId: string,
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.json
index 5447e11cae..fdcaa8414e 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
@@ -202,7 +202,7 @@
{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"897f3a115b67","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"114433bf62ba","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"cc66c1b66f31","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view","paginates":false},
@@ -294,7 +294,7 @@
{"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"8af29a9b1929","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"404db2e47d09","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false},
- {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"897f3a115b67","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"114433bf62ba","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"c07433aded5b","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
@@ -396,7 +396,7 @@
{"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},
{"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"897f3a115b67","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"114433bf62ba","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view","paginates":false},
@@ -495,6 +495,7 @@
{"name":"items_getUnitOfMeasure","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"124234df769c","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getUnitOfMeasures","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"e19fb7f07a6a","injectAuth":"companyId","permission":"parts:view","paginates":true},
{"name":"items_getUnitOfMeasuresList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"1333b6f93ca5","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getUnitOfMeasureUsage","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"bf91be568e5a","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_insertChangeNotice","classification":"WRITE","paramCount":12,"schema":"c534f032ec75","response":"9645fed81b3e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},
{"name":"items_lookupBuyPrice","classification":"WRITE","paramCount":3,"schema":"c440ca0b7efc","response":"cddf8275afa1","injectAuth":"companyId","permission":"parts:update","paginates":false},
{"name":"items_matchItemIdByText","classification":"WRITE","paramCount":1,"schema":"f2e9aceb3e6b","response":"174e29b899b9","injectAuth":"companyId","permission":"parts:update","paginates":false},
@@ -772,13 +773,13 @@
{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"897f3a115b67","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"114433bf62ba","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"897f3a115b67","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"a736fffaf614","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"897f3a115b67","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"114433bf62ba","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"9feb22a88104","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"114433bf62ba","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
diff --git a/apps/erp/app/routes/x+/items+/uom.delete.$uomId.tsx b/apps/erp/app/routes/x+/items+/uom.delete.$uomId.tsx
index d2496c422e..762315f4e5 100644
--- a/apps/erp/app/routes/x+/items+/uom.delete.$uomId.tsx
+++ b/apps/erp/app/routes/x+/items+/uom.delete.$uomId.tsx
@@ -9,9 +9,24 @@ import type {
} from "react-router";
import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
import { ConfirmDelete } from "~/components/Modals";
-import { deleteUnitOfMeasure, getUnitOfMeasure } from "~/modules/items";
+import {
+ deleteUnitOfMeasure,
+ getUnitOfMeasure,
+ getUnitOfMeasureUsage
+} from "~/modules/items";
import { getParams, path } from "~/utils/path";
import { getCompanyId, uomsQuery } from "~/utils/react-query";
+import { camelCaseToWords } from "~/utils/string";
+
+// "purchase order line (12), item (4)" — humanized table names, no lookup to maintain.
+function describeUsage(usage: { tableName: string; count: number }[]) {
+ return usage
+ .map(
+ (u) =>
+ `${camelCaseToWords(u.tableName).trim().toLowerCase()} (${u.count})`
+ )
+ .join(", ");
+}
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
@@ -32,7 +47,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- return { unitOfMeasure: unitOfMeasure.data };
+ // Checked up front so the modal can explain before the DB guard has to.
+ const usage = await getUnitOfMeasureUsage(client, uomId);
+ if (usage.error) {
+ throw redirect(
+ `${path.to.uoms}?${getParams(request)}`,
+ await flash(
+ request,
+ error(usage.error, "Failed to check where the unit of measure is used")
+ )
+ );
+ }
+
+ return {
+ unitOfMeasure: unitOfMeasure.data,
+ usage: usage.data ?? []
+ };
}
export async function action({ request, params }: ActionFunctionArgs) {
@@ -48,13 +78,43 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Re-checked: the code may have been put on a document while the modal was open.
+ const usage = await getUnitOfMeasureUsage(client, uomId);
+ if (usage.error) {
+ throw redirect(
+ path.to.uoms,
+ await flash(
+ request,
+ error(usage.error, "Failed to check where the unit of measure is used")
+ )
+ );
+ }
+
+ const inUse = usage.data ?? [];
+ if (inUse.length > 0) {
+ throw redirect(
+ path.to.uoms,
+ await flash(
+ request,
+ error(
+ inUse,
+ `Cannot delete a unit of measure that is in use: ${describeUsage(inUse)}`
+ )
+ )
+ );
+ }
+
const { error: deleteTypeError } = await deleteUnitOfMeasure(client, uomId);
if (deleteTypeError) {
throw redirect(
path.to.uoms,
await flash(
request,
- error(deleteTypeError, "Failed to delete unit of measure")
+ // The trigger's refusal names the referencing tables — show it.
+ error(
+ deleteTypeError,
+ deleteTypeError.message || "Failed to delete unit of measure"
+ )
)
);
}
@@ -72,7 +132,7 @@ export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
export default function DeleteUnitOfMeasureRoute() {
const { uomId } = useParams();
- const { unitOfMeasure } = useLoaderData<typeof loader>();
+ const { unitOfMeasure, usage } = useLoaderData<typeof loader>();
const navigate = useNavigate();
const { t } = useLingui();
@@ -80,12 +140,19 @@ export default function DeleteUnitOfMeasureRoute() {
if (!uomId) throw notFound("uomId not found");
const onCancel = () => navigate(path.to.uoms);
+ const isInUse = usage.length > 0;
+ const where = describeUsage(usage);
return (
<ConfirmDelete
action={path.to.deleteUom(uomId)}
name={unitOfMeasure.name}
- text={t`Are you sure you want to delete the unit of measure: ${unitOfMeasure.name}? This cannot be undone.`}
+ isDisabled={isInUse}
+ text={
+ isInUse
+ ? t`${unitOfMeasure.name} cannot be deleted because it is still in use by ${where}. Change those records to a different unit of measure first.`
+ : t`Are you sure you want to delete the unit of measure: ${unitOfMeasure.name}? This cannot be undone.`
+ }
onCancel={onCancel}
/>
);
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 6a89262b67..524544dcf2 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -95552,6 +95552,63 @@ export default {
tags: ["(rpc) sync_update_quote_material_make_method_item_id"]
}
},
+ "/rpc/get_unit_of_measure_usage": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "p_id",
+ required: true,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_unit_of_measure_usage"]
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_id: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_id"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_unit_of_measure_usage"]
+ }
+ },
"/rpc/sync_update_supplier_type_group_name": {
post: {
parameters: [
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5d794cb2c9..59d0ff6382 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -82552,6 +82552,13 @@ export type Database = {
version: number
}[]
}
+ get_unit_of_measure_usage: {
+ Args: { p_id: string }
+ Returns: {
+ count: number
+ tableName: string
+ }[]
+ }
get_unscheduled_jobs: {
Args: { location_id: string }
Returns: {
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 5d794cb2c9..59d0ff6382 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -82552,6 +82552,13 @@ export type Database = {
version: number
}[]
}
+ get_unit_of_measure_usage: {
+ Args: { p_id: string }
+ Returns: {
+ count: number
+ tableName: string
+ }[]
+ }
get_unscheduled_jobs: {
Args: { location_id: string }
Returns: {
diff --git a/packages/database/supabase/migrations/20260814061809_prevent-unit-of-measure-deletion-in-use.sql b/packages/database/supabase/migrations/20260814061809_prevent-unit-of-measure-deletion-in-use.sql
new file mode 100644
index 0000000000..d96a9cc96b
--- /dev/null
+++ b/packages/database/supabase/migrations/20260814061809_prevent-unit-of-measure-deletion-in-use.sql
@@ -0,0 +1,180 @@
+-- Prohibit deleting a unit of measure that is still referenced anywhere.
+--
+-- The 23 foreign keys to "unitOfMeasure"("code","companyId") disagree about
+-- ON DELETE: six CASCADE (purchaseOrderLine x2, purchaseInvoiceLine x2,
+-- salesOrderLine, kanban), four SET NULL, thirteen RESTRICT. So deleting a code
+-- that had only ever reached the CASCADE tables silently deleted those order,
+-- invoice and kanban rows with it. Ten further UoM columns carry no FK at all
+-- (salesInvoiceLine, receiptLine, shipmentLine, supplierPart, the three
+-- *OperationStep tables, both maintenance item tables, workCenterReplacementPart),
+-- so they never blocked anything and were left pointing at a code that no longer
+-- existed.
+--
+-- One BEFORE DELETE guard covers every case, FK or not. The FK actions are
+-- deliberately left as they are: the CASCADEs exist so that deleting a company
+-- still works (20250430131239_delete-company-2.sql), and this guard returns early
+-- on that path exactly as protect_system_required_actions does
+-- (20260321002430_delete-company-fix.sql).
+--
+-- Known limit: for the columns without a foreign key the check is not
+-- concurrency-safe. Writing one of them takes no lock on the "unitOfMeasure" row,
+-- so a write that commits between this check and the delete's commit can still
+-- leave a dangling code. Closing that needs a foreign key or a validating trigger
+-- on each of those tables, which is out of scope here.
+--
+-- Company restore/import are unaffected. They wipe in reverse topological order
+-- under session_replication_role='replica' where the role allows it, which
+-- disables user triggers outright; and because "unitOfMeasure" references only
+-- "company" it sorts first and is therefore wiped last — after every table that
+-- points at it — so the guard is a no-op in non-replica mode too.
+
+CREATE SCHEMA IF NOT EXISTS util;
+
+-- Every base-table column that stores a unitOfMeasure."code", read from the
+-- catalog rather than hard-coded, so a table added later is covered without
+-- another migration. Views are excluded (they mirror their base tables), as is
+-- "unitOfMeasure" itself. A referencing table must be company-scoped, since the
+-- code is only unique per company.
+CREATE OR REPLACE FUNCTION util.unit_of_measure_referencing_columns()
+RETURNS TABLE ("tableName" TEXT, "columnNames" TEXT[])
+LANGUAGE sql
+STABLE
+AS $$
+ SELECT c.table_name::TEXT, array_agg(c.column_name::TEXT ORDER BY c.column_name)
+ FROM information_schema.columns c
+ JOIN information_schema.tables t
+ ON t.table_schema = c.table_schema
+ AND t.table_name = c.table_name
+ WHERE c.table_schema = 'public'
+ AND t.table_type = 'BASE TABLE'
+ AND c.table_name <> 'unitOfMeasure'
+ AND c.column_name ILIKE '%unitofmeasure%'
+ AND c.data_type IN ('text', 'character varying')
+ AND EXISTS (
+ SELECT 1
+ FROM information_schema.columns cc
+ WHERE cc.table_schema = c.table_schema
+ AND cc.table_name = c.table_name
+ AND cc.column_name = 'companyId'
+ )
+ GROUP BY c.table_name
+ ORDER BY c.table_name;
+$$;
+
+-- Rows per table that use this code. A table with two UoM columns
+-- (purchaseOrderLine, purchaseInvoiceLine, supplierQuoteLine, purchasingRfqLine)
+-- ORs them so one row is counted once, not twice. Tables with no matching rows
+-- are omitted, so "returns nothing" means "not in use".
+CREATE OR REPLACE FUNCTION util.unit_of_measure_usage(
+ p_code TEXT,
+ p_company_id TEXT
+)
+RETURNS TABLE ("tableName" TEXT, "count" BIGINT)
+LANGUAGE plpgsql
+STABLE
+AS $$
+DECLARE
+ ref RECORD;
+ predicate TEXT;
+ matches BIGINT;
+BEGIN
+ IF p_code IS NULL OR p_company_id IS NULL THEN
+ RETURN;
+ END IF;
+
+ FOR ref IN SELECT * FROM util.unit_of_measure_referencing_columns() LOOP
+ SELECT string_agg(format('%I = $1', col), ' OR ')
+ INTO predicate
+ FROM unnest(ref."columnNames") AS col;
+
+ EXECUTE format(
+ 'SELECT count(*) FROM %I WHERE "companyId" = $2 AND (%s)',
+ ref."tableName",
+ predicate
+ )
+ INTO matches
+ USING p_code, p_company_id;
+
+ IF matches > 0 THEN
+ "tableName" := ref."tableName";
+ "count" := matches;
+ RETURN NEXT;
+ END IF;
+ END LOOP;
+END;
+$$;
+
+-- Where a unit of measure is used, for the delete confirmation. SECURITY DEFINER
+-- because the answer must not depend on which modules the caller can read: a user
+-- with only purchasing access still needs to be told the code is on a sales order.
+-- Takes the id rather than a (code, companyId) pair so there is no cross-tenant
+-- surface — the company is resolved from the row, which is looked up only among
+-- the caller's companies.
+CREATE OR REPLACE FUNCTION get_unit_of_measure_usage(p_id TEXT)
+RETURNS TABLE ("tableName" TEXT, "count" BIGINT)
+LANGUAGE plpgsql
+STABLE
+SECURITY DEFINER
+SET search_path = public, util, pg_temp
+AS $$
+DECLARE
+ uom RECORD;
+BEGIN
+ -- The same predicate as the "unitOfMeasure" SELECT policy, applied in the
+ -- lookup itself: an id in another company returns nothing, exactly like an id
+ -- that does not exist, so the function cannot be used to probe for existence.
+ -- A caller with no memberships gets NULL from the helper, and `x = ANY (NULL)`
+ -- filters the row out.
+ SELECT "code", "companyId" INTO uom
+ FROM "unitOfMeasure"
+ WHERE "id" = p_id
+ AND "companyId" = ANY ((SELECT get_companies_with_any_role())::TEXT[]);
+
+ IF NOT FOUND THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY
+ SELECT u."tableName", u."count"
+ FROM util.unit_of_measure_usage(uom."code", uom."companyId") u
+ ORDER BY u."count" DESC, u."tableName";
+END;
+$$;
+
+-- No REVOKE here: EXECUTE is granted broadly on every public function by
+-- Supabase's own DDL trigger, so the company filter above is the gate, exactly
+-- as it is for get_claims and get_companies_with_any_role. An unauthenticated
+-- caller resolves to no companies and gets no rows.
+
+CREATE OR REPLACE FUNCTION prevent_unit_of_measure_deletion_when_in_use()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public, util, pg_temp
+AS $$
+DECLARE
+ usage TEXT;
+BEGIN
+ -- The company itself is being deleted; let the cascade through.
+ IF NOT EXISTS (SELECT 1 FROM "company" WHERE id = OLD."companyId") THEN
+ RETURN OLD;
+ END IF;
+
+ SELECT string_agg(format('%s (%s)', u."tableName", u."count"), ', ' ORDER BY u."count" DESC)
+ INTO usage
+ FROM util.unit_of_measure_usage(OLD."code", OLD."companyId") u;
+
+ IF usage IS NOT NULL THEN
+ RAISE EXCEPTION
+ 'Cannot delete unit of measure "%" because it is in use: %', OLD."code", usage
+ USING ERRCODE = 'foreign_key_violation';
+ END IF;
+
+ RETURN OLD;
+END;
+$$;
+
+DROP TRIGGER IF EXISTS "prevent_unit_of_measure_deletion_when_in_use_trigger" ON "unitOfMeasure";
+CREATE TRIGGER "prevent_unit_of_measure_deletion_when_in_use_trigger"
+ BEFORE DELETE ON "unitOfMeasure"
+ FOR EACH ROW EXECUTE FUNCTION prevent_unit_of_measure_deletion_when_in_use();
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 4f9dc9b641..166ed0dea5 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} bereits in einem Batch"
msgid "{0} already started"
msgstr "{0} bereits gestartet"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} kann nicht gelöscht werden, da es noch verwendet wird von: {where}. Ändern Sie diese Datensätze zuerst auf eine andere Mengeneinheit."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} Zellen mit Deltas"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 48ae936592..bf3b774556 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} already in a batch"
msgid "{0} already started"
msgstr "{0} already started"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} cells with deltas"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index f26bed0dd1..32dd79f161 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} ya en un lote"
msgid "{0} already started"
msgstr "{0} ya iniciado"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} no se puede eliminar porque todavía está en uso por {where}. Cambie primero esos registros a otra unidad de medida."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} celdas con diferencias"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 5819501a5e..20850136ce 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} déjà dans un lot"
msgid "{0} already started"
msgstr "{0} déjà commencé"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} ne peut pas être supprimé car il est encore utilisé par {where}. Modifiez d'abord ces enregistrements vers une autre unité de mesure."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} cellules avec écarts"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index a4bdd2bd09..67535b1a61 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} पहले से एक बैच में है"
msgid "{0} already started"
msgstr "{0} पहले से शुरू हो गया है"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} को हटाया नहीं जा सकता क्योंकि यह अभी भी {where} में उपयोग में है। पहले उन रिकॉर्ड को किसी दूसरी माप की इकाई में बदलें।"
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} अंतर वाली कोशिकाएँ"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 4d31741b28..794a60909d 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} già in un lotto"
msgid "{0} already started"
msgstr "{0} già avviato"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} non può essere eliminato perché è ancora in uso da {where}. Modifica prima quei record impostando un'altra unità di misura."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} celle con delta"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 2d7f92743f..09c1202aac 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -76,6 +76,10 @@ msgstr "{0}はすでにバッチに含まれています"
msgid "{0} already started"
msgstr "{0}はすでに開始されています"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0}は{where}でまだ使用されているため削除できません。先にそれらのレコードを別の単位に変更してください。"
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0}個のデルタを持つセル"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 82ab2fe7ed..98ea201f04 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -76,6 +76,10 @@ msgstr "{0}은 이미 배치에 포함됨"
msgid "{0} already started"
msgstr "{0}은 이미 시작됨"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0}은(는) {where}에서 아직 사용 중이므로 삭제할 수 없습니다. 먼저 해당 레코드를 다른 단위로 변경하세요."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0}개 셀에 변경사항 있음"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 18668228f6..48ecb76e32 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} już w partii"
msgid "{0} already started"
msgstr "{0} już uruchomiono"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "Nie można usunąć {0}, ponieważ jest nadal używana przez: {where}. Najpierw zmień te rekordy na inną jednostkę miary."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} komórek z różnicami"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 19360ce423..c874aef2eb 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} já em um lote"
msgid "{0} already started"
msgstr "{0} já iniciado"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} não pode ser excluído porque ainda está em uso por {where}. Altere primeiro esses registros para outra unidade de medida."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} células com deltas"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 27dffc50d9..36e6d7c455 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} уже в партии"
msgid "{0} already started"
msgstr "{0} уже начата"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} нельзя удалить, так как она всё ещё используется: {where}. Сначала измените эти записи на другую единицу измерения."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} ячеек с разницами"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index e03003f69d..53782f9dc1 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} zaten bir toplu işte"
msgid "{0} already started"
msgstr "{0} zaten başlatıldı"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} hâlâ {where} tarafından kullanıldığı için silinemez. Önce bu kayıtları farklı bir ölçü birimine değiştirin."
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} deltaları olan hücreler"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 9c3a6237dc..f0246eeb6f 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -76,6 +76,10 @@ msgstr "{0} 已在批次中"
msgid "{0} already started"
msgstr "{0} 已启动"
+#. placeholder {0}: unitOfMeasure.name
+msgid "{0} cannot be deleted because it is still in use by {where}. Change those records to a different unit of measure first."
+msgstr "{0} 仍被 {where} 使用,无法删除。请先将这些记录更改为其他计量单位。"
+
#. placeholder {0}: tieOut.deltaCellCount
msgid "{0} cells with deltas"
msgstr "{0} 个单元格有差异"