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: add sort order to workflows and respect it in issues
Brad Barbin005d86d8922c
diff --git a/apps/erp/app/modules/quality/quality.models.ts b/apps/erp/app/modules/quality/quality.models.tsindex 4505ccfaa1..5db946b609 100644--- a/apps/erp/app/modules/quality/quality.models.ts+++ b/apps/erp/app/modules/quality/quality.models.ts@@ -194,7 +194,17 @@ export const issueWorkflowValidator = z.object({}),priority: z.enum(nonConformancePriority),source: z.enum(nonConformanceSource),- requiredActionIds: z.array(z.string()).optional(),+ requiredActionIds: z+ .string()+ .optional()+ .transform((val) => {+ if (!val) return [];+ try {+ return JSON.parse(val) as string[];+ } catch (e) {+ return [];+ }+ }),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 26dbb8848c..f539708b04 100644--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@ -13,7 +13,6 @@ import type {gaugeCalibrationStatus,gaugeTypeValidator,gaugeValidator,- investigationTypeValidator,issueTypeValidator,issueValidator,issueWorkflowValidator,@@ -22,7 +21,6 @@ import type {qualityDocumentStepValidator,qualityDocumentValidator,} from "./quality.models";-export async function activateGauge(client: SupabaseClient<Database>,gaugeId: stringdiff --git a/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsx b/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsxindex c520a5ba48..8f44d35a40 100644--- a/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsx@@ -13,9 +13,11 @@ import {ModalHeader,ModalOverlay,ModalTitle,+ useDebounce,VStack,} from "@carbon/react";import { useFetcher, useParams } from "@remix-run/react";+import { Reorder, useDragControls } from "framer-motion";import { useCallback, useEffect, useState } from "react";import { LuCirclePlus } from "react-icons/lu";import { useRouteData } from "~/hooks";@@ -24,6 +26,38 @@ import type { ListItem } from "~/types";import { path } from "~/utils/path";import { TaskItem, TaskProgress } from "./IssueTask";+function ReorderableTaskItem({+ taskId,+ task,+ suppliers,+ isDisabled,+}: {+ taskId: string;+ task: IssueActionTask;+ suppliers: { supplierId: string; externalLinkId: string | null }[];+ isDisabled: boolean;+}) {+ const dragControls = useDragControls();++ return (+ <Reorder.Item+ key={taskId}+ value={taskId}+ dragListener={false}+ dragControls={dragControls}+ >+ <TaskItem+ task={task}+ type="action"+ suppliers={suppliers}+ isDisabled={isDisabled}+ showDragHandle={true}+ dragControls={dragControls}+ />+ </Reorder.Item>+ );+}+export function ActionTasksList({tasks,suppliers,@@ -33,6 +67,49 @@ export function ActionTasksList({suppliers: { supplierId: string; externalLinkId: string | null }[];isDisabled: boolean;}) {+ const sortOrderFetcher = useFetcher<{}>();++ // Initialize sort order state based on existing tasks+ const [sortOrder, setSortOrder] = useState<string[]>(() =>+ [...tasks]+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))+ .map((task) => task.id)+ );++ // Update sort order when tasks change+ useEffect(() => {+ if (tasks && tasks.length > 0) {+ const sorted = [...tasks]+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))+ .map((task) => task.id);+ setSortOrder(sorted);+ }+ }, [tasks]);++ const onReorder = (newOrder: string[]) => {+ if (isDisabled) return;++ const updates: Record<string, number> = {};+ newOrder.forEach((id, index) => {+ updates[id] = index + 1;+ });+ setSortOrder(newOrder);+ updateSortOrder(updates);+ };++ const updateSortOrder = useDebounce(+ (updates: Record<string, number>) => {+ let formData = new FormData();+ formData.append("updates", JSON.stringify(updates));+ sortOrderFetcher.submit(formData, {+ method: "post",+ action: path.to.issueActionTasksOrder,+ });+ },+ 1000,+ true+ );+if (tasks.length === 0) return <NewAction isDisabled={isDisabled} />;return (@@ -44,19 +121,26 @@ export function ActionTasksList({<TaskProgress tasks={tasks} /></HStack><CardContent>- <VStack spacing={3}>- {tasks- .sort((a, b) => a.name?.localeCompare(b.name ?? "") ?? 0)- .map((task) => (- <TaskItem- key={task.id}+ <Reorder.Group+ axis="y"+ values={sortOrder}+ onReorder={onReorder}+ className="w-full space-y-3"+ >+ {sortOrder.map((taskId) => {+ const task = tasks.find((t) => t.id === taskId);+ if (!task) return null;+ return (+ <ReorderableTaskItem+ key={taskId}+ taskId={taskId}task={task}- type="action"suppliers={suppliers}isDisabled={isDisabled}/>- ))}- </VStack>+ );+ })}+ </Reorder.Group></CardContent></Card>);diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueForm.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueForm.tsxindex 43501847bf..df4fe9e061 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueForm.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueForm.tsx@@ -42,7 +42,6 @@ type IssueFormProps = {initialValues: IssueFormValues;nonConformanceWorkflows: IssueWorkflow[];nonConformanceTypes: ListItem[];- investigationTypes: ListItem[];requiredActions: ListItem[];};@@ -50,7 +49,6 @@ const IssueForm = ({initialValues,nonConformanceWorkflows,nonConformanceTypes,- investigationTypes,requiredActions,}: IssueFormProps) => {const permissions = usePermissions();@@ -59,13 +57,11 @@ const IssueForm = ({const [workflow, setWorkflow] = useState<{priority: string;source: string;- investigationTypeIds: string[];requiredActionIds: string[];approvalRequirements: string[];}>({priority: initialValues.priority,source: initialValues.source,- investigationTypeIds: initialValues.investigationTypeIds ?? [],requiredActionIds: initialValues.requiredActionIds ?? [],approvalRequirements: initialValues.approvalRequirements ?? [],});@@ -82,7 +78,6 @@ const IssueForm = ({setWorkflow({priority: selectedWorkflow.priority,source: selectedWorkflow.source,- investigationTypeIds: selectedWorkflow.investigationTypeIds ?? [],requiredActionIds: selectedWorkflow.requiredActionIds ?? [],approvalRequirements: selectedWorkflow.approvalRequirements ?? [],});@@ -157,21 +152,6 @@ const IssueForm = ({</div><VStack spacing={4}>- <MultiSelect- name="investigationTypeIds"- label="Investigation Types"- options={investigationTypes.map((type) => ({- label: type.name,- value: type.id,- }))}- value={workflow.investigationTypeIds}- onChange={(value) => {- setWorkflow({- ...workflow,- investigationTypeIds: value.map((v) => v.value),- });- }}- /><MultiSelectname="requiredActionIds"label="Required Actions"diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsxindex dc532292b3..772a9682da 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx@@ -31,6 +31,7 @@ import { formatDate } from "@carbon/utils";import { parseDate } from "@internationalized/date";import { useFetchers, useParams, useSubmit } from "@remix-run/react";import { nanoid } from "nanoid";+import type { DragControls } from "framer-motion";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {LuCalendar,@@ -39,6 +40,7 @@ import {LuCirclePlay,LuCog,LuContainer,+ LuGripVertical,LuLoaderCircle,} from "react-icons/lu";import { RxCheck } from "react-icons/rx";@@ -243,11 +245,15 @@ export function TaskItem({type,suppliers,isDisabled = false,+ showDragHandle = false,+ dragControls,}: {task: IssueInvestigationTask | IssueActionTask | IssueReviewer;type: "investigation" | "action" | "review";suppliers: { supplierId: string; externalLinkId: string | null }[];isDisabled?: boolean;+ showDragHandle?: boolean;+ dragControls?: DragControls;}) {const permissions = usePermissions();const disclosure = useDisclosure({@@ -277,20 +283,30 @@ export function TaskItem({? (task as IssueActionTask).name: (task as IssueReviewer).title;return (- <div className="rounded-lg border w-full flex flex-col">+ <div className="rounded-lg border w-full flex flex-col bg-card"><div className="flex w-full justify-between px-4 py-2 items-center">- <div className="flex flex-col">+ <div className="flex flex-col flex-1"><span className="text-base font-semibold tracking-tight">{taskTitle}</span></div>- <IconButton- icon={<LuChevronRight />}- variant="ghost"- onClick={disclosure.onToggle}- aria-label="Open task details"- className={cn(disclosure.isOpen && "rotate-90")}- />+ <div className="flex items-center gap-1">+ {showDragHandle && !isDisabled && dragControls && (+ <button+ className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground transition-colors p-1"+ onPointerDown={(e) => dragControls.start(e)}+ >+ <LuGripVertical size={16} />+ </button>+ )}+ <IconButton+ icon={<LuChevronRight />}+ variant="ghost"+ onClick={disclosure.onToggle}+ aria-label="Open task details"+ className={cn(disclosure.isOpen && "rotate-90")}+ />+ </div></div>{disclosure.isOpen && (diff --git a/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowForm.tsx b/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowForm.tsxindex 0b7ca4992f..18bbf79f6f 100644--- a/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowForm.tsx+++ b/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowForm.tsx@@ -5,6 +5,7 @@ import {Button,Card,CardContent,+ Checkbox,generateHTML,Heading,HStack,@@ -12,8 +13,10 @@ import {VStack,} from "@carbon/react";import { Editor } from "@carbon/react/Editor";+import { Reorder, useDragControls } from "framer-motion";import { nanoid } from "nanoid";-import { useState } from "react";+import { useEffect, useState } from "react";+import { LuGripVertical, LuX } from "react-icons/lu";import type { z } from "zod/v3";import { Hidden, Input, Submit } from "~/components/Form";import { usePermissions, useUser } from "~/hooks";@@ -29,14 +32,48 @@ import { getPriorityIcon } from "../Issue/IssueIcons";type IssueWorkflowFormProps = {initialValues: z.infer<typeof issueWorkflowValidator>;- investigationTypes: ListItem[];requiredActions: ListItem[];onClose: () => void;};+function ReorderableActionItem({+ action,+ onRemove,+}: {+ action: ListItem;+ onRemove: () => void;+}) {+ const dragControls = useDragControls();++ return (+ <Reorder.Item+ value={action.id}+ dragListener={false}+ dragControls={dragControls}+ className="w-full"+ >+ <div className="flex items-center gap-2 bg-card border rounded-lg px-3 py-2 w-full">+ <button+ className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground transition-colors p-1"+ onPointerDown={(e) => dragControls.start(e)}+ >+ <LuGripVertical size={16} />+ </button>+ <span className="flex-1 text-sm">{action.name}</span>+ <button+ type="button"+ onClick={onRemove}+ className="text-muted-foreground hover:text-destructive transition-colors p-1"+ >+ <LuX size={16} />+ </button>+ </div>+ </Reorder.Item>+ );+}+const IssueWorkflowForm = ({initialValues,- investigationTypes,requiredActions,onClose,}: IssueWorkflowFormProps) => {@@ -46,11 +83,45 @@ const IssueWorkflowForm = ({(JSON.parse(initialValues?.content ?? {}) as JSONContent) ?? {});+ // State for managing selected required actions in order+ const [selectedActionIds, setSelectedActionIds] = useState<string[]>(+ initialValues.requiredActionIds ?? []+ );++ // Update selectedActionIds when initialValues changes+ useEffect(() => {+ setSelectedActionIds(initialValues.requiredActionIds ?? []);+ }, [initialValues.requiredActionIds]);+const isEditing = initialValues.id !== undefined;const isDisabled = isEditing? !permissions.can("update", "quality"): !permissions.can("create", "quality");+ // Get the ordered list of selected actions+ const orderedActions = selectedActionIds+ .map((id) => requiredActions.find((action) => action.id === id))+ .filter((action): action is ListItem => action !== undefined);++ // Get available actions that haven't been selected yet+ const availableActions = requiredActions.filter(+ (action) => !selectedActionIds.includes(action.id)+ );++ const handleReorder = (newOrder: string[]) => {+ setSelectedActionIds(newOrder);+ };++ const handleAddAction = (actionId: string) => {+ if (!selectedActionIds.includes(actionId)) {+ setSelectedActionIds([...selectedActionIds, actionId]);+ }+ };++ const handleRemoveAction = (actionId: string) => {+ setSelectedActionIds(selectedActionIds.filter((id) => id !== actionId));+ };+const { carbon } = useCarbon();const {company: { id: companyId },@@ -88,6 +159,10 @@ const IssueWorkflowForm = ({><Hidden name="id" value={initialValues.id} /><Hidden name="content" value={JSON.stringify(content)} />+ <Hidden+ name="requiredActionIds"+ value={JSON.stringify(selectedActionIds)}+ /><VStackspacing={4}className="py-12 px-4 max-w-[50rem] h-full mx-auto gap-2"@@ -158,24 +233,62 @@ const IssueWorkflowForm = ({}))}/></div>- <MultiSelect- name="investigationTypeIds"- label="Investigation Types"- options={investigationTypes.map((type) => ({- label: type.name,- value: type.id,- }))}- value={initialValues.investigationTypeIds}- />+ <VStack spacing={2}>+ <label+ htmlFor="requiredActions"+ className="text-xs text-muted-foreground font-medium"+ >+ Required Actions (in order)+ </label>- <MultiSelect- name="requiredActionIds"- label="Required Actions"- options={requiredActions.map((action) => ({- label: action.name,- value: action.id,- }))}- />+ {orderedActions.length > 0 && (+ <Reorder.Group+ axis="y"+ values={selectedActionIds}+ onReorder={handleReorder}+ className="w-full space-y-2"+ >+ {orderedActions.map((action) => (+ <ReorderableActionItem+ key={action.id}+ action={action}+ onRemove={() => handleRemoveAction(action.id)}+ />+ ))}+ </Reorder.Group>+ )}++ {availableActions.length > 0 && (+ <VStack spacing={2} className="mt-2">+ <p className="text-xs text-muted-foreground">+ Available Actions (click to add):+ </p>+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">+ {availableActions.map((action) => (+ <button+ key={action.id}+ type="button"+ onClick={() => handleAddAction(action.id)}+ className="flex items-center gap-2 px-3 py-2 border border-dashed rounded-lg hover:bg-accent hover:text-accent-foreground transition-colors text-left text-sm"+ >+ <Checkbox+ onClick={(e) => e.preventDefault()}+ isChecked={false}+ readOnly+ />+ <span>{action.name}</span>+ </button>+ ))}+ </div>+ </VStack>+ )}++ {orderedActions.length === 0 && availableActions.length === 0 && (+ <p className="text-sm text-muted-foreground italic">+ No required actions available+ </p>+ )}+ </VStack><MultiSelectname="approvalRequirements"diff --git a/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsxindex 40da75dcd7..d06e7c7c29 100644--- a/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx@@ -3,11 +3,9 @@ import { IssuePDF } from "@carbon/documents/pdf";import { renderToStream } from "@react-pdf/renderer";import { type LoaderFunctionArgs } from "@vercel/remix";import {- getInvestigationTypesList,getIssue,getIssueActionTasks,getIssueApprovalTasks,- getIssueInvestigationTasks,getIssueItems,getIssueReviewers,getIssueTypes,@@ -28,22 +26,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {company,nonConformance,nonConformanceTypes,- investigationTasks,actionTasks,approvalTasks,reviewers,- investigationTypes,- actionTypes,+ requiredActions,items,] = await Promise.all([getCompany(client, companyId),getIssue(client, id),getIssueTypes(client, companyId),- getIssueInvestigationTasks(client, id, companyId),getIssueActionTasks(client, id, companyId),getIssueApprovalTasks(client, id, companyId),getIssueReviewers(client, id, companyId),- getInvestigationTypesList(client, companyId),getRequiredActionsList(client, companyId),getIssueItems(client, id, companyId),]);@@ -60,10 +54,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {console.error(nonConformanceTypes.error);}- if (investigationTasks.error) {- console.error(investigationTasks.error);- }-if (actionTasks.error) {console.error(actionTasks.error);}@@ -80,7 +70,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {company.error ||nonConformance.error ||nonConformanceTypes.error ||- investigationTasks.error ||actionTasks.error ||approvalTasks.error ||items.error@@ -96,10 +85,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {locale={locale}nonConformance={nonConformance.data}nonConformanceTypes={nonConformanceTypes.data ?? []}- investigationTasks={investigationTasks.data ?? []}- investigationTypes={investigationTypes.data ?? []}actionTasks={actionTasks.data ?? []}- actionTypes={actionTypes.data ?? []}+ requiredActions={requiredActions.data ?? []}reviewers={reviewers.data ?? []}items={items.data ?? []}/>diff --git a/apps/erp/app/routes/x+/issue+/action-tasks.order.tsx b/apps/erp/app/routes/x+/issue+/action-tasks.order.tsxnew file mode 100644index 0000000000..b6c95959f4--- /dev/null+++ b/apps/erp/app/routes/x+/issue+/action-tasks.order.tsx@@ -0,0 +1,45 @@+import { json, type ActionFunctionArgs } from "@vercel/remix";++import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "quality",+ });++ const updateMap = (await request.formData()).get("updates") as string;+ if (!updateMap) {+ return json(+ {},+ await flash(request, error(null, "Failed to receive a new sort order"))+ );+ }++ const updates = Object.entries(JSON.parse(updateMap)).map(+ ([id, sortOrderString]) => ({+ id,+ sortOrder: Number(sortOrderString),+ updatedBy: userId,+ })+ );++ const updatePromises = updates.map(({ id, sortOrder, updatedBy }) =>+ client+ .from("nonConformanceActionTask")+ .update({ sortOrder, updatedBy })+ .eq("id", id)+ );++ const results = await Promise.all(updatePromises);++ if (results.some((result) => result.error))+ return json(+ {},+ await flash(request, error(results, "Failed to update sort order"))+ );++ return null;+}diff --git a/apps/erp/app/routes/x+/issue+/new.tsx b/apps/erp/app/routes/x+/issue+/new.tsxindex 0db03b3c9e..a623ef34b6 100644--- a/apps/erp/app/routes/x+/issue+/new.tsx+++ b/apps/erp/app/routes/x+/issue+/new.tsx@@ -11,7 +11,6 @@ import { json, redirect } from "@vercel/remix";import { useUrlParams, useUser } from "~/hooks";import {deleteIssue,- getInvestigationTypesList,getIssueTypesList,getIssueWorkflowsList,getRequiredActionsList,@@ -36,18 +35,15 @@ export async function loader({ request }: LoaderFunctionArgs) {view: "quality",});- const [workflows, types, investigationTypes, requiredActions] =- await Promise.all([- getIssueWorkflowsList(client, companyId),- getIssueTypesList(client, companyId),- getInvestigationTypesList(client, companyId),- getRequiredActionsList(client, companyId),- ]);+ const [workflows, types, requiredActions] = await Promise.all([+ getIssueWorkflowsList(client, companyId),+ getIssueTypesList(client, companyId),+ getRequiredActionsList(client, companyId),+ ]);return json({workflows: workflows.data ?? [],types: types.data ?? [],- investigationTypes: investigationTypes.data ?? [],requiredActions: requiredActions.data ?? [],});}@@ -147,8 +143,7 @@ export async function action({ request }: ActionFunctionArgs) {}export default function IssueNewRoute() {- const { workflows, types, investigationTypes, requiredActions } =- useLoaderData<typeof loader>();+ const { workflows, types, requiredActions } = useLoaderData<typeof loader>();const { defaults } = useUser();const [params] = useUrlParams();@@ -170,7 +165,6 @@ export default function IssueNewRoute() {nonConformanceId: undefined,approvalRequirements: [],customerId: customerId ?? "",- investigationTypeIds: [],items: itemId ? [itemId] : [],jobId: jobId ?? "",jobOperationId: jobOperationId ?? "",@@ -201,7 +195,6 @@ export default function IssueNewRoute() {initialValues={initialValues}nonConformanceWorkflows={workflows}nonConformanceTypes={types}- investigationTypes={investigationTypes}requiredActions={requiredActions}/></div>diff --git a/apps/erp/app/routes/x+/issue-workflow+/$id.tsx b/apps/erp/app/routes/x+/issue-workflow+/$id.tsxindex c6b415149d..097f1aec48 100644--- a/apps/erp/app/routes/x+/issue-workflow+/$id.tsx+++ b/apps/erp/app/routes/x+/issue-workflow+/$id.tsx@@ -8,7 +8,6 @@ import { useLoaderData, useNavigate, useParams } from "@remix-run/react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";import { json, redirect } from "@vercel/remix";import {- getInvestigationTypesList,getIssueWorkflow,getRequiredActionsList,issueWorkflowValidator,@@ -34,9 +33,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { id } = params;if (!id) throw new Error("Could not find id");- const [workflow, investigationTypes, requiredActions] = await Promise.all([+ const [workflow, requiredActions] = await Promise.all([getIssueWorkflow(client, id),- getInvestigationTypesList(client, companyId),getRequiredActionsList(client, companyId),]);@@ -52,7 +50,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return json({workflow: workflow.data,- investigationTypes: investigationTypes.data ?? [],requiredActions: requiredActions.data ?? [],});}@@ -100,8 +97,7 @@ export default function IssueWorkflowRoute() {const { id } = useParams();if (!id) throw new Error("Could not find id");- const { workflow, investigationTypes, requiredActions } =- useLoaderData<typeof loader>();+ const { workflow, requiredActions } = useLoaderData<typeof loader>();const navigate = useNavigate();const onClose = () => {navigate(path.to.issueWorkflows);@@ -113,7 +109,6 @@ export default function IssueWorkflowRoute() {content: JSON.stringify(workflow?.content),priority: (workflow?.priority ?? "Medium") as "Medium",source: (workflow?.source ?? "Internal") as "Internal",- investigationTypeIds: workflow?.investigationTypeIds ?? [],requiredActionIds: workflow?.requiredActionIds ?? [],approvalRequirements: workflow?.approvalRequirements ?? [],};@@ -122,7 +117,6 @@ export default function IssueWorkflowRoute() {<ScrollArea className="w-full h-[calc(100dvh-49px)] bg-card"><IssueWorkflowForminitialValues={initialValues}- investigationTypes={investigationTypes}requiredActions={requiredActions}onClose={onClose}/>diff --git a/apps/erp/app/routes/x+/issue-workflow+/new.tsx b/apps/erp/app/routes/x+/issue-workflow+/new.tsxindex 0226cb96ba..16f684ba47 100644--- a/apps/erp/app/routes/x+/issue-workflow+/new.tsx+++ b/apps/erp/app/routes/x+/issue-workflow+/new.tsx@@ -8,7 +8,6 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";import { json, redirect } from "@vercel/remix";import { issueWorkflowValidator } from "~/modules/quality/quality.models";import {- getInvestigationTypesList,getRequiredActionsList,upsertIssueWorkflow,} from "~/modules/quality/quality.service";@@ -20,13 +19,9 @@ export async function loader({ request }: LoaderFunctionArgs) {create: "quality",});- const [investigationTypes, requiredActions] = await Promise.all([- getInvestigationTypesList(client, companyId),- getRequiredActionsList(client, companyId),- ]);+ const requiredActions = await getRequiredActionsList(client, companyId);return json({- investigationTypes: investigationTypes.data ?? [],requiredActions: requiredActions.data ?? [],});}@@ -68,15 +63,13 @@ export async function action({ request }: ActionFunctionArgs) {}export default function NewIssueWorkflowRoute() {- const { investigationTypes, requiredActions } =- useLoaderData<typeof loader>();+ const { requiredActions } = useLoaderData<typeof loader>();const navigate = useNavigate();const initialValues = {name: "",content: "{}",priority: "Medium" as const,source: "Internal" as const,- investigationTypeIds: [],requiredActionIds: [],approvalRequirements: [],};@@ -85,7 +78,6 @@ export default function NewIssueWorkflowRoute() {<ScrollArea className="w-full h-[calc(100dvh-49px)] bg-card"><IssueWorkflowForminitialValues={initialValues}- investigationTypes={investigationTypes}requiredActions={requiredActions}onClose={() => navigate(-1)}/>diff --git a/apps/erp/app/routes/x+/quality+/investigation-types.$id.tsx b/apps/erp/app/routes/x+/quality+/investigation-types.$id.tsxdeleted file mode 100644index f1ed5c9026..0000000000--- a/apps/erp/app/routes/x+/quality+/investigation-types.$id.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { assertIsPost, error, success } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { validator } from "@carbon/form";-import { useLoaderData, useNavigate } from "@remix-run/react";--import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";-import { json, redirect } from "@vercel/remix";-import {- getInvestigationType,- investigationTypeValidator,- upsertInvestigationType,-} from "~/modules/quality";-import { InvestigationTypeForm } from "~/modules/quality/ui/InvestigationTypes";--import { path } from "~/utils/path";--export async function loader({ request, params }: LoaderFunctionArgs) {- const { id } = params;- if (!id) throw new Error("Investigation type ID is required");-- const { client } = await requirePermissions(request, {- view: "quality",- role: "employee",- });-- const result = await getInvestigationType(client, id);- if (!result.data) {- return redirect(- path.to.investigationTypes,- await flash(request, error(result.error, "Investigation type not found"))- );- }-- return json({ investigationType: result.data });-}--export async function action({ request, params }: ActionFunctionArgs) {- assertIsPost(request);- const { id } = params;- if (!id) throw new Error("Investigation type ID is required");-- const { client, userId } = await requirePermissions(request, {- update: "quality",- });-- const formData = await request.formData();- const validation = await validator(investigationTypeValidator).validate(- formData- );-- if (validation.error) {- return json({ success: false, message: "Invalid form data" });- }-- const { name, active } = validation.data;-- const updateResult = await upsertInvestigationType(client, {- id,- name,- active: active ?? true,- updatedBy: userId,- });-- if (updateResult.error) {- return redirect(- path.to.investigationTypes,- await flash(- request,- error(updateResult.error, "Failed to update investigation type")- )- );- }-- return redirect(- path.to.investigationTypes,- await flash(request, success("Investigation type updated successfully"))- );-}--export default function EditInvestigationTypeRoute() {- const { investigationType } = useLoaderData<typeof loader>();- const navigate = useNavigate();- const onClose = () => navigate(path.to.investigationTypes);-- return (- <InvestigationTypeForm- type="modal"- initialValues={investigationType}- onClose={onClose}- />- );-}diff --git a/apps/erp/app/routes/x+/quality+/investigation-types.delete.$id.tsx b/apps/erp/app/routes/x+/quality+/investigation-types.delete.$id.tsxdeleted file mode 100644index 14ab3bc8ec..0000000000--- a/apps/erp/app/routes/x+/quality+/investigation-types.delete.$id.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { error, notFound, success } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import type { ActionFunctionArgs } from "@vercel/remix";-import { redirect } from "@vercel/remix";-import { deleteInvestigationType } from "~/modules/quality";-import { path } from "~/utils/path";--export async function action({ request, params }: ActionFunctionArgs) {- const { id } = params;- if (!id) throw notFound("Investigation type ID is required");-- const { client } = await requirePermissions(request, {- delete: "quality",- });-- const deleteResult = await deleteInvestigationType(client, id);-- if (deleteResult.error) {- return redirect(- path.to.investigationTypes,- await flash(- request,- error(deleteResult.error, "Failed to delete investigation type")- )- );- }-- return redirect(- path.to.investigationTypes,- await flash(request, success("Investigation type deleted successfully"))- );-}diff --git a/apps/erp/app/routes/x+/quality+/investigation-types.new.tsx b/apps/erp/app/routes/x+/quality+/investigation-types.new.tsxdeleted file mode 100644index 101df79cdd..0000000000--- a/apps/erp/app/routes/x+/quality+/investigation-types.new.tsx+++ /dev/null@@ -1,69 +0,0 @@-import { assertIsPost, error, success } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { validator } from "@carbon/form";-import { useNavigate } from "@remix-run/react";-import type { ActionFunctionArgs } from "@vercel/remix";-import { json, redirect } from "@vercel/remix";-import {- investigationTypeValidator,- upsertInvestigationType,-} from "~/modules/quality";-import { InvestigationTypeForm } from "~/modules/quality/ui/InvestigationTypes";-import { path } from "~/utils/path";--export async function action({ request }: ActionFunctionArgs) {- assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {- create: "quality",- });-- const formData = await request.formData();- const validation = await validator(investigationTypeValidator).validate(- formData- );-- if (validation.error) {- return json({ success: false, message: "Invalid form data" });- }-- const { name, active } = validation.data;-- const createResult = await upsertInvestigationType(client, {- name,- active: active ?? true,- companyId,- createdBy: userId,- });-- if (createResult.error) {- return redirect(- path.to.investigationTypes,- await flash(- request,- error(createResult.error, "Failed to create investigation type")- )- );- }-- return redirect(- path.to.investigationTypes,- await flash(request, success("Investigation type created successfully"))- );-}--export default function NewInvestigationTypeRoute() {- const navigate = useNavigate();- const onClose = () => navigate(path.to.investigationTypes);-- return (- <InvestigationTypeForm- type="modal"- initialValues={{- name: "",- active: true,- }}- onClose={onClose}- />- );-}diff --git a/apps/erp/app/routes/x+/quality+/investigation-types.tsx b/apps/erp/app/routes/x+/quality+/investigation-types.tsxdeleted file mode 100644index 7997a33770..0000000000--- a/apps/erp/app/routes/x+/quality+/investigation-types.tsx+++ /dev/null@@ -1,49 +0,0 @@-import { requirePermissions } from "@carbon/auth/auth.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 { getInvestigationTypes } from "~/modules/quality";-import InvestigationTypesTable from "~/modules/quality/ui/InvestigationTypes/InvestigationTypesTable";-import type { Handle } from "~/utils/handle";-import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--export const handle: Handle = {- breadcrumb: "Investigation Types",- to: path.to.investigationTypes,-};--export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee",- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return json(- await getInvestigationTypes(client, companyId, {- search,- limit,- offset,- sorts,- filters,- })- );-}--export default function InvestigationTypesRoute() {- const { data, count } = useLoaderData<typeof loader>();-- return (- <VStack spacing={0} className="h-full">- <InvestigationTypesTable data={data ?? []} count={count ?? 0} />- <Outlet />- </VStack>- );-}\ No newline at end of filediff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex d699bbcd49..ff842d6c61 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -365,6 +365,7 @@ export const path = {bulkUpdateJob: `${x}/job/update`,bulkUpdateIssue: `${x}/issue/update`,updateIssueItem: `${x}/issue/item/update`,+ issueActionTasksOrder: `${x}/issue/action-tasks/order`,bulkUpdateIssueWorkflow: `${x}/issue-workflow/update`,bulkUpdatePurchaseOrder: `${x}/purchase-order/update`,bulkUpdatePurchaseInvoice: `${x}/purchase-invoice/update`,diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.tsindex 1cb11645d9..97c68e9427 100644--- a/packages/database/supabase/functions/create/index.ts+++ b/packages/database/supabase/functions/create/index.ts@@ -212,16 +212,19 @@ serve(async (req: Request) => {const reviewerInserts: Database["public"]["Tables"]["nonConformanceReviewer"]["Insert"][] =[];- nonConformance.data?.requiredActionIds?.forEach((actionTypeId) => {- if (!currentActionTasks[actionTypeId]) {- actionTaskInserts.push({- nonConformanceId: id,- actionTypeId,- companyId,- createdBy: userId,- });+ nonConformance.data?.requiredActionIds?.forEach(+ (actionTypeId, index) => {+ if (!currentActionTasks[actionTypeId]) {+ actionTaskInserts.push({+ nonConformanceId: id,+ actionTypeId,+ sortOrder: index + 1,+ companyId,+ createdBy: userId,+ });+ }}- });+ );nonConformance.data?.approvalRequirements?.forEach((approvalType) => {if (!currentApprovalTasks[approvalType]) {diff --git a/packages/documents/src/pdf/IssuePDF.tsx b/packages/documents/src/pdf/IssuePDF.tsxindex 160f605fd5..378d83c6d6 100644--- a/packages/documents/src/pdf/IssuePDF.tsx+++ b/packages/documents/src/pdf/IssuePDF.tsx@@ -15,11 +15,6 @@ type IssueItem = Database["public"]["Tables"]["nonConformanceItem"]["Row"] & {name: string | null;};-type InvestigationTask =- Database["public"]["Tables"]["nonConformanceInvestigationTask"]["Row"] & {- supplier: { name: string } | null;- };-type ActionTask =Database["public"]["Tables"]["nonConformanceActionTask"]["Row"] & {supplier: { name: string } | null;@@ -28,10 +23,8 @@ type ActionTask =interface IssuePDFProps extends PDF {nonConformance: Database["public"]["Tables"]["nonConformance"]["Row"];nonConformanceTypes: Database["public"]["Tables"]["nonConformanceType"]["Row"][];- investigationTasks: InvestigationTask[];- investigationTypes: ListItem[];actionTasks: ActionTask[];- actionTypes: ListItem[];+ requiredActions: ListItem[];reviewers: Database["public"]["Tables"]["nonConformanceReviewer"]["Row"][];items: IssueItem[];}@@ -58,14 +51,16 @@ const IssuePDF = ({meta,nonConformance,nonConformanceTypes,- investigationTasks,- investigationTypes,actionTasks,- actionTypes,+ requiredActions,reviewers,items,title = "Issue Report",}: IssuePDFProps) => {+ // Sort action tasks by sortOrder+ const sortedActionTasks = [...actionTasks].sort(+ (a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)+ );return (<Templatetitle={title}@@ -141,9 +136,10 @@ const IssuePDF = ({))}</View>)}- {investigationTasks.length > 0 && (+ {sortedActionTasks.length > 0 && (<View style={tw("mb-10")} wrap={false}>- {investigationTasks.map((task) => (+ <Text style={tw("font-bold mb-2")}>Actions</Text>+ {sortedActionTasks.map((task) => (<Viewkey={task.id}style={tw("flex flex-col gap-2 border-b border-gray-300 mb-10")}@@ -151,8 +147,8 @@ const IssuePDF = ({<View style={tw("flex flex-row justify-between")}><Text style={tw("font-bold")}>{- investigationTypes.find(- (type) => type.id === task.investigationTypeId+ requiredActions.find(+ (action) => action.id === task.actionTypeId)?.name}</Text>@@ -175,39 +171,6 @@ const IssuePDF = ({</View>)}- {actionTasks.length > 0 && (- <View style={tw("mb-10")} wrap={false}>- {actionTasks.map((task) => (- <View- key={task.id}- style={tw("flex flex-col gap-2 border-b border-gray-300 mb-10")}- >- <View style={tw("flex flex-row justify-between")}>- <Text style={tw("font-bold")}>- {- actionTypes.find((type) => type.id === task.actionTypeId)- ?.name- }- </Text>- </View>- {task.supplier?.name && (- <View style={tw("flex flex-row items-center gap-2")}>- <Badge>{task.supplier.name}</Badge>- </View>- )}- {task.completedDate && (- <Text style={tw("text-sm")}>- Completed: {task.completedDate}- </Text>- )}- {Object.keys(task.notes ?? {}).length > 0 && (- <Note content={task.notes as JSONContent} />- )}- </View>- ))}- </View>- )}-{reviewers.length > 0 && (<View style={tw("mb-5")} wrap={false}><Text style={tw("font-bold mb-2")}>Reviewers</Text>