Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add mechanism for disabling bill of process and bill of materials
Brad Barbindcfa1c136bad
diff --git a/apps/erp/app/components/SortableList.tsx b/apps/erp/app/components/SortableList.tsxindex 6ce3b6b4fa..9b170c5960 100644--- a/apps/erp/app/components/SortableList.tsx+++ b/apps/erp/app/components/SortableList.tsx@@ -35,6 +35,7 @@ interface SortableListItemProps<T> {isHighlighted?: boolean;className?: string;handleDrag: () => void;+ isReadOnly?: boolean;}function SortableListItem<T>({@@ -49,14 +50,15 @@ function SortableListItem<T>({isExpanded,isHighlighted,className,+ isReadOnly = false,}: SortableListItemProps<T>) {const [isDragging, setIsDragging] = useState(false);- const [isDraggable] = useState(!isExpanded);+ const [isDraggable] = useState(!isExpanded && !isReadOnly);const dragControls = useDragControls();const itemRef = useRef<HTMLDivElement>(null);const handleDragStart = (event: any) => {- if (isExpanded) return;+ if (isExpanded || isReadOnly) return;flushSync(() => setIsDragging(true));dragControls.start(event, { snapToCursor: true });handleDrag();@@ -85,12 +87,12 @@ function SortableListItem<T>({"relative z-auto grow","h-full rounded-md bg-muted/30","border border-border rounded-lg ",- !isExpanded && "cursor-grab",+ !isExpanded && !isReadOnly && "cursor-grab",isHighlighted && "border-2 border-primary",item.checked && !isDragging ? "w-7/10" : "w-full")}key={item.id}- dragListener={!item.checked && !isExpanded}+ dragListener={!item.checked && !isExpanded && !isReadOnly}dragControls={dragControls}onDragEnd={handleDragEnd}style={@@ -116,15 +118,17 @@ function SortableListItem<T>({>{!isExpanded ? (<div className="flex flex-col w-full">- <div className="flex w-full items-center gap-x-2 truncate">+ <div className="flex w-full items-center gap-x-2 truncate pl-3">{/* List Remove Actions */}- <Checkbox- checked={item.checked}- id={`checkbox-${item.id}`}- aria-label="Mark to delete"- onCheckedChange={() => onToggleItem(item.id)}- className="ml-3 border-foreground/20 bg-background/30 data-[state=checked]:bg-background data-[state=checked]:text-red-200 flex flex-shrink-0 "- />+ {!isReadOnly && (+ <Checkbox+ checked={item.checked}+ id={`checkbox-${item.id}`}+ aria-label="Mark to delete"+ onCheckedChange={() => onToggleItem(item.id)}+ className="border-foreground/20 bg-background/30 data-[state=checked]:bg-background data-[state=checked]:text-red-200 flex flex-shrink-0 "+ />+ )}{/* List Order */}<p className="font-medium text-xs pl-1 text-foreground/50 flex flex-shrink-0">{getParallelizedOrder(order, item, items)}@@ -135,7 +139,12 @@ function SortableListItem<T>({className="px-1 flex flex-grow truncate"role="button">- <HStack className="w-full justify-between cursor-grab">+ <HStack+ className={cn(+ "w-full justify-between",+ !isReadOnly && "cursor-grab"+ )}+ >{/* List Title */}{typeof item.title === "string" ? (<span@@ -184,16 +193,20 @@ function SortableListItem<T>({</div>)}</div>- <div- onPointerDown={isDraggable ? handleDragStart : undefined}- style={{ touchAction: "none" }}- />+ {!isReadOnly && (+ <div+ onPointerDown={isDraggable ? handleDragStart : undefined}+ style={{ touchAction: "none" }}+ />+ )}</Reorder.Item>{/* List Delete Action Animation */}- {item.checked ? <div className="h-[1.5rem] w-3" /> : null}+ {!isReadOnly && item.checked ? (+ <div className="h-[1.5rem] w-3" />+ ) : null}- {item.checked ? (+ {!isReadOnly && item.checked ? (<div className="inset-0 z-0 rounded-full bg-card border-border border dark:shadow-[0_1px_0_0_rgba(255,255,255,0.03)_inset,0_0_0_1px_rgba(255,255,255,0.03)_inset,0_0_0_1px_rgba(0,0,0,0.1),0_2px_2px_0_rgba(0,0,0,0.1),0_4px_4px_0_rgba(0,0,0,0.1),0_8px_8px_0_rgba(0,0,0,0.1)] dark:bg-[#161716]/50"><buttonclassName="inline-flex h-10 items-center justify-center space-nowrap rounded-md px-3 text-sm font-medium transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"@@ -222,6 +235,7 @@ interface SortableListProps<T extends Item> {onRemoveItem: (id: string) => void;onReorder: (items: T[]) => void;renderItem: (props: SortableItemRenderProps<T>) => React.ReactNode;+ isReadOnly?: boolean;}function SortableList<T extends Item>({@@ -230,6 +244,7 @@ function SortableList<T extends Item>({onToggleItem,onReorder,renderItem,+ isReadOnly = false,}: SortableListProps<T>) {if (items && Array.isArray(items) && items.length > 0) {return (@@ -237,7 +252,7 @@ function SortableList<T extends Item>({<Reorder.Groupaxis="y"values={items}- onReorder={onReorder}+ onReorder={isReadOnly ? () => {} : onReorder}className="flex flex-col">{items?.map((item, index) =>@@ -263,12 +278,10 @@ export { SortableList, SortableListItem };function getParallelizedOrder(index: number, item: Item, items: 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--) {if (items[i].order !== "With Previous") {return i + 1;}}-return 1;}diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsxindex 3b1478cee1..4215e7f8ca 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -37,6 +37,7 @@ import { useCallback, useEffect, useState } from "react";import { flushSync } from "react-dom";import {LuChevronDown,+ LuLock,LuSettings2,LuSquareFunction,LuX,@@ -73,7 +74,11 @@ import { useBom } from "~/stores";import { path } from "~/utils/path";import type { methodOperationValidator } from "../../items.models";import { methodMaterialValidator } from "../../items.models";-import type { ConfigurationParameter, ConfigurationRule } from "../../types";+import type {+ ConfigurationParameter,+ ConfigurationRule,+ MakeMethod,+} from "../../types";type Material = z.infer<typeof methodMaterialValidator> & {description: string;@@ -91,7 +96,7 @@ type ItemWithData = SortableItem & {type BillOfMaterialProps = {configurable?: boolean;- makeMethodId: string;+ makeMethod: MakeMethod;materials: Material[];operations: Operation[];parameters?: ConfigurationParameter[];@@ -126,15 +131,22 @@ const initialMethodMaterial: Omit<Material, "makeMethodId" | "order"> & {const BillOfMaterial = ({configurable = false,configurationRules,- makeMethodId,+ makeMethod,materials: initialMaterials,operations,parameters,}: BillOfMaterialProps) => {- const fetcher = useFetcher<{}>();const permissions = usePermissions();+ const isReadOnly =+ permissions.can("update", "parts") === false ||+ makeMethod.status === "Active";++ const fetcher = useFetcher<{}>();const [searchParams] = useSearchParams();++ const makeMethodId = makeMethod.id;const materialId = searchParams.get("materialId");+const [selectedItemId, setSelectedItemId] = useState<string | null>(null);const [temporaryItems, setTemporaryItems] = useState<TemporaryItems>({});const [checkedState, setCheckedState] = useState<CheckedState>({});@@ -186,7 +198,7 @@ const BillOfMaterial = ({).sort((a, b) => a.data.order - b.data.order);const onToggleItem = (id: string) => {- if (!permissions.can("update", "parts")) return;+ if (isReadOnly) return;setCheckedState((prev) => ({...prev,[id]: !prev[id],@@ -194,7 +206,7 @@ const BillOfMaterial = ({};const onAddItem = () => {- if (!permissions.can("update", "parts")) return;+ if (isReadOnly) return;const temporaryId = Math.random().toString(16).slice(2);setSelectedItemId(temporaryId);@@ -220,7 +232,7 @@ const BillOfMaterial = ({};const onRemoveItem = async (id: string) => {- if (!permissions.can("update", "parts")) return;+ if (isReadOnly) return;if (isTemporaryId(id)) {setTemporaryItems((prev) => {@@ -252,7 +264,7 @@ const BillOfMaterial = ({}, 1000);const onReorder = (items: ItemWithData[]) => {- if (!permissions.can("update", "parts")) return;+ if (isReadOnly) return;// Create new order stateconst newOrderState = items.reduce<OrderState>((acc, item, index) => {@@ -311,6 +323,7 @@ const BillOfMaterial = ({return (<SortableListItem<Material>+ isReadOnly={isReadOnly}item={item}items={items}order={order}@@ -410,6 +423,7 @@ const BillOfMaterial = ({><MaterialFormconfigurable={configurable}+ isReadOnly={isReadOnly}item={item}methodOperations={operations}orderState={orderState}@@ -453,16 +467,16 @@ const BillOfMaterial = ({<Card><HStack className="justify-between"><CardHeader>- <CardTitle>Bill of Material</CardTitle>+ <CardTitle className="flex flex-row items-center gap-2">+ Bill of Material {isReadOnly && <LuLock />}+ </CardTitle></CardHeader><CardAction><div className="flex items-center gap-2"><Buttonvariant="secondary"- isDisabled={- !permissions.can("update", "parts") || selectedItemId !== null- }+ isDisabled={isReadOnly || selectedItemId !== null}onClick={onAddItem}>Add Material@@ -497,6 +511,7 @@ const BillOfMaterial = ({</HStack><CardContent><SortableList+ isReadOnly={isReadOnly}items={materials}onReorder={onReorder}onToggleItem={onToggleItem}@@ -524,6 +539,7 @@ function isTemporaryId(id: string) {function MaterialForm({configurable,+ isReadOnly,item,methodOperations,rulesByField,@@ -533,6 +549,7 @@ function MaterialForm({setTemporaryItems,}: {configurable: boolean;+ isReadOnly: boolean;item: ItemWithData;methodOperations: Operation[];orderState: OrderState;@@ -547,7 +564,7 @@ function MaterialForm({const methodMaterialFetcher = useFetcher<{ id: string }>();const params = useParams();const { company } = useUser();- const permissions = usePermissions();+const unitOfMeasures = useUnitOfMeasure();useEffect(() => {@@ -853,9 +870,7 @@ function MaterialForm({<div />)}- <Submit isDisabled={!permissions.can("update", "parts")}>- Save- </Submit>+ <Submit isDisabled={isReadOnly}>Save</Submit></motion.div></motion.div></VStack>diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsxindex 1ef8e52d90..7523f11fe3 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx@@ -50,6 +50,7 @@ import {LuHammer,LuInfo,LuList,+ LuLock,LuMaximize2,LuMinimize2,LuSettings2,@@ -117,7 +118,11 @@ import { ProcedureAttributeTypeIcon } from "~/components/Icons";import { useTools } from "~/stores";import { getPrivateUrl, path } from "~/utils/path";import { methodOperationValidator } from "../../items.models";-import type { ConfigurationParameter, ConfigurationRule } from "../../types";+import type {+ ConfigurationParameter,+ ConfigurationRule,+ MakeMethod,+} from "../../types";type Operation = z.infer<typeof methodOperationValidator> & {workInstruction: JSONContent | null;@@ -131,7 +136,7 @@ type ItemWithData = Item & {type BillOfProcessProps = {configurable?: boolean;configurationRules?: ConfigurationRule[];- makeMethodId: string;+ makeMethod: MakeMethod;operations: (Operation & {methodOperationTool: OperationTool[];methodOperationParameter: OperationParameter[];@@ -180,12 +185,18 @@ const initialOperation: Omit<Operation, "makeMethodId" | "order" | "tools"> = {const BillOfProcess = ({configurable = false,configurationRules,- makeMethodId,+ makeMethod,operations: initialOperations,parameters,tags,}: BillOfProcessProps) => {const permissions = usePermissions();+ const isReadOnly =+ permissions.can("update", "parts") === false ||+ makeMethod.status === "Active";++ const makeMethodId = makeMethod.id;+const { carbon } = useCarbon();const sortOrderFetcher = useFetcher<{}>();const deleteOperationFetcher = useFetcher<{ success: boolean }>();@@ -306,7 +317,7 @@ const BillOfProcess = ({};const onToggleItem = (id: string) => {- if (!permissions.can("update", "parts")) return;+ if (isReadOnly) return;setCheckedState((prev) => ({...prev,[id]: !prev[id],@@ -314,7 +325,7 @@ const BillOfProcess = ({};const onReorder = (items: ItemWithData[]) => {- if (!permissions.can("update", "parts")) return;+ if (isReadOnly) return;// Create new order stateconst newOrderState = items.reduce<OrderState>((acc, item, index) => {@@ -374,7 +385,7 @@ const BillOfProcess = ({};const onRemoveItem = async (id: string) => {- if (!permissions.can("update", "parts")) return;+ if (isReadOnly) return;const operation = operationsById.get(id);if (!operation) return;@@ -443,6 +454,7 @@ const BillOfProcess = ({}}><OperationForm+ isReadOnly={isReadOnly}configurable={configurable}item={item}rulesByField={rulesByField}@@ -479,14 +491,14 @@ const BillOfProcess = ({content: (<div className="flex flex-col"><div>- {permissions.can("update", "parts") ? (+ {!isReadOnly ? (<EditorinitialValue={workInstructions[item.id] ?? ({} as JSONContent)}onUpload={onUploadImage}onChange={(content) => {- if (!permissions.can("update", "parts")) return;+ if (isReadOnly) return;setWorkInstructions((prev) => ({...prev,[item.id]: content,@@ -610,6 +622,7 @@ const BillOfProcess = ({return (<SortableListItem<Operation>+ isReadOnly={isReadOnly}item={item}items={items}order={order}@@ -737,16 +750,16 @@ const BillOfProcess = ({<Card><HStack className="justify-between"><CardHeader>- <CardTitle>Bill of Process</CardTitle>+ <CardTitle className="flex flex-row items-center gap-2">+ Bill of Process {isReadOnly && <LuLock />}+ </CardTitle></CardHeader><CardAction><div className="flex items-center gap-2"><Buttonvariant="secondary"- isDisabled={- !permissions.can("update", "parts") || selectedItemId !== null- }+ isDisabled={isReadOnly || selectedItemId !== null}onClick={onAddItem}>Add Operation@@ -781,6 +794,7 @@ const BillOfProcess = ({</HStack><CardContent><SortableList+ isReadOnly={isReadOnly}items={items}onReorder={onReorder}onToggleItem={onToggleItem}@@ -809,6 +823,7 @@ function isTemporaryId(id: string) {type OperationFormProps = {configurable: boolean;+ isReadOnly: boolean;item: ItemWithData;rulesByField: Map<string, ConfigurationRule>;workInstruction: JSONContent;@@ -819,6 +834,7 @@ type OperationFormProps = {};function OperationForm({+ isReadOnly,configurable,item,rulesByField,@@ -831,7 +847,7 @@ function OperationForm({const methodOperationFetcher = useFetcher<{ id: string }>();const { id: userId, company } = useUser();const { carbon } = useCarbon();- const permissions = usePermissions();+const addingWorkInstruction = useRef(false);const baseCurrency = company?.baseCurrencyCode ?? "USD";@@ -1632,7 +1648,7 @@ function OperationForm({}}><motion.div layout className="ml-auto mr-1 pt-2">- <Submit isDisabled={!permissions.can("update", "parts")}>Save</Submit>+ <Submit isDisabled={isReadOnly}>Save</Submit></motion.div></motion.div></ValidatedForm>diff --git a/apps/erp/app/routes/x+/items+/methods+/version.new.tsx b/apps/erp/app/routes/x+/items+/methods+/version.new.tsxnew file mode 100644index 0000000000..91ddff9cdb--- /dev/null+++ b/apps/erp/app/routes/x+/items+/methods+/version.new.tsx@@ -0,0 +1,64 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";+import {+ makeMethodVersionValidator,+ upsertMakeMethodVersion,+} from "~/modules/items";+import { path, requestReferrer } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "parts",+ });++ const formData = await request.formData();+ const validation = await validator(makeMethodVersionValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const insertMethodOperation = await upsertMakeMethodVersion(client, {+ ...validation.data,+ companyId,+ createdBy: userId,+ });+ if (insertMethodOperation.error) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(insertMethodOperation.error, "Failed to insert new version")+ )+ );+ }++ const methodOperationId = insertMethodOperation.data?.id;+ if (!methodOperationId) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(insertMethodOperation, "Failed to insert new version")+ )+ );+ }++ const redirectFrom = requestReferrer(request);+ const redirectTo = redirectFrom?.replace(+ validation.data.copyFromId,+ methodOperationId+ );++ return redirect(redirectTo ?? path.to.items);+}diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.$makeMethodId.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.$makeMethodId.tsxindex 24b9cd33f7..273c1b303b 100644--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.$makeMethodId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.$makeMethodId.tsx@@ -156,7 +156,7 @@ export default function MethodMaterialMakePage() {<BillOfProcesskey={`bop:${itemId}`}- makeMethodId={makeMethodId}+ makeMethod={makeMethod}// @ts-ignoreoperations={methodOperations}configurable={routeData?.partManufacturing.requiresConfiguration}@@ -166,7 +166,7 @@ export default function MethodMaterialMakePage() {/><BillOfMaterialkey={`bom:${itemId}`}- makeMethodId={makeMethodId}+ makeMethod={makeMethod}materials={methodMaterials}operations={methodOperations}configurable={routeData?.partManufacturing.requiresConfiguration}@@ -178,7 +178,7 @@ export default function MethodMaterialMakePage() {{(model) => (<CadModelkey={`cad:${model.itemId}`}- isReadOnly={!permissions.can("update", "sales")}+ isReadOnly={!permissions.can("update", "parts")}metadata={{itemId: model?.itemId ?? undefined,}}diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.method.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.method.tsxindex 95d131c7b5..93795ff7e7 100644--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.method.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.method.tsx@@ -161,7 +161,7 @@ export default function MakeMethodRoute() {<BillOfProcesskey={`bop:${itemId}`}- makeMethodId={makeMethodId}+ makeMethod={manufacturingRouteData?.makeMethod}// @ts-ignoreoperations={manufacturingRouteData?.methodOperations ?? []}configurable={@@ -175,7 +175,7 @@ export default function MakeMethodRoute() {/><BillOfMaterialkey={`bom:${itemId}`}- makeMethodId={makeMethodId}+ makeMethod={manufacturingRouteData?.makeMethod}// @ts-ignorematerials={manufacturingRouteData?.methodMaterials ?? []}// @ts-ignorediff --git a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.$makeMethodId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.$makeMethodId.tsxindex 23f918d1d6..07ab3630c5 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.$makeMethodId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.$makeMethodId.tsx@@ -137,7 +137,7 @@ export default function MethodMaterialMakePage() {<BillOfProcesskey={`bop:${itemId}`}- makeMethodId={makeMethodId}+ makeMethod={makeMethod}// @ts-ignoreoperations={methodOperations}// configurable={routeData?.toolManufacturing.requiresConfiguration}@@ -147,7 +147,7 @@ export default function MethodMaterialMakePage() {/><BillOfMaterialkey={`bom:${itemId}`}- makeMethodId={makeMethodId}+ makeMethod={makeMethod}materials={methodMaterials}operations={methodOperations}// configurable={routeData?.toolManufacturing.requiresConfiguration}diff --git a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.method.tsx b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.method.tsxindex 3f5950cf9f..b482f906f5 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.method.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.method.tsx@@ -71,14 +71,14 @@ export default function MakeMethodRoute() {<BillOfProcesskey={`bop:${itemId}`}- makeMethodId={makeMethodId}+ makeMethod={manufacturingRouteData?.makeMethod}// @ts-ignoreoperations={manufacturingRouteData?.methodOperations ?? []}tags={tags}/><BillOfMaterialkey={`bom:${itemId}`}- makeMethodId={makeMethodId}+ makeMethod={manufacturingRouteData?.makeMethod}// @ts-ignorematerials={manufacturingRouteData?.methodMaterials ?? []}// @ts-ignore