Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

refactor: bill of process to use remix best practices

Brad Barbin7a6ceff9a7bd
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index 6d3fe70821..44a62843a2 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -26,15 +26,15 @@ import {
generateHTML,
useDebounce,
useDisclosure,
+ useThrottle,
} from "@carbon/react";
import { formatRelativeTime } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
-import { useFetcher } from "@remix-run/react";
+import { useFetcher, useFetchers } from "@remix-run/react";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
import { nanoid } from "nanoid";
import type { Dispatch, SetStateAction } from "react";
-import { useCallback, useEffect, useRef, useState } from "react";
-import { flushSync } from "react-dom";
+import { useEffect, useRef, useState } from "react";
import {
LuAlertTriangle,
LuChevronDown,
@@ -82,13 +82,33 @@ type Operation = z.infer<typeof methodOperationValidator> & {
workInstruction: JSONContent | null;
};
+type OperationWithTools = Operation & {
+ methodOperationTool: OperationTool[];
+};
+
type ItemWithData = Item & {
data: Operation;
};
type BillOfProcessProps = {
makeMethodId: string;
- operations: (Operation & { methodOperationTool: OperationTool[] })[];
+ operations: OperationWithTools[];
+};
+
+type PendingWorkInstructions = {
+ [key: string]: JSONContent;
+};
+
+type OrderState = {
+ [key: string]: number;
+};
+
+type CheckedState = {
+ [key: string]: boolean;
+};
+
+type TemporaryItems = {
+ [key: string]: Operation;
};
function makeItems(operations: Operation[]): ItemWithData[] {
@@ -152,96 +172,167 @@ const initialOperation: Omit<Operation, "makeMethodId" | "order" | "tools"> = {
workInstruction: {},
};
-const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
+const usePendingOperations = () => {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return (
+ (fetcher.formAction === path.to.newMethodOperation ||
+ fetcher.formAction?.includes("/items/methods/operation/")) ??
+ false
+ );
+ })
+ .reduce<z.infer<typeof methodOperationValidator>[]>((acc, fetcher) => {
+ const formData = fetcher.formData;
+ const operation = methodOperationValidator.safeParse(
+ Object.fromEntries(formData)
+ );
+
+ if (operation.success) {
+ return [...acc, operation.data];
+ }
+ return acc;
+ }, []);
+};
+
+const BillOfProcess = ({
+ makeMethodId,
+ operations: initialOperations,
+}: BillOfProcessProps) => {
const permissions = usePermissions();
const { carbon } = useCarbon();
const sortOrderFetcher = useFetcher<{}>();
- const {
- id: userId,
- company: { id: companyId },
- } = useUser();
+ const deleteOperationFetcher = useFetcher<{ success: boolean }>();
+ const { id: userId } = useUser();
- const [items, setItems] = useState<ItemWithData[]>(
- makeItems(operations ?? [])
- );
const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
+ const [temporaryItems, setTemporaryItems] = useState<TemporaryItems>({});
+ const [workInstructions, setWorkInstructions] =
+ useState<PendingWorkInstructions>(() => {
+ return initialOperations.reduce((acc, operation) => {
+ if (operation.workInstruction) {
+ acc[operation.id!] = operation.workInstruction;
+ }
+ return acc;
+ }, {} as PendingWorkInstructions);
+ });
+ const [checkedState, setCheckedState] = useState<CheckedState>({});
+ const [orderState, setOrderState] = useState<OrderState>(() => {
+ return initialOperations.reduce((acc, op) => {
+ acc[op.id!] = op.order;
+ return acc;
+ }, {} as OrderState);
+ });
- const onToggleItem = (id: string) => {
- if (!permissions.can("update", "parts")) return;
- setItems((prevItems) =>
- prevItems.map((i) => (i.id === id ? { ...i, checked: !i.checked } : i))
- );
- };
+ const operationsById = new Map<
+ string,
+ Operation & { methodOperationTool: OperationTool[] }
+ >();
- // we create a temporary item and append it to the list
- const onAddItem = () => {
- const temporaryId = Math.random().toString(16).slice(2);
- setSelectedItemId(temporaryId);
- setItems((prevItems) => {
- let newOrder = 1;
- if (prevItems.length) {
- newOrder = prevItems[prevItems.length - 1].data.order + 1;
- }
+ // Add initial operations to map
+ initialOperations.forEach((operation) => {
+ if (!operation.id) return;
+ operationsById.set(operation.id, operation);
+ });
- return [
- ...prevItems,
- {
- title: "",
- checked: false,
- id: temporaryId,
- data: {
- ...initialOperation,
- order: newOrder,
- makeMethodId,
- },
- },
- ];
+ const pendingOperations = usePendingOperations();
+
+ // Replace existing operations with pending ones
+ pendingOperations.forEach((pendingOperation) => {
+ if (!pendingOperation.id) {
+ operationsById.set("temporary", {
+ ...pendingOperation,
+ workInstruction: {},
+ methodOperationTool: [],
+ });
+ return;
+ }
+
+ // Remove existing operation if it exists
+ operationsById.delete(pendingOperation.id);
+
+ // Add pending operation
+ operationsById.set(pendingOperation.id, {
+ ...pendingOperation,
+ workInstruction: workInstructions[pendingOperation.id] || null,
+ order: orderState[pendingOperation.id] ?? pendingOperation.order,
+ methodOperationTool: [],
});
- };
+ });
- const onRemoveItem = async (id: string) => {
- if (!permissions.can("update", "parts")) return;
- // get the item and it's order in the list
- const itemIndex = items.findIndex((i) => i.id === id);
- const item = items[itemIndex];
-
- setItems((prevItems) => prevItems.filter((item) => item.id !== id));
-
- const response = await carbon
- ?.from("methodOperation")
- .delete()
- .eq("id", id);
- if (response?.error) {
- // add the item back to the list if there was an error
- setItems((prevItems) => {
- const updatedItems = [...prevItems];
- updatedItems.splice(itemIndex, 0, item);
- return updatedItems;
+ // Add temporary items to operations
+ Object.entries(temporaryItems).forEach(([id, operation]) => {
+ if (!operationsById.has(id)) {
+ operationsById.set(id, {
+ ...operation,
+ methodOperationTool: [],
});
}
+ });
+
+ const operations = Array.from(operationsById.values()).sort(
+ (a, b) => (orderState[a.id!] ?? a.order) - (orderState[b.id!] ?? b.order)
+ );
+
+ const items = makeItems(operations).map((item) => ({
+ ...item,
+ checked: checkedState[item.id] ?? false,
+ }));
+
+ const onToggleItem = (id: string) => {
+ if (!permissions.can("update", "parts")) return;
+ setCheckedState((prev) => ({
+ ...prev,
+ [id]: !prev[id],
+ }));
};
+ const onUpdateWorkInstruction = useDebounce(
+ async (id: string, content: JSONContent) => {
+ if (!isTemporaryId(id)) {
+ await carbon
+ ?.from("methodOperation")
+ .update({
+ workInstruction: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", id);
+ }
+ },
+ 1000,
+ true
+ );
+
const onReorder = (items: ItemWithData[]) => {
if (!permissions.can("update", "parts")) return;
- const newItems = items.map((item, index) => ({
- ...item,
- data: {
- ...item.data,
- order: index + 1,
- },
- }));
- const updates = newItems.reduce<Record<string, number>>((acc, item) => {
- if (!isTemporaryId(item.id)) {
- acc[item.id] = item.data.order;
+
+ // Create new order state
+ const newOrderState = items.reduce<OrderState>((acc, item, index) => {
+ acc[item.id] = index + 1;
+ return acc;
+ }, {});
+
+ // Update order state immediately
+ setOrderState(newOrderState);
+
+ // Only send non-temporary items to the server
+ const updates = Object.entries(newOrderState).reduce<
+ Record<string, number>
+ >((acc, [id, order]) => {
+ if (!isTemporaryId(id)) {
+ acc[id] = order;
}
return acc;
}, {});
- setItems(newItems);
updateSortOrder(updates);
};
- const updateSortOrder = useDebounce(
+ const updateSortOrder = useThrottle(
(updates: Record<string, number>) => {
let formData = new FormData();
formData.append("updates", JSON.stringify(updates));
@@ -254,30 +345,59 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
true
);
- const onCloseOnDrag = useCallback(() => {
- setItems((prevItems) => {
- const updatedItems = prevItems.map((i) =>
- i.checked ? { ...i, checked: false } : i
+ const onAddItem = () => {
+ const temporaryId = Math.random().toString(16).slice(2);
+
+ let newOrder = 1;
+ if (operations.length) {
+ newOrder = Math.max(...operations.map((op) => op.order)) + 1;
+ }
+
+ const newOperation: Operation = {
+ ...initialOperation,
+ id: temporaryId,
+ order: newOrder,
+ makeMethodId,
+ };
+
+ setTemporaryItems((prev) => ({
+ ...prev,
+ [temporaryId]: newOperation,
+ }));
+ setSelectedItemId(temporaryId);
+ };
+
+ const onRemoveItem = async (id: string) => {
+ if (!permissions.can("update", "parts")) return;
+
+ const operation = operationsById.get(id);
+ if (!operation) return;
+
+ if (isTemporaryId(id)) {
+ setTemporaryItems((prev) => {
+ const { [id]: _, ...rest } = prev;
+ return rest;
+ });
+ } else {
+ deleteOperationFetcher.submit(
+ { id },
+ {
+ method: "post",
+ action: path.to.methodOperationsDelete,
+ }
);
- return updatedItems.some(
- (i, index) => i.checked !== prevItems[index].checked
- )
- ? updatedItems
- : prevItems;
+ }
+
+ setSelectedItemId(null);
+ setOrderState((prev) => {
+ const { [id]: _, ...rest } = prev;
+ return rest;
});
- }, []);
-
- const onUpdateWorkInstruction = useDebounce(async (content: JSONContent) => {
- if (selectedItemId !== null && !isTemporaryId(selectedItemId))
- await carbon
- ?.from("methodOperation")
- .update({
- workInstruction: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", selectedItemId!);
- }, 2000);
+ };
+
+ const {
+ company: { id: companyId },
+ } = useUser();
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
@@ -328,8 +448,9 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
>
<OperationForm
item={item}
- setItems={setItems}
+ workInstruction={workInstructions[item.id] ?? {}}
setSelectedItemId={setSelectedItemId}
+ setTemporaryItems={setTemporaryItems}
/>
</motion.div>
</div>
@@ -344,25 +465,16 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
{permissions.can("update", "parts") ? (
<Editor
initialValue={
- item.data.workInstruction ?? ({} as JSONContent)
+ workInstructions[item.id] ?? ({} as JSONContent)
}
onUpload={onUploadImage}
onChange={(content) => {
if (!permissions.can("update", "parts")) return;
- setItems((prevItems) =>
- prevItems.map((i) =>
- i.id === selectedItemId
- ? {
- ...i,
- data: {
- ...i.data,
- workInstruction: content,
- },
- }
- : i
- )
- );
- onUpdateWorkInstruction(content);
+ setWorkInstructions((prev) => ({
+ ...prev,
+ [item.id]: content,
+ }));
+ onUpdateWorkInstruction(item.id, content);
}}
className="py-8"
/>
@@ -387,8 +499,8 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
<div className="flex w-full flex-col py-4">
<ToolsForm
tools={
- operations.find((o) => o.id === item.id)?.methodOperationTool ??
- []
+ initialOperations.find((o) => o.id === item.id)
+ ?.methodOperationTool ?? []
}
operationId={item.id!}
isDisabled={
@@ -410,8 +522,8 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
onSelectItem={setSelectedItemId}
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
- handleDrag={onCloseOnDrag}
- className="my-2 "
+ handleDrag={() => setSelectedItemId(null)}
+ className="my-2"
renderExtra={(item) => (
<div
key={`${isOpen}`}
@@ -425,11 +537,6 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
onClick={
isOpen
? () => {
- if (isTemporaryId(item.id)) {
- setItems((prevItems) =>
- prevItems.filter((i) => i.id !== item.id)
- );
- }
setSelectedItemId(null);
}
: () => {
@@ -550,15 +657,19 @@ function isTemporaryId(id: string) {
return id.length < 20;
}
+type OperationFormProps = {
+ item: ItemWithData;
+ setSelectedItemId: Dispatch<SetStateAction<string | null>>;
+ workInstruction: JSONContent;
+ setTemporaryItems: Dispatch<SetStateAction<TemporaryItems>>;
+};
+
function OperationForm({
item,
- setItems,
setSelectedItemId,
-}: {
- item: ItemWithData;
- setItems: Dispatch<SetStateAction<ItemWithData[]>>;
- setSelectedItemId: Dispatch<SetStateAction<string | null>>;
-}) {
+ workInstruction,
+ setTemporaryItems,
+}: OperationFormProps) {
const methodOperationFetcher = useFetcher<{ id: string }>();
const { id: userId } = useUser();
const { carbon } = useCarbon();
@@ -567,47 +678,35 @@ function OperationForm({
useEffect(() => {
// replace the temporary id with the actual id
if (methodOperationFetcher.data && methodOperationFetcher.data.id) {
- flushSync(() => {
- setItems((prevItems) =>
- prevItems.map((i) =>
- i.id === item.id
- ? {
- ...i,
- id: methodOperationFetcher.data!.id!,
- data: {
- ...i.data,
- ...methodOperationFetcher.data,
- },
- }
- : i
- )
- );
- });
- // save the work instructions
if (isTemporaryId(item.id) && carbon) {
carbon
.from("methodOperation")
.update({
- workInstruction: item.data.workInstruction,
+ workInstruction: workInstruction,
createdAt: today(getLocalTimeZone()).toString(),
updatedBy: userId,
})
.eq("id", methodOperationFetcher.data.id)
.then(() => {
setSelectedItemId(null);
+ // Clear temporary item after successful save
+ setTemporaryItems((prev) => {
+ const { [item.id]: _, ...rest } = prev;
+ return rest;
+ });
});
} else {
setSelectedItemId(null);
}
}
}, [
- item.data.workInstruction,
item.id,
methodOperationFetcher.data,
- setItems,
setSelectedItemId,
carbon,
userId,
+ workInstruction,
+ setTemporaryItems,
]);
const [showMachine, setShowMachine] = useState(false);
@@ -695,22 +794,13 @@ function OperationForm({
validator={methodOperationValidator}
className="w-full flex flex-col gap-y-4"
fetcher={methodOperationFetcher}
- onSubmit={(values) => {
- setItems((prevItems) =>
- prevItems.map((i) =>
- i.id === item.id
- ? {
- ...makeItem({
- ...values,
- workInstruction: i.data.workInstruction,
- }),
- id: item.id,
- }
- : i
- )
- );
+ onSubmit={() => {
+ if (!isTemporaryId(item.id)) {
+ setSelectedItemId(null);
+ }
}}
>
+ <Hidden name="id" />
<Hidden name="makeMethodId" />
<Hidden name="order" />
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
@@ -1239,14 +1329,18 @@ function ToolsForm({
{tools.length > 0 && (
<div className="border rounded-lg">
- {tools.map((t, index) => (
- <ToolsListItem
- key={t.id}
- tool={t}
- operationId={operationId}
- className={index === tools.length - 1 ? "border-none" : ""}
- />
- ))}
+ {tools
+ .sort((a, b) =>
+ String(a.id ?? "").localeCompare(String(b.id ?? ""))
+ )
+ .map((t, index) => (
+ <ToolsListItem
+ key={t.id}
+ tool={t}
+ operationId={operationId}
+ className={index === tools.length - 1 ? "border-none" : ""}
+ />
+ ))}
</div>
)}
</div>
diff --git a/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx b/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx
index 2df05ed59a..ae67048688 100644
--- a/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx
@@ -12,15 +12,12 @@ import {
Boolean,
CustomFormFields,
Hidden,
- InputControlled,
Number,
Submit,
} from "~/components/Form";
-import { usePermissions, useRouteData } from "~/hooks";
-import type { PartSummary } from "~/modules/items";
+import { usePermissions } from "~/hooks";
import { partManufacturingValidator } from "~/modules/items";
import type { action } from "~/routes/x+/part+/$itemId.manufacturing.method";
-import { path } from "~/utils/path";
type PartManufacturingFormProps = {
initialValues: z.infer<typeof partManufacturingValidator>;
@@ -34,10 +31,6 @@ const PartManufacturingForm = ({
const { itemId } = useParams();
if (!itemId) throw new Error("Could not find itemId");
- const routeData = useRouteData<{ partSummary: PartSummary }>(
- path.to.part(itemId)
- );
-
return (
<Card>
<ValidatedForm
@@ -52,19 +45,6 @@ const PartManufacturingForm = ({
<CardContent>
<Hidden name="itemId" />
<div className="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4 w-full">
- <InputControlled
- isReadOnly
- name="id"
- label="Part ID"
- value={routeData?.partSummary?.id ?? ""}
- />
- <InputControlled
- isReadOnly
- name="name"
- label="Short Description"
- className="col-span-2"
- value={routeData?.partSummary?.name ?? ""}
- />
<Number name="lotSize" label="Lot Size" />
<Number
name="scrapPercentage"
diff --git a/apps/carbon/app/routes/x+/items+/methods+/operation.delete.tsx b/apps/carbon/app/routes/x+/items+/methods+/operation.delete.tsx
new file mode 100644
index 0000000000..455d3b8cbe
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/methods+/operation.delete.tsx
@@ -0,0 +1,34 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "parts",
+ });
+
+ const formData = await request.formData();
+ const id = formData.get("id") as string;
+
+ if (!id) {
+ return json(
+ { error: "Operation ID is required" },
+ {
+ status: 400,
+ }
+ );
+ }
+
+ const { error } = await client.from("methodOperation").delete().eq("id", id);
+
+ if (error) {
+ return json(
+ { success: false, error: error.message },
+ {
+ status: 400,
+ }
+ );
+ }
+
+ return json({ success: true });
+}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
index f594f10313..ce226f0c9e 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
@@ -118,7 +118,7 @@ export default function MakeMethodRoute() {
initialValues={manufacturingInitialValues}
/>
<BillOfProcess
- key={`bop:${itemId}:${manufacturingRouteData?.methodOperations?.length}`}
+ key={`bop:${itemId}`}
makeMethodId={makeMethodId}
// @ts-ignore
operations={manufacturingRouteData?.methodOperations ?? []}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.manufacturing.$makeMethodId.$materialId.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
index a782f9a7b2..e5b8ce5c34 100644
--- a/apps/carbon/app/routes/x+/tool+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
@@ -113,12 +113,12 @@ export default function MethodMaterialMakePage() {
initialValues={item}
/>
<BillOfProcess
- key={`bop:${itemId}:${methodOperations.length}`}
+ key={`bop:${itemId}`}
makeMethodId={makeMethodId}
operations={methodOperations}
/>
<BillOfMaterial
- key={`bom:${itemId}:${methodMaterials.length}`}
+ key={`bom:${itemId}`}
makeMethodId={makeMethodId}
materials={methodMaterials}
operations={methodOperations}
diff --git a/apps/carbon/app/routes/x+/tool+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/tool+/$itemId.manufacturing.method.tsx
index 03b93b1ba7..5a8c6ded0f 100644
--- a/apps/carbon/app/routes/x+/tool+/$itemId.manufacturing.method.tsx
+++ b/apps/carbon/app/routes/x+/tool+/$itemId.manufacturing.method.tsx
@@ -27,13 +27,13 @@ export default function MakeMethodRoute() {
<VStack spacing={2} className="p-2">
<MakeMethodTools itemId={itemId} type="Tool" />
<BillOfProcess
- key={`bop:${itemId}:${manufacturingRouteData?.methodOperations?.length}`}
+ key={`bop:${itemId}`}
makeMethodId={makeMethodId}
// @ts-ignore
operations={manufacturingRouteData?.methodOperations ?? []}
/>
<BillOfMaterial
- key={`bom:${itemId}:${manufacturingRouteData?.methodMaterials?.length}`}
+ key={`bom:${itemId}`}
makeMethodId={makeMethodId}
// @ts-ignore
materials={manufacturingRouteData?.methodMaterials ?? []}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 4d38e6330d..906b328364 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -447,6 +447,7 @@ export const path = {
generatePath(`${x}/items/methods/operation/${id}`),
methodOperations: `${x}/items/methods/operations`,
methodOperationsOrder: `${x}/items/methods/operation/order`,
+ methodOperationsDelete: `${x}/items/methods/operation/delete`,
methodOperationTool: (id: string) =>
generatePath(`${x}/items/methods/operation/tool/${id}`),
newAbility: `${x}/resources/abilities/new`,