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.

feat: add procedure to bill of process

Brad Barbin62376bc5a638
diff --git a/apps/erp/app/components/DirectionAwareTabs.tsx b/apps/erp/app/components/DirectionAwareTabs.tsx
index f235778504..eade6aacc9 100644
--- a/apps/erp/app/components/DirectionAwareTabs.tsx
+++ b/apps/erp/app/components/DirectionAwareTabs.tsx
@@ -74,11 +74,11 @@ function DirectionAwareTabs({
filter: "blur(0px)",
}}
transition={{ duration: 0.2, delay: 0.3 }}
- className=" flex flex-col items-center w-full"
+ className="flex flex-col items-center w-full"
>
<div
className={cn(
- "flex space-x-1 rounded-lg cursor-pointer bg-muted px-[3px] py-[3.2px] shadow-inner-shadow",
+ "flex flex-wrap gap-1 rounded-lg cursor-pointer bg-muted p-1 shadow-inner-shadow w-auto",
className,
rounded
)}
@@ -89,7 +89,7 @@ function DirectionAwareTabs({
disabled={tab.disabled}
onClick={() => handleTabClick(tab.id)}
className={cn(
- "relative rounded-md px-3.5 py-1.5 text-xs sm:text-sm font-medium text-foreground/80 transition focus-visible:outline-1 focus-visible:ring-2 ring-ring ring-offset-ring focus-visible:outline-none flex gap-2 items-center ",
+ "relative rounded-md px-3.5 py-1.5 text-sm font-medium text-foreground/80 transition focus-visible:outline-1 focus-visible:ring-2 ring-ring ring-offset-ring focus-visible:outline-none flex gap-2 items-center justify-center flex-initial",
activeTab === tab.id
? "text-foreground"
: "hover:text-foreground/60 text-foreground/80",
@@ -105,7 +105,7 @@ function DirectionAwareTabs({
transition={{ type: "spring", bounce: 0, duration: 0.4 }}
/>
)}
- <span className="z-20">{tab.label}</span>
+ <span className="z-20 text-center">{tab.label}</span>
</button>
))}
</div>
diff --git a/apps/erp/app/components/Form/Procedure.tsx b/apps/erp/app/components/Form/Procedure.tsx
new file mode 100644
index 0000000000..6911dd36f4
--- /dev/null
+++ b/apps/erp/app/components/Form/Procedure.tsx
@@ -0,0 +1,76 @@
+import type { ComboboxProps } from "@carbon/form";
+import { Combobox } from "@carbon/form";
+import { HStack, useMount } from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useMemo } from "react";
+import { getProceduresList } from "~/modules/production/production.service";
+import ProcedureStatus from "~/modules/production/ui/Procedures/ProcedureStatus";
+import { path } from "~/utils/path";
+
+type ProcedureSelectProps = Omit<ComboboxProps, "options"> & {
+ processId?: string;
+ isConfigured?: boolean;
+ onConfigure?: () => void;
+};
+
+const Procedure = (props: ProcedureSelectProps) => {
+ const options = useProcedures({
+ processId: props?.processId,
+ });
+
+ return (
+ <>
+ <Combobox
+ options={options}
+ isOptional={props?.isOptional ?? true}
+ {...props}
+ label={props?.label ?? "Procedure"}
+ />
+ </>
+ );
+};
+
+Procedure.displayName = "Procedure";
+
+export default Procedure;
+
+export const useProcedures = (args: { processId?: string }) => {
+ const { processId } = args;
+ const procedureFetcher =
+ useFetcher<Awaited<ReturnType<typeof getProceduresList>>>();
+
+ useMount(() => {
+ procedureFetcher.load(path.to.api.procedures);
+ });
+
+ const options = useMemo(
+ () =>
+ procedureFetcher.data?.data
+ ? procedureFetcher.data?.data
+ .filter((f) => {
+ if (processId) {
+ return f.processId === processId;
+ }
+
+ return true;
+ })
+ .map((c) => ({
+ value: c.id!,
+ label: (
+ <div className="flex justify-between items-center gap-1 w-full">
+ <HStack className="items-end">
+ <span className="text-sm truncate">{c.name} </span>
+ <span className="text-xs text-muted-foreground">
+ v{c.version}
+ </span>
+ </HStack>
+ <ProcedureStatus status={c.status} />
+ </div>
+ ),
+ }))
+ : [],
+ [procedureFetcher.data, processId]
+ );
+
+ return options;
+};
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index 9c39349d01..fecb910336 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -282,6 +282,7 @@ export const methodOperationValidator = z
}),
processId: z.string().min(20, { message: "Process is required" }),
workCenterId: zfd.text(z.string().optional()),
+ procedureId: zfd.text(z.string().optional()),
description: zfd.text(
z.string().min(0, { message: "Description is required" })
),
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
index 12a9bcbaab..91e7ac09a8 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -42,7 +42,7 @@ import type { Dispatch, SetStateAction } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import {
LuActivity,
- LuChevronDown,
+ LuChevronRight,
LuCirclePlus,
LuEllipsisVertical,
LuHammer,
@@ -54,6 +54,7 @@ import {
LuSquareFunction,
LuTriangleAlert,
LuX,
+ LuWaypoints,
} from "react-icons/lu";
import { z } from "zod";
import { DirectionAwareTabs, EmployeeAvatar, TimeTypeIcon } from "~/components";
@@ -113,6 +114,7 @@ import { methodOperationValidator } from "../../items.models";
import type { ConfigurationParameter, ConfigurationRule } from "../../types";
import { ProcedureAttributeTypeIcon } from "~/components/Icons";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
+import Procedure from "~/components/Form/Procedure";
type Operation = z.infer<typeof methodOperationValidator> & {
workInstruction: JSONContent | null;
@@ -161,6 +163,7 @@ const initialOperation: Omit<Operation, "makeMethodId" | "order" | "tools"> = {
operationOrder: "After Previous",
operationType: "Inside",
processId: "",
+ procedureId: "",
setupTime: 0,
setupUnit: "Total Minutes",
tags: [],
@@ -415,6 +418,8 @@ const BillOfProcess = ({
initialOperations.find((o) => o.id === item.id)
?.methodOperationAttribute ?? [];
+ const hasProcedure = !!item.data.procedureId;
+
const tabs = [
{
id: 0,
@@ -447,7 +452,24 @@ const BillOfProcess = ({
},
{
id: 1,
- label: "Instructions",
+ label: (
+ <span className="flex items-center gap-2">
+ Instructions
+ {hasProcedure && (
+ <Tooltip>
+ <TooltipTrigger>
+ <Badge variant="gray">
+ <LuWaypoints />
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="opacity-100">
+ <p>Instructions are inherited from the procedure.</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </span>
+ ),
+ disabled: hasProcedure,
content: (
<div className="flex flex-col">
<div>
@@ -483,10 +505,25 @@ const BillOfProcess = ({
},
{
id: 2,
+ disabled: hasProcedure,
label: (
<span className="flex items-center gap-2">
<span>Parameters</span>
- {parameters.length > 0 && <Count count={parameters.length} />}
+ {hasProcedure && (
+ <Tooltip>
+ <TooltipTrigger>
+ <Badge variant="gray">
+ <LuWaypoints />
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="opacity-100">
+ <p>Parameters are inherited from the procedure.</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {!hasProcedure && parameters.length > 0 && (
+ <Count count={parameters.length} />
+ )}
</span>
),
content: (
@@ -506,10 +543,25 @@ const BillOfProcess = ({
},
{
id: 3,
+ disabled: hasProcedure,
label: (
<span className="flex items-center gap-2">
<span>Attributes</span>
- {attributes.length > 0 && <Count count={attributes.length} />}
+ {hasProcedure && (
+ <Tooltip>
+ <TooltipTrigger>
+ <Badge variant="gray">
+ <LuWaypoints />
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="opacity-100">
+ <p>Attributes are inherited from the procedure.</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {!hasProcedure && attributes.length > 0 && (
+ <Count count={attributes.length} />
+ )}
</span>
),
content: (
@@ -815,9 +867,10 @@ function OperationForm({
setWorkInstructions,
]);
- const [showMachine, setShowMachine] = useState(false);
- const [showLabor, setShowLabor] = useState(false);
- const [showSetup, setShowSetup] = useState(false);
+ const machineDisclosure = useDisclosure();
+ const laborDisclosure = useDisclosure();
+ const setupDisclosure = useDisclosure();
+ const procedureDisclosure = useDisclosure();
const [processData, setProcessData] = useState<{
description: string;
@@ -830,6 +883,7 @@ function OperationForm({
operationType: string;
operationOrder: string;
processId: string;
+ procedureId: string;
workCenterId: string;
setupTime: number;
setupUnit: string;
@@ -845,6 +899,7 @@ function OperationForm({
operationOrder: item.data.operationOrder ?? "After Previous",
operationType: item.data.operationType ?? "Inside",
processId: item.data.processId ?? "",
+ procedureId: item.data.procedureId ?? "",
workCenterId: item.data.workCenterId ?? "",
setupTime: item.data.setupTime ?? 0,
setupUnit: item.data.setupUnit ?? "Total Minutes",
@@ -864,6 +919,7 @@ function OperationForm({
setProcessData((p) => ({
...p,
processId,
+ procedureId: "",
description: data?.name ?? "",
laborUnit: data?.defaultStandardFactor ?? "Hours/Piece",
laborUnitHint: getUnitHint(data?.defaultStandardFactor),
@@ -1082,12 +1138,13 @@ function OperationForm({
}
/>
</div>
+
{processData.operationType === "Inside" && (
<>
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowSetup(!showSetup)}
+ onClick={setupDisclosure.onToggle}
>
<HStack>
<TimeTypeIcon type="Setup" />
@@ -1101,23 +1158,25 @@ function OperationForm({
</Badge>
)}
<IconButton
- icon={<LuChevronDown />}
- aria-label={showSetup ? "Collapse Setup" : "Expand Setup"}
+ icon={<LuChevronRight />}
+ aria-label={
+ setupDisclosure.isOpen ? "Collapse Setup" : "Expand Setup"
+ }
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowSetup(!showSetup);
+ setupDisclosure.onToggle();
}}
className={`transition-transform ${
- showSetup ? "rotate-180" : ""
+ setupDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showSetup ? "" : "hidden"
+ setupDisclosure.isOpen ? "" : "hidden"
}`}
>
<UnitHint
@@ -1196,7 +1255,7 @@ function OperationForm({
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowLabor(!showLabor)}
+ onClick={laborDisclosure.onToggle}
>
<HStack>
<TimeTypeIcon type="Labor" />
@@ -1210,23 +1269,25 @@ function OperationForm({
</Badge>
)}
<IconButton
- icon={<LuChevronDown />}
- aria-label={showLabor ? "Collapse Labor" : "Expand Labor"}
+ icon={<LuChevronRight />}
+ aria-label={
+ laborDisclosure.isOpen ? "Collapse Labor" : "Expand Labor"
+ }
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowLabor(!showLabor);
+ laborDisclosure.onToggle();
}}
className={`transition-transform ${
- showLabor ? "rotate-180" : ""
+ laborDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showLabor ? "" : "hidden"
+ laborDisclosure.isOpen ? "" : "hidden"
}`}
>
<UnitHint
@@ -1304,7 +1365,7 @@ function OperationForm({
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowMachine(!showMachine)}
+ onClick={machineDisclosure.onToggle}
>
<HStack>
<TimeTypeIcon type="Machine" />
@@ -1318,25 +1379,27 @@ function OperationForm({
</Badge>
)}
<IconButton
- icon={<LuChevronDown />}
+ icon={<LuChevronRight />}
aria-label={
- showMachine ? "Collapse Machine" : "Expand Machine"
+ machineDisclosure.isOpen
+ ? "Collapse Machine"
+ : "Expand Machine"
}
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowMachine(!showMachine);
+ machineDisclosure.onToggle();
}}
className={`transition-transform ${
- showMachine ? "rotate-180" : ""
+ machineDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showMachine ? "" : "hidden"
+ machineDisclosure.isOpen ? "" : "hidden"
}`}
>
<UnitHint
@@ -1411,6 +1474,79 @@ function OperationForm({
/>
</div>
</div>
+
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={procedureDisclosure.onToggle}
+ >
+ <HStack>
+ <LuWaypoints />
+ <Label>Procedure</Label>
+ </HStack>
+ <HStack>
+ {processData.procedureId && (
+ <Badge variant="secondary">
+ <LuWaypoints className="h-3 w-3 mr-1" />
+ Procedure
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ procedureDisclosure.isOpen
+ ? "Collapse Procedure"
+ : "Expand Procedure"
+ }
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ procedureDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ procedureDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
+ procedureDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <Procedure
+ name="procedureId"
+ label="Procedure"
+ processId={processData.processId}
+ value={processData.procedureId}
+ isConfigured={rulesByField.has(key("procedureId"))}
+ onConfigure={
+ configurable && !isTemporaryId(item.id)
+ ? () => {
+ onConfigure({
+ label: "Procedure",
+ field: key("procedureId"),
+ code: rulesByField.get(key("procedureId"))?.code,
+ defaultValue: processData.procedureId,
+ returnType: {
+ type: "text",
+ helperText:
+ "the unique identifier for the procedure. you can get this from the URL when editing a procedure",
+ },
+ });
+ }
+ : undefined
+ }
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ procedureId: value?.value as string,
+ }));
+ }}
+ />
+ </div>
+ </div>
</>
)}
<motion.div
@@ -1848,7 +1984,7 @@ function AttributesListItem({
)}
</HStack>
{attribute.type === "Measurement" && (
- <span className="text-xs text-muted-foreground text-right">
+ <span className="text-xs text-muted-foreground">
{attribute.minValue !== null && attribute.maxValue !== null
? `Must be between ${attribute.minValue} and ${
attribute.maxValue
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 950414b4ff..ddc3d10a00 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -139,6 +139,7 @@ export const jobOperationValidator = z
}),
}),
processId: z.string().min(20, { message: "Process is required" }),
+ procedureId: zfd.text(z.string().optional()),
workCenterId: zfd.text(z.string().optional()),
description: zfd.text(
z.string().min(0, { message: "Description is required" })
@@ -415,6 +416,7 @@ export const procedureValidator = z.object({
version: zfd.numeric(z.number().min(0)),
processId: zfd.text(z.string().optional()),
content: zfd.text(z.string().optional()),
+ copyFromId: zfd.text(z.string().optional()),
});
export const procedureAttributeValidator = z
@@ -480,6 +482,11 @@ export const procedureParameterValidator = z.object({
value: z.string().min(1, { message: "Value is required" }),
});
+export const procedureSyncValidator = z.object({
+ operationId: z.string().min(1, { message: "Operation is required" }),
+ procedureId: z.string().min(1, { message: "Procedure is required" }),
+});
+
export const productionEventValidator = z
.object({
id: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index eacaff564b..4a7ee0eb40 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -24,6 +24,7 @@ import type {
scrapReasonValidator,
} from "./production.models";
import type { Job } from "./types";
+import { JSONContent } from "@carbon/react";
export async function deleteJob(
client: SupabaseClient<Database>,
@@ -440,7 +441,7 @@ export async function getJobOperationsByMethodId(
return client
.from("jobOperation")
.select(
- "*, jobOperationTool(*), jobOperationParameter(*), jobOperationAttribute(*)"
+ "*, jobOperationTool(*), jobOperationParameter(*), jobOperationAttribute(*, jobOperationAttributeRecord(*))"
)
.eq("jobMakeMethodId", jobMakeMethodId)
.order("order", { ascending: true });
@@ -516,6 +517,18 @@ export async function getProcedures(
return query;
}
+export async function getProceduresList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("procedure")
+ .select("*")
+ .eq("companyId", companyId)
+ .order("name", { ascending: true })
+ .order("version", { ascending: false });
+}
+
export async function getProductionEvent(
client: SupabaseClient<Database>,
id: string
@@ -965,6 +978,7 @@ export async function upsertJobOperation(
| (Omit<z.infer<typeof jobOperationValidator>, "id"> & {
id: string;
jobId: string;
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
@@ -977,11 +991,36 @@ export async function upsertJobOperation(
.select("id")
.single();
}
- return client
+ const operationInsert = await client
.from("jobOperation")
.insert([jobOperation])
.select("id")
.single();
+
+ if (operationInsert.error) {
+ return operationInsert;
+ }
+ const operationId = operationInsert.data?.id;
+ if (!operationId) return operationInsert;
+
+ if (jobOperation.procedureId) {
+ const { error } = await client.functions.invoke("get-method", {
+ body: {
+ type: "procedureToOperation",
+ sourceId: jobOperation.procedureId,
+ targetId: operationId,
+ companyId: jobOperation.companyId,
+ userId: jobOperation.createdBy,
+ },
+ });
+ if (error) {
+ return {
+ data: null,
+ error: { message: "Failed to get procedure" } as PostgrestError,
+ };
+ }
+ }
+ return operationInsert;
}
export async function upsertJobOperationAttribute(
@@ -1203,15 +1242,84 @@ export async function upsertProcedure(
updatedBy: string;
})
) {
- if ("id" in procedure) {
+ const { copyFromId, ...rest } = procedure;
+ if ("id" in rest) {
return client
.from("procedure")
- .update(sanitize(procedure))
- .eq("id", procedure.id)
+ .update(sanitize(rest))
+ .eq("id", rest.id)
.select("id")
.single();
}
- return client.from("procedure").insert([procedure]).select("id").single();
+
+ const insert = await client
+ .from("procedure")
+ .insert([rest])
+ .select("id")
+ .single();
+ if (insert.error) {
+ return insert;
+ }
+ if (copyFromId) {
+ const procedure = await client
+ .from("procedure")
+ .select("*, procedureAttribute(*), procedureParameter(*)")
+ .eq("id", copyFromId)
+ .single();
+
+ if (procedure.error) {
+ return procedure;
+ }
+
+ const attributes = procedure.data.procedureAttribute ?? [];
+ const parameters = procedure.data.procedureParameter ?? [];
+ const workInstruction = (procedure.data.content ?? {}) as JSONContent;
+
+ const [updateWorkInstructions, insertAttributes, insertParameters] =
+ await Promise.all([
+ client
+ .from("procedure")
+ .update({
+ content: workInstruction,
+ })
+ .eq("id", insert.data.id),
+ attributes.length > 0
+ ? client.from("procedureAttribute").insert(
+ attributes.map((attribute) => {
+ const { id, procedureId, ...rest } = attribute;
+ return {
+ ...rest,
+ procedureId: insert.data.id,
+ companyId: procedure.data.companyId!,
+ };
+ })
+ )
+ : Promise.resolve({ data: null, error: null }),
+ parameters.length > 0
+ ? client.from("procedureParameter").insert(
+ parameters.map((parameter) => {
+ const { id, procedureId, ...rest } = parameter;
+ return {
+ ...rest,
+ procedureId: insert.data.id,
+ companyId: procedure.data.companyId!,
+ };
+ })
+ )
+ : Promise.resolve({ data: null, error: null }),
+ ]);
+
+ if (updateWorkInstructions.error) {
+ return updateWorkInstructions;
+ }
+ if (insertAttributes.error) {
+ return insertAttributes;
+ }
+ if (insertParameters.error) {
+ return insertParameters;
+ }
+ }
+ return insert;
}
export async function upsertProcedureAttribute(
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index a9b6f56fe8..534f3dea2b 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -25,6 +25,12 @@ import {
Input as InputField,
Label,
Loading,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
ScrollArea,
ToggleGroup,
ToggleGroupItem,
@@ -36,6 +42,7 @@ import {
useDebounce,
useDisclosure,
useMount,
+ Checkbox,
} from "@carbon/react";
import { Editor, generateHTML } from "@carbon/react/Editor";
import {
@@ -53,18 +60,20 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { flushSync } from "react-dom";
import {
LuActivity,
- LuChevronDown,
+ LuChevronRight,
LuCirclePlus,
LuDollarSign,
LuEllipsisVertical,
LuHammer,
LuInfo,
- LuList,
LuMaximize2,
+ LuPaperclip,
LuMinimize2,
+ LuRefreshCcw,
LuSend,
LuSettings2,
LuTriangleAlert,
+ LuWaypoints,
LuX,
} from "react-icons/lu";
import { z } from "zod";
@@ -121,7 +130,10 @@ import type { action as newJobOperationToolAction } from "~/routes/x+/job+/metho
import { usePeople, useTools } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
-import { jobOperationValidator } from "../../production.models";
+import {
+ jobOperationValidator,
+ procedureSyncValidator,
+} from "../../production.models";
import { getProductionEventsPage } from "../../production.service";
import type { Job, JobOperation } from "../../types";
import UnitOfMeasure, {
@@ -129,6 +141,8 @@ import UnitOfMeasure, {
} from "~/components/Form/UnitOfMeasure";
import { JobOperationStatus } from "./JobOperationStatus";
import { ProcedureAttributeTypeIcon } from "~/components/Icons";
+import Procedure from "~/components/Form/Procedure";
+import { useNumberFormatter } from "@react-aria/i18n";
export type Operation = z.infer<typeof jobOperationValidator> & {
assignee: string | null;
@@ -141,13 +155,19 @@ type ItemWithData = Item & {
data: Operation;
};
+type JobOperationAttribute = OperationAttribute & {
+ jobOperationAttributeRecord?:
+ | Database["public"]["Tables"]["jobOperationAttributeRecord"]["Row"]
+ | null;
+};
+
type JobBillOfProcessProps = {
jobMakeMethodId: string;
locationId: string;
operations: (Operation & {
jobOperationTool: OperationTool[];
jobOperationParameter: OperationParameter[];
- jobOperationAttribute: OperationAttribute[];
+ jobOperationAttribute: JobOperationAttribute[];
})[];
tags: { name: string }[];
};
@@ -239,6 +259,7 @@ const initialOperation: Omit<
operationType: "Inside",
overheadRate: 0,
processId: "",
+ procedureId: "",
setupTime: 0,
setupUnit: "Total Minutes",
status: "Todo",
@@ -325,6 +346,7 @@ const JobBillOfProcess = ({
return acc;
}, {} as PendingWorkInstructions);
});
+
const [checkedState, setCheckedState] = useState<CheckedState>({});
const [orderState, setOrderState] = useState<OrderState>(() => {
return initialOperations.reduce((acc, op) => {
@@ -620,6 +642,19 @@ const JobBillOfProcess = ({
const [tabChangeRerender, setTabChangeRerender] = useState<number>(1);
+ useEffect(() => {
+ if (initialOperations) {
+ setWorkInstructions(
+ initialOperations.reduce((acc, operation) => {
+ if (operation.workInstruction && operation.id) {
+ acc[operation.id] = operation.workInstruction;
+ }
+ return acc;
+ }, {} as PendingWorkInstructions)
+ );
+ }
+ }, [initialOperations]);
+
const renderListItem = ({
item,
items,
@@ -707,7 +742,7 @@ const JobBillOfProcess = ({
id: 2,
label: (
<span className="flex items-center gap-2">
- <span>Parameters</span>
+ <span>Params</span>
{parameters.length > 0 && <Count count={parameters.length} />}
</span>
),
@@ -949,7 +984,7 @@ function AttributesForm({
}: {
operationId: string;
isDisabled: boolean;
- attributes: OperationAttribute[];
+ attributes: JobOperationAttribute[];
}) {
const fetcher = useFetcher<typeof newJobOperationParameterAction>();
const [type, setType] = useState<OperationAttribute["type"]>("Value");
@@ -1113,7 +1148,7 @@ function AttributesListItem({
typeOptions,
className,
}: {
- attribute: OperationAttribute;
+ attribute: JobOperationAttribute;
operationId: string;
typeOptions: { label: JSX.Element; value: string }[];
className?: string;
@@ -1286,7 +1321,7 @@ function AttributesListItem({
)}
</HStack>
{attribute.type === "Measurement" && (
- <span className="text-xs text-muted-foreground text-right">
+ <span className="text-xs text-muted-foreground">
{attribute.minValue !== null && attribute.maxValue !== null
? `Must be between ${attribute.minValue} and ${
attribute.maxValue
@@ -1309,22 +1344,9 @@ function AttributesListItem({
</span>
)}
</VStack>
-
- {attribute.type === "List" &&
- Array.isArray(attribute.listValues) && (
- <Tooltip>
- <TooltipTrigger>
- <LuList className="size-4 text-muted-foreground" />
- </TooltipTrigger>
- <TooltipContent>
- {attribute.listValues.map((value) => (
- <p key={value} className="text-foreground text-sm">
- {value}
- </p>
- ))}
- </TooltipContent>
- </Tooltip>
- )}
+ {attribute.jobOperationAttributeRecord && (
+ <PreviewAttributeRecord attribute={attribute} />
+ )}
</HStack>
</HStack>
<div className="flex items-center justify-end gap-2">
@@ -1375,6 +1397,88 @@ function AttributesListItem({
);
}
+function PreviewAttributeRecord({
+ attribute,
+}: {
+ attribute: JobOperationAttribute;
+}) {
+ const unitOfMeasures = useUnitOfMeasure();
+ const [employees] = usePeople();
+ const numberFormatter = useNumberFormatter();
+
+ if (!attribute.jobOperationAttributeRecord) return null;
+ return (
+ <div className="min-w-[200px] truncate text-right font-medium">
+ {attribute.type === "Checkbox" && (
+ <Checkbox
+ checked={attribute.jobOperationAttributeRecord.booleanValue ?? false}
+ />
+ )}
+ {attribute.type === "Value" && (
+ <p className="text-sm">{attribute.jobOperationAttributeRecord.value}</p>
+ )}
+ {attribute.type === "Measurement" &&
+ typeof attribute.jobOperationAttributeRecord?.numericValue ===
+ "number" && (
+ <p
+ className={cn(
+ "text-sm",
+ attribute.minValue !== null &&
+ attribute.minValue !== undefined &&
+ attribute.jobOperationAttributeRecord.numericValue <
+ attribute.minValue &&
+ "text-red-500",
+ attribute.maxValue !== null &&
+ attribute.maxValue !== undefined &&
+ attribute.jobOperationAttributeRecord.numericValue >
+ attribute.maxValue &&
+ "text-red-500"
+ )}
+ >
+ {numberFormatter.format(
+ attribute.jobOperationAttributeRecord.numericValue
+ )}{" "}
+ {
+ unitOfMeasures.find(
+ (u) => u.value === attribute.unitOfMeasureCode
+ )?.label
+ }
+ </p>
+ )}
+ {attribute.type === "Timestamp" && (
+ <p className="text-sm">
+ {formatDateTime(attribute.jobOperationAttributeRecord.value ?? "")}
+ </p>
+ )}
+ {attribute.type === "List" && (
+ <p className="text-sm">{attribute.jobOperationAttributeRecord.value}</p>
+ )}
+ {attribute.type === "Person" && (
+ <p className="text-sm">
+ {
+ employees.find(
+ (e) => e.id === attribute.jobOperationAttributeRecord?.userValue
+ )?.name
+ }
+ </p>
+ )}
+ {attribute.type === "File" &&
+ attribute.jobOperationAttributeRecord?.value && (
+ <div className="flex justify-end gap-2 text-sm">
+ <LuPaperclip className="size-4 text-muted-foreground" />
+ <a
+ href={getPrivateUrl(attribute.jobOperationAttributeRecord.value)}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ View File
+ </a>
+ </div>
+ )}
+ </div>
+ );
+}
+
function ParametersForm({
operationId,
isDisabled,
@@ -1533,9 +1637,7 @@ function ParametersListItem({
<VStack spacing={0}>
<span className="text-sm font-medium">{key}</span>
</VStack>
- <span className="text-base text-muted-foreground text-right">
- {value}
- </span>
+ <span className="text-base text-muted-foreground">{value}</span>
</HStack>
</HStack>
<div className="flex items-center justify-end gap-2">
@@ -1616,28 +1718,12 @@ function OperationForm({
// replace the temporary id with the actual id
if (fetcher.data && fetcher.data.id) {
if (isTemporaryId(item.id) && carbon && !addingWorkInstruction.current) {
- addingWorkInstruction.current = true;
- carbon
- .from("jobOperation")
- .update({
- workInstruction: workInstruction,
- createdAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", fetcher.data.id)
- .then(() => {
- setWorkInstructions((prev) => ({
- ...prev,
- [fetcher.data?.id!]: workInstruction,
- }));
- setSelectedItemId(null);
- // Clear temporary item after successful save
- setTemporaryItems((prev) => {
- const { [item.id]: _, ...rest } = prev;
- return rest;
- });
- addingWorkInstruction.current = false;
- });
+ setSelectedItemId(null);
+ // Clear temporary item after successful save
+ setTemporaryItems((prev) => {
+ const { [item.id]: _, ...rest } = prev;
+ return rest;
+ });
} else {
setSelectedItemId(null);
}
@@ -1654,10 +1740,13 @@ function OperationForm({
setTemporaryItems,
]);
- const [showMachine, setShowMachine] = useState(false);
- const [showLabor, setShowLabor] = useState(false);
- const [showSetup, setShowSetup] = useState(false);
- const [showCost, setShowCost] = useState(false);
+ const machineDisclosure = useDisclosure();
+ const laborDisclosure = useDisclosure();
+ const setupDisclosure = useDisclosure();
+ const costingDisclosure = useDisclosure();
+ const procedureDisclosure = useDisclosure();
+ const [procedureWasChanged, setProcedureWasChanged] = useState(false);
+ const procedureSyncDisclosure = useDisclosure();
const [processData, setProcessData] = useState<{
description: string;
@@ -1675,6 +1764,7 @@ function OperationForm({
operationUnitCost: number;
overheadRate: number;
processId: string;
+ procedureId: string;
setupTime: number;
setupUnit: string;
setupUnitHint: string;
@@ -1694,6 +1784,7 @@ function OperationForm({
operationUnitCost: item.data.operationUnitCost ?? 0,
overheadRate: item.data.overheadRate ?? 0,
processId: item.data.processId ?? "",
+ procedureId: item.data.procedureId ?? "",
setupTime: item.data.setupTime ?? 0,
setupUnit: item.data.setupUnit ?? "Total Minutes",
setupUnitHint: getUnitHint(item.data.setupUnit),
@@ -1719,6 +1810,7 @@ function OperationForm({
setProcessData((p) => ({
...p,
processId,
+ procedureId: "",
description: process.data?.name ?? "",
laborUnit: process.data?.defaultStandardFactor ?? "Hours/Piece",
laborUnitHint: getUnitHint(process.data?.defaultStandardFactor),
@@ -1961,7 +2053,7 @@ function OperationForm({
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowSetup(!showSetup)}
+ onClick={setupDisclosure.onToggle}
>
<HStack>
<TimeTypeIcon type="Setup" />
@@ -1975,23 +2067,25 @@ function OperationForm({
</Badge>
)}
<IconButton
- icon={<LuChevronDown />}
- aria-label={showSetup ? "Collapse Setup" : "Expand Setup"}
+ icon={<LuChevronRight />}
+ aria-label={
+ setupDisclosure.isOpen ? "Collapse Setup" : "Expand Setup"
+ }
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowSetup(!showSetup);
+ setupDisclosure.onToggle();
}}
className={`transition-transform ${
- showSetup ? "rotate-180" : ""
+ setupDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showSetup ? "" : "hidden"
+ setupDisclosure.isOpen ? "" : "hidden"
}`}
>
<UnitHint
@@ -2033,10 +2127,11 @@ function OperationForm({
/>
</div>
</div>
+
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowLabor(!showLabor)}
+ onClick={laborDisclosure.onToggle}
>
<HStack>
<TimeTypeIcon type="Labor" />
@@ -2050,23 +2145,25 @@ function OperationForm({
</Badge>
)}
<IconButton
- icon={<LuChevronDown />}
- aria-label={showLabor ? "Collapse Labor" : "Expand Labor"}
+ icon={<LuChevronRight />}
+ aria-label={
+ laborDisclosure.isOpen ? "Collapse Labor" : "Expand Labor"
+ }
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowLabor(!showLabor);
+ laborDisclosure.onToggle();
}}
className={`transition-transform ${
- showLabor ? "rotate-180" : ""
+ laborDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showLabor ? "" : "hidden"
+ laborDisclosure.isOpen ? "" : "hidden"
}`}
>
<UnitHint
@@ -2112,7 +2209,7 @@ function OperationForm({
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowMachine(!showMachine)}
+ onClick={machineDisclosure.onToggle}
>
<HStack>
<TimeTypeIcon type="Machine" />
@@ -2126,25 +2223,27 @@ function OperationForm({
</Badge>
)}
<IconButton
- icon={<LuChevronDown />}
+ icon={<LuChevronRight />}
aria-label={
- showMachine ? "Collapse Machine" : "Expand Machine"
+ machineDisclosure.isOpen
+ ? "Collapse Machine"
+ : "Expand Machine"
}
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowMachine(!showMachine);
+ machineDisclosure.onToggle();
}}
className={`transition-transform ${
- showMachine ? "rotate-180" : ""
+ machineDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showMachine ? "" : "hidden"
+ machineDisclosure.isOpen ? "" : "hidden"
}`}
>
<UnitHint
@@ -2190,7 +2289,7 @@ function OperationForm({
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowCost(!showCost)}
+ onClick={costingDisclosure.onToggle}
>
<HStack>
<LuDollarSign />
@@ -2198,23 +2297,27 @@ function OperationForm({
</HStack>
<HStack>
<IconButton
- icon={<LuChevronDown />}
- aria-label={showCost ? "Collapse Costing" : "Expand Costing"}
+ icon={<LuChevronRight />}
+ aria-label={
+ costingDisclosure.isOpen
+ ? "Collapse Costing"
+ : "Expand Costing"
+ }
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowCost(!showCost);
+ costingDisclosure.onToggle();
}}
className={`transition-transform ${
- showCost ? "rotate-180" : ""
+ costingDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showCost ? "" : "hidden"
+ costingDisclosure.isOpen ? "" : "hidden"
}`}
>
<NumberControlled
@@ -2267,6 +2370,90 @@ function OperationForm({
/>
</div>
</div>
+
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={procedureDisclosure.onToggle}
+ >
+ <HStack>
+ <LuWaypoints />
+ <Label>Procedure</Label>
+ </HStack>
+ <HStack>
+ {processData.procedureId && (
+ <Badge variant="secondary">
+ <LuWaypoints className="h-3 w-3 mr-1" />
+ Procedure
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ procedureDisclosure.isOpen
+ ? "Collapse Procedure"
+ : "Expand Procedure"
+ }
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ procedureDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ procedureDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
+ procedureDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <Procedure
+ name="procedureId"
+ label="Procedure"
+ processId={processData.processId}
+ value={processData.procedureId}
+ onChange={(value) => {
+ if (value && value.value !== item.data.procedureId) {
+ setProcedureWasChanged(true);
+ }
+ setProcessData((d) => ({
+ ...d,
+ procedureId: value?.value as string,
+ }));
+ }}
+ />
+ {!isTemporaryId(item.id) && processData.procedureId && (
+ <div className="flex flex-col gap-2 w-auto">
+ {procedureWasChanged && (
+ <span className="text-sm text-muted-foreground">
+ The procedure was changed, but not synced to the
+ operation.
+ </span>
+ )}
+ <div>
+ <Button
+ variant="secondary"
+ rightIcon={<LuRefreshCcw />}
+ onClick={procedureSyncDisclosure.onOpen}
+ >
+ Sync Procedure
+ </Button>
+ {procedureSyncDisclosure.isOpen && (
+ <ProcedureSyncModal
+ operationId={item.id}
+ procedureId={processData.procedureId}
+ onClose={procedureSyncDisclosure.onClose}
+ />
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
</>
)}
<motion.div
@@ -2287,6 +2474,75 @@ function OperationForm({
);
}
+function ProcedureSyncModal({
+ operationId,
+ procedureId,
+ onClose,
+}: {
+ operationId: string;
+ procedureId: string;
+ onClose: () => void;
+}) {
+ const fetcher = useFetcher<{ success: boolean }>();
+ useEffect(() => {
+ if (fetcher.data?.success) {
+ onClose();
+ }
+ }, [fetcher.data?.success, onClose]);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ validator={procedureSyncValidator}
+ action={path.to.jobOperationProcedureSync}
+ method="post"
+ fetcher={fetcher}
+ defaultValues={{
+ operationId,
+ procedureId,
+ }}
+ >
+ <ModalHeader>
+ <ModalTitle>Are you sure?</ModalTitle>
+ </ModalHeader>
+ <ModalBody className="py-4">
+ <Hidden name="operationId" />
+ <Hidden name="procedureId" />
+ <Alert variant="warning">
+ <LuTriangleAlert className="h-4 w-4" />
+ <AlertTitle>Potential Data Loss</AlertTitle>
+ <AlertDescription>
+ Syncing the procedure will update the operation with the new
+ work instructions, attributes, and parameters. Any attributes
+ that are not part of the procedure will be removed.
+ </AlertDescription>
+ </Alert>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Submit
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle"}
+ >
+ Sync
+ </Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
+
type ProductionEventActivityProps = {
item: Database["public"]["Tables"]["productionEvent"]["Row"];
};
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
index ea58dfdef0..bc31e6d1c4 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
@@ -298,7 +298,7 @@ const JobEstimatesVsActuals = ({
return (
<>
<Tr key={operation.id} className="border-b border-border">
- <Td className="border-r border-border min-w-[200px] px-2">
+ <Td className="border-r border-border px-2">
<HStack className="w-full justify-between ">
<span>{operation.description}</span>
<JobOperationStatus operation={operation} />
@@ -326,9 +326,11 @@ const JobEstimatesVsActuals = ({
actual.total > estimated.total && "text-red-500"
)}
>
- {percentFormatter.format(
- actual.total / estimated.total
- )}
+ {estimated.total
+ ? percentFormatter.format(
+ actual.total / estimated.total
+ )
+ : null}
</span>
</Td>
<Td className="px-2">
@@ -550,7 +552,7 @@ const JobEstimatesVsActuals = ({
return (
<>
<Tr key={material.id} className="border-b border-border">
- <Td className="border-r border-border min-w-[200px]">
+ <Td className="border-r border-border">
<HStack className="w-full justify-start">
<Tooltip>
<TooltipTrigger>
diff --git a/apps/erp/app/modules/production/ui/Procedures/ProcedureForm.tsx b/apps/erp/app/modules/production/ui/Procedures/ProcedureForm.tsx
index d274d94b7e..838bab399f 100644
--- a/apps/erp/app/modules/production/ui/Procedures/ProcedureForm.tsx
+++ b/apps/erp/app/modules/production/ui/Procedures/ProcedureForm.tsx
@@ -67,6 +67,7 @@ const ProcedureForm = ({
</ModalDrawerHeader>
<ModalDrawerBody>
<Hidden name="id" />
+ <Hidden name="copyFromId" />
{type === "copy" && (
<>
<Hidden name="name" />
diff --git a/apps/erp/app/modules/production/ui/Procedures/ProcedureHeader.tsx b/apps/erp/app/modules/production/ui/Procedures/ProcedureHeader.tsx
index 73662d10dd..1d4d755298 100644
--- a/apps/erp/app/modules/production/ui/Procedures/ProcedureHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Procedures/ProcedureHeader.tsx
@@ -124,6 +124,7 @@ const ProcedureHeader = () => {
version: (routeData?.procedure?.version ?? 0) + 1,
processId: routeData?.procedure?.processId ?? "",
content: JSON.stringify(routeData?.procedure?.content) ?? "",
+ copyFromId: routeData?.procedure?.id ?? "",
}}
open={newVersionDisclosure.isOpen}
onClose={newVersionDisclosure.onClose}
diff --git a/apps/erp/app/modules/production/ui/Procedures/ProcedureStatus.tsx b/apps/erp/app/modules/production/ui/Procedures/ProcedureStatus.tsx
index 38099acc90..5e94899b51 100644
--- a/apps/erp/app/modules/production/ui/Procedures/ProcedureStatus.tsx
+++ b/apps/erp/app/modules/production/ui/Procedures/ProcedureStatus.tsx
@@ -1,5 +1,6 @@
import { Status } from "@carbon/react";
import type { procedureStatus } from "../../production.models";
+import { LuLock } from "react-icons/lu";
type ProcedureStatusProps = {
status?: (typeof procedureStatus)[number] | null;
@@ -10,9 +11,19 @@ const ProcedureStatus = ({ status }: ProcedureStatusProps) => {
case "Draft":
return <Status color="gray">{status}</Status>;
case "Active":
- return <Status color="green">{status}</Status>;
+ return (
+ <Status color="green">
+ <LuLock className="size-3 mr-1" />
+ {status}
+ </Status>
+ );
case "Archived":
- return <Status color="red">{status}</Status>;
+ return (
+ <Status color="red">
+ <LuLock className="size-3 mr-1" />
+ {status}
+ </Status>
+ );
default:
return null;
}
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index 2cf500dd86..9e5a372aa9 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -313,6 +313,7 @@ export const quoteOperationValidator = z
}),
}),
processId: z.string().min(20, { message: "Process is required" }),
+ procedureId: zfd.text(z.string().optional()),
workCenterId: zfd.text(z.string().optional()),
description: zfd.text(
z.string().min(0, { message: "Description is required" })
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index 83f1be55ae..06f88bea07 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -41,7 +41,7 @@ import type { Dispatch, SetStateAction } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import {
LuActivity,
- LuChevronDown,
+ LuChevronRight,
LuCirclePlus,
LuDollarSign,
LuEllipsisVertical,
@@ -52,6 +52,7 @@ import {
LuMinimize2,
LuSettings2,
LuTriangleAlert,
+ LuWaypoints,
LuX,
} from "react-icons/lu";
import type { z } from "zod";
@@ -105,6 +106,7 @@ import UnitOfMeasure, {
useUnitOfMeasure,
} from "~/components/Form/UnitOfMeasure";
import { ProcedureAttributeTypeIcon } from "~/components/Icons";
+import Procedure from "~/components/Form/Procedure";
export type Operation = z.infer<typeof quoteOperationValidator> & {
workInstruction: JSONContent | null;
@@ -211,6 +213,7 @@ const initialOperation: Omit<
operationType: "Inside",
overheadRate: 0,
processId: "",
+ procedureId: "",
setupTime: 0,
setupUnit: "Total Minutes",
tags: [],
@@ -485,6 +488,8 @@ const QuoteBillOfProcess = ({
initialOperations.find((o) => o.id === item.id)
?.quoteOperationAttribute ?? [];
+ const hasProcedure = !!item.data.procedureId;
+
const tabs = [
{
id: 0,
@@ -515,7 +520,24 @@ const QuoteBillOfProcess = ({
},
{
id: 1,
- label: "Instructions",
+ disabled: hasProcedure,
+ label: (
+ <span className="flex items-center gap-2">
+ Instructions
+ {hasProcedure && (
+ <Tooltip>
+ <TooltipTrigger>
+ <Badge variant="gray">
+ <LuWaypoints />
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="opacity-100">
+ <p>Instructions are inherited from the procedure.</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </span>
+ ),
content: (
<div className="flex flex-col">
<div>
@@ -549,12 +571,28 @@ const QuoteBillOfProcess = ({
</div>
),
},
+
{
id: 2,
+ disabled: hasProcedure,
label: (
<span className="flex items-center gap-2">
<span>Parameters</span>
- {parameters.length > 0 && <Count count={parameters.length} />}
+ {hasProcedure && (
+ <Tooltip>
+ <TooltipTrigger>
+ <Badge variant="gray">
+ <LuWaypoints />
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="opacity-100">
+ <p>Parameters are inherited from the procedure.</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {!hasProcedure && parameters.length > 0 && (
+ <Count count={parameters.length} />
+ )}
</span>
),
content: (
@@ -571,10 +609,25 @@ const QuoteBillOfProcess = ({
},
{
id: 3,
+ disabled: hasProcedure,
label: (
<span className="flex items-center gap-2">
<span>Attributes</span>
- {attributes.length > 0 && <Count count={attributes.length} />}
+ {hasProcedure && (
+ <Tooltip>
+ <TooltipTrigger>
+ <Badge variant="gray">
+ <LuWaypoints />
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="opacity-100">
+ <p>Attributes are inherited from the procedure.</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {!hasProcedure && attributes.length > 0 && (
+ <Count count={attributes.length} />
+ )}
</span>
),
content: (
@@ -1102,7 +1155,7 @@ function AttributesListItem({
)}
</HStack>
{attribute.type === "Measurement" && (
- <span className="text-xs text-muted-foreground text-right">
+ <span className="text-xs text-muted-foreground">
{attribute.minValue !== null && attribute.maxValue !== null
? `Must be between ${attribute.minValue} and ${
attribute.maxValue
@@ -1467,10 +1520,11 @@ function OperationForm({
setWorkInstructions,
]);
- const [showMachine, setShowMachine] = useState(false);
- const [showLabor, setShowLabor] = useState(false);
- const [showSetup, setShowSetup] = useState(false);
- const [showCost, setShowCost] = useState(false);
+ const machineDisclosure = useDisclosure();
+ const laborDisclosure = useDisclosure();
+ const setupDisclosure = useDisclosure();
+ const costingDisclosure = useDisclosure();
+ const procedureDisclosure = useDisclosure();
const [processData, setProcessData] = useState<{
description: string;
@@ -1488,6 +1542,7 @@ function OperationForm({
operationUnitCost: number;
overheadRate: number;
processId: string;
+ procedureId: string;
setupTime: number;
setupUnit: string;
setupUnitHint: string;
@@ -1507,6 +1562,7 @@ function OperationForm({
operationUnitCost: item.data.operationUnitCost ?? 0,
overheadRate: item.data.overheadRate ?? 0,
processId: item.data.processId ?? "",
+ procedureId: item.data.procedureId ?? "",
setupTime: item.data.setupTime ?? 0,
setupUnit: item.data.setupUnit ?? "Total Minutes",
setupUnitHint: getUnitHint(item.data.setupUnit),
@@ -1532,6 +1588,7 @@ function OperationForm({
setProcessData((p) => ({
...p,
processId,
+ procedureId: "",
description: process.data?.name ?? "",
laborUnit: process.data?.defaultStandardFactor ?? "Hours/Piece",
laborUnitHint: getUnitHint(process.data?.defaultStandardFactor),
@@ -1772,7 +1829,7 @@ function OperationForm({
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowSetup(!showSetup)}
+ onClick={setupDisclosure.onToggle}
>
<HStack>
<TimeTypeIcon type="Setup" />
@@ -1786,23 +1843,25 @@ function OperationForm({
</Badge>
)}
<IconButton
- icon={<LuChevronDown />}
- aria-label={showSetup ? "Collapse Setup" : "Expand Setup"}
+ icon={<LuChevronRight />}
+ aria-label={
+ setupDisclosure.isOpen ? "Collapse Setup" : "Expand Setup"
+ }
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowSetup(!showSetup);
+ setupDisclosure.onToggle();
}}
className={`transition-transform ${
- showSetup ? "rotate-180" : ""
+ setupDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showSetup ? "" : "hidden"
+ setupDisclosure.isOpen ? "" : "hidden"
}`}
>
<UnitHint
@@ -1847,7 +1906,7 @@ function OperationForm({
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowLabor(!showLabor)}
+ onClick={laborDisclosure.onToggle}
>
<HStack>
<TimeTypeIcon type="Labor" />
@@ -1861,23 +1920,25 @@ function OperationForm({
</Badge>
)}
<IconButton
- icon={<LuChevronDown />}
- aria-label={showLabor ? "Collapse Labor" : "Expand Labor"}
+ icon={<LuChevronRight />}
+ aria-label={
+ laborDisclosure.isOpen ? "Collapse Labor" : "Expand Labor"
+ }
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowLabor(!showLabor);
+ laborDisclosure.onToggle();
}}
className={`transition-transform ${
- showLabor ? "rotate-180" : ""
+ laborDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showLabor ? "" : "hidden"
+ laborDisclosure.isOpen ? "" : "hidden"
}`}
>
<UnitHint
@@ -1923,7 +1984,7 @@ function OperationForm({
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowMachine(!showMachine)}
+ onClick={machineDisclosure.onToggle}
>
<HStack>
<TimeTypeIcon type="Machine" />
@@ -1937,25 +1998,27 @@ function OperationForm({
</Badge>
)}
<IconButton
- icon={<LuChevronDown />}
+ icon={<LuChevronRight />}
aria-label={
- showMachine ? "Collapse Machine" : "Expand Machine"
+ machineDisclosure.isOpen
+ ? "Collapse Machine"
+ : "Expand Machine"
}
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowMachine(!showMachine);
+ machineDisclosure.onToggle();
}}
className={`transition-transform ${
- showMachine ? "rotate-180" : ""
+ machineDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showMachine ? "" : "hidden"
+ machineDisclosure.isOpen ? "" : "hidden"
}`}
>
<UnitHint
@@ -2001,29 +2064,33 @@ function OperationForm({
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
- onClick={() => setShowCost(!showCost)}
+ onClick={costingDisclosure.onToggle}
>
<HStack>
<LuDollarSign />
<Label>Costing</Label>
</HStack>
<IconButton
- icon={<LuChevronDown />}
- aria-label={showCost ? "Collapse Costing" : "Expand Costing"}
+ icon={<LuChevronRight />}
+ aria-label={
+ costingDisclosure.isOpen
+ ? "Collapse Costing"
+ : "Expand Costing"
+ }
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
- setShowCost(!showCost);
+ costingDisclosure.onToggle();
}}
className={`transition-transform ${
- showCost ? "rotate-180" : ""
+ costingDisclosure.isOpen ? "rotate-90" : ""
}`}
/>
</HStack>
<div
className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- showCost ? "" : "hidden"
+ costingDisclosure.isOpen ? "" : "hidden"
}`}
>
<NumberControlled
@@ -2076,6 +2143,61 @@ function OperationForm({
/>
</div>
</div>
+
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={procedureDisclosure.onToggle}
+ >
+ <HStack>
+ <LuWaypoints />
+ <Label>Procedure</Label>
+ </HStack>
+ <HStack>
+ {processData.procedureId && (
+ <Badge variant="secondary">
+ <LuWaypoints className="h-3 w-3 mr-1" />
+ Procedure
+ </Badge>
+ )}
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ procedureDisclosure.isOpen
+ ? "Collapse Procedure"
+ : "Expand Procedure"
+ }
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ procedureDisclosure.onToggle();
+ }}
+ className={`transition-transform ${
+ procedureDisclosure.isOpen ? "rotate-90" : ""
+ }`}
+ />
+ </HStack>
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-1 pb-4 ${
+ procedureDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <Procedure
+ name="procedureId"
+ label="Procedure"
+ processId={processData.processId}
+ value={processData.procedureId}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ procedureId: value?.value as string,
+ }));
+ }}
+ />
+ </div>
+ </div>
</>
)}
<motion.div
diff --git a/apps/erp/app/routes/api+/production.procedures.ts b/apps/erp/app/routes/api+/production.procedures.ts
new file mode 100644
index 0000000000..6e09320e83
--- /dev/null
+++ b/apps/erp/app/routes/api+/production.procedures.ts
@@ -0,0 +1,12 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { getProceduresList } from "~/modules/production";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ return json(await getProceduresList(client, companyId));
+}
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.procedure.sync.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.procedure.sync.tsx
new file mode 100644
index 0000000000..e907cdeb00
--- /dev/null
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.procedure.sync.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { validator } from "@carbon/form";
+import { procedureSyncValidator } from "~/modules/production";
+import { flash } from "@carbon/auth/session.server";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "production",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(procedureSyncValidator).validate(formData);
+
+ if (validation.error) {
+ return json(
+ { success: false },
+ await flash(request, error(validation.error, "Invalid form data"))
+ );
+ }
+
+ const serviceRole = await getCarbonServiceRole();
+ const sync = await serviceRole.functions.invoke("get-method", {
+ body: {
+ type: "procedureToOperation",
+ sourceId: validation.data.procedureId,
+ targetId: validation.data.operationId,
+ companyId,
+ userId,
+ },
+ });
+
+ if (sync.error) {
+ return json(
+ { success: false },
+ await flash(request, error(sync.error, "Failed to sync procedure"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/procedure+/$id.tsx b/apps/erp/app/routes/x+/procedure+/$id.tsx
index 82eb38859c..37ecbeed71 100644
--- a/apps/erp/app/routes/x+/procedure+/$id.tsx
+++ b/apps/erp/app/routes/x+/procedure+/$id.tsx
@@ -52,21 +52,34 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function ProcedureRoute() {
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find id");
+
+ const { procedure } = useLoaderData<typeof loader>();
+
return (
- <PanelProvider>
+ <PanelProvider key={`${id}-${procedure.version}`}>
<div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">
<ProcedureHeader />
<div className="flex h-[calc(100dvh-99px)] overflow-hidden w-full">
<div className="flex flex-grow overflow-hidden">
<ResizablePanels
- explorer={<ProcedureExplorer />}
+ explorer={
+ <ProcedureExplorer
+ key={`explorer-${id}-${procedure.version}`}
+ />
+ }
content={
<div className="bg-background h-[calc(100dvh-99px)] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full">
<ProcedureEditor />
<Outlet />
</div>
}
- properties={<ProcedureProperties />}
+ properties={
+ <ProcedureProperties
+ key={`properties-${id}-${procedure.version}`}
+ />
+ }
/>
</div>
</div>
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 3761bc7eea..ada388be36 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -48,6 +48,7 @@ export const path = {
modelUpload: `${api}/model/upload`,
purchasingKpi: (key: string) =>
generatePath(`${api}/purchasing/kpi/${key}`),
+ procedures: `${api}/production/procedures`,
processes: `${api}/resources/processes`,
productionKpi: (key: string) =>
generatePath(`${api}/production/kpi/${key}`),
@@ -487,6 +488,7 @@ export const path = {
generatePath(`${x}/job/methods/operation/attribute/${id}`),
jobOperationParameter: (id: string) =>
generatePath(`${x}/job/methods/operation/parameter/${id}`),
+ jobOperationProcedureSync: `${x}/job/methods/operation/procedure/sync`,
jobOperationTool: (id: string) =>
generatePath(`${x}/job/methods/operation/tool/${id}`),
jobOperationStatus: `${x}/job/methods/operation/status`,
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 80d346c3a8..7c5e8ddf01 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -2386,13 +2386,6 @@ function IssueModal({
);
}
-const unitOfMeasures = [
- { label: "Ohms", value: "OHM" },
- { label: "Degrees (F)", value: "F" },
- { label: "Volts", value: "VOLT" },
- { label: "Hertz", value: "HZ" },
-];
-
function AttributesListItem({
attribute,
compact = false,
@@ -2435,22 +2428,10 @@ function AttributesListItem({
{type === "Measurement" && (
<span className="text-xs text-muted-foreground">
{minValue !== null && maxValue !== null
- ? `Must be between ${minValue} and ${maxValue} ${
- unitOfMeasures.find(
- (u) => u.value === unitOfMeasureCode
- )?.label
- }`
+ ? `Must be between ${minValue} and ${maxValue} ${unitOfMeasureCode}`
: minValue !== null
- ? `Must be > ${minValue} ${
- unitOfMeasures.find(
- (u) => u.value === unitOfMeasureCode
- )?.label
- }`
- : `Must be < ${maxValue} ${
- unitOfMeasures.find(
- (u) => u.value === unitOfMeasureCode
- )?.label
- }`}
+ ? `Must be > ${minValue} ${unitOfMeasureCode}`
+ : `Must be < ${maxValue} ${unitOfMeasureCode}`}
</span>
)}
</VStack>
@@ -2563,11 +2544,7 @@ function PreviewAttributeRecord({
{numberFormatter.format(
attribute.jobOperationAttributeRecord.numericValue
)}{" "}
- {
- unitOfMeasures.find(
- (u) => u.value === attribute.unitOfMeasureCode
- )?.label
- }
+ {attribute.unitOfMeasureCode}
</p>
)}
{attribute.type === "Timestamp" && (
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index f131d5fa1b..ee9e2d93a7 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -29517,6 +29517,7 @@ export type Database = {
order: number | null
overheadRate: number | null
priority: number | null
+ procedureId: string | null
processId: string | null
quantityComplete: number | null
quantityReworked: number | null
@@ -29657,6 +29658,20 @@ export type Database = {
referencedRelation: "jobMaterialWithMakeMethodId"
referencedColumns: ["jobMaterialMakeMethodId"]
},
+ {
+ foreignKeyName: "jobOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_processId_fkey"
columns: ["processId"]
@@ -30336,14 +30351,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -31640,14 +31655,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -32499,6 +32514,7 @@ export type Database = {
operationUnitCost: number | null
order: number | null
overheadRate: number | null
+ procedureId: string | null
processId: string | null
quoteId: string | null
quoteLineId: string | null
@@ -32589,6 +32605,20 @@ export type Database = {
referencedRelation: "supplierProcesses"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_processId_fkey"
columns: ["processId"]
@@ -33283,14 +33313,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index e0bc2f1215..cc9380043e 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -23,6 +23,7 @@ import {
traverseQuoteMethod,
} from "../lib/methods.ts";
import { importTypeScript } from "../lib/sandbox.ts";
+import { Transaction } from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -36,6 +37,7 @@ const payloadValidator = z.object({
"itemToQuoteMakeMethod",
"jobMakeMethodToItem",
"jobToItem",
+ "procedureToOperation",
"quoteLineToItem",
"quoteLineToJob",
"quoteMakeMethodToItem",
@@ -76,10 +78,19 @@ serve(async (req: Request) => {
switch (type) {
case "itemToItem": {
const [sourceMakeMethod, targetMakeMethod] = await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", sourceId).single(),
- client.from("makeMethod").select("*").eq("itemId", targetId).single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", sourceId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", targetId)
+ .eq("companyId", companyId)
+ .single(),
]);
-
if (sourceMakeMethod.error || targetMakeMethod.error) {
throw new Error("Failed to get make methods");
}
@@ -88,13 +99,15 @@ serve(async (req: Request) => {
client
.from("methodMaterial")
.select("*")
- .eq("makeMethodId", sourceMakeMethod.data.id),
+ .eq("makeMethodId", sourceMakeMethod.data.id)
+ .eq("companyId", companyId),
client
.from("methodOperation")
.select(
"*, methodOperationTool(*), methodOperationParameter(*), methodOperationAttribute(*)"
)
- .eq("makeMethodId", sourceMakeMethod.data.id),
+ .eq("makeMethodId", sourceMakeMethod.data.id)
+ .eq("companyId", companyId),
]);
if (sourceMaterials.error || sourceOperations.error) {
@@ -155,6 +168,7 @@ serve(async (req: Request) => {
methodOperationTool,
methodOperationParameter,
methodOperationAttribute,
+ procedureId,
} = operation;
const operationId = operationIds[index].id;
@@ -177,39 +191,41 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(methodOperationParameter) &&
- methodOperationParameter.length > 0
- ) {
- await trx
- .insertInto("methodOperationParameter")
- .values(
- methodOperationParameter.map((param) => ({
- operationId: operationId!,
- key: param.key,
- value: param.value,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ if (!procedureId) {
+ if (
+ Array.isArray(methodOperationParameter) &&
+ methodOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("methodOperationParameter")
+ .values(
+ methodOperationParameter.map((param) => ({
+ operationId: operationId!,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
- if (
- Array.isArray(methodOperationAttribute) &&
- methodOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("methodOperationAttribute")
- .values(
- methodOperationAttribute.map((attribute) => ({
- ...attribute,
- operationId: operationId!,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
+ if (
+ Array.isArray(methodOperationAttribute) &&
+ methodOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("methodOperationAttribute")
+ .values(
+ methodOperationAttribute.map((attribute) => ({
+ ...attribute,
+ operationId: operationId!,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
}
}
}
@@ -227,12 +243,18 @@ serve(async (req: Request) => {
const [makeMethod, jobMakeMethod, workCenters, supplierProcesses] =
await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("jobMakeMethod")
.select("*")
.eq("jobId", jobId)
.is("parentMaterialId", null)
+ .eq("companyId", companyId)
.single(),
client.from("workCenters").select("*").eq("companyId", companyId),
client
@@ -354,6 +376,7 @@ serve(async (req: Request) => {
for await (const op of relatedOperations?.data ?? []) {
const [
processId,
+ procedureId,
workCenterId,
description,
setupTime,
@@ -370,6 +393,11 @@ serve(async (req: Request) => {
field: "processId",
defaultValue: op.processId,
}),
+ getConfiguredValue({
+ id: op.id,
+ field: "procedureId",
+ defaultValue: op.procedureId,
+ }),
getConfiguredValue({
id: op.id,
field: "workCenterId",
@@ -426,6 +454,7 @@ serve(async (req: Request) => {
jobId,
jobMakeMethodId: parentJobMakeMethodId!,
processId,
+ procedureId,
workCenterId,
description,
setupTime,
@@ -495,6 +524,7 @@ serve(async (req: Request) => {
methodOperationTool,
methodOperationParameter,
methodOperationAttribute,
+ procedureId,
} = operation;
if (
@@ -515,57 +545,66 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(methodOperationParameter) &&
- methodOperationParameter.length > 0
- ) {
- const parameters = await Promise.all(
- methodOperationParameter.map(async (param) => ({
- operationId,
- key: param.key,
- value: await getConfiguredValue({
- id: operation.id,
- field: `parameter:${param.id}:value`,
- defaultValue: param.value,
- }),
- companyId,
- createdBy: userId,
- }))
- );
+ if (procedureId) {
+ await insertProcedureDataForJobOperation(trx, client, {
+ operationId,
+ procedureId,
+ companyId,
+ userId,
+ });
+ } else {
+ if (
+ Array.isArray(methodOperationParameter) &&
+ methodOperationParameter.length > 0
+ ) {
+ const parameters = await Promise.all(
+ methodOperationParameter.map(async (param) => ({
+ operationId,
+ key: param.key,
+ value: await getConfiguredValue({
+ id: operation.id,
+ field: `parameter:${param.id}:value`,
+ defaultValue: param.value,
+ }),
+ companyId,
+ createdBy: userId,
+ }))
+ );
- await trx
- .insertInto("jobOperationParameter")
- .values(parameters)
- .execute();
- }
+ await trx
+ .insertInto("jobOperationParameter")
+ .values(parameters)
+ .execute();
+ }
- if (
- Array.isArray(methodOperationAttribute) &&
- methodOperationAttribute.length > 0
- ) {
- const attributes = await Promise.all(
- methodOperationAttribute.map(async (attribute) => ({
- ...attribute,
- operationId,
- minValue: await getConfiguredValue({
- id: operation.id,
- field: `attribute:${attribute.id}:minValue`,
- defaultValue: attribute.minValue,
- }),
- maxValue: await getConfiguredValue({
- id: operation.id,
- field: `attribute:${attribute.id}:maxValue`,
- defaultValue: attribute.maxValue,
- }),
- companyId,
- createdBy: userId,
- }))
- );
+ if (
+ Array.isArray(methodOperationAttribute) &&
+ methodOperationAttribute.length > 0
+ ) {
+ const attributes = await Promise.all(
+ methodOperationAttribute.map(async (attribute) => ({
+ ...attribute,
+ operationId,
+ minValue: await getConfiguredValue({
+ id: operation.id,
+ field: `attribute:${attribute.id}:minValue`,
+ defaultValue: attribute.minValue,
+ }),
+ maxValue: await getConfiguredValue({
+ id: operation.id,
+ field: `attribute:${attribute.id}:maxValue`,
+ defaultValue: attribute.maxValue,
+ }),
+ companyId,
+ createdBy: userId,
+ }))
+ );
- await trx
- .insertInto("jobOperationAttribute")
- .values(attributes)
- .execute();
+ await trx
+ .insertInto("jobOperationAttribute")
+ .values(attributes)
+ .execute();
+ }
}
}
}
@@ -628,6 +667,7 @@ serve(async (req: Request) => {
.from("item")
.select("readableId, type, name, itemCost(unitCost)")
.eq("id", itemId)
+ .eq("companyId", companyId)
.single();
if (item.data) {
itemReadableId = item.data.readableId;
@@ -758,11 +798,17 @@ serve(async (req: Request) => {
const [makeMethod, jobMakeMethod, workCenters, supplierProcesses] =
await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("jobMakeMethod")
.select("*")
.eq("id", jobMakeMethodId)
+ .eq("companyId", companyId)
.single(),
client.from("workCenters").select("*").eq("companyId", companyId),
client
@@ -830,6 +876,7 @@ serve(async (req: Request) => {
jobId: jobMakeMethod.data?.jobId!,
jobMakeMethodId: parentJobMakeMethodId!,
processId: op.processId,
+ procedureId: op.procedureId,
workCenterId: op.workCenterId,
description: op.description,
setupTime: op.setupTime,
@@ -872,7 +919,9 @@ serve(async (req: Request) => {
methodOperationTool,
methodOperationParameter,
methodOperationAttribute,
+ procedureId,
} = operation;
+
if (
Array.isArray(methodOperationTool) &&
methodOperationTool.length > 0
@@ -891,39 +940,48 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(methodOperationParameter) &&
- methodOperationParameter.length > 0
- ) {
- await trx
- .insertInto("jobOperationParameter")
- .values(
- methodOperationParameter.map((param) => ({
- operationId,
- key: param.key,
- value: param.value,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ if (procedureId) {
+ await insertProcedureDataForJobOperation(trx, client, {
+ operationId,
+ procedureId,
+ companyId,
+ userId,
+ });
+ } else {
+ if (
+ Array.isArray(methodOperationParameter) &&
+ methodOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("jobOperationParameter")
+ .values(
+ methodOperationParameter.map((param) => ({
+ operationId,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
- if (
- Array.isArray(methodOperationAttribute) &&
- methodOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("jobOperationAttribute")
- .values(
- methodOperationAttribute.map((attribute) => ({
- ...attribute,
- operationId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
+ if (
+ Array.isArray(methodOperationAttribute) &&
+ methodOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("jobOperationAttribute")
+ .values(
+ methodOperationAttribute.map((attribute) => ({
+ ...attribute,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
}
}
}
@@ -1025,12 +1083,18 @@ serve(async (req: Request) => {
supplierProcesses,
configurationRules,
] = await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("quoteMakeMethod")
.select("*")
.eq("quoteLineId", quoteLineId)
.is("parentMaterialId", null)
+ .eq("companyId", companyId)
.single(),
client.from("workCenters").select("*").eq("companyId", companyId),
client.from("supplierProcess").select("*").eq("companyId", companyId),
@@ -1039,6 +1103,7 @@ serve(async (req: Request) => {
.from("configurationRule")
.select("field, code")
.eq("itemId", itemId)
+ .eq("companyId", companyId)
: Promise.resolve({ data: null, error: null }),
]);
@@ -1152,6 +1217,7 @@ serve(async (req: Request) => {
for await (const op of relatedOperations?.data ?? []) {
const [
processId,
+ procedureId,
workCenterId,
description,
setupTime,
@@ -1168,6 +1234,11 @@ serve(async (req: Request) => {
field: "processId",
defaultValue: op.processId,
}),
+ getConfiguredValue({
+ id: op.id,
+ field: "procedureId",
+ defaultValue: op.procedureId,
+ }),
getConfiguredValue({
id: op.id,
field: "workCenterId",
@@ -1225,6 +1296,7 @@ serve(async (req: Request) => {
quoteLineId,
quoteMakeMethodId: parentQuoteMakeMethodId!,
processId,
+ procedureId,
workCenterId,
description,
setupTime,
@@ -1299,6 +1371,7 @@ serve(async (req: Request) => {
methodOperationTool,
methodOperationParameter,
methodOperationAttribute,
+ procedureId,
} = operation;
if (
@@ -1319,57 +1392,59 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(methodOperationParameter) &&
- methodOperationParameter.length > 0
- ) {
- const parameters = await Promise.all(
- methodOperationParameter.map(async (param) => ({
- operationId,
- key: param.key,
- value: await getConfiguredValue({
- id: operation.id,
- field: `parameter:${param.id}:value`,
- defaultValue: param.value,
- }),
- companyId,
- createdBy: userId,
- }))
- );
+ if (!procedureId) {
+ if (
+ Array.isArray(methodOperationParameter) &&
+ methodOperationParameter.length > 0
+ ) {
+ const parameters = await Promise.all(
+ methodOperationParameter.map(async (param) => ({
+ operationId,
+ key: param.key,
+ value: await getConfiguredValue({
+ id: operation.id,
+ field: `parameter:${param.id}:value`,
+ defaultValue: param.value,
+ }),
+ companyId,
+ createdBy: userId,
+ }))
+ );
- await trx
- .insertInto("quoteOperationParameter")
- .values(parameters)
- .execute();
- }
+ await trx
+ .insertInto("quoteOperationParameter")
+ .values(parameters)
+ .execute();
+ }
- if (
- Array.isArray(methodOperationAttribute) &&
- methodOperationAttribute.length > 0
- ) {
- const attributes = await Promise.all(
- methodOperationAttribute.map(async (attribute) => ({
- ...attribute,
- operationId,
- minValue: await getConfiguredValue({
- id: operation.id,
- field: `attribute:${attribute.id}:minValue`,
- defaultValue: attribute.minValue,
- }),
- maxValue: await getConfiguredValue({
- id: operation.id,
- field: `attribute:${attribute.id}:maxValue`,
- defaultValue: attribute.maxValue,
- }),
- companyId,
- createdBy: userId,
- }))
- );
+ if (
+ Array.isArray(methodOperationAttribute) &&
+ methodOperationAttribute.length > 0
+ ) {
+ const attributes = await Promise.all(
+ methodOperationAttribute.map(async (attribute) => ({
+ ...attribute,
+ operationId,
+ minValue: await getConfiguredValue({
+ id: operation.id,
+ field: `attribute:${attribute.id}:minValue`,
+ defaultValue: attribute.minValue,
+ }),
+ maxValue: await getConfiguredValue({
+ id: operation.id,
+ field: `attribute:${attribute.id}:maxValue`,
+ defaultValue: attribute.maxValue,
+ }),
+ companyId,
+ createdBy: userId,
+ }))
+ );
- await trx
- .insertInto("quoteOperationAttribute")
- .values(attributes)
- .execute();
+ await trx
+ .insertInto("quoteOperationAttribute")
+ .values(attributes)
+ .execute();
+ }
}
}
}
@@ -1434,6 +1509,7 @@ serve(async (req: Request) => {
.from("item")
.select("readableId, type, name, itemCost(unitCost)")
.eq("id", itemId)
+ .eq("companyId", companyId)
.single();
if (item.data) {
itemReadableId = item.data.readableId;
@@ -1565,11 +1641,17 @@ serve(async (req: Request) => {
const [makeMethod, quoteMakeMethod, workCenters, supplierProcesses] =
await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("quoteMakeMethod")
.select("*")
.eq("id", quoteMakeMethodId)
+ .eq("companyId", companyId)
.single(),
client.from("workCenters").select("*").eq("companyId", companyId),
client
@@ -1638,6 +1720,7 @@ serve(async (req: Request) => {
quoteLineId: quoteMakeMethod.data?.quoteLineId!,
quoteMakeMethodId: parentQuoteMakeMethodId!,
processId: op.processId,
+ procedureId: op.procedureId,
workCenterId: op.workCenterId,
description: op.description,
setupTime: op.setupTime,
@@ -1680,7 +1763,9 @@ serve(async (req: Request) => {
methodOperationTool,
methodOperationParameter,
methodOperationAttribute,
+ procedureId,
} = operation;
+
if (
Array.isArray(methodOperationTool) &&
methodOperationTool.length > 0
@@ -1699,39 +1784,41 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(methodOperationParameter) &&
- methodOperationParameter.length > 0
- ) {
- await trx
- .insertInto("quoteOperationParameter")
- .values(
- methodOperationParameter.map((param) => ({
- operationId,
- key: param.key,
- value: param.value,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ if (!procedureId) {
+ if (
+ Array.isArray(methodOperationParameter) &&
+ methodOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationParameter")
+ .values(
+ methodOperationParameter.map((param) => ({
+ operationId,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
- if (
- Array.isArray(methodOperationAttribute) &&
- methodOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("quoteOperationAttribute")
- .values(
- methodOperationAttribute.map((attribute) => ({
- ...attribute,
- operationId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
+ if (
+ Array.isArray(methodOperationAttribute) &&
+ methodOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationAttribute")
+ .values(
+ methodOperationAttribute.map((attribute) => ({
+ ...attribute,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
}
}
}
@@ -1826,11 +1913,17 @@ serve(async (req: Request) => {
const itemId = targetId;
const [makeMethod, jobMakeMethod] = await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("jobMakeMethod")
.select("*")
.eq("id", jobMakeMethodId)
+ .eq("companyId", companyId)
.single(),
]);
@@ -1848,7 +1941,8 @@ serve(async (req: Request) => {
.select(
"*, jobOperationTool(*), jobOperationParameter(*), jobOperationAttribute(*)"
)
- .eq("jobId", jobMakeMethod.data.jobId),
+ .eq("jobId", jobMakeMethod.data.jobId)
+ .eq("companyId", companyId),
]);
if (jobOperations.error) {
@@ -1968,6 +2062,7 @@ serve(async (req: Request) => {
operationInserts.push({
makeMethodId: op.makeMethodId!,
processId: op.processId!,
+ procedureId: op.procedureId,
workCenterId: op.workCenterId,
description: op.description ?? "",
setupTime: op.setupTime ?? 0,
@@ -2012,6 +2107,7 @@ serve(async (req: Request) => {
jobOperationTool,
jobOperationParameter,
jobOperationAttribute,
+ procedureId,
} = operation;
if (
@@ -2032,39 +2128,41 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(jobOperationParameter) &&
- jobOperationParameter.length > 0
- ) {
- await trx
- .insertInto("methodOperationParameter")
- .values(
- jobOperationParameter.map((param) => ({
- operationId,
- key: param.key,
- value: param.value,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ if (!procedureId) {
+ if (
+ Array.isArray(jobOperationParameter) &&
+ jobOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("methodOperationParameter")
+ .values(
+ jobOperationParameter.map((param) => ({
+ operationId,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
- if (
- Array.isArray(jobOperationAttribute) &&
- jobOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("jobOperationAttribute")
- .values(
- jobOperationAttribute.map((attribute) => ({
- ...attribute,
- operationId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
+ if (
+ Array.isArray(jobOperationAttribute) &&
+ jobOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("jobOperationAttribute")
+ .values(
+ jobOperationAttribute.map((attribute) => ({
+ ...attribute,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
}
}
}
@@ -2081,19 +2179,26 @@ serve(async (req: Request) => {
const itemId = targetId;
const [makeMethod, jobMakeMethod, jobOperations] = await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("jobMakeMethod")
.select("*")
.eq("jobId", jobId)
.is("parentMaterialId", null)
+ .eq("companyId", companyId)
.single(),
client
.from("jobOperationsWithMakeMethods")
.select(
"*, jobOperationTool(*), jobOperationParameter(*), jobOperationAttribute(*)"
)
- .eq("jobId", jobId),
+ .eq("jobId", jobId)
+ .eq("companyId", companyId),
]);
if (makeMethod.error) {
@@ -2130,7 +2235,8 @@ serve(async (req: Request) => {
const makeMethods = await client
.from("makeMethod")
.select("*")
- .in("itemId", madeItemIds);
+ .in("itemId", madeItemIds)
+ .eq("companyId", companyId);
if (makeMethods.error) {
throw new Error("Failed to get make methods");
}
@@ -2213,6 +2319,7 @@ serve(async (req: Request) => {
operationInserts.push({
makeMethodId: op.makeMethodId!,
processId: op.processId!,
+ procedureId: op.procedureId,
// workCenterId: op.workCenterId,
description: op.description ?? "",
setupTime: op.setupTime ?? 0,
@@ -2258,6 +2365,7 @@ serve(async (req: Request) => {
jobOperationTool,
jobOperationParameter,
jobOperationAttribute,
+ procedureId,
} = operation;
if (
@@ -2278,39 +2386,41 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(jobOperationParameter) &&
- jobOperationParameter.length > 0
- ) {
- await trx
- .insertInto("methodOperationParameter")
- .values(
- jobOperationParameter.map((param) => ({
- operationId,
- key: param.key,
- value: param.value,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ if (!procedureId) {
+ if (
+ Array.isArray(jobOperationParameter) &&
+ jobOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("methodOperationParameter")
+ .values(
+ jobOperationParameter.map((param) => ({
+ operationId,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
- if (
- Array.isArray(jobOperationAttribute) &&
- jobOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("jobOperationAttribute")
- .values(
- jobOperationAttribute.map((attribute) => ({
- ...attribute,
- operationId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
+ if (
+ Array.isArray(jobOperationAttribute) &&
+ jobOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("jobOperationAttribute")
+ .values(
+ jobOperationAttribute.map((attribute) => ({
+ ...attribute,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
}
}
}
@@ -2319,6 +2429,136 @@ serve(async (req: Request) => {
break;
}
+ case "procedureToOperation": {
+ const procedureId = sourceId;
+ const operationId = targetId;
+ if (!procedureId) {
+ throw new Error("Invalid sourceId");
+ }
+
+ if (!operationId) {
+ throw new Error("Invalid targetId");
+ }
+
+ const [procedure, operation] = await Promise.all([
+ client
+ .from("procedure")
+ .select("*, procedureAttribute(*), procedureParameter(*)")
+ .eq("id", procedureId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("jobOperation")
+ .select("*, jobOperationAttribute(*)")
+ .eq("id", operationId)
+ .eq("companyId", companyId)
+ .single(),
+ ]);
+
+ if (procedure.error) {
+ throw new Error("Failed to get procedure");
+ }
+
+ if (operation.error) {
+ throw new Error("Failed to get operation");
+ }
+
+ const existingAttributes = operation.data?.jobOperationAttribute ?? [];
+
+ await db.transaction().execute(async (trx) => {
+ // Update or delete existing attributes
+ for (const existingAttribute of existingAttributes) {
+ const matchingProcedureAttribute =
+ procedure.data.procedureAttribute.find(
+ (pa) =>
+ pa.name === existingAttribute.name &&
+ pa.type === existingAttribute.type
+ );
+
+ if (matchingProcedureAttribute) {
+ // Update matching attribute
+ await trx
+ .updateTable("jobOperationAttribute")
+ .set({
+ description: matchingProcedureAttribute.description,
+ minValue: matchingProcedureAttribute.minValue,
+ maxValue: matchingProcedureAttribute.maxValue,
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ })
+ .where("id", "=", existingAttribute.id)
+ .execute();
+ } else {
+ // Delete non-matching attribute
+ await trx
+ .deleteFrom("jobOperationAttribute")
+ .where("id", "=", existingAttribute.id)
+ .execute();
+ }
+ }
+
+ // Delete all existing parameters
+ await trx
+ .deleteFrom("jobOperationParameter")
+ .where("operationId", "=", operationId)
+ .execute();
+
+ // Add new attributes that don't exist yet
+ const newAttributes = procedure.data.procedureAttribute.filter(
+ (pa) =>
+ !existingAttributes.some(
+ (ea) => ea.name === pa.name && ea.type === pa.type
+ )
+ );
+
+ if (newAttributes.length > 0) {
+ await trx
+ .insertInto("jobOperationAttribute")
+ .values(
+ newAttributes.map((attr) => ({
+ operationId: operationId,
+ name: attr.name,
+ type: attr.type,
+ description: attr.description,
+ minValue: attr.minValue,
+ maxValue: attr.maxValue,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId,
+ }))
+ )
+ .execute();
+ }
+
+ // Add all parameters from procedure
+ if (procedure.data.procedureParameter.length > 0) {
+ await trx
+ .insertInto("jobOperationParameter")
+ .values(
+ procedure.data.procedureParameter.map((param) => ({
+ operationId: operationId,
+ companyId,
+ key: param.key,
+ value: param.value,
+ createdBy: userId,
+ updatedBy: userId,
+ }))
+ )
+ .execute();
+ }
+
+ // update work instruction
+ await trx
+ .updateTable("jobOperation")
+ .set({
+ workInstruction: procedure.data.content,
+ procedureId: procedureId,
+ })
+ .where("id", "=", operationId)
+ .execute();
+ });
+ break;
+ }
case "quoteLineToItem": {
const [quoteId, quoteLineId] = (sourceId as string).split(":");
if (!quoteId || !quoteLineId) {
@@ -2328,19 +2568,26 @@ serve(async (req: Request) => {
const [makeMethod, quoteMakeMethod, quoteOperations] =
await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("quoteMakeMethod")
.select("*")
.eq("quoteLineId", quoteLineId)
.is("parentMaterialId", null)
+ .eq("companyId", companyId)
.single(),
client
.from("quoteOperationsWithMakeMethods")
.select(
"*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"
)
- .eq("quoteLineId", quoteLineId),
+ .eq("quoteLineId", quoteLineId)
+ .eq("companyId", companyId),
]);
if (makeMethod.error) {
@@ -2381,7 +2628,8 @@ serve(async (req: Request) => {
const makeMethods = await client
.from("makeMethod")
.select("*")
- .in("itemId", madeItemIds);
+ .in("itemId", madeItemIds)
+ .eq("companyId", companyId);
if (makeMethods.error) {
throw new Error("Failed to get make methods");
}
@@ -2467,6 +2715,7 @@ serve(async (req: Request) => {
operationInserts.push({
makeMethodId: op.makeMethodId!,
processId: op.processId!,
+ procedureId: op.procedureId,
workCenterId: op.workCenterId,
description: op.description ?? "",
setupTime: op.setupTime ?? 0,
@@ -2512,6 +2761,7 @@ serve(async (req: Request) => {
quoteOperationTool,
quoteOperationParameter,
quoteOperationAttribute,
+ procedureId,
} = operation;
if (
@@ -2532,39 +2782,41 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(quoteOperationParameter) &&
- quoteOperationParameter.length > 0
- ) {
- await trx
- .insertInto("methodOperationParameter")
- .values(
- quoteOperationParameter.map((param) => ({
- operationId,
- key: param.key,
- value: param.value,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ if (!procedureId) {
+ if (
+ Array.isArray(quoteOperationParameter) &&
+ quoteOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("methodOperationParameter")
+ .values(
+ quoteOperationParameter.map((param) => ({
+ operationId,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
- if (
- Array.isArray(quoteOperationAttribute) &&
- quoteOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("quoteOperationAttribute")
- .values(
- quoteOperationAttribute.map((attribute) => ({
- ...attribute,
- operationId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
+ if (
+ Array.isArray(quoteOperationAttribute) &&
+ quoteOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationAttribute")
+ .values(
+ quoteOperationAttribute.map((attribute) => ({
+ ...attribute,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
}
}
}
@@ -2595,23 +2847,27 @@ serve(async (req: Request) => {
.select("*")
.eq("jobId", jobId)
.is("parentMaterialId", null)
+ .eq("companyId", companyId)
.single(),
client
.from("quoteMakeMethod")
.select("*")
.is("parentMaterialId", null)
.eq("quoteLineId", quoteLineId)
+ .eq("companyId", companyId)
.single(),
client
.from("quoteMaterial")
.select("*")
- .eq("quoteLineId", quoteLineId),
+ .eq("quoteLineId", quoteLineId)
+ .eq("companyId", companyId),
client
.from("quoteOperation")
.select(
"*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"
)
- .eq("quoteLineId", quoteLineId),
+ .eq("quoteLineId", quoteLineId)
+ .eq("companyId", companyId),
]);
if (jobMakeMethod.error || !jobMakeMethod.data) {
@@ -2739,6 +2995,7 @@ serve(async (req: Request) => {
? jobMakeMethod.data.id
: quoteMakeMethodIdToJobMakeMethodId[op.quoteMakeMethodId!],
processId: op.processId,
+ procedureId: op.procedureId,
workCenterId: op.workCenterId,
description: op.description,
setupTime: op.setupTime,
@@ -2774,6 +3031,7 @@ serve(async (req: Request) => {
quoteOperationTool,
quoteOperationParameter,
quoteOperationAttribute,
+ procedureId,
} = operation;
if (
@@ -2794,39 +3052,48 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(quoteOperationParameter) &&
- quoteOperationParameter.length > 0
- ) {
- await trx
- .insertInto("jobOperationParameter")
- .values(
- quoteOperationParameter.map((param) => ({
- operationId,
- key: param.key,
- value: param.value,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ if (procedureId) {
+ await insertProcedureDataForJobOperation(trx, client, {
+ operationId,
+ procedureId,
+ companyId,
+ userId,
+ });
+ } else {
+ if (
+ Array.isArray(quoteOperationParameter) &&
+ quoteOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("jobOperationParameter")
+ .values(
+ quoteOperationParameter.map((param) => ({
+ operationId,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
- if (
- Array.isArray(quoteOperationAttribute) &&
- quoteOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("quoteOperationAttribute")
- .values(
- quoteOperationAttribute.map((attribute) => ({
- ...attribute,
- operationId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
+ if (
+ Array.isArray(quoteOperationAttribute) &&
+ quoteOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationAttribute")
+ .values(
+ quoteOperationAttribute.map((attribute) => ({
+ ...attribute,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
}
}
}
@@ -2840,11 +3107,17 @@ serve(async (req: Request) => {
const itemId = targetId;
const [makeMethod, quoteMakeMethod] = await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single(),
client
.from("quoteMakeMethod")
.select("*")
.eq("id", quoteMakeMethodId)
+ .eq("companyId", companyId)
.single(),
]);
@@ -2862,7 +3135,8 @@ serve(async (req: Request) => {
.select(
"*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"
)
- .eq("quoteLineId", quoteMakeMethod.data.quoteLineId),
+ .eq("quoteLineId", quoteMakeMethod.data.quoteLineId)
+ .eq("companyId", companyId),
]);
if (quoteOperations.error) {
@@ -2986,6 +3260,7 @@ serve(async (req: Request) => {
operationInserts.push({
makeMethodId: op.makeMethodId!,
processId: op.processId!,
+ procedureId: op.procedureId,
workCenterId: op.workCenterId,
description: op.description ?? "",
setupTime: op.setupTime ?? 0,
@@ -3030,6 +3305,7 @@ serve(async (req: Request) => {
quoteOperationTool,
quoteOperationParameter,
quoteOperationAttribute,
+ procedureId,
} = operation;
if (
@@ -3050,39 +3326,41 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(quoteOperationParameter) &&
- quoteOperationParameter.length > 0
- ) {
- await trx
- .insertInto("methodOperationParameter")
- .values(
- quoteOperationParameter.map((param) => ({
- operationId,
- key: param.key,
- value: param.value,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
+ if (!procedureId) {
+ if (
+ Array.isArray(quoteOperationParameter) &&
+ quoteOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("methodOperationParameter")
+ .values(
+ quoteOperationParameter.map((param) => ({
+ operationId,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
- if (
- Array.isArray(quoteOperationAttribute) &&
- quoteOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("methodOperationAttribute")
- .values(
- quoteOperationAttribute.map((attribute) => ({
- ...attribute,
- operationId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
+ if (
+ Array.isArray(quoteOperationAttribute) &&
+ quoteOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("methodOperationAttribute")
+ .values(
+ quoteOperationAttribute.map((attribute) => ({
+ ...attribute,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
}
}
}
@@ -3188,3 +3466,79 @@ function getMethodTreeArrayToTree(items: Method[]): MethodTreeItem[] {
function getFieldKey(field: string, id: string) {
return `${field}:${id}`;
}
+
+async function insertProcedureDataForJobOperation(
+ trx: Transaction<DB>,
+ client: SupabaseClient<Database>,
+ args: {
+ operationId: string;
+ procedureId: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ const { operationId, procedureId, companyId, userId } = args;
+ const procedure = await client
+ .from("procedure")
+ .select("*, procedureAttribute(*), procedureParameter(*)")
+ .eq("id", procedureId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (procedure.error) return;
+
+ const attributes = procedure.data?.procedureAttribute ?? [];
+ const parameters = procedure.data?.procedureParameter ?? [];
+
+ if (attributes.length > 0) {
+ await trx
+ .insertInto("jobOperationAttribute")
+ .values(
+ attributes.map((attr) => {
+ const {
+ id: _id,
+ procedureId: _procedureId,
+ createdAt: _createdAt,
+ ...rest
+ } = attr;
+ return {
+ ...rest,
+ operationId,
+ companyId,
+ createdBy: userId,
+ };
+ })
+ )
+ .execute();
+ }
+
+ if (parameters.length > 0) {
+ await trx
+ .insertInto("jobOperationParameter")
+ .values(
+ parameters.map((param) => {
+ const {
+ id: _id,
+ procedureId: _procedureId,
+ createdAt: _createdAt,
+ ...rest
+ } = param;
+ return {
+ ...rest,
+ operationId,
+ companyId,
+ createdBy: userId,
+ };
+ })
+ )
+ .execute();
+ }
+
+ await trx
+ .updateTable("jobOperation")
+ .set({
+ workInstruction: procedure?.data?.content ?? {},
+ })
+ .where("id", "=", operationId)
+ .execute();
+}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index f131d5fa1b..ee9e2d93a7 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -29517,6 +29517,7 @@ export type Database = {
order: number | null
overheadRate: number | null
priority: number | null
+ procedureId: string | null
processId: string | null
quantityComplete: number | null
quantityReworked: number | null
@@ -29657,6 +29658,20 @@ export type Database = {
referencedRelation: "jobMaterialWithMakeMethodId"
referencedColumns: ["jobMaterialMakeMethodId"]
},
+ {
+ foreignKeyName: "jobOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_processId_fkey"
columns: ["processId"]
@@ -30336,14 +30351,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -31640,14 +31655,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -32499,6 +32514,7 @@ export type Database = {
operationUnitCost: number | null
order: number | null
overheadRate: number | null
+ procedureId: string | null
processId: string | null
quoteId: string | null
quoteLineId: string | null
@@ -32589,6 +32605,20 @@ export type Database = {
referencedRelation: "supplierProcesses"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_processId_fkey"
columns: ["processId"]
@@ -33283,14 +33313,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/migrations/20250216192838_procedures.sql b/packages/database/supabase/migrations/20250216192838_procedures.sql
index b17b100af3..b79cbb0f1f 100644
--- a/packages/database/supabase/migrations/20250216192838_procedures.sql
+++ b/packages/database/supabase/migrations/20250216192838_procedures.sql
@@ -549,4 +549,27 @@ FOR INSERT WITH CHECK (
bucket_id = 'private'
AND has_role('employee', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'job'
-);
\ No newline at end of file
+);
+
+CREATE OR REPLACE VIEW "jobOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ jo.*
+ FROM "jobOperation" jo
+ INNER JOIN "jobMakeMethod" jmm
+ ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "makeMethod" mm
+ ON jmm."itemId" = mm."itemId";
+
+
+DROP VIEW "quoteOperationsWithMakeMethods";
+COMMIT;
+CREATE OR REPLACE VIEW "quoteOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ qo.*
+ FROM "quoteOperation" qo
+ INNER JOIN "quoteMakeMethod" qmm
+ ON qo."quoteMakeMethodId" = qmm.id
+ LEFT JOIN "makeMethod" mm
+ ON qmm."itemId" = mm."itemId";
\ No newline at end of file
diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsx
index 16d289fd87..1cd21f056f 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -14,6 +14,7 @@ import { IconButton } from "./IconButton";
import { Popover, PopoverContent, PopoverTrigger } from "./Popover";
import { Spinner } from "./Spinner";
import { cn } from "./utils/cn";
+import { reactNodeToString } from "./utils/react";
export type ComboboxProps = Omit<
ComponentPropsWithoutRef<"button">,
@@ -161,9 +162,12 @@ function VirtualizedCommand({
const filteredOptions = useMemo(() => {
return search
? options.filter((option) => {
- return `${option.label} ${option.helper}`
- .toLowerCase()
- .includes(search.toLowerCase());
+ const value =
+ typeof option.label === "string"
+ ? `${option.label} ${option.helper}`
+ : reactNodeToString(option.label);
+
+ return value.toLowerCase().includes(search.toLowerCase());
})
: options;
}, [options, search]);
@@ -201,6 +205,10 @@ function VirtualizedCommand({
>
{items.map((virtualRow) => {
const item = filteredOptions[virtualRow.index];
+ const value =
+ typeof item.label === "string"
+ ? CSS.escape(item.label) + CSS.escape(item.helper ?? "")
+ : reactNodeToString(item.label);
return (
<CommandItem
@@ -208,7 +216,7 @@ function VirtualizedCommand({
value={
typeof item.label === "string"
? CSS.escape(item.label) + CSS.escape(item.helper ?? "")
- : undefined
+ : reactNodeToString(item.label)
}
onSelect={() => {
onChange?.(item.value);
diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsx
index c229f0e1d5..3db250efef 100644
--- a/packages/react/src/CreateableCombobox.tsx
+++ b/packages/react/src/CreateableCombobox.tsx
@@ -13,6 +13,7 @@ import { HStack } from "./HStack";
import { IconButton } from "./IconButton";
import { Popover, PopoverContent, PopoverTrigger } from "./Popover";
import { cn } from "./utils/cn";
+import { reactNodeToString } from "./utils/react";
export type CreatableComboboxProps = Omit<
ComponentPropsWithoutRef<"button">,
@@ -185,9 +186,12 @@ function VirtualizedCommand({
const filteredOptions = useMemo(() => {
const filtered = search
? options.filter((option) => {
- return `${option.label} ${option.helper}`
- .toLowerCase()
- .includes(search.toLowerCase());
+ const value =
+ typeof option.label === "string"
+ ? `${option.label} ${option.helper}`
+ : reactNodeToString(option.label);
+
+ return value.toLowerCase().includes(search.toLowerCase());
})
: options;
diff --git a/packages/react/src/CreateableMultiSelect.tsx b/packages/react/src/CreateableMultiSelect.tsx
index 940db4300a..8262eeca82 100644
--- a/packages/react/src/CreateableMultiSelect.tsx
+++ b/packages/react/src/CreateableMultiSelect.tsx
@@ -18,6 +18,7 @@ import { HStack } from "./HStack";
import { IconButton } from "./IconButton";
import { Popover, PopoverContent, PopoverTrigger } from "./Popover";
import { cn } from "./utils/cn";
+import { reactNodeToString } from "./utils/react";
export type CreatableMultiSelectProps = Omit<
ComponentPropsWithoutRef<"button">,
@@ -231,9 +232,12 @@ function VirtualizedCommand({
const filteredOptions = useMemo(() => {
const filtered = search
? options.filter((option) => {
- return `${option.label} ${option.helper}`
- .toLowerCase()
- .includes(search.toLowerCase());
+ const value =
+ typeof option.label === "string"
+ ? `${option.label} ${option.helper}`
+ : reactNodeToString(option.label);
+
+ return value.toLowerCase().includes(search.toLowerCase());
})
: options;
diff --git a/packages/react/src/MultiSelect.tsx b/packages/react/src/MultiSelect.tsx
index a325d5919b..15096b52d1 100644
--- a/packages/react/src/MultiSelect.tsx
+++ b/packages/react/src/MultiSelect.tsx
@@ -15,6 +15,7 @@ import {
} from "./Command";
import { Popover, PopoverContent, PopoverTrigger } from "./Popover";
import { cn } from "./utils/cn";
+import { reactNodeToString } from "./utils/react";
export type MultiSelectProps = Omit<
ComponentPropsWithoutRef<"button">,
@@ -147,9 +148,14 @@ function VirtualizedCommand({
const filteredOptions = useMemo(() => {
return search
- ? options.filter((option) =>
- option.label.toLowerCase().includes(search.toLowerCase())
- )
+ ? options.filter((option) => {
+ const value =
+ typeof option.label === "string"
+ ? option.label.toLowerCase()
+ : reactNodeToString(option.label);
+
+ return value.includes(search.toLowerCase());
+ })
: options;
}, [options, search]);