Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: update and delete for operations
Brad Barbinc7b6013286f0
diff --git a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsxindex a862476445..050c266476 100644--- a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx+++ b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx@@ -17,7 +17,7 @@ const GroupedContentSidebar = ({ groups }: { groups: RouteGroup[] }) => {spacing={1}className="border-b border-border p-2">- <h4 className="text-xs text-muted-foreground font-bold pl-4 py-1 uppercase">+ <h4 className="text-xs text-muted-foreground font-mono pl-4 py-1 uppercase">{group.name}</h4>{group.routes.map((route) => {diff --git a/apps/carbon/app/components/SortableList.tsx b/apps/carbon/app/components/SortableList.tsxindex ca6fbd28a9..2552f0ba04 100644--- a/apps/carbon/app/components/SortableList.tsx+++ b/apps/carbon/app/components/SortableList.tsx@@ -29,7 +29,7 @@ interface SortableListItemProps<T> {item: SortableItem<T>;items: SortableItem<T>[];order: number;- onCompleteItem: (id: string) => void;+ onToggleItem: (id: string) => void;onRemoveItem: (id: string) => void;renderExtra?: (item: SortableItem<T>) => React.ReactNode;isExpanded?: boolean;@@ -41,7 +41,7 @@ function SortableListItem<T>({item,items,order,- onCompleteItem,+ onToggleItem,onRemoveItem,renderExtra,handleDrag,@@ -135,7 +135,7 @@ function SortableListItem<T>({checked={item.checked}id={`checkbox-${item.id}`}aria-label="Mark to delete"- onCheckedChange={() => onCompleteItem(item.id)}+ onCheckedChange={() => onToggleItem(item.id)}className=" ml-3 h-5 w-5 rounded-md border-foreground/20 bg-background/30 data-[state=checked]:bg-background data-[state=checked]:text-red-200"/>{/* List Order */}@@ -257,13 +257,13 @@ export type SortableItemRenderProps<T extends Item> = {item: T;items: T[];order: number;- onCompleteItem: (id: string) => void;+ onToggleItem: (id: string) => void;onRemoveItem: (id: string) => void;};interface SortableListProps<T extends Item> {items: T[];- onCompleteItem: (id: string) => void;+ onToggleItem: (id: string) => void;onRemoveItem: (id: string) => void;onReorder: Dispatch<SetStateAction<T[]>>;renderItem: (props: SortableItemRenderProps<T>) => React.ReactNode;@@ -272,7 +272,7 @@ interface SortableListProps<T extends Item> {function SortableList<T extends Item>({items,onRemoveItem,- onCompleteItem,+ onToggleItem,onReorder,renderItem,}: SortableListProps<T>) {@@ -291,7 +291,7 @@ function SortableList<T extends Item>({item,items,order: index,- onCompleteItem,+ onToggleItem,onRemoveItem,}))}@@ -308,6 +308,7 @@ SortableList.displayName = "SortableList";export { SortableList, SortableListItem };function getParallelizedOrder(index: number, item: Item, items: Item[]) {+ console.log({ index, item });if (item?.order !== "With Previous") return index + 1;// traverse backwards through the list of items to find the first item that is not "With Previous" and return its index + 1for (let i = index - 1; i >= 0; i--) {diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.tsindex 3529f6ab24..631405cd6c 100644--- a/apps/carbon/app/modules/items/items.models.ts+++ b/apps/carbon/app/modules/items/items.models.ts@@ -108,7 +108,11 @@ export const methodOperationValidator = z.object({standardFactor: z.enum(standardFactorType, {errorMap: () => ({ message: "Standard factor is required" }),}),- productionStandard: zfd.numeric(z.number().min(0)),+ productionStandard: zfd.numeric(+ z.number().min(0.00000001, {+ message: "Should be greater than 0",+ })+ ),});export const itemCostValidator = z.object({diff --git a/apps/carbon/app/modules/items/ui/Consumables/ConsumableForm.tsx b/apps/carbon/app/modules/items/ui/Consumables/ConsumableForm.tsxindex 41d0583432..302988e7e1 100644--- a/apps/carbon/app/modules/items/ui/Consumables/ConsumableForm.tsx+++ b/apps/carbon/app/modules/items/ui/Consumables/ConsumableForm.tsx@@ -118,20 +118,20 @@ const ConsumableForm = ({)}<Input name="name" label="Name" />- <ItemGroup name="itemGroupId" label="Posting Group" />- {isEditing && (- <TextArea name="description" label="Description" />- )}-<Selectname="itemInventoryType"label="Tracking Type"options={itemInventoryTypeOptions}/>+ {isEditing && (+ <TextArea name="description" label="Description" />+ )}+<UnitOfMeasurename="unitOfMeasureCode"label="Unit of Measure"/>+ <ItemGroup name="itemGroupId" label="Posting Group" /><Boolean name="pullFromInventory" label="Pull from Inventory" /><Boolean name="active" label="Active" />diff --git a/apps/carbon/app/modules/items/ui/Fixtures/FixtureForm.tsx b/apps/carbon/app/modules/items/ui/Fixtures/FixtureForm.tsxindex b9e4d19565..4fa1090674 100644--- a/apps/carbon/app/modules/items/ui/Fixtures/FixtureForm.tsx+++ b/apps/carbon/app/modules/items/ui/Fixtures/FixtureForm.tsx@@ -120,7 +120,7 @@ const FixtureForm = ({)}<Input name="name" label="Name" />- <ItemGroup name="itemGroupId" label="Posting Group" />+ <Customer name="customerId" label="Customer" />{isEditing && (<TextArea name="description" label="Description" />)}@@ -130,7 +130,7 @@ const FixtureForm = ({label="Tracking Type"options={itemInventoryTypeOptions}/>- <Customer name="customerId" label="Customer" />+ <ItemGroup name="itemGroupId" label="Posting Group" /><Boolean name="active" label="Active" /><CustomFormFields table="fixture" />diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsxindex 7e5b2bee24..9ad0fce3c7 100644--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx@@ -14,7 +14,9 @@ import {import { ValidatedForm } from "@carbon/remix-validated-form";import { useFetcher } from "@remix-run/react";import { AnimatePresence, LayoutGroup, motion } from "framer-motion";+import type { Dispatch, SetStateAction } from "react";import { useCallback, useEffect, useState } from "react";+import { flushSync } from "react-dom";import { LuSettings2, LuX } from "react-icons/lu";import type { z } from "zod";import { DirectionAwareTabs } from "~/components/DirectionAwareTabs";@@ -186,16 +188,20 @@ type BillOfProcessProps = {};function makeItems(operations: Operation[]): ItemWithData[] {- return operations.map((operation) => ({+ return operations.map(makeItem);+}++function makeItem(operation: Operation): ItemWithData {+ return {id: operation.id!,text: operation.description ?? "",checked: false,order: operation.operationOrder,data: operation,- }));+ };}-const initialMethodOperation: Omit<Operation, "order"> = {+const initialMethodOperation: Omit<Operation, "makeMethodId" | "order"> = {description: "",workCellTypeId: "",equipmentTypeId: "",@@ -206,13 +212,14 @@ const initialMethodOperation: Omit<Operation, "order"> = {};const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {+ const { supabase } = useSupabase();const [items, setItems] = useState<ItemWithData[]>(makeItems(operations ?? []));- const [openItemId, setOpenItemId] = useState<string | null>(null);+ const [selectedItemId, setSelectedItemId] = useState<string | null>(null);const [tabChangeRerender, setTabChangeRerender] = useState<number>(1);- const onCompleteItem = (id: string) => {+ const onToggleItem = (id: string) => {setItems((prevItems) =>prevItems.map((item) =>item.id === id ? { ...item, checked: !item.checked } : item@@ -220,22 +227,51 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {);};+ // we create a temporary item and append it to the listconst onAddItem = () => {const temporaryId = Math.random().toString(16).slice(2);- setOpenItemId(temporaryId);- setItems((prevItems) => [- ...prevItems,- {- text: "",- checked: false,- id: temporaryId,- data: {- ...initialMethodOperation,- order: prevItems.length + 1,- makeMethodId,+ setSelectedItemId(temporaryId);+ setItems((prevItems) => {+ let newOrder = 1;+ if (prevItems.length) {+ newOrder = prevItems[prevItems.length - 1].data.order + 1;+ }++ return [+ ...prevItems,+ {+ text: "",+ checked: false,+ id: temporaryId,+ data: {+ ...initialMethodOperation,+ order: newOrder,+ makeMethodId,+ },},- },- ]);+ ];+ });+ };++ const onRemoveItem = async (id: string) => {+ // 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 supabase+ ?.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;+ });+ }};const onCloseOnDrag = useCallback(() => {@@ -255,10 +291,10 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {item,items,order,- onCompleteItem,+ onToggleItem,onRemoveItem,}: SortableItemRenderProps<ItemWithData>) => {- const isOpen = item.id === openItemId;+ const isOpen = item.id === selectedItemId;const tabs = [{@@ -276,7 +312,11 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {delay: 0.15,}}>- <OperationForm item={item} setItems={setItems} />+ <OperationForm+ item={item}+ setItems={setItems}+ setSelectedItemId={setSelectedItemId}+ /></motion.div></div>),@@ -314,7 +354,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {order={order}key={item.id}isExpanded={isOpen}- onCompleteItem={onCompleteItem}+ onToggleItem={onToggleItem}onRemoveItem={onRemoveItem}handleDrag={onCloseOnDrag}className="my-2 "@@ -331,16 +371,15 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {onClick={isOpen? () => {- console.log("onClose", item.id, isTemporaryId(item.id));if (isTemporaryId(item.id)) {setItems((prevItems) =>prevItems.filter((i) => i.id !== item.id));}- setOpenItemId(null);+ setSelectedItemId(null);}: () => {- setOpenItemId(item.id);+ setSelectedItemId(item.id);}}key="collapse"@@ -429,7 +468,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {<CardAction><Buttonvariant="secondary"- isDisabled={openItemId !== null}+ isDisabled={selectedItemId !== null}onClick={onAddItem}>Add Operation@@ -440,10 +479,8 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {<SortableListitems={items}onReorder={setItems}- onCompleteItem={onCompleteItem}- onRemoveItem={(id) =>- setItems((prevItems) => prevItems.filter((item) => item.id !== id))- }+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}renderItem={renderListItem}/></CardContent>@@ -460,18 +497,37 @@ function isTemporaryId(id: string) {function OperationForm({item,setItems,+ setSelectedItemId,}: {item: ItemWithData;- setItems: (items: ItemWithData[]) => void;+ setItems: Dispatch<SetStateAction<ItemWithData[]>>;+ setSelectedItemId: Dispatch<SetStateAction<string | null>>;}) {- const methodOperationFetcher = useFetcher();+ const methodOperationFetcher = useFetcher<{ id: string }>();const { supabase } = useSupabase();useEffect(() => {- if (methodOperationFetcher.data) {- console.log({ fetcherData: methodOperationFetcher.data });+ // 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+ )+ );+ });+ setSelectedItemId(null);}- }, [methodOperationFetcher.data]);+ }, [item.id, methodOperationFetcher.data, setItems, setSelectedItemId]);const [workCellData, setWorkCellData] = useState<{workCellTypeId: string;@@ -526,7 +582,7 @@ function OperationForm({action={isTemporaryId(item.id)? path.to.newMethodOperation(item.data.makeMethodId!)- : path.to.methodOperation(item.data.makeMethodId)+ : path.to.methodOperation(item.data.makeMethodId, item.id!)}method="post"defaultValues={item.data}@@ -534,7 +590,11 @@ function OperationForm({className="w-full flex flex-col gap-y-4"fetcher={methodOperationFetcher}onSubmit={(values) => {- console.log({ values });+ setItems((prevItems) =>+ prevItems.map((i) =>+ i.id === item.id ? { ...makeItem(values), id: item.id } : i+ )+ );}}><Hidden name="makeMethodId" />diff --git a/apps/carbon/app/modules/items/ui/Materials/MaterialForm.tsx b/apps/carbon/app/modules/items/ui/Materials/MaterialForm.tsxindex e3d80d694d..4af25c8a1f 100644--- a/apps/carbon/app/modules/items/ui/Materials/MaterialForm.tsx+++ b/apps/carbon/app/modules/items/ui/Materials/MaterialForm.tsx@@ -131,14 +131,13 @@ const MaterialForm = ({label="Substance"options={substances}/>+ {isEditing && (+ <TextArea name="description" label="Description" />+ )}<Select name="materialFormId" label="Form" options={forms} /><Input name="finish" label="Finish" /><Input name="grade" label="Grade" /><Input name="dimensions" label="Dimensions" />- <ItemGroup name="itemGroupId" label="Posting Group" />- {isEditing && (- <TextArea name="description" label="Description" />- )}<Selectname="itemInventoryType"@@ -149,6 +148,7 @@ const MaterialForm = ({name="unitOfMeasureCode"label="Unit of Measure"/>+ <ItemGroup name="itemGroupId" label="Posting Group" /><Boolean name="pullFromInventory" label="Pull from Inventory" /><Boolean name="active" label="Active" />diff --git a/apps/carbon/app/modules/items/ui/Parts/PartForm.tsx b/apps/carbon/app/modules/items/ui/Parts/PartForm.tsxindex 6f75fd3760..aa9f3c35f2 100644--- a/apps/carbon/app/modules/items/ui/Parts/PartForm.tsx+++ b/apps/carbon/app/modules/items/ui/Parts/PartForm.tsx@@ -124,24 +124,25 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {)}<Input name="name" label="Name" />- <ItemGroup name="itemGroupId" label="Posting Group" />+ <Select+ name="itemInventoryType"+ label="Tracking Type"+ options={itemInventoryTypeOptions}+ />{isEditing && (<TextArea name="description" label="Description" />)}+<Selectname="replenishmentSystem"label="Replenishment System"options={partReplenishmentSystemOptions}/>- <Select- name="itemInventoryType"- label="Tracking Type"- options={itemInventoryTypeOptions}- /><UnitOfMeasurename="unitOfMeasureCode"label="Unit of Measure"/>+ <ItemGroup name="itemGroupId" label="Posting Group" /><Boolean name="pullFromInventory" label="Pull from Inventory" /><Boolean name="active" label="Active" />diff --git a/apps/carbon/app/modules/items/ui/Services/ServiceForm.tsx b/apps/carbon/app/modules/items/ui/Services/ServiceForm.tsxindex 5e30358f11..12bf6b4ff3 100644--- a/apps/carbon/app/modules/items/ui/Services/ServiceForm.tsx+++ b/apps/carbon/app/modules/items/ui/Services/ServiceForm.tsx@@ -80,7 +80,6 @@ const ServiceForm = ({ initialValues }: ServiceFormProps) => {/>)}<Input name="name" label="Name" />- <ItemGroup name="itemGroupId" label="Posting Group" /><TextArea name="description" label="Description" /><Select@@ -88,6 +87,7 @@ const ServiceForm = ({ initialValues }: ServiceFormProps) => {label="Service Type"options={serviceTypeOptions}/>+ <ItemGroup name="itemGroupId" label="Posting Group" /><Boolean name="active" label="Active" /><CustomFormFields table="service" />diff --git a/apps/carbon/app/modules/items/ui/Tools/ToolForm.tsx b/apps/carbon/app/modules/items/ui/Tools/ToolForm.tsxindex 37c39ea831..d9e9ceb821 100644--- a/apps/carbon/app/modules/items/ui/Tools/ToolForm.tsx+++ b/apps/carbon/app/modules/items/ui/Tools/ToolForm.tsx@@ -114,20 +114,20 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {)}<Input name="name" label="Name" />- <ItemGroup name="itemGroupId" label="Posting Group" />- {isEditing && (- <TextArea name="description" label="Description" />- )}-<Selectname="itemInventoryType"label="Tracking Type"options={itemInventoryTypeOptions}/>+ {isEditing && (+ <TextArea name="description" label="Description" />+ )}+<UnitOfMeasurename="unitOfMeasureCode"label="Unit of Measure"/>+ <ItemGroup name="itemGroupId" label="Posting Group" /><Boolean name="pullFromInventory" label="Pull from Inventory" /><Boolean name="active" label="Active" />diff --git a/apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operation.$id.tsx b/apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operation.$id.tsxnew file mode 100644index 0000000000..ff49ed5cf3--- /dev/null+++ b/apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operation.$id.tsx@@ -0,0 +1,69 @@+import { validationError, validator } from "@carbon/remix-validated-form";+import { json, type ActionFunctionArgs } from "@remix-run/node";+import {+ methodOperationValidator,+ upsertMethodOperation,+} from "~/modules/items";+import { requirePermissions } from "~/services/auth/auth.server";+import { flash } from "~/services/session.server";+import { setCustomFields } from "~/utils/form";+import { assertIsPost } from "~/utils/http";+import { error } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "parts",+ });++ const { makeMethodId, id } = params;+ if (!makeMethodId) {+ throw new Error("makeMethodId not found");+ }+ if (!id) {+ throw new Error("id not found");+ }++ const formData = await request.formData();+ const validation = await validator(methodOperationValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const updateMethodOperation = await upsertMethodOperation(client, {+ ...validation.data,+ id: id,+ companyId,+ updatedBy: userId,+ customFields: setCustomFields(formData),+ });+ if (updateMethodOperation.error) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(updateMethodOperation.error, "Failed to update method operation")+ )+ );+ }++ const methodOperationId = updateMethodOperation.data?.id;+ if (!methodOperationId) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(updateMethodOperation, "Failed to update method operation")+ )+ );+ }++ return json({ id: methodOperationId });+}diff --git a/apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operations.new.tsx b/apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operation.new.tsxsimilarity index 100%rename from apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operations.new.tsxrename to apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operation.new.tsxdiff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing._index.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing._index.tsxnew file mode 100644index 0000000000..3968f50245--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing._index.tsx@@ -0,0 +1,10 @@+import type { LoaderFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { path } from "~/utils/path";++export async function loader({ params }: LoaderFunctionArgs) {+ const { itemId } = params;+ if (!itemId) throw new Error("Could not find itemId");++ throw redirect(path.to.makeMethod(itemId));+}diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsxnew file mode 100644index 0000000000..95a002207e--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx@@ -0,0 +1,180 @@+import {+ ResizableHandle,+ ResizablePanel,+ ScrollArea,+ VStack,+} from "@carbon/react";+import { validationError, validator } from "@carbon/remix-validated-form";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";+import { json, useLoaderData, useParams } from "@remix-run/react";+import { redirect } from "remix-typedjson";++import {+ BillOfProcess,+ PartManufacturingForm,+ getItemManufacturing,+ getMakeMethod,+ getMethodOperations,+ partManufacturingValidator,+ upsertItemManufacturing,+} from "~/modules/items";+import { requirePermissions } from "~/services/auth/auth.server";+import { flash } from "~/services/session.server";+import { getCustomFields, setCustomFields } from "~/utils/form";+import { assertIsPost } from "~/utils/http";+import { path } from "~/utils/path";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts",+ });++ const { itemId } = params;+ if (!itemId) throw new Error("Could not find itemId");++ const [partManufacturing, makeMethod] = await Promise.all([+ getItemManufacturing(client, itemId, companyId),+ getMakeMethod(client, itemId, companyId),+ ]);++ if (partManufacturing.error) {+ throw redirect(+ path.to.partDetails(itemId),+ await flash(+ request,+ error(partManufacturing.error, "Failed to load part manufacturing")+ )+ );+ }++ if (makeMethod.error) {+ throw redirect(+ path.to.partDetails(itemId),+ await flash(+ request,+ error(makeMethod.error, "Failed to load make method")+ )+ );+ }++ const methodOperations = await getMethodOperations(+ client,+ makeMethod.data.id+ );+ if (methodOperations.error) {+ throw redirect(+ path.to.partDetails(itemId),+ await flash(+ request,+ error(methodOperations.error, "Failed to load method operations")+ )+ );+ }++ return json({+ partManufacturing: partManufacturing.data,+ makeMethod: makeMethod.data,+ methodOperations:+ methodOperations.data?.map((operation) => ({+ ...operation,+ equipmentTypeId: operation.equipmentTypeId ?? undefined,+ })) ?? [],+ });+}++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { itemId } = params;+ if (!itemId) throw new Error("Could not find itemId");++ const formData = await request.formData();+ const validation = await validator(partManufacturingValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const updatePartManufacturing = await upsertItemManufacturing(client, {+ ...validation.data,+ itemId,+ updatedBy: userId,+ customFields: setCustomFields(formData),+ });+ if (updatePartManufacturing.error) {+ throw redirect(+ path.to.part(itemId),+ await flash(+ request,+ error(+ updatePartManufacturing.error,+ "Failed to update part manufacturing"+ )+ )+ );+ }++ throw redirect(+ path.to.partManufacturing(itemId),+ await flash(request, success("Updated part manufacturing"))+ );+}++export default function MakeMethodRoute() {+ const { makeMethod, partManufacturing, methodOperations } =+ useLoaderData<typeof loader>();+ const { itemId } = useParams();+ if (!itemId) throw new Error("Could not find itemId");+ const makeMethodId = makeMethod?.id;+ if (!makeMethodId) throw new Error("Could not find makeMethodId");++ const manufacturingInitialValues = {+ ...partManufacturing,+ lotSize: partManufacturing.lotSize ?? 0,+ ...getCustomFields(partManufacturing.customFields),+ };++ return (+ <>+ <ResizablePanel+ order={2}+ minSize={40}+ defaultSize={60}+ className="border-t border-border"+ >+ <ScrollArea className="h-[calc(100vh-99px)]">+ <VStack spacing={2} className="p-2">+ <PartManufacturingForm+ key={itemId}+ initialValues={manufacturingInitialValues}+ />+ <BillOfProcess+ key={itemId}+ makeMethodId={makeMethodId}+ operations={methodOperations}+ />+ </VStack>+ </ScrollArea>+ </ResizablePanel>+ <ResizableHandle withHandle />+ <ResizablePanel+ order={3}+ minSize={20}+ defaultSize={20}+ className="bg-card"+ >+ <ScrollArea className="h-[calc(100vh-99px)]">+ <VStack spacing={2} className="px-4 py-2">+ <h3 className="text-xs text-muted-foreground">Properties</h3>+ </VStack>+ </ScrollArea>+ </ResizablePanel>+ </>+ );+}diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsxindex d69abd4f4f..101514b5a0 100644--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx@@ -15,27 +15,13 @@ import {} from "@carbon/react";import { TreeView, useTree } from "~/components/TreeView/TreeView";-import { validationError, validator } from "@carbon/remix-validated-form";-import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";-import { useParams } from "@remix-run/react";+import type { LoaderFunctionArgs } from "@remix-run/node";+import { Outlet, useParams } from "@remix-run/react";import { useRef, useState } from "react";import { LuChevronDown, LuChevronUp, LuPlus, LuSearch } from "react-icons/lu";-import { redirect, typedjson, useTypedLoaderData } from "remix-typedjson";-import {- BillOfProcess,- MethodIcon,- PartManufacturingForm,- getItemManufacturing,- getMakeMethod,- partManufacturingValidator,- upsertItemManufacturing,-} from "~/modules/items";+import { typedjson, useTypedLoaderData } from "remix-typedjson";+import { MethodIcon } from "~/modules/items";import { requirePermissions } from "~/services/auth/auth.server";-import { flash } from "~/services/session.server";-import { getCustomFields, setCustomFields } from "~/utils/form";-import { assertIsPost } from "~/utils/http";-import { path } from "~/utils/path";-import { error, success } from "~/utils/result";type Method = {id: string;@@ -55,41 +41,14 @@ type Method = {};export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {+ await requirePermissions(request, {view: "parts",});const { itemId } = params;if (!itemId) throw new Error("Could not find itemId");- const [partManufacturing, makeMethod] = await Promise.all([- getItemManufacturing(client, itemId, companyId),- getMakeMethod(client, itemId, companyId),- ]);-- if (partManufacturing.error) {- throw redirect(- path.to.partDetails(itemId),- await flash(- request,- error(partManufacturing.error, "Failed to load part manufacturing")- )- );- }-- if (makeMethod.error) {- throw redirect(- path.to.partDetails(itemId),- await flash(- request,- error(makeMethod.error, "Failed to load make method")- )- );- }-return typedjson({- partManufacturing: partManufacturing.data,- makeMethod: makeMethod.data,methods: [{id: "1",@@ -160,62 +119,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {});}-export async function action({ request, params }: ActionFunctionArgs) {- assertIsPost(request);- const { client, userId } = await requirePermissions(request, {- update: "parts",- });-- const { itemId } = params;- if (!itemId) throw new Error("Could not find itemId");-- const formData = await request.formData();- const validation = await validator(partManufacturingValidator).validate(- formData- );-- if (validation.error) {- return validationError(validation.error);- }-- const updatePartManufacturing = await upsertItemManufacturing(client, {- ...validation.data,- itemId,- updatedBy: userId,- customFields: setCustomFields(formData),- });- if (updatePartManufacturing.error) {- throw redirect(- path.to.part(itemId),- await flash(- request,- error(- updatePartManufacturing.error,- "Failed to update part manufacturing"- )- )- );- }-- throw redirect(- path.to.partManufacturing(itemId),- await flash(request, success("Updated part manufacturing"))- );-}--export default function Item() {- const { makeMethod, methods, partManufacturing } =- useTypedLoaderData<typeof loader>();+export default function PartManufacturing() {+ const { methods } = useTypedLoaderData<typeof loader>();const { itemId } = useParams();if (!itemId) throw new Error("Could not find itemId");- const makeMethodId = makeMethod?.id;- if (!makeMethodId) throw new Error("Could not find makeMethodId");-- const manufacturingInitialValues = {- ...partManufacturing,- lotSize: partManufacturing.lotSize ?? 0,- ...getCustomFields(partManufacturing.customFields),- };return (<div className="flex flex-grow overflow-hidden">@@ -241,39 +148,7 @@ export default function Item() {</ResizablePanel><ResizableHandle withHandle />- <ResizablePanel- order={2}- minSize={40}- defaultSize={60}- className="border-t border-border"- >- <ScrollArea className="h-[calc(100vh-99px)]">- <VStack spacing={2} className="p-2">- <PartManufacturingForm- key={itemId}- initialValues={manufacturingInitialValues}- />- <BillOfProcess- key={itemId}- makeMethodId={makeMethodId}- operations={[]}- />- </VStack>- </ScrollArea>- </ResizablePanel>- <ResizableHandle withHandle />- <ResizablePanel- order={3}- minSize={20}- defaultSize={20}- className="bg-card"- >- <ScrollArea className="h-[calc(100vh-99px)]">- <VStack spacing={2} className="px-4 py-2">- <h3 className="text-xs text-muted-foreground">Properties</h3>- </VStack>- </ScrollArea>- </ResizablePanel>+ <Outlet /></ResizablePanelGroup>)}</ClientOnly>@@ -299,10 +174,10 @@ function BoMExplorer({nodes,getTreeProps,getNodeProps,- toggleNodeSelection,+ // toggleNodeSelection,toggleExpandNode,expandAllBelowDepth,- toggleExpandLevel,+ // toggleExpandLevel,collapseAllBelowDepth,selectNode,scrollToNode,diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex ba498e5f6b..ba98ad2d8e 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -324,6 +324,8 @@ export const path = {locations: `${x}/resources/locations`,login: "/login",logout: "/logout",+ makeMethod: (id: string) =>+ generatePath(`${x}/part/${id}/manufacturing/method`),material: (id: string) => generatePath(`${x}/material/${id}`),materialCosting: (id: string) =>generatePath(`${x}/material/${id}/costing`),@@ -352,6 +354,8 @@ export const path = {materialSubstance: (id: string) =>generatePath(`${x}/items/substances/${id}`),materialSubstances: `${x}/items/substances`,+ methodOperation: (makeMethodId: string, id: string) =>+ generatePath(`${x}/items/methods/${makeMethodId}/operation/${id}`),newAbility: `${x}/resources/abilities/new`,newAccountingCategory: `${x}/accounting/categories/new`,newAccountingSubcategory: (id: string) =>@@ -395,7 +399,7 @@ export const path = {newLocation: `${x}/resources/locations/new`,newMaterial: `${x}/material/new`,newMethodOperation: (id: string) =>- generatePath(`${x}/items/methods/${id}/operations/new`),+ generatePath(`${x}/items/methods/${id}/operation/new`),newNote: `${x}/shared/notes/new`,newPart: `${x}/part/new`,newItemGroup: `${x}/items/groups/new`,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 839e2d63ca..6255d1c2a5 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -8335,7 +8335,7 @@ export type Database = {createdAt: stringcreatedBy: stringcustomFields: Json | null- description: string | null+ description: stringequipmentTypeId: string | nullid: stringmakeMethodId: string@@ -8353,7 +8353,7 @@ export type Database = {createdAt?: stringcreatedBy: stringcustomFields?: Json | null- description?: string | null+ description: stringequipmentTypeId?: string | nullid?: stringmakeMethodId: string@@ -8371,7 +8371,7 @@ export type Database = {createdAt?: stringcreatedBy?: stringcustomFields?: Json | null- description?: string | null+ description?: stringequipmentTypeId?: string | nullid?: stringmakeMethodId?: string@@ -21638,14 +21638,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 839e2d63ca..6255d1c2a5 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -8335,7 +8335,7 @@ export type Database = {createdAt: stringcreatedBy: stringcustomFields: Json | null- description: string | null+ description: stringequipmentTypeId: string | nullid: stringmakeMethodId: string@@ -8353,7 +8353,7 @@ export type Database = {createdAt?: stringcreatedBy: stringcustomFields?: Json | null- description?: string | null+ description: stringequipmentTypeId?: string | nullid?: stringmakeMethodId: string@@ -8371,7 +8371,7 @@ export type Database = {createdAt?: stringcreatedBy?: stringcustomFields?: Json | null- description?: string | null+ description?: stringequipmentTypeId?: string | nullid?: stringmakeMethodId?: string@@ -21638,14 +21638,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]diff --git a/packages/database/supabase/migrations/20240621114604_method-rls.sql b/packages/database/supabase/migrations/20240621114604_method-rls.sqlindex f3b9076bd1..0e8d0e62e8 100644--- a/packages/database/supabase/migrations/20240621114604_method-rls.sql+++ b/packages/database/supabase/migrations/20240621114604_method-rls.sql@@ -6,3 +6,29 @@ VALUES('methodOperation', 'Items', 'Method Operation'),('methodMaterial', 'Items', 'Method Material');++ALTER TABLE "makeMethod" ADD CONSTRAINT "makeMethod_unique_itemId" UNIQUE ("itemId", "companyId");++DROP TRIGGER IF EXISTS create_part_make_method_related_records ON public.part;+DROP TRIGGER IF EXISTS update_part_make_method_related_records ON public.part;++DROP FUNCTION IF EXISTS public.create_make_method_related_records();+DROP FUNCTION IF EXISTS public.update_make_method_related_records();++CREATE FUNCTION public.create_make_method_related_records()+RETURNS TRIGGER AS $$+BEGIN+ INSERT INTO public."makeMethod"("itemId", "createdBy", "companyId")+ VALUES (new."itemId", new."createdBy", new."companyId");+++ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER create_part_make_method_related_records+ AFTER INSERT on public.part+ FOR EACH ROW EXECUTE PROCEDURE public.create_make_method_related_records();+++ALTER TABLE "methodOperation" ALTER COLUMN "description" SET NOT NULL;