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.

refactor: combine investigations and actions into a single primitive

Brad Barbin9d4f92f79c6b
diff --git a/apps/erp/app/modules/quality/quality.models.ts b/apps/erp/app/modules/quality/quality.models.ts
index ba9309788a..4505ccfaa1 100644
--- a/apps/erp/app/modules/quality/quality.models.ts
+++ b/apps/erp/app/modules/quality/quality.models.ts
@@ -152,7 +152,6 @@ export const issueValidator = z.object({
source: z.enum(nonConformanceSource),
name: z.string().min(1, { message: "Name is required" }),
description: zfd.text(z.string().optional()),
- investigationTypeIds: z.array(z.string()).optional(),
requiredActionIds: z.array(z.string()).optional(),
approvalRequirements: z
.array(z.enum(nonConformanceApprovalRequirement))
@@ -175,12 +174,6 @@ export const nonConformanceReviewerValidator = z.object({
title: z.string().min(1, { message: "Title is required" }),
});
-export const investigationTypeValidator = z.object({
- id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Name is required" }),
- active: zfd.checkbox(),
-});
-
export const issueTypeValidator = z.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }),
@@ -201,7 +194,6 @@ export const issueWorkflowValidator = z.object({
}),
priority: z.enum(nonConformancePriority),
source: z.enum(nonConformanceSource),
- investigationTypeIds: z.array(z.string()).optional(),
requiredActionIds: z.array(z.string()).optional(),
approvalRequirements: z
.array(z.enum(nonConformanceApprovalRequirement))
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index 4df3ecde0d..26dbb8848c 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -130,16 +130,6 @@ export async function deleteIssueAssociation(
}
}
-export async function deleteInvestigationType(
- client: SupabaseClient<Database>,
- investigationTypeId: string
-) {
- return client
- .from("nonConformanceInvestigationType")
- .delete()
- .eq("id", investigationTypeId);
-}
-
export async function deleteIssueType(
client: SupabaseClient<Database>,
nonConformanceTypeId: string
@@ -382,24 +372,6 @@ export async function getIssueWorkflow(
.single();
}
-export async function getIssueInvestigationTasks(
- client: SupabaseClient<Database>,
- id: string,
- companyId: string,
- supplierId?: string
-) {
- let query = client
- .from("nonConformanceInvestigationTask")
- .select("*, ...nonConformanceInvestigationType(name), supplier(name)")
- .eq("nonConformanceId", id)
- .eq("companyId", companyId);
-
- if (supplierId) {
- query = query.eq("supplierId", supplierId);
- }
- return query;
-}
-
export async function getIssueActionTasks(
client: SupabaseClient<Database>,
id: string,
@@ -713,18 +685,12 @@ export async function getIssueTasks(
companyId: string
) {
return Promise.all([
- client
- .from("nonConformanceInvestigationTask")
- .select("*")
- .eq("nonConformanceId", id)
- .eq("companyId", companyId)
- .order("investigationType", { ascending: true }),
client
.from("nonConformanceActionTask")
.select("*")
.eq("nonConformanceId", id)
.eq("companyId", companyId)
- .order("actionType", { ascending: true }),
+ .order("createdAt", { ascending: true }),
client
.from("nonConformanceApprovalTask")
.select("*")
@@ -815,55 +781,6 @@ export async function getIssueTypesList(
.order("name");
}
-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: "name", ascending: true },
- ]);
- } else {
- query = query.order("name");
- }
-
- const result = await query;
- return result;
-}
-
-export async function getInvestigationType(
- client: SupabaseClient<Database>,
- investigationTypeId: string
-) {
- return client
- .from("nonConformanceInvestigationType")
- .select("*")
- .eq("id", investigationTypeId)
- .single();
-}
-
-export async function getInvestigationTypesList(
- client: SupabaseClient<Database>,
- companyId: string
-) {
- return client
- .from("nonConformanceInvestigationType")
- .select("id, name")
- .eq("companyId", companyId)
- .eq("active", true)
- .order("name");
-}
-
export async function getQualityActions(
client: SupabaseClient<Database>,
companyId: string,
@@ -1092,16 +1009,14 @@ export async function updateIssueTaskStatus(
args: {
id: string;
status: "Pending" | "Completed" | "Skipped" | "In Progress";
- type: "investigation" | "action" | "approval" | "review";
+ type: "action" | "approval" | "review";
userId?: string;
assignee?: string | null;
}
) {
const { id, status, type, userId, assignee } = args;
const table =
- type === "investigation"
- ? "nonConformanceInvestigationTask"
- : type === "action"
+ type === "action"
? "nonConformanceActionTask"
: type === "review"
? "nonConformanceReviewer"
@@ -1121,15 +1036,13 @@ export async function updateIssueTaskContent(
client: SupabaseClient<Database>,
args: {
id: string;
- type: "investigation" | "action" | "approval" | "review";
+ type: "action" | "approval" | "review";
content: JSONContent;
}
) {
const { id, content, type } = args;
const table =
- type === "investigation"
- ? "nonConformanceInvestigationTask"
- : type === "action"
+ type === "action"
? "nonConformanceActionTask"
: type === "review"
? "nonConformanceReviewer"
@@ -1500,33 +1413,6 @@ export async function upsertIssueType(
}
}
-export async function upsertInvestigationType(
- client: SupabaseClient<Database>,
- investigationType:
- | (Omit<z.infer<typeof investigationTypeValidator>, "id"> & {
- companyId: string;
- active?: boolean;
- createdBy: string;
- })
- | (Omit<z.infer<typeof investigationTypeValidator>, "id"> & {
- id: string;
- active?: boolean;
- updatedBy: string;
- })
-) {
- if ("createdBy" in investigationType) {
- return client
- .from("nonConformanceInvestigationType")
- .insert([investigationType])
- .select("id");
- } else {
- return client
- .from("nonConformanceInvestigationType")
- .update(sanitize(investigationType))
- .eq("id", investigationType.id);
- }
-}
-
export async function upsertRequiredAction(
client: SupabaseClient<Database>,
requiredAction:
diff --git a/apps/erp/app/modules/quality/ui/InvestigationTypes/InvestigationTypeForm.tsx b/apps/erp/app/modules/quality/ui/InvestigationTypes/InvestigationTypeForm.tsx
deleted file mode 100644
index f350ef0bbd..0000000000
--- a/apps/erp/app/modules/quality/ui/InvestigationTypes/InvestigationTypeForm.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-import { ValidatedForm } from "@carbon/form";
-import {
- Button,
- HStack,
- ModalDrawer,
- ModalDrawerBody,
- ModalDrawerContent,
- ModalDrawerFooter,
- ModalDrawerHeader,
- ModalDrawerProvider,
- ModalDrawerTitle,
- VStack,
- toast,
-} from "@carbon/react";
-import { useFetcher } from "@remix-run/react";
-import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useEffect } from "react";
-import type { z } from 'zod/v3';
-import { Boolean, CustomFormFields, Hidden, Input, Submit } from "~/components/Form";
-import { usePermissions } from "~/hooks";
-import { path } from "~/utils/path";
-import { investigationTypeValidator } from "../../quality.models";
-
-type InvestigationTypeFormProps = {
- initialValues: z.infer<typeof investigationTypeValidator>;
- type?: "modal" | "drawer";
- open?: boolean;
- onClose: () => void;
-};
-
-const InvestigationTypeForm = ({
- initialValues,
- open = true,
- type = "drawer",
- onClose,
-}: InvestigationTypeFormProps) => {
- const permissions = usePermissions();
- const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
-
- useEffect(() => {
- if (type !== "modal") return;
-
- if (fetcher.state === "loading" && fetcher.data?.data) {
- onClose?.();
- toast.success(`Created investigation type`);
- } else if (fetcher.state === "idle" && fetcher.data?.error) {
- toast.error(
- `Failed to create investigation type: ${fetcher.data.error.message}`
- );
- }
- }, [fetcher.data, fetcher.state, onClose, type]);
-
- const isEditing = initialValues.id !== undefined;
- const isDisabled = isEditing
- ? !permissions.can("update", "quality")
- : !permissions.can("create", "quality");
-
- return (
- <ModalDrawerProvider type={type}>
- <ModalDrawer
- open={open}
- onOpenChange={(open) => {
- if (!open) onClose?.();
- }}
- >
- <ModalDrawerContent>
- <ValidatedForm
- validator={investigationTypeValidator}
- method="post"
- action={
- isEditing
- ? path.to.investigationType(initialValues.id!)
- : path.to.newInvestigationType
- }
- defaultValues={initialValues}
- fetcher={fetcher}
- className="flex flex-col h-full"
- >
- <ModalDrawerHeader>
- <ModalDrawerTitle>
- {isEditing ? "Edit" : "New"} Investigation Type
- </ModalDrawerTitle>
- </ModalDrawerHeader>
- <ModalDrawerBody>
- <Hidden name="id" />
- <Hidden name="type" value={type} />
- <VStack spacing={4}>
- <Input name="name" label="Investigation Type" />
- <Boolean
- name="active"
- label="Active"
- description="Inactive types will not appear in selection lists"
- />
- <CustomFormFields table="nonConformanceInvestigationType" />
- </VStack>
- </ModalDrawerBody>
- <ModalDrawerFooter>
- <HStack>
- <Submit isDisabled={isDisabled}>Save</Submit>
- <Button size="md" variant="solid" onClick={() => onClose()}>
- Cancel
- </Button>
- </HStack>
- </ModalDrawerFooter>
- </ValidatedForm>
- </ModalDrawerContent>
- </ModalDrawer>
- </ModalDrawerProvider>
- );
-};
-
-export default InvestigationTypeForm;
\ No newline at end of file
diff --git a/apps/erp/app/modules/quality/ui/InvestigationTypes/InvestigationTypesTable.tsx b/apps/erp/app/modules/quality/ui/InvestigationTypes/InvestigationTypesTable.tsx
deleted file mode 100644
index b506e4e1e2..0000000000
--- a/apps/erp/app/modules/quality/ui/InvestigationTypes/InvestigationTypesTable.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-import { Checkbox, MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
-import { useNavigate } from "@remix-run/react";
-import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useCallback, useMemo, useState } from "react";
-import { flushSync } from "react-dom";
-import { LuFlaskConical, LuPencil, LuTrash } from "react-icons/lu";
-import { Hyperlink, New, Table } from "~/components";
-import { Enumerable } from "~/components/Enumerable";
-import { ConfirmDelete } from "~/components/Modals";
-import { usePermissions, useUrlParams } from "~/hooks";
-import { path } from "~/utils/path";
-import type { InvestigationType } from "../../types";
-
-type InvestigationTypesTableProps = {
- data: InvestigationType[];
- count: number;
-};
-
-const InvestigationTypesTable = memo(
- ({ data, count }: InvestigationTypesTableProps) => {
- const [params] = useUrlParams();
- const navigate = useNavigate();
- const permissions = usePermissions();
- const deleteDisclosure = useDisclosure();
- const [selectedInvestigationType, setSelectedInvestigationType] =
- useState<InvestigationType | null>(null);
-
- const columns = useMemo<ColumnDef<InvestigationType>[]>(() => {
- const defaultColumns: ColumnDef<InvestigationType>[] = [
- {
- accessorKey: "name",
- header: "Investigation Type",
- cell: ({ row }) => (
- <Hyperlink to={row.original.id}>
- <Enumerable value={row.original.name} />
- </Hyperlink>
- ),
- meta: {
- icon: <LuFlaskConical />,
- },
- },
- {
- accessorKey: "active",
- header: "Active",
- cell: ({ row }) => <Checkbox checked={row.original.active} />,
- },
- ];
- return defaultColumns;
- }, []);
-
- const renderContextMenu = useCallback(
- (row: InvestigationType) => {
- return (
- <>
- <MenuItem
- onClick={() => {
- navigate(
- `${path.to.investigationType(row.id)}?${params.toString()}`
- );
- }}
- >
- <MenuIcon icon={<LuPencil />} />
- Edit Type
- </MenuItem>
- <MenuItem
- destructive
- disabled={!permissions.can("delete", "quality")}
- onClick={() => {
- flushSync(() => {
- setSelectedInvestigationType(row);
- });
- deleteDisclosure.onOpen();
- }}
- >
- <MenuIcon icon={<LuTrash />} />
- Delete Type
- </MenuItem>
- </>
- );
- },
- [navigate, params, permissions, deleteDisclosure]
- );
-
- return (
- <>
- <Table<InvestigationType>
- data={data}
- columns={columns}
- count={count}
- primaryAction={
- permissions.can("create", "quality") && (
- <New
- label="Investigation Type"
- to={`${path.to.newInvestigationType}?${params.toString()}`}
- />
- )
- }
- renderContextMenu={renderContextMenu}
- title="Investigation Types"
- />
- {deleteDisclosure.isOpen && selectedInvestigationType && (
- <ConfirmDelete
- action={path.to.deleteInvestigationType(
- selectedInvestigationType.id
- )}
- isOpen
- onCancel={() => {
- setSelectedInvestigationType(null);
- deleteDisclosure.onClose();
- }}
- onSubmit={() => {
- setSelectedInvestigationType(null);
- deleteDisclosure.onClose();
- }}
- name={selectedInvestigationType.name ?? "investigation type"}
- text="Are you sure you want to delete this investigation type?"
- />
- )}
- </>
- );
- }
-);
-
-InvestigationTypesTable.displayName = "InvestigationTypesTable";
-export default InvestigationTypesTable;
diff --git a/apps/erp/app/modules/quality/ui/InvestigationTypes/index.ts b/apps/erp/app/modules/quality/ui/InvestigationTypes/index.ts
deleted file mode 100644
index b8287cd262..0000000000
--- a/apps/erp/app/modules/quality/ui/InvestigationTypes/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { default as InvestigationTypeForm } from "./InvestigationTypeForm";
-export { default as InvestigationTypesTable } from "./InvestigationTypesTable";
\ No newline at end of file
diff --git a/apps/erp/app/modules/quality/ui/Issue/InvestigationTasksList.tsx b/apps/erp/app/modules/quality/ui/Issue/InvestigationTasksList.tsx
deleted file mode 100644
index ec63b96020..0000000000
--- a/apps/erp/app/modules/quality/ui/Issue/InvestigationTasksList.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-import {
- Button,
- Card,
- CardContent,
- CardHeader,
- CardTitle,
- Checkbox,
- HStack,
- Modal,
- ModalBody,
- ModalContent,
- ModalFooter,
- ModalHeader,
- ModalOverlay,
- ModalTitle,
- VStack,
-} from "@carbon/react";
-import { useFetcher, useParams } from "@remix-run/react";
-import { useCallback, useEffect, useState } from "react";
-import { LuCirclePlus } from "react-icons/lu";
-import { useRouteData } from "~/hooks";
-import type { IssueInvestigationTask } from "~/modules/quality";
-import type { ListItem } from "~/types";
-import { path } from "~/utils/path";
-import { TaskItem, TaskProgress } from "./IssueTask";
-
-export function InvestigationTasksList({
- tasks,
- suppliers,
- isDisabled,
-}: {
- tasks: IssueInvestigationTask[];
- suppliers: { supplierId: string; externalLinkId: string | null }[];
- isDisabled: boolean;
-}) {
- if (tasks.length === 0) return <NewInvestigation isDisabled={isDisabled} />;
-
- return (
- <Card className="w-full" isCollapsible>
- <HStack className="justify-between w-full">
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- Investigations
- </CardTitle>
- </CardHeader>
- <TaskProgress tasks={tasks} />
- </HStack>
- <CardContent>
- <VStack spacing={3}>
- {tasks
- .sort((a, b) => a.name?.localeCompare(b.name ?? "") ?? 0)
- .map((task) => (
- <TaskItem
- key={task.id}
- task={task}
- type="investigation"
- suppliers={suppliers}
- isDisabled={isDisabled}
- />
- ))}
- </VStack>
- </CardContent>
- </Card>
- );
-}
-
-function NewInvestigation({ isDisabled }: { isDisabled: boolean }) {
- const { id } = useParams();
- if (!id) throw new Error("id not found");
-
- const [isOpen, setIsOpen] = useState(false);
- const [selectedTypeIds, setSelectedTypeIds] = useState<string[]>([]);
-
- const routeData = useRouteData<{
- investigationTypes: ListItem[];
- }>(path.to.issue(id));
-
- const fetcher = useFetcher();
-
- useEffect(() => {
- if (fetcher.state === "idle" && fetcher.data) {
- setIsOpen(false);
- setSelectedTypeIds([]);
- }
- }, [fetcher.state, fetcher.data]);
-
- const handleSubmit = useCallback(() => {
- const formData = new FormData();
- formData.append("ids", id);
- formData.append("field", "investigationTypeIds");
- formData.append("value", selectedTypeIds.join(","));
-
- fetcher.submit(formData, {
- method: "post",
- action: path.to.bulkUpdateIssue,
- });
- }, [id, selectedTypeIds, fetcher]);
-
- const handleCheckboxChange = useCallback(
- (typeId: string, checked: boolean) => {
- setSelectedTypeIds((prev) =>
- checked ? [...prev, typeId] : prev.filter((id) => id !== typeId)
- );
- },
- []
- );
-
- return (
- <>
- <button
- className="flex items-center justify-start bg-card border-2 border-dashed border-background w-full hover:bg-background/80 rounded-lg px-10 py-6 text-muted-foreground hover:text-foreground gap-2 transition-colors duration-200 text-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
- onClick={() => setIsOpen(true)}
- disabled={isDisabled}
- >
- <LuCirclePlus size={16} /> <span>Add Investigations</span>
- </button>
-
- <Modal
- open={isOpen}
- onOpenChange={(open) => {
- if (!open) {
- setIsOpen(false);
- setSelectedTypeIds([]);
- }
- }}
- >
- <ModalOverlay />
- <ModalContent>
- <ModalHeader>
- <ModalTitle>Add Investigation Types</ModalTitle>
- </ModalHeader>
- <ModalBody>
- <VStack spacing={2}>
- {routeData?.investigationTypes.map((type) => (
- <label
- key={type.id}
- htmlFor={type.id}
- className="flex items-center gap-2 w-full px-4 py-3 rounded-lg hover:bg-accent hover:text-accent-foreground border border-border cursor-pointer"
- >
- <Checkbox
- id={type.id}
- isChecked={selectedTypeIds.includes(type.id)}
- onCheckedChange={(checked) =>
- handleCheckboxChange(type.id, !!checked)
- }
- />
- <span className="text-sm font-medium">{type.name}</span>
- </label>
- ))}
- </VStack>
- </ModalBody>
- <ModalFooter>
- <Button
- variant="secondary"
- onClick={() => {
- setIsOpen(false);
- setSelectedTypeIds([]);
- }}
- >
- Cancel
- </Button>
- <Button
- onClick={handleSubmit}
- disabled={
- selectedTypeIds.length === 0 || fetcher.state !== "idle"
- }
- isLoading={fetcher.state === "submitting"}
- >
- {fetcher.state !== "idle" ? "Adding..." : "Add Investigations"}
- </Button>
- </ModalFooter>
- </ModalContent>
- </Modal>
- </>
- );
-}
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx
index d6c170e2ce..4b525894d2 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx
@@ -372,35 +372,6 @@ const IssueProperties = () => {
/>
</ValidatedForm>
- <ValidatedForm
- defaultValues={{
- investigationTypeIds:
- routeData?.nonConformance?.investigationTypeIds ?? [],
- }}
- validator={z.object({
- investigationTypeIds: z.array(z.string()).optional(),
- })}
- className="w-full"
- >
- <MultiSelect
- options={(routeData?.investigationTypes ?? []).map((type) => ({
- value: type.id,
- label: type.name,
- }))}
- isReadOnly={disableStructureUpdate}
- label="Investigation Types"
- name="investigationTypeIds"
- inline
- value={routeData?.nonConformance?.investigationTypeIds ?? []}
- onChange={(value) => {
- onUpdate(
- "investigationTypeIds",
- value.map((v) => v.value).join(",")
- );
- }}
- />
- </ValidatedForm>
-
<ValidatedForm
defaultValues={{
requiredActionIds: routeData?.nonConformance?.requiredActionIds ?? [],
diff --git a/apps/erp/app/modules/quality/ui/Issue/index.ts b/apps/erp/app/modules/quality/ui/Issue/index.ts
index ea099d240a..cf3a4ea0da 100644
--- a/apps/erp/app/modules/quality/ui/Issue/index.ts
+++ b/apps/erp/app/modules/quality/ui/Issue/index.ts
@@ -1,6 +1,5 @@
export * from "./ActionTasksList";
export * from "./AssociatedItemsList";
-export * from "./InvestigationTasksList";
export * from "./IssueAssociations";
export * from "./IssueContent";
export * from "./IssueForm";
diff --git a/apps/erp/app/modules/quality/ui/useQualitySubmodules.tsx b/apps/erp/app/modules/quality/ui/useQualitySubmodules.tsx
index aa53ceb194..0327a5c542 100644
--- a/apps/erp/app/modules/quality/ui/useQualitySubmodules.tsx
+++ b/apps/erp/app/modules/quality/ui/useQualitySubmodules.tsx
@@ -4,7 +4,6 @@ import {
LuFileText,
LuListChecks,
LuOctagonX,
- LuSearch,
LuShapes,
LuShieldX,
LuSquareCheck,
@@ -80,11 +79,6 @@ const qualityRoutes: AuthenticatedRouteGroup[] = [
to: path.to.gaugeTypes,
icon: <LuShapes />,
},
- {
- name: "Investigation Types",
- to: path.to.investigationTypes,
- icon: <LuSearch />,
- },
{
name: "Issue Types",
to: path.to.issueTypes,
diff --git a/apps/erp/app/routes/x+/issue+/$id.details.tsx b/apps/erp/app/routes/x+/issue+/$id.details.tsx
index 814a62c82d..f510b10efb 100644
--- a/apps/erp/app/routes/x+/issue+/$id.details.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.details.tsx
@@ -12,7 +12,6 @@ import { useRouteData } from "~/hooks";
import type { IssueAssociationNode } from "~/modules/quality";
import {
getIssueActionTasks,
- getIssueInvestigationTasks,
getIssueReviewers,
issueValidator,
upsertIssue,
@@ -20,7 +19,6 @@ import {
import {
ActionTasksList,
AssociatedItemsList,
- InvestigationTasksList,
IssueContent,
ReviewersList,
} from "~/modules/quality/ui/Issue";
@@ -49,7 +47,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return defer({
nonConformance: nonConformance.data,
- investigationTasks: getIssueInvestigationTasks(client, id, companyId),
actionTasks: getIssueActionTasks(client, id, companyId),
reviewers: getIssueReviewers(client, id, companyId),
});
@@ -104,7 +101,7 @@ export default function IssueDetailsRoute() {
const { id } = useParams();
if (!id) throw new Error("Could not find id");
- const { nonConformance, investigationTasks, actionTasks, reviewers } =
+ const { nonConformance, actionTasks, reviewers } =
useLoaderData<typeof loader>();
const routeData = useRouteData<{
@@ -161,24 +158,6 @@ export default function IssueDetailsRoute() {
</Await>
</Suspense>
- <Suspense
- fallback={
- <div className="flex min-h-[420px] w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center">
- <Spinner className="size-10" />
- </div>
- }
- >
- <Await resolve={investigationTasks}>
- {(resolvedTasks) => (
- <InvestigationTasksList
- tasks={resolvedTasks?.data ?? []}
- suppliers={routeData?.suppliers ?? []}
- isDisabled={nonConformance?.status === "Closed"}
- />
- )}
- </Await>
- </Suspense>
-
<Suspense
fallback={
<div className="flex min-h-[420px] w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center">
diff --git a/apps/erp/app/routes/x+/issue+/$id.tsx b/apps/erp/app/routes/x+/issue+/$id.tsx
index 59c442961a..eb2d459d6c 100644
--- a/apps/erp/app/routes/x+/issue+/$id.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.tsx
@@ -9,7 +9,6 @@ import { Suspense } from "react";
import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
import { getItemFiles } from "~/modules/items";
import {
- getInvestigationTypesList,
getIssue,
getIssueAssociations,
getIssueSuppliers,
@@ -45,14 +44,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const [
nonConformance,
nonConformanceTypes,
- investigationTypes,
requiredActions,
suppliers,
tags,
] = await Promise.all([
getIssue(client, id),
getIssueTypesList(client, companyId),
- getInvestigationTypesList(client, companyId),
getRequiredActionsList(client, companyId),
getIssueSuppliers(client, id, companyId),
getTagsList(client, companyId, "nonConformance"),
@@ -68,7 +65,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return defer({
associations: getIssueAssociations(client, id, companyId),
files: getItemFiles(client, id, companyId),
- investigationTypes: investigationTypes.data ?? [],
nonConformance: nonConformance.data,
nonConformanceTypes: nonConformanceTypes.data ?? [],
requiredActions: requiredActions.data ?? [],
diff --git a/apps/erp/app/routes/x+/issue+/task.supplier.tsx b/apps/erp/app/routes/x+/issue+/task.supplier.tsx
index 8a5e35c12e..ce49828326 100644
--- a/apps/erp/app/routes/x+/issue+/task.supplier.tsx
+++ b/apps/erp/app/routes/x+/issue+/task.supplier.tsx
@@ -27,10 +27,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- if (
- table !== "nonConformanceInvestigationTask" &&
- table !== "nonConformanceActionTask"
- ) {
+ if (table !== "nonConformanceActionTask") {
return json(
{ success: false },
await flash(request, error(null, "Invalid table"))
diff --git a/apps/erp/app/routes/x+/quality+/issues.tsx b/apps/erp/app/routes/x+/quality+/issues.tsx
index 35c87dbadc..b13f319e80 100644
--- a/apps/erp/app/routes/x+/quality+/issues.tsx
+++ b/apps/erp/app/routes/x+/quality+/issues.tsx
@@ -1,8 +1,10 @@
+import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
import { Outlet, useLoaderData } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
-import { json } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
import { getIssues, getIssueTypesList } from "~/modules/quality";
import IssuesTable from "~/modules/quality/ui/Issue/IssuesTable";
import type { Handle } from "~/utils/handle";
@@ -37,11 +39,19 @@ export async function loader({ request }: LoaderFunctionArgs) {
getIssueTypesList(client, companyId),
]);
- return json({
+ if (issues.error) {
+ console.error(issues.error);
+ throw redirect(
+ path.to.authenticatedRoot,
+ await flash(request, error(issues.error, "Error loading issues"))
+ );
+ }
+
+ return {
issues: issues.data ?? [],
count: issues.count ?? 0,
types: nonConformanceTypes.data ?? [],
- });
+ };
}
export default function IssuesRoute() {
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index c34759b38b..da5052c211 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -14526,7 +14526,6 @@ export type Database = {
description: string | null
dueDate: string | null
id: string
- investigationTypeIds: string[] | null
locationId: string
name: string
nonConformanceId: string
@@ -14556,7 +14555,6 @@ export type Database = {
description?: string | null
dueDate?: string | null
id?: string
- investigationTypeIds?: string[] | null
locationId: string
name: string
nonConformanceId: string
@@ -14588,7 +14586,6 @@ export type Database = {
description?: string | null
dueDate?: string | null
id?: string
- investigationTypeIds?: string[] | null
locationId?: string
name?: string
nonConformanceId?: string
@@ -15545,385 +15542,6 @@ export type Database = {
},
]
}
- nonConformanceInvestigationTask: {
- Row: {
- assignee: string | null
- companyId: string
- completedDate: string | null
- createdAt: string
- createdBy: string
- dueDate: string | null
- id: string
- investigationTypeId: string | null
- nonConformanceId: string
- notes: Json
- sortOrder: number
- status: Database["public"]["Enums"]["nonConformanceTaskStatus"]
- supplierId: string | null
- tags: string[] | null
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- assignee?: string | null
- companyId: string
- completedDate?: string | null
- createdAt?: string
- createdBy: string
- dueDate?: string | null
- id?: string
- investigationTypeId?: string | null
- nonConformanceId: string
- notes?: Json
- sortOrder?: number
- status?: Database["public"]["Enums"]["nonConformanceTaskStatus"]
- supplierId?: string | null
- tags?: string[] | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- assignee?: string | null
- companyId?: string
- completedDate?: string | null
- createdAt?: string
- createdBy?: string
- dueDate?: string | null
- id?: string
- investigationTypeId?: string | null
- nonConformanceId?: string
- notes?: Json
- sortOrder?: number
- status?: Database["public"]["Enums"]["nonConformanceTaskStatus"]
- supplierId?: string | null
- tags?: string[] | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_investigationTypeId_fkey"
- columns: ["investigationTypeId"]
- isOneToOne: false
- referencedRelation: "nonConformanceInvestigationType"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_nonConformanceId_fkey"
- columns: ["nonConformanceId"]
- isOneToOne: false
- referencedRelation: "issues"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_nonConformanceId_fkey"
- columns: ["nonConformanceId"]
- isOneToOne: false
- referencedRelation: "nonConformance"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "contractors"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "partners"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "purchaseOrderSuppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "supplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "suppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- nonConformanceInvestigationType: {
- Row: {
- active: boolean
- companyId: string
- createdAt: string
- createdBy: string
- id: string
- name: string
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- active?: boolean
- companyId: string
- createdAt?: string
- createdBy: string
- id?: string
- name: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- active?: boolean
- companyId?: string
- createdAt?: string
- createdBy?: string
- id?: string
- name?: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "nonConformanceInvestigationType_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
nonConformanceItem: {
Row: {
companyId: string
@@ -17849,7 +17467,6 @@ export type Database = {
createdBy: string
description: string | null
id: string
- investigationTypeIds: string[] | null
name: string
priority: Database["public"]["Enums"]["nonConformancePriority"]
requiredActionIds: string[] | null
@@ -17869,7 +17486,6 @@ export type Database = {
createdBy: string
description?: string | null
id?: string
- investigationTypeIds?: string[] | null
name: string
priority?: Database["public"]["Enums"]["nonConformancePriority"]
requiredActionIds?: string[] | null
@@ -17889,7 +17505,6 @@ export type Database = {
createdBy?: string
description?: string | null
id?: string
- investigationTypeIds?: string[] | null
name?: string
priority?: Database["public"]["Enums"]["nonConformancePriority"]
requiredActionIds?: string[] | null
@@ -39587,7 +39202,6 @@ export type Database = {
description: string | null
dueDate: string | null
id: string | null
- investigationTypeIds: string[] | null
items: string[] | null
locationId: string | null
name: string | null
@@ -42192,14 +41806,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -43563,14 +43177,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -46625,14 +46239,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -50608,21 +50222,7 @@ export type Database = {
| "October"
| "November"
| "December"
- nonConformanceAction:
- | "Corrective Action"
- | "Preventive Action"
- | "Containment Action"
- | "Verification"
- | "Customer Communication"
nonConformanceApproval: "MRB"
- nonConformanceInvestigation:
- | "Root Cause Analysis"
- | "Inventory"
- | "WIP"
- | "Finished Goods"
- | "Incoming Materials"
- | "Process"
- | "Documentation"
nonConformancePriority: "Low" | "Medium" | "High" | "Critical"
nonConformanceSource: "Internal" | "External"
nonConformanceStatus: "Registered" | "In Progress" | "Closed"
@@ -51717,23 +51317,7 @@ export const Constants = {
"November",
"December",
],
- nonConformanceAction: [
- "Corrective Action",
- "Preventive Action",
- "Containment Action",
- "Verification",
- "Customer Communication",
- ],
nonConformanceApproval: ["MRB"],
- nonConformanceInvestigation: [
- "Root Cause Analysis",
- "Inventory",
- "WIP",
- "Finished Goods",
- "Incoming Materials",
- "Process",
- "Documentation",
- ],
nonConformancePriority: ["Low", "Medium", "High", "Critical"],
nonConformanceSource: ["Internal", "External"],
nonConformanceStatus: ["Registered", "In Progress", "Closed"],
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index 1153173787..1cb11645d9 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -133,16 +133,11 @@ serve(async (req: Request) => {
const [
nonConformance,
- investigationTasks,
actionTasks,
approvalTasks,
existingReviewers,
] = await Promise.all([
client.from("nonConformance").select("*").eq("id", id).single(),
- client
- .from("nonConformanceInvestigationTask")
- .select("*")
- .eq("nonConformanceId", id),
client
.from("nonConformanceActionTask")
.select("*")
@@ -169,14 +164,6 @@ serve(async (req: Request) => {
if (workflow?.error) throw new Error(workflow.error.message);
- const currentInvestigationTasks =
- investigationTasks.data?.reduce<Record<string, string>>((acc, d) => {
- 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.actionTypeId && !acc[d.actionTypeId]) {
@@ -193,25 +180,10 @@ serve(async (req: Request) => {
return acc;
}, {}) ?? {};
- const investigationTasksToDelete: string[] = [];
const actionTasksToDelete: string[] = [];
const approvalTasksToDelete: string[] = [];
const reviewersToDelete: string[] = [];
- Object.keys(currentInvestigationTasks).forEach(
- (investigationTypeId) => {
- if (
- !(nonConformance.data?.investigationTypeIds ?? []).some(
- (d) => d === investigationTypeId
- )
- ) {
- investigationTasksToDelete.push(
- currentInvestigationTasks[investigationTypeId]
- );
- }
- }
- );
-
Object.keys(currentActionTasks).forEach((actionTypeId) => {
if (
!(nonConformance.data?.requiredActionIds ?? []).some(
@@ -232,8 +204,6 @@ serve(async (req: Request) => {
}
});
- const investigationTaskInserts: Database["public"]["Tables"]["nonConformanceInvestigationTask"]["Insert"][] =
- [];
const actionTaskInserts: Database["public"]["Tables"]["nonConformanceActionTask"]["Insert"][] =
[];
const approvalTaskInserts: Database["public"]["Tables"]["nonConformanceApprovalTask"]["Insert"][] =
@@ -242,19 +212,6 @@ serve(async (req: Request) => {
const reviewerInserts: Database["public"]["Tables"]["nonConformanceReviewer"]["Insert"][] =
[];
- nonConformance.data?.investigationTypeIds?.forEach(
- (investigationTypeId) => {
- if (!currentInvestigationTasks[investigationTypeId]) {
- investigationTaskInserts.push({
- nonConformanceId: id,
- investigationTypeId,
- companyId,
- createdBy: userId,
- });
- }
- }
- );
-
nonConformance.data?.requiredActionIds?.forEach((actionTypeId) => {
if (!currentActionTasks[actionTypeId]) {
actionTaskInserts.push({
@@ -352,12 +309,6 @@ serve(async (req: Request) => {
}
}
- if (investigationTaskInserts.length > 0) {
- await trx
- .insertInto("nonConformanceInvestigationTask")
- .values(investigationTaskInserts)
- .execute();
- }
if (actionTaskInserts.length > 0) {
await trx
.insertInto("nonConformanceActionTask")
@@ -371,12 +322,6 @@ serve(async (req: Request) => {
.execute();
}
- if (investigationTasksToDelete.length > 0) {
- await trx
- .deleteFrom("nonConformanceInvestigationTask")
- .where("id", "=", investigationTasksToDelete)
- .execute();
- }
if (actionTasksToDelete.length > 0) {
await trx
.deleteFrom("nonConformanceActionTask")
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index c34759b38b..da5052c211 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -14526,7 +14526,6 @@ export type Database = {
description: string | null
dueDate: string | null
id: string
- investigationTypeIds: string[] | null
locationId: string
name: string
nonConformanceId: string
@@ -14556,7 +14555,6 @@ export type Database = {
description?: string | null
dueDate?: string | null
id?: string
- investigationTypeIds?: string[] | null
locationId: string
name: string
nonConformanceId: string
@@ -14588,7 +14586,6 @@ export type Database = {
description?: string | null
dueDate?: string | null
id?: string
- investigationTypeIds?: string[] | null
locationId?: string
name?: string
nonConformanceId?: string
@@ -15545,385 +15542,6 @@ export type Database = {
},
]
}
- nonConformanceInvestigationTask: {
- Row: {
- assignee: string | null
- companyId: string
- completedDate: string | null
- createdAt: string
- createdBy: string
- dueDate: string | null
- id: string
- investigationTypeId: string | null
- nonConformanceId: string
- notes: Json
- sortOrder: number
- status: Database["public"]["Enums"]["nonConformanceTaskStatus"]
- supplierId: string | null
- tags: string[] | null
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- assignee?: string | null
- companyId: string
- completedDate?: string | null
- createdAt?: string
- createdBy: string
- dueDate?: string | null
- id?: string
- investigationTypeId?: string | null
- nonConformanceId: string
- notes?: Json
- sortOrder?: number
- status?: Database["public"]["Enums"]["nonConformanceTaskStatus"]
- supplierId?: string | null
- tags?: string[] | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- assignee?: string | null
- companyId?: string
- completedDate?: string | null
- createdAt?: string
- createdBy?: string
- dueDate?: string | null
- id?: string
- investigationTypeId?: string | null
- nonConformanceId?: string
- notes?: Json
- sortOrder?: number
- status?: Database["public"]["Enums"]["nonConformanceTaskStatus"]
- supplierId?: string | null
- tags?: string[] | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_investigationTypeId_fkey"
- columns: ["investigationTypeId"]
- isOneToOne: false
- referencedRelation: "nonConformanceInvestigationType"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_nonConformanceId_fkey"
- columns: ["nonConformanceId"]
- isOneToOne: false
- referencedRelation: "issues"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_nonConformanceId_fkey"
- columns: ["nonConformanceId"]
- isOneToOne: false
- referencedRelation: "nonConformance"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "contractors"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "partners"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "purchaseOrderSuppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "supplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "suppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationTask_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- nonConformanceInvestigationType: {
- Row: {
- active: boolean
- companyId: string
- createdAt: string
- createdBy: string
- id: string
- name: string
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- active?: boolean
- companyId: string
- createdAt?: string
- createdBy: string
- id?: string
- name: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- active?: boolean
- companyId?: string
- createdAt?: string
- createdBy?: string
- id?: string
- name?: string
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "nonConformanceInvestigationType_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "nonConformanceInvestigationType_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
nonConformanceItem: {
Row: {
companyId: string
@@ -17849,7 +17467,6 @@ export type Database = {
createdBy: string
description: string | null
id: string
- investigationTypeIds: string[] | null
name: string
priority: Database["public"]["Enums"]["nonConformancePriority"]
requiredActionIds: string[] | null
@@ -17869,7 +17486,6 @@ export type Database = {
createdBy: string
description?: string | null
id?: string
- investigationTypeIds?: string[] | null
name: string
priority?: Database["public"]["Enums"]["nonConformancePriority"]
requiredActionIds?: string[] | null
@@ -17889,7 +17505,6 @@ export type Database = {
createdBy?: string
description?: string | null
id?: string
- investigationTypeIds?: string[] | null
name?: string
priority?: Database["public"]["Enums"]["nonConformancePriority"]
requiredActionIds?: string[] | null
@@ -39587,7 +39202,6 @@ export type Database = {
description: string | null
dueDate: string | null
id: string | null
- investigationTypeIds: string[] | null
items: string[] | null
locationId: string | null
name: string | null
@@ -42192,14 +41806,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -43563,14 +43177,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -46625,14 +46239,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -50608,21 +50222,7 @@ export type Database = {
| "October"
| "November"
| "December"
- nonConformanceAction:
- | "Corrective Action"
- | "Preventive Action"
- | "Containment Action"
- | "Verification"
- | "Customer Communication"
nonConformanceApproval: "MRB"
- nonConformanceInvestigation:
- | "Root Cause Analysis"
- | "Inventory"
- | "WIP"
- | "Finished Goods"
- | "Incoming Materials"
- | "Process"
- | "Documentation"
nonConformancePriority: "Low" | "Medium" | "High" | "Critical"
nonConformanceSource: "Internal" | "External"
nonConformanceStatus: "Registered" | "In Progress" | "Closed"
@@ -51717,23 +51317,7 @@ export const Constants = {
"November",
"December",
],
- nonConformanceAction: [
- "Corrective Action",
- "Preventive Action",
- "Containment Action",
- "Verification",
- "Customer Communication",
- ],
nonConformanceApproval: ["MRB"],
- nonConformanceInvestigation: [
- "Root Cause Analysis",
- "Inventory",
- "WIP",
- "Finished Goods",
- "Incoming Materials",
- "Process",
- "Documentation",
- ],
nonConformancePriority: ["Low", "Medium", "High", "Critical"],
nonConformanceSource: ["Internal", "External"],
nonConformanceStatus: ["Registered", "In Progress", "Closed"],
diff --git a/packages/database/supabase/migrations/20251120214020_action-investigation-merge.sql b/packages/database/supabase/migrations/20251120214020_action-investigation-merge.sql
new file mode 100644
index 0000000000..80a4aebd43
--- /dev/null
+++ b/packages/database/supabase/migrations/20251120214020_action-investigation-merge.sql
@@ -0,0 +1,117 @@
+-- Migration: Merge nonConformanceInvestigationTask into nonConformanceActionTask
+-- and nonConformanceInvestigationType into nonConformanceRequiredAction
+
+-- Step 1: Migrate investigation types to nonConformanceRequiredAction
+-- Insert all investigation types into the required action table
+INSERT INTO "nonConformanceRequiredAction" (
+ "id",
+ "companyId",
+ "name",
+ "active",
+ "createdAt",
+ "createdBy",
+ "updatedAt",
+ "updatedBy"
+)
+SELECT
+ "id",
+ "companyId",
+ "name",
+ "active",
+ "createdAt",
+ "createdBy",
+ "updatedAt",
+ "updatedBy"
+FROM "nonConformanceInvestigationType"
+ON CONFLICT ("companyId", "name") DO NOTHING;
+
+-- Step 2: Migrate investigation tasks to nonConformanceActionTask
+-- Insert all investigation tasks into the action task table
+INSERT INTO "nonConformanceActionTask" (
+ "id",
+ "nonConformanceId",
+ "actionTypeId",
+ "status",
+ "dueDate",
+ "completedDate",
+ "assignee",
+ "notes",
+ "supplierId",
+ "sortOrder",
+ "tags",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ "updatedAt",
+ "updatedBy"
+)
+SELECT
+ "id",
+ "nonConformanceId",
+ "investigationTypeId" as "actionTypeId",
+ "status",
+ "dueDate",
+ "completedDate",
+ "assignee",
+ "notes",
+ "supplierId",
+ "sortOrder",
+ "tags",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ "updatedAt",
+ "updatedBy"
+FROM "nonConformanceInvestigationTask";
+
+-- Step 3: Merge investigationTypeIds into requiredActionIds for nonConformance table
+-- Combine both arrays, removing duplicates
+UPDATE "nonConformance"
+SET "requiredActionIds" = (
+ SELECT ARRAY(
+ SELECT DISTINCT unnest("requiredActionIds" || "investigationTypeIds")
+ )
+)
+WHERE "investigationTypeIds" IS NOT NULL
+ AND array_length("investigationTypeIds", 1) > 0;
+
+-- Step 4: Merge investigationTypeIds into requiredActionIds for nonConformanceWorkflow table
+-- Combine both arrays, removing duplicates
+UPDATE "nonConformanceWorkflow"
+SET "requiredActionIds" = (
+ SELECT ARRAY(
+ SELECT DISTINCT unnest("requiredActionIds" || "investigationTypeIds")
+ )
+)
+WHERE "investigationTypeIds" IS NOT NULL
+ AND array_length("investigationTypeIds", 1) > 0;
+
+-- Step 5: Drop the investigationTypeIds columns (CASCADE to drop dependent views)
+ALTER TABLE "nonConformance" DROP COLUMN IF EXISTS "investigationTypeIds" CASCADE;
+ALTER TABLE "nonConformanceWorkflow" DROP COLUMN IF EXISTS "investigationTypeIds" CASCADE;
+
+-- Step 6: Drop the trigger function for investigation types (no longer needed)
+DROP FUNCTION IF EXISTS remove_investigation_type_from_arrays();
+
+-- Step 7: Drop the old investigation task table
+DROP TABLE IF EXISTS "nonConformanceInvestigationTask";
+
+-- Step 8: Drop the old investigation type table
+DROP TABLE IF EXISTS "nonConformanceInvestigationType";
+
+-- Step 9: Drop any old enums if they still exist (they were deprecated in earlier migrations)
+DROP TYPE IF EXISTS "nonConformanceInvestigation";
+DROP TYPE IF EXISTS "nonConformanceAction";
+
+CREATE OR REPLACE VIEW "issues" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ ncr.*,
+ nci."items"
+ FROM "nonConformance" ncr
+ LEFT JOIN (
+ SELECT
+ "nonConformanceId",
+ array_agg("itemId"::text) as items
+ FROM "nonConformanceItem" nci
+ GROUP BY "nonConformanceId"
+ ) nci ON nci."nonConformanceId" = ncr."id";
\ No newline at end of file