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
feat: llm implementation of custom issue types and actions
Brad Barbince29e12c2995
diff --git a/apps/erp/app/modules/quality/quality.models.ts b/apps/erp/app/modules/quality/quality.models.tsindex d65a486457..a1113410b6 100644--- a/apps/erp/app/modules/quality/quality.models.ts+++ b/apps/erp/app/modules/quality/quality.models.ts@@ -137,10 +137,8 @@ export const issueValidator = z.object({priority: z.enum(nonConformancePriority),source: z.enum(nonConformanceSource),name: z.string().min(1, { message: "Name is required" }),- investigationTypes: z- .array(z.enum(nonConformanceInvestigationType))- .optional(),- requiredActions: z.array(z.enum(nonConformanceRequiredAction)).optional(),+ investigationTypes: z.array(z.string()).optional(),+ requiredActions: z.array(z.string()).optional(),approvalRequirements: z.array(z.enum(nonConformanceApprovalRequirement)).optional(),@@ -178,10 +176,8 @@ export const issueWorkflowValidator = z.object({}),priority: z.enum(nonConformancePriority),source: z.enum(nonConformanceSource),- investigationTypes: z- .array(z.enum(nonConformanceInvestigationType))- .optional(),- requiredActions: z.array(z.enum(nonConformanceRequiredAction)).optional(),+ investigationTypes: z.array(z.string()).optional(),+ requiredActions: z.array(z.string()).optional(),approvalRequirements: z.array(z.enum(nonConformanceApprovalRequirement)).optional(),diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.tsindex 62e24ea6fb..9992ae78e2 100644--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@ -666,6 +666,120 @@ export async function getIssueTypesList(.order("name");}+export async function getInvestigationTypesList(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return client+ .from("nonConformanceInvestigationType")+ .select("id, name")+ .eq("companyId", companyId)+ .eq("active", true)+ .order("sortOrder");+}++export async function getRequiredActionsList(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return client+ .from("nonConformanceRequiredAction")+ .select("id, name")+ .eq("companyId", companyId)+ .eq("active", true)+ .order("sortOrder");+}++export async function getInvestigationTypes(+ client: SupabaseClient<Database>,+ companyId: string,+ args?: GenericQueryFilters & { search: string | null }+) {+ let query = client+ .from("nonConformanceInvestigationType")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args?.search) {+ query = query.ilike("name", `%${args.search}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, [+ { column: "sortOrder", ascending: true },+ { column: "name", ascending: true },+ ]);+ }++ return query;+}++export async function getRequiredActions(+ client: SupabaseClient<Database>,+ companyId: string,+ args?: GenericQueryFilters & { search: string | null }+) {+ let query = client+ .from("nonConformanceRequiredAction")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args?.search) {+ query = query.ilike("name", `%${args.search}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, [+ { column: "sortOrder", ascending: true },+ { column: "name", ascending: true },+ ]);+ }++ return query;+}++export async function getInvestigationType(+ client: SupabaseClient<Database>,+ investigationTypeId: string+) {+ return client+ .from("nonConformanceInvestigationType")+ .select("*")+ .eq("id", investigationTypeId)+ .single();+}++export async function getRequiredAction(+ client: SupabaseClient<Database>,+ requiredActionId: string+) {+ return client+ .from("nonConformanceRequiredAction")+ .select("*")+ .eq("id", requiredActionId)+ .single();+}++export async function deleteInvestigationType(+ client: SupabaseClient<Database>,+ investigationTypeId: string+) {+ return client+ .from("nonConformanceInvestigationType")+ .delete()+ .eq("id", investigationTypeId);+}++export async function deleteRequiredAction(+ client: SupabaseClient<Database>,+ requiredActionId: string+) {+ return client+ .from("nonConformanceRequiredAction")+ .delete()+ .eq("id", requiredActionId);+}+export async function getIssueType(client: SupabaseClient<Database>,nonConformanceTypeId: string@@ -945,3 +1059,61 @@ export async function upsertIssueType(.eq("id", nonConformanceType.id);}}++export async function upsertInvestigationType(+ client: SupabaseClient<Database>,+ investigationType:+ | (Omit<z.infer<typeof issueTypeValidator>, "id"> & {+ companyId: string;+ sortOrder?: number;+ active?: boolean;+ createdBy: string;+ })+ | (Omit<z.infer<typeof issueTypeValidator>, "id"> & {+ id: string;+ sortOrder?: number;+ active?: boolean;+ updatedBy: string;+ })+) {+ if ("createdBy" in investigationType) {+ return client+ .from("nonConformanceInvestigationType")+ .insert([{ sortOrder: 1, active: true, ...investigationType }])+ .select("id");+ } else {+ return client+ .from("nonConformanceInvestigationType")+ .update(sanitize(investigationType))+ .eq("id", investigationType.id);+ }+}++export async function upsertRequiredAction(+ client: SupabaseClient<Database>,+ requiredAction:+ | (Omit<z.infer<typeof issueTypeValidator>, "id"> & {+ companyId: string;+ sortOrder?: number;+ active?: boolean;+ createdBy: string;+ })+ | (Omit<z.infer<typeof issueTypeValidator>, "id"> & {+ id: string;+ sortOrder?: number;+ active?: boolean;+ updatedBy: string;+ })+) {+ if ("createdBy" in requiredAction) {+ return client+ .from("nonConformanceRequiredAction")+ .insert([{ sortOrder: 1, active: true, ...requiredAction }])+ .select("id");+ } else {+ return client+ .from("nonConformanceRequiredAction")+ .update(sanitize(requiredAction))+ .eq("id", requiredAction.id);+ }+}diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueForm.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueForm.tsxindex 42930f8ded..fc266a575b 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueForm.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueForm.tsx@@ -31,9 +31,7 @@ import type { ListItem } from "~/types";import {issueValidator,nonConformanceApprovalRequirement,- nonConformanceInvestigationType,nonConformancePriority,- nonConformanceRequiredAction,nonConformanceSource,} from "../../quality.models";import type { IssueWorkflow } from "../../types";@@ -45,12 +43,16 @@ type IssueFormProps = {initialValues: IssueFormValues;nonConformanceWorkflows: IssueWorkflow[];nonConformanceTypes: ListItem[];+ investigationTypes: ListItem[];+ requiredActions: ListItem[];};const IssueForm = ({initialValues,nonConformanceWorkflows,nonConformanceTypes,+ investigationTypes,+ requiredActions,}: IssueFormProps) => {const permissions = usePermissions();const isEditing = initialValues.id !== undefined;@@ -156,9 +158,9 @@ const IssueForm = ({<MultiSelectname="investigationTypes"label="Investigation Types"- options={nonConformanceInvestigationType.map((type) => ({- label: type,- value: type,+ options={investigationTypes.map((type) => ({+ label: type.name,+ value: type.id,}))}value={workflow.investigationTypes}onChange={(value) => {@@ -171,9 +173,9 @@ const IssueForm = ({<MultiSelectname="requiredActions"label="Required Actions"- options={nonConformanceRequiredAction.map((action) => ({- label: action,- value: action,+ options={requiredActions.map((action) => ({+ label: action.name,+ value: action.id,}))}value={workflow.requiredActions}onChange={(value) => {diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsxindex b9e268c9cb..50bb3cb6d7 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx@@ -31,8 +31,6 @@ import { path } from "~/utils/path";import { copyToClipboard } from "~/utils/string";import {nonConformanceApprovalRequirement,- nonConformanceInvestigationType,- nonConformanceRequiredAction,nonConformanceSource,} from "../../quality.models";import type { Issue } from "../../types";@@ -47,6 +45,8 @@ const IssueProperties = () => {const routeData = useRouteData<{nonConformance: Issue;nonConformanceTypes: ListItem[];+ investigationTypes: ListItem[];+ requiredActions: ListItem[];files: Promise<StorageItem[]>;tags: { name: string }[];}>(path.to.issue(id));@@ -74,8 +74,8 @@ const IssueProperties = () => {field:| "source"| "priority"- | "investigationTypes"- | "requiredActions"+ | "investigationTypeIds"+ | "requiredActionIds"| "approvalRequirements"| "name"| "description"@@ -356,49 +356,49 @@ const IssueProperties = () => {<ValidatedFormdefaultValues={{- investigationTypes:- routeData?.nonConformance?.investigationTypes ?? [],+ investigationTypeIds:+ routeData?.nonConformance?.investigationTypeIds ?? [],}}validator={z.object({- investigationTypes: z.array(z.string()).optional(),+ investigationTypeIds: z.array(z.string()).optional(),})}className="w-full"><MultiSelect- options={nonConformanceInvestigationType.map((type) => ({- value: type,- label: type,+ options={(routeData?.investigationTypes ?? []).map((type) => ({+ value: type.id,+ label: type.name,}))}isReadOnly={disableStructureUpdate}label="Investigation Types"- name="investigationTypes"+ name="investigationTypeIds"inlineonChange={(value) => {- onUpdate("investigationTypes", value.map((v) => v.value).join(","));+ onUpdate("investigationTypeIds", value.map((v) => v.value).join(","));}}/></ValidatedForm><ValidatedFormdefaultValues={{- requiredActions: routeData?.nonConformance?.requiredActions ?? [],+ requiredActionIds: routeData?.nonConformance?.requiredActionIds ?? [],}}validator={z.object({- requiredActions: z.array(z.string()).optional(),+ requiredActionIds: z.array(z.string()).optional(),})}className="w-full"><MultiSelect- options={nonConformanceRequiredAction.map((type) => ({- value: type,- label: type,+ options={(routeData?.requiredActions ?? []).map((type) => ({+ value: type.id,+ label: type.name,}))}isReadOnly={disableStructureUpdate}label="Required Actions"- name="requiredActions"+ name="requiredActionIds"inlineonChange={(value) => {- onUpdate("requiredActions", value.map((v) => v.value).join(","));+ onUpdate("requiredActionIds", value.map((v) => v.value).join(","));}}/></ValidatedForm>diff --git a/apps/erp/app/routes/x+/issue+/$id.tsx b/apps/erp/app/routes/x+/issue+/$id.tsxindex 31d4254e49..fd879173e9 100644--- a/apps/erp/app/routes/x+/issue+/$id.tsx+++ b/apps/erp/app/routes/x+/issue+/$id.tsx@@ -9,9 +9,11 @@ import { Suspense } from "react";import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";import { getItemFiles } from "~/modules/items";import {+ getInvestigationTypesList,getIssue,getIssueAssociations,getIssueTypesList,+ getRequiredActionsList,} from "~/modules/quality";import type { IssueAssociationNode } from "~/modules/quality/types";import {@@ -39,9 +41,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { id } = params;if (!id) throw new Error("Could not find id");- const [nonConformance, nonConformanceTypes, tags] = await Promise.all([+ const [nonConformance, nonConformanceTypes, investigationTypes, requiredActions, tags] = await Promise.all([getIssue(client, id),getIssueTypesList(client, companyId),+ getInvestigationTypesList(client, companyId),+ getRequiredActionsList(client, companyId),getTagsList(client, companyId, "nonConformance"),]);@@ -55,6 +59,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return defer({nonConformance: nonConformance.data,nonConformanceTypes: nonConformanceTypes.data ?? [],+ investigationTypes: investigationTypes.data ?? [],+ requiredActions: requiredActions.data ?? [],files: getItemFiles(client, id, companyId),associations: getIssueAssociations(client, id, companyId),tags: tags.data ?? [],diff --git a/apps/erp/app/routes/x+/issue+/new.tsx b/apps/erp/app/routes/x+/issue+/new.tsxindex 976d392e14..c6ab7daa89 100644--- a/apps/erp/app/routes/x+/issue+/new.tsx+++ b/apps/erp/app/routes/x+/issue+/new.tsx@@ -10,8 +10,10 @@ import { json, redirect } from "@vercel/remix";import { useUrlParams, useUser } from "~/hooks";import {deleteIssue,+ getInvestigationTypesList,getIssueTypesList,getIssueWorkflowsList,+ getRequiredActionsList,issueValidator,upsertIssue,} from "~/modules/quality";@@ -32,14 +34,18 @@ export async function loader({ request }: LoaderFunctionArgs) {view: "quality",});- const [workflows, types] = await Promise.all([+ const [workflows, types, investigationTypes, requiredActions] = await Promise.all([getIssueWorkflowsList(client, companyId),getIssueTypesList(client, companyId),+ getInvestigationTypesList(client, companyId),+ getRequiredActionsList(client, companyId),]);return json({workflows: workflows.data ?? [],types: types.data ?? [],+ investigationTypes: investigationTypes.data ?? [],+ requiredActions: requiredActions.data ?? [],});}@@ -119,7 +125,7 @@ export async function action({ request }: ActionFunctionArgs) {}export default function IssueNewRoute() {- const { workflows, types } = useLoaderData<typeof loader>();+ const { workflows, types, investigationTypes, requiredActions } = useLoaderData<typeof loader>();const { defaults } = useUser();const [params] = useUrlParams();@@ -166,6 +172,8 @@ export default function IssueNewRoute() {initialValues={initialValues}nonConformanceWorkflows={workflows}nonConformanceTypes={types}+ investigationTypes={investigationTypes}+ requiredActions={requiredActions}/></div>);diff --git a/apps/erp/app/routes/x+/issue+/update.tsx b/apps/erp/app/routes/x+/issue+/update.tsxindex c593963f51..975f124c5c 100644--- a/apps/erp/app/routes/x+/issue+/update.tsx+++ b/apps/erp/app/routes/x+/issue+/update.tsx@@ -25,8 +25,8 @@ export async function action({ request }: ActionFunctionArgs) {}switch (field) {- case "investigationTypes":- case "requiredActions":+ case "investigationTypeIds":+ case "requiredActionIds":case "approvalRequirements":const arrayValue = value ? value.split(",") : [];const update = await clientdiff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.tsindex 5d68a7d5d5..db2f1d1266 100644--- a/packages/database/supabase/functions/create/index.ts+++ b/packages/database/supabase/functions/create/index.ts@@ -171,16 +171,16 @@ serve(async (req: Request) => {const currentInvestigationTasks =investigationTasks.data?.reduce<Record<string, string>>((acc, d) => {- if (d.investigationType && !acc[d.investigationType]) {- acc[d.investigationType] = d.id;+ if (d.investigationTypeId && !acc[d.investigationTypeId]) {+ acc[d.investigationTypeId] = d.id;}return acc;}, {}) ?? {};const currentActionTasks =actionTasks.data?.reduce<Record<string, string>>((acc, d) => {- if (d.actionType && !acc[d.actionType]) {- acc[d.actionType] = d.id;+ if (d.actionTypeId && !acc[d.actionTypeId]) {+ acc[d.actionTypeId] = d.id;}return acc;}, {}) ?? {};@@ -198,25 +198,25 @@ serve(async (req: Request) => {const approvalTasksToDelete: string[] = [];const reviewersToDelete: string[] = [];- Object.keys(currentInvestigationTasks).forEach((investigationType) => {+ Object.keys(currentInvestigationTasks).forEach((investigationTypeId) => {if (- !(nonConformance.data?.investigationTypes ?? []).some(- (d) => d === investigationType+ !(nonConformance.data?.investigationTypeIds ?? []).some(+ (d) => d === investigationTypeId)) {investigationTasksToDelete.push(- currentInvestigationTasks[investigationType]+ currentInvestigationTasks[investigationTypeId]);}});- Object.keys(currentActionTasks).forEach((actionType) => {+ Object.keys(currentActionTasks).forEach((actionTypeId) => {if (- !(nonConformance.data?.requiredActions ?? []).some(- (d) => d === actionType+ !(nonConformance.data?.requiredActionIds ?? []).some(+ (d) => d === actionTypeId)) {- actionTasksToDelete.push(currentActionTasks[actionType]);+ actionTasksToDelete.push(currentActionTasks[actionTypeId]);}});@@ -240,12 +240,12 @@ serve(async (req: Request) => {const reviewerInserts: Database["public"]["Tables"]["nonConformanceReviewer"]["Insert"][] =[];- nonConformance.data?.investigationTypes?.forEach(- (investigationType) => {- if (!currentInvestigationTasks[investigationType]) {+ nonConformance.data?.investigationTypeIds?.forEach(+ (investigationTypeId) => {+ if (!currentInvestigationTasks[investigationTypeId]) {investigationTaskInserts.push({nonConformanceId: id,- investigationType,+ investigationTypeId,companyId,createdBy: userId,});@@ -253,11 +253,11 @@ serve(async (req: Request) => {});- nonConformance.data?.requiredActions?.forEach((actionType) => {- if (!currentActionTasks[actionType]) {+ nonConformance.data?.requiredActionIds?.forEach((actionTypeId) => {+ if (!currentActionTasks[actionTypeId]) {actionTaskInserts.push({nonConformanceId: id,- actionType,+ actionTypeId,companyId,createdBy: userId,});diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.tsindex c0bbb27361..d61bebbd22 100644--- a/packages/database/supabase/functions/lib/seed.ts+++ b/packages/database/supabase/functions/lib/seed.ts@@ -1630,6 +1630,78 @@ export const nonConformanceTypes: Omit<},];+export const nonConformanceInvestigationTypes: Omit<+ Database["public"]["Tables"]["nonConformanceInvestigationType"]["Insert"],+ "companyId"+>[] = [+ {+ name: "Root Cause Analysis",+ sortOrder: 1,+ createdBy: "system",+ },+ {+ name: "Inventory",+ sortOrder: 2,+ createdBy: "system",+ },+ {+ name: "WIP",+ sortOrder: 3,+ createdBy: "system",+ },+ {+ name: "Finished Goods",+ sortOrder: 4,+ createdBy: "system",+ },+ {+ name: "Incoming Materials",+ sortOrder: 5,+ createdBy: "system",+ },+ {+ name: "Process",+ sortOrder: 6,+ createdBy: "system",+ },+ {+ name: "Documentation",+ sortOrder: 7,+ createdBy: "system",+ },+];++export const nonConformanceRequiredActions: Omit<+ Database["public"]["Tables"]["nonConformanceRequiredAction"]["Insert"],+ "companyId"+>[] = [+ {+ name: "Corrective Action",+ sortOrder: 1,+ createdBy: "system",+ },+ {+ name: "Preventive Action",+ sortOrder: 2,+ createdBy: "system",+ },+ {+ name: "Containment Action",+ sortOrder: 3,+ createdBy: "system",+ },+ {+ name: "Verification",+ sortOrder: 4,+ createdBy: "system",+ },+ {+ name: "Customer Communication",+ sortOrder: 5,+ createdBy: "system",+ },+];+export const paymentTerms: Omit<Database["public"]["Tables"]["paymentTerm"]["Insert"],"companyId"diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.tsindex 34823c8d49..7ca1f0a121 100644--- a/packages/database/supabase/functions/seed-company/index.ts+++ b/packages/database/supabase/functions/seed-company/index.ts@@ -12,6 +12,8 @@ import {gaugeTypes,groupCompanyTemplate,groups,+ nonConformanceInvestigationTypes,+ nonConformanceRequiredActions,nonConformanceTypes,paymentTerms,postingGroupInventory,@@ -189,6 +191,20 @@ serve(async (req: Request) => {.values(nonConformanceTypes.map((nc) => ({ ...nc, companyId }))).execute();+ await trx+ .insertInto("nonConformanceInvestigationType")+ .values(+ nonConformanceInvestigationTypes.map((nc) => ({ ...nc, companyId }))+ )+ .execute();++ await trx+ .insertInto("nonConformanceRequiredAction")+ .values(+ nonConformanceRequiredActions.map((nc) => ({ ...nc, companyId }))+ )+ .execute();+await trx.insertInto("sequence").values(sequences.map((s) => ({ ...s, companyId })))diff --git a/packages/database/supabase/migrations/20250806000000_custom-investigation-types-and-actions.sql b/packages/database/supabase/migrations/20250806000000_custom-investigation-types-and-actions.sqlnew file mode 100644index 0000000000..ac181ecc9b--- /dev/null+++ b/packages/database/supabase/migrations/20250806000000_custom-investigation-types-and-actions.sql@@ -0,0 +1,165 @@+-- Create custom investigation types table+CREATE TABLE "nonConformanceInvestigationType" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "companyId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "active" BOOLEAN NOT NULL DEFAULT true,+ "sortOrder" INTEGER NOT NULL DEFAULT 1,+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "nonConformanceInvestigationType_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "nonConformanceInvestigationType_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceInvestigationType_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceInvestigationType_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceInvestigationType_company_name_unique" UNIQUE ("companyId", "name")+);++-- Create custom required actions table+CREATE TABLE "nonConformanceRequiredAction" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "companyId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "active" BOOLEAN NOT NULL DEFAULT true,+ "sortOrder" INTEGER NOT NULL DEFAULT 1,+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "nonConformanceRequiredAction_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "nonConformanceRequiredAction_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceRequiredAction_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceRequiredAction_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceRequiredAction_company_name_unique" UNIQUE ("companyId", "name")+);++-- Create indexes+CREATE INDEX "nonConformanceInvestigationType_companyId_idx" ON "nonConformanceInvestigationType" ("companyId");+CREATE INDEX "nonConformanceInvestigationType_sortOrder_idx" ON "nonConformanceInvestigationType" ("sortOrder");+CREATE INDEX "nonConformanceRequiredAction_companyId_idx" ON "nonConformanceRequiredAction" ("companyId");+CREATE INDEX "nonConformanceRequiredAction_sortOrder_idx" ON "nonConformanceRequiredAction" ("sortOrder");++-- RLS policies for nonConformanceInvestigationType+CREATE POLICY "SELECT" ON "public"."nonConformanceInvestigationType"+FOR SELECT USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('quality_view')+ )::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."nonConformanceInvestigationType"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('quality_create')+ )::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."nonConformanceInvestigationType"+FOR UPDATE USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('quality_update')+ )::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."nonConformanceInvestigationType"+FOR DELETE USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('quality_delete')+ )::text[]+ )+);++-- RLS policies for nonConformanceRequiredAction+CREATE POLICY "SELECT" ON "public"."nonConformanceRequiredAction"+FOR SELECT USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('quality_view')+ )::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."nonConformanceRequiredAction"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('quality_create')+ )::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."nonConformanceRequiredAction"+FOR UPDATE USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('quality_update')+ )::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."nonConformanceRequiredAction"+FOR DELETE USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('quality_delete')+ )::text[]+ )+);++-- Enable RLS+ALTER TABLE "nonConformanceInvestigationType" ENABLE ROW LEVEL SECURITY;+ALTER TABLE "nonConformanceRequiredAction" ENABLE ROW LEVEL SECURITY;++-- Populate all existing companies with default investigation types+INSERT INTO "nonConformanceInvestigationType" ("companyId", "name", "sortOrder", "createdBy")+SELECT+ c."id" as "companyId",+ inv_type.name,+ inv_type.sort_order,+ 'system' as "createdBy"+FROM "company" c+CROSS JOIN (+ VALUES+ ('Root Cause Analysis', 1),+ ('Inventory', 2),+ ('WIP', 3),+ ('Finished Goods', 4),+ ('Incoming Materials', 5),+ ('Process', 6),+ ('Documentation', 7)+) AS inv_type(name, sort_order);++-- Populate all existing companies with default required actions+INSERT INTO "nonConformanceRequiredAction" ("companyId", "name", "sortOrder", "createdBy")+SELECT+ c."id" as "companyId",+ action_type.name,+ action_type.sort_order,+ 'system' as "createdBy"+FROM "company" c+CROSS JOIN (+ VALUES+ ('Corrective Action', 1),+ ('Preventive Action', 2),+ ('Containment Action', 3),+ ('Verification', 4),+ ('Customer Communication', 5)+) AS action_type(name, sort_order);\ No newline at end of filediff --git a/packages/database/supabase/migrations/20250806000001_update-schema-custom-types.sql b/packages/database/supabase/migrations/20250806000001_update-schema-custom-types.sqlnew file mode 100644index 0000000000..c74cecd0e2--- /dev/null+++ b/packages/database/supabase/migrations/20250806000001_update-schema-custom-types.sql@@ -0,0 +1,57 @@+-- Add new foreign key columns to nonConformance table for custom types/actions+ALTER TABLE "nonConformance"+ADD COLUMN "investigationTypeIds" TEXT[] DEFAULT ARRAY[]::TEXT[],+ADD COLUMN "requiredActionIds" TEXT[] DEFAULT ARRAY[]::TEXT[];++-- Add new foreign key columns to task tables+ALTER TABLE "nonConformanceInvestigationTask"+ADD COLUMN "investigationTypeId" TEXT;++ALTER TABLE "nonConformanceActionTask"+ADD COLUMN "actionTypeId" TEXT;++-- Add foreign key constraints+ALTER TABLE "nonConformanceInvestigationTask"+ADD CONSTRAINT "nonConformanceInvestigationTask_investigationTypeId_fkey"+FOREIGN KEY ("investigationTypeId") REFERENCES "nonConformanceInvestigationType"("id") ON UPDATE CASCADE ON DELETE SET NULL;++ALTER TABLE "nonConformanceActionTask"+ADD CONSTRAINT "nonConformanceActionTask_actionTypeId_fkey"+FOREIGN KEY ("actionTypeId") REFERENCES "nonConformanceRequiredAction"("id") ON UPDATE CASCADE ON DELETE SET NULL;++-- Create indexes for the new foreign key columns+CREATE INDEX "nonConformanceInvestigationTask_investigationTypeId_idx" ON "nonConformanceInvestigationTask" ("investigationTypeId");+CREATE INDEX "nonConformanceActionTask_actionTypeId_idx" ON "nonConformanceActionTask" ("actionTypeId");++-- Migrate existing data from ENUM arrays to foreign key arrays in nonConformance table+UPDATE "nonConformance"+SET "investigationTypeIds" = (+ SELECT ARRAY_AGG(ict."id")+ FROM UNNEST("investigationTypes") AS inv_type(name)+ JOIN "nonConformanceInvestigationType" ict ON ict."name" = inv_type.name AND ict."companyId" = "nonConformance"."companyId"+)+WHERE "investigationTypes" IS NOT NULL AND ARRAY_LENGTH("investigationTypes", 1) > 0;++UPDATE "nonConformance"+SET "requiredActionIds" = (+ SELECT ARRAY_AGG(rac."id")+ FROM UNNEST("requiredActions") AS req_action(name)+ JOIN "nonConformanceRequiredAction" rac ON rac."name" = req_action.name AND rac."companyId" = "nonConformance"."companyId"+)+WHERE "requiredActions" IS NOT NULL AND ARRAY_LENGTH("requiredActions", 1) > 0;++-- Migrate existing data from ENUM to foreign key in investigation task table+UPDATE "nonConformanceInvestigationTask"+SET "investigationTypeId" = ict."id"+FROM "nonConformanceInvestigationType" ict+WHERE ict."name" = "nonConformanceInvestigationTask"."investigationType"::text+ AND ict."companyId" = "nonConformanceInvestigationTask"."companyId"+ AND "nonConformanceInvestigationTask"."investigationType" IS NOT NULL;++-- Migrate existing data from ENUM to foreign key in action task table+UPDATE "nonConformanceActionTask"+SET "actionTypeId" = rac."id"+FROM "nonConformanceRequiredAction" rac+WHERE rac."name" = "nonConformanceActionTask"."actionType"::text+ AND rac."companyId" = "nonConformanceActionTask"."companyId"+ AND "nonConformanceActionTask"."actionType" IS NOT NULL;\ No newline at end of file