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: method operation creation

Brad Barbin7a58bb39bf7b
diff --git a/apps/carbon/app/components/DirectionAwareTabs.tsx b/apps/carbon/app/components/DirectionAwareTabs.tsx
index d139d10272..3255627af7 100644
--- a/apps/carbon/app/components/DirectionAwareTabs.tsx
+++ b/apps/carbon/app/components/DirectionAwareTabs.tsx
@@ -10,6 +10,7 @@ type Tab = {
id: number;
label: string;
content: ReactNode;
+ disabled?: boolean;
};
interface OgImageSectionProps {
@@ -74,13 +75,15 @@ function DirectionAwareTabs({
{tabs.map((tab) => (
<button
key={tab.id}
+ 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-1 focus-visible:outline-none flex gap-2 items-center ",
activeTab === tab.id
? "text-foreground"
: "hover:text-foreground/60 text-foreground/80",
- rounded
+ rounded,
+ tab.disabled && "cursor-not-allowed opacity-50"
)}
style={{ WebkitTapHighlightColor: "transparent" }}
>
diff --git a/apps/carbon/app/components/SortableList.tsx b/apps/carbon/app/components/SortableList.tsx
index c1cd598442..ca6fbd28a9 100644
--- a/apps/carbon/app/components/SortableList.tsx
+++ b/apps/carbon/app/components/SortableList.tsx
@@ -14,7 +14,7 @@ import useMeasure from "react-use-measure";
import { Checkbox, cn } from "@carbon/react";
import { LuTrash } from "react-icons/lu";
-interface Item {
+export interface Item {
id: string;
text: string;
checked: boolean;
@@ -265,7 +265,7 @@ interface SortableListProps<T extends Item> {
items: T[];
onCompleteItem: (id: string) => void;
onRemoveItem: (id: string) => void;
- onReorder: Dispatch<SetStateAction<Item[]>>;
+ onReorder: Dispatch<SetStateAction<T[]>>;
renderItem: (props: SortableItemRenderProps<T>) => React.ReactNode;
}
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.ts
index a1029aa3f7..3529f6ab24 100644
--- a/apps/carbon/app/modules/items/items.models.ts
+++ b/apps/carbon/app/modules/items/items.models.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
+import { standardFactorType } from "../shared";
export const itemInventoryTypes = ["Inventory", "Non-Inventory"] as const;
export const partReplenishmentSystems = [
@@ -20,6 +21,11 @@ export const itemReorderingPolicies = [
"Maximum Quantity",
] as const;
+export const methodOperationOrders = [
+ "After Previous",
+ "With Previous",
+] as const;
+
export const partManufacturingPolicies = [
"Make to Stock",
"Make to Order",
@@ -44,6 +50,17 @@ export const itemValidator = z.object({
active: zfd.checkbox(),
});
+export const buyMethodValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ itemId: z.string().min(1, { message: "Item ID is required" }),
+ supplierId: z.string().min(36, { message: "Supplier ID is required" }),
+ supplierPartId: z.string().optional(),
+ supplierUnitOfMeasureCode: zfd.text(z.string().optional()),
+ minimumOrderQuantity: zfd.numeric(z.number().min(0)),
+ conversionFactor: zfd.numeric(z.number().min(0)),
+ unitPrice: zfd.numeric(z.number().min(0)),
+});
+
export const consumableValidator = itemValidator.merge(
z.object({
id: z.string().min(1, { message: "Consumable ID is required" }).max(255),
@@ -73,36 +90,26 @@ export const materialValidator = itemValidator.merge(
})
);
-export const partValidator = itemValidator.merge(
- z.object({
- id: z.string().min(1, { message: "Part ID is required" }).max(255),
- replenishmentSystem: z.enum(partReplenishmentSystems, {
- errorMap: (issue, ctx) => ({
- message: "Replenishment system is required",
- }),
- }),
- })
-);
-
-export const serviceValidator = itemValidator.merge(
- z.object({
- id: z.string().min(1, { message: "Service ID is required" }).max(255),
- serviceType: z.enum(serviceType, {
- errorMap: (issue, ctx) => ({
- message: "Service type is required",
- }),
+export const methodOperationValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ makeMethodId: z.string().min(0, { message: "Make method is required" }),
+ order: zfd.numeric(z.number().min(0)),
+ operationOrder: z.enum(methodOperationOrders, {
+ errorMap: (issue, ctx) => ({
+ message: "Operation order is required",
}),
- })
-);
-
-export const toolValidator = itemValidator.merge(
- z.object({
- id: z.string().min(1, { message: "Tool ID is required" }).max(255),
- unitOfMeasureCode: z
- .string()
- .min(1, { message: "Unit of Measure is required" }),
- })
-);
+ }),
+ workCellTypeId: z.string().min(20, { message: "Work cell is required" }),
+ equipmentTypeId: zfd.text(z.string().optional()),
+ description: zfd.text(
+ z.string().min(0, { message: "Description is required" })
+ ),
+ setupHours: zfd.numeric(z.number().min(0)),
+ standardFactor: z.enum(standardFactorType, {
+ errorMap: () => ({ message: "Standard factor is required" }),
+ }),
+ productionStandard: zfd.numeric(z.number().min(0)),
+});
export const itemCostValidator = z.object({
itemId: z.string().min(1, { message: "Item ID is required" }),
@@ -122,31 +129,6 @@ export const itemGroupValidator = z.object({
description: z.string().optional(),
});
-export const pickMethodValidator = z.object({
- itemId: z.string().min(1, { message: "Item ID is required" }),
- locationId: z.string().min(20, { message: "Location is required" }),
- defaultShelfId: zfd.text(z.string().optional()),
-});
-
-export const materialFormValidator = z.object({
- id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Name is required" }).max(255),
-});
-
-export const materialSubstanceValidator = z.object({
- id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Name is required" }).max(255),
-});
-
-export const partManufacturingValidator = z.object({
- itemId: z.string().min(1, { message: "Item ID is required" }),
- manufacturingLeadTime: zfd.numeric(z.number().min(0)),
- manufacturingBlocked: zfd.checkbox(),
- requiresConfiguration: zfd.checkbox(),
- scrapPercentage: zfd.numeric(z.number().min(0).max(100)),
- lotSize: zfd.numeric(z.number().min(0)),
-});
-
export const itemPlanningValidator = z.object({
itemId: z.string().min(1, { message: "Item ID is required" }),
locationId: z.string().min(20, { message: "Location is required" }),
@@ -178,17 +160,6 @@ export const itemPurchasingValidator = z.object({
purchasingBlocked: zfd.checkbox(),
});
-export const buyMethodValidator = z.object({
- id: zfd.text(z.string().optional()),
- itemId: z.string().min(1, { message: "Item ID is required" }),
- supplierId: z.string().min(36, { message: "Supplier ID is required" }),
- supplierPartId: z.string().optional(),
- supplierUnitOfMeasureCode: zfd.text(z.string().optional()),
- minimumOrderQuantity: zfd.numeric(z.number().min(0)),
- conversionFactor: zfd.numeric(z.number().min(0)),
- unitPrice: zfd.numeric(z.number().min(0)),
-});
-
export const itemUnitSalePriceValidator = z.object({
itemId: z.string().min(1, { message: "Item ID is required" }),
unitSalePrice: zfd.numeric(z.number().min(0)),
@@ -201,6 +172,62 @@ export const itemUnitSalePriceValidator = z.object({
allowInvoiceDiscount: zfd.checkbox(),
});
+export const materialFormValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }).max(255),
+});
+
+export const materialSubstanceValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }).max(255),
+});
+
+export const partValidator = itemValidator.merge(
+ z.object({
+ id: z.string().min(1, { message: "Part ID is required" }).max(255),
+ replenishmentSystem: z.enum(partReplenishmentSystems, {
+ errorMap: (issue, ctx) => ({
+ message: "Replenishment system is required",
+ }),
+ }),
+ })
+);
+
+export const partManufacturingValidator = z.object({
+ itemId: z.string().min(1, { message: "Item ID is required" }),
+ manufacturingLeadTime: zfd.numeric(z.number().min(0)),
+ manufacturingBlocked: zfd.checkbox(),
+ requiresConfiguration: zfd.checkbox(),
+ scrapPercentage: zfd.numeric(z.number().min(0).max(100)),
+ lotSize: zfd.numeric(z.number().min(0)),
+});
+
+export const pickMethodValidator = z.object({
+ itemId: z.string().min(1, { message: "Item ID is required" }),
+ locationId: z.string().min(20, { message: "Location is required" }),
+ defaultShelfId: zfd.text(z.string().optional()),
+});
+
+export const serviceValidator = itemValidator.merge(
+ z.object({
+ id: z.string().min(1, { message: "Service ID is required" }).max(255),
+ serviceType: z.enum(serviceType, {
+ errorMap: (issue, ctx) => ({
+ message: "Service type is required",
+ }),
+ }),
+ })
+);
+
+export const toolValidator = itemValidator.merge(
+ z.object({
+ id: z.string().min(1, { message: "Tool ID is required" }).max(255),
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of Measure is required" }),
+ })
+);
+
export const unitOfMeasureValidator = z.object({
id: zfd.text(z.string().optional()),
code: z.string().min(1, { message: "Code is required" }).max(10),
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index b8402af929..bfd8fc9cdb 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -18,6 +18,7 @@ import type {
materialFormValidator,
materialSubstanceValidator,
materialValidator,
+ methodOperationValidator,
partManufacturingValidator,
partValidator,
pickMethodValidator,
@@ -316,6 +317,19 @@ export async function getItemUnitSalePrice(
.single();
}
+export async function getMakeMethod(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ return client
+ .from("makeMethod")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .single();
+}
+
export async function getMaterial(
client: SupabaseClient<Database>,
itemId: string,
@@ -1202,6 +1216,36 @@ export async function upsertItemUnitSalePrice(
.eq("itemId", itemUnitSalePrice.itemId);
}
+export async function upsertMethodOperation(
+ client: SupabaseClient<Database>,
+
+ methodOperation:
+ | (Omit<z.infer<typeof methodOperationValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof methodOperationValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in methodOperation) {
+ return client
+ .from("methodOperation")
+ .insert([methodOperation])
+ .select("id")
+ .single();
+ }
+ return client
+ .from("methodOperation")
+ .update(sanitize(methodOperation))
+ .eq("id", methodOperation.id)
+ .select("id")
+ .single();
+}
+
export async function upsertMaterial(
client: SupabaseClient<Database>,
material:
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index 05d66c750a..7e5b2bee24 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -10,23 +10,33 @@ import {
Editor,
HStack,
cn,
- toast,
} from "@carbon/react";
import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useFetcher } from "@remix-run/react";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
-import { useCallback, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { LuSettings2, LuX } from "react-icons/lu";
+import type { z } from "zod";
import { DirectionAwareTabs } from "~/components/DirectionAwareTabs";
import {
EquipmentType,
+ Hidden,
InputControlled,
Number,
NumberControlled,
+ Select,
StandardFactor,
+ Submit,
WorkCellType,
} from "~/components/Form";
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
+import { useSupabase } from "~/lib/supabase";
+import { path } from "~/utils/path";
+import {
+ methodOperationOrders,
+ methodOperationValidator,
+} from "../../items.models";
export const workInstructions = {
type: "doc",
@@ -164,37 +174,41 @@ export const workInstructions = {
],
};
-type ItemWithData = Item & {};
+type Operation = z.infer<typeof methodOperationValidator>;
-const initialState = [
- {
- id: "1",
- text: "Plasma Cut",
- checked: false,
- order: "After Previous",
- },
- {
- id: "2",
- text: "Deburring",
- checked: false,
- order: "With Previous",
- },
- {
- id: "3",
- text: "Brake Press",
- checked: false,
- order: "After Previous",
- },
- {
- id: "5",
- text: "Paint",
+type ItemWithData = Item & {
+ data: Operation;
+};
+
+type BillOfProcessProps = {
+ makeMethodId: string;
+ operations: Operation[];
+};
+
+function makeItems(operations: Operation[]): ItemWithData[] {
+ return operations.map((operation) => ({
+ id: operation.id!,
+ text: operation.description ?? "",
checked: false,
- order: "After Previous",
- },
-];
+ order: operation.operationOrder,
+ data: operation,
+ }));
+}
-const BillOfProcess = () => {
- const [items, setItems] = useState<ItemWithData[]>(initialState);
+const initialMethodOperation: Omit<Operation, "order"> = {
+ description: "",
+ workCellTypeId: "",
+ equipmentTypeId: "",
+ setupHours: 0,
+ productionStandard: 0,
+ standardFactor: "Hours/Piece",
+ operationOrder: "After Previous",
+};
+
+const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
+ const [items, setItems] = useState<ItemWithData[]>(
+ makeItems(operations ?? [])
+ );
const [openItemId, setOpenItemId] = useState<string | null>(null);
const [tabChangeRerender, setTabChangeRerender] = useState<number>(1);
@@ -207,12 +221,19 @@ const BillOfProcess = () => {
};
const onAddItem = () => {
+ const temporaryId = Math.random().toString(16).slice(2);
+ setOpenItemId(temporaryId);
setItems((prevItems) => [
...prevItems,
{
- text: `Item ${prevItems.length + 1}`,
+ text: "",
checked: false,
- id: Math.random().toString(16).slice(2),
+ id: temporaryId,
+ data: {
+ ...initialMethodOperation,
+ order: prevItems.length + 1,
+ makeMethodId,
+ },
},
]);
};
@@ -255,56 +276,7 @@ const BillOfProcess = () => {
delay: 0.15,
}}
>
- <ValidatedForm className="w-full flex flex-col gap-y-4">
- <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <WorkCellType
- name="workCellTypeId"
- label="Work Cell"
- onChange={(value) => {
- // onWorkCellChange(value?.value as string);
- }}
- />
- <EquipmentType
- name="equipmentTypeId"
- label="Equipment"
- onChange={(value) =>
- // onEquipmentChange(value?.value as string)
- console.log(value)
- }
- />
- </div>
- <InputControlled
- name="description"
- label="Description"
- value={""}
- // value={workCellData.description}
- onChange={(newValue) => {
- // setWorkCellData((d) => ({ ...d, description: newValue }));
- }}
- />
- <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <NumberControlled
- name="setupHours"
- label="Setup Time (hours)"
- minValue={0}
- value={0}
- // value={equipmentData.setupHours}
- onChange={(newValue) => {
- console.log(newValue);
- // setEquipmentData((d) => ({ ...d, setupHours: newValue }));
- }}
- />
- <Number
- name="productionStandard"
- label="Production Standard"
- minValue={0}
- />
- <StandardFactor
- name="standardFactor"
- label="Standard Factor"
- />
- </div>
- </ValidatedForm>
+ <OperationForm item={item} setItems={setItems} />
</motion.div>
</div>
),
@@ -312,6 +284,7 @@ const BillOfProcess = () => {
{
id: 1,
label: "Work Instructions",
+ disabled: isTemporaryId(item.id),
content: (
<div className="flex flex-col p-2">
<motion.div
@@ -335,7 +308,7 @@ const BillOfProcess = () => {
];
return (
- <SortableListItem<ItemWithData>
+ <SortableListItem<Operation>
item={item}
items={items}
order={order}
@@ -355,7 +328,21 @@ const BillOfProcess = () => {
>
<motion.button
layout
- onClick={() => setOpenItemId(!isOpen ? item.id : null)}
+ 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);
+ }
+ : () => {
+ setOpenItemId(item.id);
+ }
+ }
key="collapse"
className={cn(
isOpen
@@ -422,30 +409,6 @@ const BillOfProcess = () => {
/>
</motion.div>
</div>
-
- <motion.div
- key={`re-render-${tabChangeRerender}`} // re-animates the button section on tab change
- className="flex w-full items-center justify-end p-2"
- initial={{ opacity: 0, filter: "blur(4px)" }}
- animate={{ opacity: 1, filter: "blur(0px)" }}
- transition={{
- type: "spring",
- bounce: 0,
- duration: 0.55,
- }}
- >
- <motion.div layout className="ml-auto mr-1 pt-2">
- <Button
- size="sm"
- onClick={() => {
- setOpenItemId(null);
- toast.info("Changes saved");
- }}
- >
- Save
- </Button>
- </motion.div>
- </motion.div>
</motion.div>
) : null}
</AnimatePresence>
@@ -464,7 +427,11 @@ const BillOfProcess = () => {
</CardHeader>
<CardAction>
- <Button variant="secondary" onClick={onAddItem}>
+ <Button
+ variant="secondary"
+ isDisabled={openItemId !== null}
+ onClick={onAddItem}
+ >
Add Operation
</Button>
</CardAction>
@@ -485,3 +452,155 @@ const BillOfProcess = () => {
};
export default BillOfProcess;
+
+function isTemporaryId(id: string) {
+ return id.length < 20;
+}
+
+function OperationForm({
+ item,
+ setItems,
+}: {
+ item: ItemWithData;
+ setItems: (items: ItemWithData[]) => void;
+}) {
+ const methodOperationFetcher = useFetcher();
+ const { supabase } = useSupabase();
+
+ useEffect(() => {
+ if (methodOperationFetcher.data) {
+ console.log({ fetcherData: methodOperationFetcher.data });
+ }
+ }, [methodOperationFetcher.data]);
+
+ const [workCellData, setWorkCellData] = useState<{
+ workCellTypeId: string;
+ description: string;
+ }>({
+ workCellTypeId: item.data.workCellTypeId ?? "",
+ description: item.data.description ?? "",
+ });
+
+ const onWorkCellChange = async (workCellTypeId: string) => {
+ if (!supabase || !workCellTypeId) return;
+ const { data, error } = await supabase
+ .from("workCellType")
+ .select("*")
+ .eq("id", workCellTypeId)
+ .single();
+
+ if (error) throw new Error(error.message);
+
+ setWorkCellData({
+ workCellTypeId,
+ description: data?.name ?? "",
+ });
+ };
+
+ const [equipmentData, setEquipmentData] = useState<{
+ equipmentTypeId: string;
+ setupHours: number;
+ }>({
+ equipmentTypeId: item.data.equipmentTypeId ?? "",
+ setupHours: item.data.setupHours ?? 0,
+ });
+
+ const onEquipmentChange = async (equipmentTypeId: string) => {
+ if (!supabase || !equipmentTypeId) return;
+ const { data, error } = await supabase
+ .from("equipmentType")
+ .select("*")
+ .eq("id", equipmentTypeId)
+ .single();
+
+ if (error) throw new Error(error.message);
+
+ setEquipmentData({
+ equipmentTypeId,
+ setupHours: data?.setupHours ?? 0,
+ });
+ };
+
+ return (
+ <ValidatedForm
+ action={
+ isTemporaryId(item.id)
+ ? path.to.newMethodOperation(item.data.makeMethodId!)
+ : path.to.methodOperation(item.data.makeMethodId)
+ }
+ method="post"
+ defaultValues={item.data}
+ validator={methodOperationValidator}
+ className="w-full flex flex-col gap-y-4"
+ fetcher={methodOperationFetcher}
+ onSubmit={(values) => {
+ console.log({ values });
+ }}
+ >
+ <Hidden name="makeMethodId" />
+ <Hidden name="order" />
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ <WorkCellType
+ name="workCellTypeId"
+ label="Work Cell"
+ onChange={(value) => {
+ onWorkCellChange(value?.value as string);
+ }}
+ />
+ <EquipmentType
+ name="equipmentTypeId"
+ label="Equipment"
+ onChange={(value) => onEquipmentChange(value?.value as string)}
+ />
+ <Select
+ name="operationOrder"
+ label="Operation Order"
+ placeholder="Operation Order"
+ options={methodOperationOrders.map((o) => ({
+ value: o,
+ label: o,
+ }))}
+ />
+ </div>
+ <InputControlled
+ name="description"
+ label="Description"
+ value={workCellData.description}
+ onChange={(newValue) => {
+ setWorkCellData((d) => ({ ...d, description: newValue }));
+ }}
+ />
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ <NumberControlled
+ name="setupHours"
+ label="Setup Time (hours)"
+ minValue={0}
+ value={equipmentData.setupHours}
+ onChange={(newValue) => {
+ setEquipmentData((d) => ({ ...d, setupHours: newValue }));
+ }}
+ />
+ <Number
+ name="productionStandard"
+ label="Production Standard"
+ minValue={0}
+ />
+ <StandardFactor name="standardFactor" label="Standard Factor" />
+ </div>
+ <motion.div
+ className="flex w-full items-center justify-end p-2"
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ bounce: 0,
+ duration: 0.55,
+ }}
+ >
+ <motion.div layout className="ml-auto mr-1 pt-2">
+ <Submit>Save</Submit>
+ </motion.div>
+ </motion.div>
+ </ValidatedForm>
+ );
+}
diff --git a/apps/carbon/app/modules/resources/ui/Departments/DepartmentForm.tsx b/apps/carbon/app/modules/resources/ui/Departments/DepartmentForm.tsx
index c46ea0c2d0..be2dfa36c6 100644
--- a/apps/carbon/app/modules/resources/ui/Departments/DepartmentForm.tsx
+++ b/apps/carbon/app/modules/resources/ui/Departments/DepartmentForm.tsx
@@ -48,9 +48,9 @@ const DepartmentForm = ({
if (fetcher.state === "loading" && fetcher.data?.data) {
onClose?.();
- toast.success(`Created location`);
+ toast.success(`Created department`);
} else if (fetcher.state === "idle" && fetcher.data?.error) {
- toast.error(`Failed to create location: ${fetcher.data.error.message}`);
+ toast.error(`Failed to create department: ${fetcher.data.error.message}`);
}
}, [fetcher.data, fetcher.state, onClose, type]);
diff --git a/apps/carbon/app/modules/resources/ui/Equipment/EquipmentTypeForm.tsx b/apps/carbon/app/modules/resources/ui/Equipment/EquipmentTypeForm.tsx
index c722d04c3f..7e0f2d696e 100644
--- a/apps/carbon/app/modules/resources/ui/Equipment/EquipmentTypeForm.tsx
+++ b/apps/carbon/app/modules/resources/ui/Equipment/EquipmentTypeForm.tsx
@@ -50,9 +50,11 @@ const EquipmentTypeForm = ({
if (fetcher.state === "loading" && fetcher.data?.data) {
onClose?.();
- toast.success(`Created location`);
+ toast.success(`Created equipment type`);
} else if (fetcher.state === "idle" && fetcher.data?.error) {
- toast.error(`Failed to create location: ${fetcher.data.error.message}`);
+ toast.error(
+ `Failed to create equipment type: ${fetcher.data.error.message}`
+ );
}
}, [fetcher.data, fetcher.state, onClose, type]);
diff --git a/apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operations.new.tsx b/apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operations.new.tsx
new file mode 100644
index 0000000000..21c59f290d
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/methods.$makeMethodId.operations.new.tsx
@@ -0,0 +1,67 @@
+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 } = params;
+ if (!makeMethodId) {
+ throw new Error("makeMethodId not found");
+ }
+
+ const formData = await request.formData();
+ const validation = await validator(methodOperationValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const insertMethodOperation = await upsertMethodOperation(client, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (insertMethodOperation.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insertMethodOperation.error, "Failed to insert method operation")
+ )
+ );
+ }
+
+ const methodOperationId = insertMethodOperation.data?.id;
+ if (!methodOperationId) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insertMethodOperation, "Failed to insert method operation")
+ )
+ );
+ }
+
+ return json({ id: methodOperationId });
+}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx
index a8cfaec621..d69abd4f4f 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx
@@ -26,6 +26,7 @@ import {
MethodIcon,
PartManufacturingForm,
getItemManufacturing,
+ getMakeMethod,
partManufacturingValidator,
upsertItemManufacturing,
} from "~/modules/items";
@@ -61,15 +62,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { itemId } = params;
if (!itemId) throw new Error("Could not find itemId");
- const partManufacturing = await getItemManufacturing(
- client,
- itemId,
- companyId
- );
+ const [partManufacturing, makeMethod] = await Promise.all([
+ getItemManufacturing(client, itemId, companyId),
+ getMakeMethod(client, itemId, companyId),
+ ]);
if (partManufacturing.error) {
throw redirect(
- path.to.items,
+ path.to.partDetails(itemId),
await flash(
request,
error(partManufacturing.error, "Failed to load part manufacturing")
@@ -77,8 +77,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ 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",
@@ -193,9 +204,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function Item() {
- const { methods, partManufacturing } = useTypedLoaderData<typeof loader>();
+ const { makeMethod, methods, partManufacturing } =
+ 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,
@@ -239,7 +253,11 @@ export default function Item() {
key={itemId}
initialValues={manufacturingInitialValues}
/>
- <BillOfProcess key={itemId} processes={[]} />
+ <BillOfProcess
+ key={itemId}
+ makeMethodId={makeMethodId}
+ operations={[]}
+ />
</VStack>
</ScrollArea>
</ResizablePanel>
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index a28bf52161..ba498e5f6b 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -394,6 +394,8 @@ export const path = {
newHoliday: `${x}/resources/holidays/new`,
newLocation: `${x}/resources/locations/new`,
newMaterial: `${x}/material/new`,
+ newMethodOperation: (id: string) =>
+ generatePath(`${x}/items/methods/${id}/operations/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.ts
index 46e1274d08..839e2d63ca 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -8173,6 +8173,7 @@ export type Database = {
companyId: string
createdAt: string
createdBy: string
+ customFields: Json | null
id: string
itemId: string
itemType: string
@@ -8187,6 +8188,7 @@ export type Database = {
companyId: string
createdAt?: string
createdBy: string
+ customFields?: Json | null
id?: string
itemId: string
itemType?: string
@@ -8201,6 +8203,7 @@ export type Database = {
companyId?: string
createdAt?: string
createdBy?: string
+ customFields?: Json | null
id?: string
itemId?: string
itemType?: string
@@ -8331,6 +8334,7 @@ export type Database = {
companyId: string
createdAt: string
createdBy: string
+ customFields: Json | null
description: string | null
equipmentTypeId: string | null
id: string
@@ -8348,6 +8352,7 @@ export type Database = {
companyId: string
createdAt?: string
createdBy: string
+ customFields?: Json | null
description?: string | null
equipmentTypeId?: string | null
id?: string
@@ -8365,6 +8370,7 @@ export type Database = {
companyId?: string
createdAt?: string
createdBy?: string
+ customFields?: Json | null
description?: string | null
equipmentTypeId?: string | null
id?: string
@@ -21632,14 +21638,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"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 46e1274d08..839e2d63ca 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -8173,6 +8173,7 @@ export type Database = {
companyId: string
createdAt: string
createdBy: string
+ customFields: Json | null
id: string
itemId: string
itemType: string
@@ -8187,6 +8188,7 @@ export type Database = {
companyId: string
createdAt?: string
createdBy: string
+ customFields?: Json | null
id?: string
itemId: string
itemType?: string
@@ -8201,6 +8203,7 @@ export type Database = {
companyId?: string
createdAt?: string
createdBy?: string
+ customFields?: Json | null
id?: string
itemId?: string
itemType?: string
@@ -8331,6 +8334,7 @@ export type Database = {
companyId: string
createdAt: string
createdBy: string
+ customFields: Json | null
description: string | null
equipmentTypeId: string | null
id: string
@@ -8348,6 +8352,7 @@ export type Database = {
companyId: string
createdAt?: string
createdBy: string
+ customFields?: Json | null
description?: string | null
equipmentTypeId?: string | null
id?: string
@@ -8365,6 +8370,7 @@ export type Database = {
companyId?: string
createdAt?: string
createdBy?: string
+ customFields?: Json | null
description?: string | null
equipmentTypeId?: string | null
id?: string
@@ -21632,14 +21638,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"]
diff --git a/packages/database/supabase/migrations/20240621114604_method-rls.sql b/packages/database/supabase/migrations/20240621114604_method-rls.sql
new file mode 100644
index 0000000000..f3b9076bd1
--- /dev/null
+++ b/packages/database/supabase/migrations/20240621114604_method-rls.sql
@@ -0,0 +1,8 @@
+ALTER TABLE "methodOperation" ADD COLUMN "customFields" JSONB;
+ALTER TABLE "methodMaterial" ADD COLUMN "customFields" JSONB;
+
+INSERT INTO "customFieldTable" ("table", "module", "name")
+VALUES
+ ('methodOperation', 'Items', 'Method Operation'),
+ ('methodMaterial', 'Items', 'Method Material');
+