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(quality): prevent duplicate issue type names (#1321)

Siddharth Gaikwadb72578094023
diff --git a/.claude/rules/issue-module.md b/.claude/rules/issue-module.md
index 4d67e392b1..d19105d8ad 100644
--- a/.claude/rules/issue-module.md
+++ b/.claude/rules/issue-module.md
@@ -127,7 +127,10 @@ Reviewers managed in `ReviewersList.tsx` (`nonConformanceReviewerValidator` = ju
`nonConformanceWorkflowId`, `nonConformanceTypeId`, `content JSON`, `locationId`,
`openDate`/`dueDate`/`closeDate`, `quantity`, `assignee`, audit. (`itemId` was
dropped `20250905122922` → moved to junction.)
-- `nonConformanceType`, `nonConformanceWorkflow`, `nonConformanceRequiredAction`.
+- `nonConformanceType` (name case-insensitively unique per company — unique
+ index on `("companyId", LOWER("name"))` since `20260804134212`; the
+ issue-type routes also pre-check case-insensitively via `getIssueTypeByName`),
+ `nonConformanceWorkflow`, `nonConformanceRequiredAction`.
- Tasks: `nonConformanceActionTask` (`actionTypeId`→requiredAction, `sortOrder`,
`status`, `supplierId` (`20251114222648`), `dueDate`), `nonConformanceApprovalTask`
(`approvalType`), `nonConformanceReviewer` (`title`, `status`).
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index db0e3cadb0..9cdfcdbdff 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -861,6 +861,27 @@ export async function getIssueType(
.single();
}
+export async function getIssueTypeByName(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ name: string,
+ excludeId?: string
+) {
+ // Case-insensitive exact match — escape LIKE wildcards in the name
+ const pattern = name.replace(/([\\%_])/g, "\\$1");
+ let query = client
+ .from("nonConformanceType")
+ .select("id")
+ .eq("companyId", companyId)
+ .ilike("name", pattern);
+
+ if (excludeId) {
+ query = query.neq("id", excludeId);
+ }
+
+ return query.limit(1).maybeSingle();
+}
+
export async function getIssueTypes(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 9292e49f6b..902542ca36 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-08-04T14:31:05.632Z",
- "totalTools": 1412,
+ "generated": "2026-08-04T16:26:26.021Z",
+ "totalTools": 1413,
"modules": 15,
"tools": [
{
@@ -28177,6 +28177,36 @@
]
}
},
+ {
+ "name": "quality_getIssueTypeByName",
+ "module": "quality",
+ "classification": "READ",
+ "description": "get issue type by name",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "name",
+ "excludeId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "excludeId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name"
+ ]
+ }
+ },
{
"name": "quality_getIssueTypes",
"module": "quality",
diff --git a/apps/erp/app/routes/x+/quality+/gauge-types.delete.$id.tsx b/apps/erp/app/routes/x+/quality+/gauge-types.delete.$id.tsx
index 21616c3e5c..5412afdd0a 100644
--- a/apps/erp/app/routes/x+/quality+/gauge-types.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/quality+/gauge-types.delete.$id.tsx
@@ -35,8 +35,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id } = params;
if (!id) {
throw redirect(
- `${path.to.issueTypes}?${getParams(request)}`,
- await flash(request, error(params, "Failed to get an gauge id"))
+ `${path.to.gaugeTypes}?${getParams(request)}`,
+ await flash(request, error(params, "Failed to get a gauge type id"))
);
}
@@ -48,14 +48,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
: "Failed to delete gauge type";
throw redirect(
- `${path.to.issueTypes}?${getParams(request)}`,
+ `${path.to.gaugeTypes}?${getParams(request)}`,
await flash(request, error(deleteGaugeTypeError, errorMessage))
);
}
throw redirect(
- `${path.to.issueTypes}?${getParams(request)}`,
- await flash(request, success("Successfully deleted scrap reason"))
+ `${path.to.gaugeTypes}?${getParams(request)}`,
+ await flash(request, success("Successfully deleted gauge type"))
);
}
diff --git a/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx b/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx
index 70cb1e4c0e..944da7e8c0 100644
--- a/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx
+++ b/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx
@@ -6,6 +6,7 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, redirect, useLoaderData, useNavigate } from "react-router";
import {
getIssueType,
+ getIssueTypeByName,
issueTypeValidator,
upsertIssueType
} from "~/modules/quality";
@@ -41,7 +42,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "quality"
});
@@ -55,6 +56,18 @@ export async function action({ request }: ActionFunctionArgs) {
const { id, ...d } = validation.data;
if (!id) throw new Error("id not found");
+ const duplicateIssueType = await getIssueTypeByName(
+ client,
+ companyId,
+ d.name,
+ id
+ );
+ if (duplicateIssueType.data) {
+ return validationError({
+ fieldErrors: { name: "An issue type with this name already exists" }
+ });
+ }
+
const updateIssueType = await upsertIssueType(client, {
id,
...d,
@@ -62,6 +75,11 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: userId
});
+ if (updateIssueType.error?.code === "23505") {
+ return validationError({
+ fieldErrors: { name: "An issue type with this name already exists" }
+ });
+ }
if (updateIssueType.error) {
return data(
{},
diff --git a/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx b/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx
index 8b035318d9..4e03d99081 100644
--- a/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx
@@ -58,7 +58,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
throw redirect(
`${path.to.issueTypes}?${getParams(request)}`,
- await flash(request, success("Successfully deleted scrap reason"))
+ await flash(request, success("Successfully deleted issue type"))
);
}
diff --git a/apps/erp/app/routes/x+/quality+/issue-types.new.tsx b/apps/erp/app/routes/x+/quality+/issue-types.new.tsx
index 3ee75c3743..b9b383d94f 100644
--- a/apps/erp/app/routes/x+/quality+/issue-types.new.tsx
+++ b/apps/erp/app/routes/x+/quality+/issue-types.new.tsx
@@ -4,7 +4,11 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { redirect, useNavigate } from "react-router";
-import { issueTypeValidator, upsertIssueType } from "~/modules/quality";
+import {
+ getIssueTypeByName,
+ issueTypeValidator,
+ upsertIssueType
+} from "~/modules/quality";
import IssueTypeForm from "~/modules/quality/ui/IssueTypes/IssueTypeForm";
import { setCustomFields } from "~/utils/form";
import { getParams, path, requestReferrer } from "~/utils/path";
@@ -35,12 +39,28 @@ export async function action({ request }: ActionFunctionArgs) {
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const { id, ...d } = validation.data;
+ const duplicateIssueType = await getIssueTypeByName(
+ client,
+ companyId,
+ d.name
+ );
+ if (duplicateIssueType.data) {
+ return validationError({
+ fieldErrors: { name: "An issue type with this name already exists" }
+ });
+ }
+
const insertIssueType = await upsertIssueType(client, {
...d,
companyId,
createdBy: userId,
customFields: setCustomFields(formData)
});
+ if (insertIssueType.error?.code === "23505") {
+ return validationError({
+ fieldErrors: { name: "An issue type with this name already exists" }
+ });
+ }
if (insertIssueType.error) {
return modal
? insertIssueType
diff --git a/packages/database/supabase/migrations/20260804134212_issue-type-duplicate-names.sql b/packages/database/supabase/migrations/20260804134212_issue-type-duplicate-names.sql
new file mode 100644
index 0000000000..74d88df2fb
--- /dev/null
+++ b/packages/database/supabase/migrations/20260804134212_issue-type-duplicate-names.sql
@@ -0,0 +1,43 @@
+-- Issue types (nonConformanceType) had no uniqueness protection, so the same
+-- name could be created repeatedly per company. Merge existing duplicates
+-- case-insensitively (keep the oldest row per company + name, repoint
+-- references), then enforce uniqueness on ("companyId", LOWER("name")) so case
+-- variants can't slip through non-UI write paths either. The list UI renders
+-- names as uppercase badges, so case variants are visually identical.
+
+-- Repoint issues that reference a duplicate type to the kept (oldest) row
+WITH ranked AS (
+ SELECT
+ "id",
+ FIRST_VALUE("id") OVER (
+ PARTITION BY "companyId", LOWER("name")
+ ORDER BY "createdAt" ASC, "id" ASC
+ ) AS "keepId"
+ FROM "nonConformanceType"
+),
+dupes AS (
+ SELECT "id", "keepId" FROM ranked WHERE "id" <> "keepId"
+)
+UPDATE "nonConformance" nc
+SET "nonConformanceTypeId" = d."keepId"
+FROM dupes d
+WHERE nc."nonConformanceTypeId" = d."id";
+
+-- Delete the duplicate rows
+WITH ranked AS (
+ SELECT
+ "id",
+ FIRST_VALUE("id") OVER (
+ PARTITION BY "companyId", LOWER("name")
+ ORDER BY "createdAt" ASC, "id" ASC
+ ) AS "keepId"
+ FROM "nonConformanceType"
+)
+DELETE FROM "nonConformanceType" nct
+USING ranked r
+WHERE nct."id" = r."id"
+ AND r."id" <> r."keepId";
+
+-- Expression index (not a table constraint) because it involves LOWER()
+CREATE UNIQUE INDEX "nonConformanceType_companyId_name_key"
+ ON "nonConformanceType" ("companyId", LOWER("name"));