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: configure high-level bom and bop

Brad Barbin43c99229d70d
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index fd5c1245a2..03fc7be984 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -412,6 +412,8 @@ const BillOfMaterial = ({
configurationRules?.map((rule) => [rule.field, rule]) ?? []
);
+ const { materialId } = useParams();
+
return (
<Card>
<HStack className="justify-between">
@@ -436,14 +438,17 @@ const BillOfMaterial = ({
aria-label="Configure"
variant="ghost"
className={cn(
- rulesByField.has("billOfMaterial") &&
- "text-emerald-500 hover:text-emerald-500"
+ rulesByField.has(
+ `billOfMaterial:${makeMethodId}:${materialId}`
+ ) && "text-emerald-500 hover:text-emerald-500"
)}
onClick={() =>
onConfigure({
label: "Bill of Material",
- field: "billOfMaterial",
- code: rulesByField.get("billOfMaterial")?.code,
+ field: `billOfMaterial:${makeMethodId}:${materialId}`,
+ code: rulesByField.get(
+ `billOfMaterial:${makeMethodId}:${materialId}`
+ )?.code,
returnType: {
type: "list",
listOptions: materials.map((m) => m.data.itemReadableId!),
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
index 09a55a6e98..da2eaaa010 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -29,7 +29,7 @@ import {
import { Editor, generateHTML } from "@carbon/react/Editor";
import { formatRelativeTime } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
-import { useFetcher, useFetchers } from "@remix-run/react";
+import { useFetcher, useFetchers, useParams } from "@remix-run/react";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
import { nanoid } from "nanoid";
import type { Dispatch, SetStateAction } from "react";
@@ -575,6 +575,8 @@ const BillOfProcess = ({
configuratorDisclosure.onOpen();
};
+ const { materialId } = useParams();
+
const rulesByField = new Map(
configurationRules?.map((rule) => [rule.field, rule]) ?? []
);
@@ -603,14 +605,17 @@ const BillOfProcess = ({
aria-label="Configure"
variant="ghost"
className={cn(
- rulesByField.has("billOfProcess") &&
- "text-emerald-500 hover:text-emerald-500"
+ rulesByField.has(
+ `billOfProcess:${makeMethodId}:${materialId}`
+ ) && "text-emerald-500 hover:text-emerald-500"
)}
onClick={() =>
onConfigure({
label: "Bill of Process",
- field: "billOfProcess",
- code: rulesByField.get("billOfProcess")?.code,
+ field: `billOfProcess:${makeMethodId}:${materialId}`,
+ code: rulesByField.get(
+ `billOfProcess:${makeMethodId}:${materialId}`
+ )?.code,
returnType: {
type: "list",
listOptions: operations.map((op) => op.description),
@@ -732,6 +737,7 @@ function OperationForm({
operationType: string;
operationOrder: string;
processId: string;
+ workCenterId: string;
setupTime: number;
setupUnit: string;
setupUnitHint: string;
@@ -746,6 +752,7 @@ function OperationForm({
operationOrder: item.data.operationOrder ?? "After Previous",
operationType: item.data.operationType ?? "Inside",
processId: item.data.processId ?? "",
+ workCenterId: item.data.workCenterId ?? "",
setupTime: item.data.setupTime ?? 0,
setupUnit: item.data.setupUnit ?? "Total Minutes",
setupUnitHint: getUnitHint(item.data.setupUnit),
@@ -785,6 +792,7 @@ function OperationForm({
setProcessData((p) => ({
...p,
+ workCenterId,
laborUnit: data?.defaultStandardFactor ?? "Hours/Piece",
laborUnitHint: getUnitHint(data?.defaultStandardFactor),
machineUnit: data?.defaultStandardFactor ?? "Hours/Piece",
@@ -858,6 +866,24 @@ function OperationForm({
label="Work Center"
isOptional
processId={processData.processId}
+ isConfigured={rulesByField.has(key("workCenterId"))}
+ onConfigure={
+ configurable && !isTemporaryId(item.id)
+ ? () => {
+ onConfigure({
+ label: "Work Center",
+ field: key("workCenterId"),
+ code: rulesByField.get(key("workCenterId"))?.code,
+ defaultValue: processData.workCenterId,
+ returnType: {
+ type: "text",
+ helperText:
+ "the unique identifier for the work center. you can get this from the URL when editing a work center",
+ },
+ });
+ }
+ : undefined
+ }
onChange={(value) => {
if (value) {
onWorkCenterChange(value?.value as string);
diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
index 74d06cb204..45e953e97c 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
@@ -6,6 +6,14 @@ import type { LoaderFunctionArgs } from "@vercel/remix";
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { useRouteData } from "@carbon/remix";
+import type { z } from "zod";
+import type {
+ ConfigurationParameter,
+ ConfigurationParameterGroup,
+ ConfigurationRule,
+ partManufacturingValidator,
+} from "~/modules/items";
import {
getItem,
getMethodMaterial,
@@ -106,6 +114,17 @@ export default function MethodMaterialMakePage() {
if (!makeMethodId) throw new Error("Could not find makeMethodId");
if (!materialId) throw new Error("Could not find materialId");
+ const routeData = useRouteData<{
+ partManufacturing: z.infer<typeof partManufacturingValidator> & {
+ customFields: Record<string, string>;
+ };
+ configurationParametersAndGroups: {
+ groups: ConfigurationParameterGroup[];
+ parameters: ConfigurationParameter[];
+ };
+ configurationRules: ConfigurationRule[];
+ }>(path.to.partManufacturing(itemId));
+
return (
<VStack spacing={2} className="p-2">
<MakeMethodTools itemId={item.id} type="Part" />
@@ -118,12 +137,18 @@ export default function MethodMaterialMakePage() {
key={`bop:${itemId}`}
makeMethodId={makeMethodId}
operations={methodOperations}
+ configurable={routeData?.partManufacturing.requiresConfiguration}
+ configurationRules={routeData?.configurationRules}
+ parameters={routeData?.configurationParametersAndGroups.parameters}
/>
<BillOfMaterial
key={`bom:${itemId}`}
makeMethodId={makeMethodId}
materials={methodMaterials}
operations={methodOperations}
+ configurable={routeData?.partManufacturing.requiresConfiguration}
+ configurationRules={routeData?.configurationRules}
+ parameters={routeData?.configurationParametersAndGroups.parameters}
/>
</VStack>
);
diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.method.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.method.tsx
index 9a8dea2f8e..831e6b09b5 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.method.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.method.tsx
@@ -3,15 +3,20 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { VStack } from "@carbon/react";
-import { useLoaderData, useParams } from "@remix-run/react";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
-import { json, redirect } from "@vercel/remix";
+import { useParams } from "@remix-run/react";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import type { z } from "zod";
import { useRouteData } from "~/hooks";
-import type { MakeMethod, Material, MethodOperation } from "~/modules/items";
+import type {
+ ConfigurationParameter,
+ ConfigurationParameterGroup,
+ ConfigurationRule,
+ MakeMethod,
+ Material,
+ MethodOperation,
+} from "~/modules/items";
import {
- getConfigurationParameters,
- getConfigurationRules,
- getItemManufacturing,
partManufacturingValidator,
upsertItemManufacturing,
} from "~/modules/items";
@@ -27,40 +32,6 @@ import {
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
-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] = await Promise.all([
- getItemManufacturing(client, itemId, companyId),
- ]);
-
- if (partManufacturing.error) {
- throw redirect(
- path.to.partDetails(itemId),
- await flash(
- request,
- error(partManufacturing.error, "Failed to load part manufacturing")
- )
- );
- }
-
- return json({
- partManufacturing: partManufacturing.data,
- configurationParametersAndGroups: partManufacturing.data
- .requiresConfiguration
- ? await getConfigurationParameters(client, itemId, companyId)
- : { groups: [], parameters: [] },
- configurationRules: partManufacturing.data.requiresConfiguration
- ? await getConfigurationRules(client, itemId, companyId)
- : [],
- });
-}
-
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { client, userId } = await requirePermissions(request, {
@@ -105,14 +76,22 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function MakeMethodRoute() {
- const {
- partManufacturing,
- configurationParametersAndGroups,
- configurationRules,
- } = useLoaderData<typeof loader>();
const { itemId } = useParams();
if (!itemId) throw new Error("Could not find itemId");
+ const routeData = useRouteData<{
+ partManufacturing: z.infer<typeof partManufacturingValidator> & {
+ customFields: Record<string, string>;
+ };
+ configurationParametersAndGroups: {
+ groups: ConfigurationParameterGroup[];
+ parameters: ConfigurationParameter[];
+ };
+ configurationRules: ConfigurationRule[];
+ }>(path.to.partManufacturing(itemId));
+
+ if (!routeData) throw new Error("Could not find route data");
+
const manufacturingRouteData = useRouteData<{
makeMethod: MakeMethod;
methodMaterials: Material[];
@@ -123,9 +102,9 @@ export default function MakeMethodRoute() {
if (!makeMethodId) throw new Error("Could not find makeMethodId");
const manufacturingInitialValues = {
- ...partManufacturing,
- lotSize: partManufacturing.lotSize ?? 0,
- ...getCustomFields(partManufacturing.customFields),
+ ...routeData?.partManufacturing,
+ lotSize: routeData?.partManufacturing.lotSize ?? 0,
+ ...getCustomFields(routeData?.partManufacturing.customFields),
};
return (
@@ -133,35 +112,36 @@ export default function MakeMethodRoute() {
<MakeMethodTools itemId={itemId} type="Part" />
<PartManufacturingForm
key={itemId}
+ // @ts-ignore
initialValues={manufacturingInitialValues}
/>
- {partManufacturing.requiresConfiguration && (
+ {routeData?.partManufacturing.requiresConfiguration && (
<ConfigurationParametersForm
key={`options:${itemId}`}
- parameters={configurationParametersAndGroups.parameters}
- groups={configurationParametersAndGroups.groups}
+ parameters={routeData?.configurationParametersAndGroups.parameters}
+ groups={routeData?.configurationParametersAndGroups.groups}
/>
)}
<BillOfProcess
key={`bop:${itemId}`}
- configurable={partManufacturing.requiresConfiguration}
makeMethodId={makeMethodId}
// @ts-ignore
operations={manufacturingRouteData?.methodOperations ?? []}
- parameters={configurationParametersAndGroups.parameters}
- configurationRules={configurationRules}
+ configurable={routeData?.partManufacturing.requiresConfiguration}
+ configurationRules={routeData?.configurationRules}
+ parameters={routeData?.configurationParametersAndGroups.parameters}
/>
<BillOfMaterial
key={`bom:${itemId}`}
- configurable={partManufacturing.requiresConfiguration}
makeMethodId={makeMethodId}
// @ts-ignore
materials={manufacturingRouteData?.methodMaterials ?? []}
// @ts-ignore
operations={manufacturingRouteData?.methodOperations}
- parameters={configurationParametersAndGroups.parameters}
- configurationRules={configurationRules}
+ configurable={routeData?.partManufacturing.requiresConfiguration}
+ configurationRules={routeData?.configurationRules}
+ parameters={routeData?.configurationParametersAndGroups.parameters}
/>
</VStack>
);
diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx
index 9637998a93..5f56822b4d 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx
@@ -16,13 +16,16 @@ import {
} from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
-import { error } from "@carbon/auth";
+import { error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { FlatTreeItem } from "~/components/TreeView";
import { flattenTree } from "~/components/TreeView";
import type { Method } from "~/modules/items";
import {
+ getConfigurationParameters,
+ getConfigurationRules,
+ getItemManufacturing,
getMakeMethod,
getMethodMaterialsByMakeMethod,
getMethodOperationsByMakeMethodId,
@@ -66,11 +69,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- const [methodTree, methodMaterials, methodOperations] = await Promise.all([
- getMethodTree(client, makeMethod.data.id),
- getMethodMaterialsByMakeMethod(client, makeMethod.data.id),
- getMethodOperationsByMakeMethodId(client, makeMethod.data.id),
- ]);
+ if (companyId !== makeMethod.data.companyId) {
+ throw redirect(
+ path.to.authenticatedRoot,
+ await flash(request, error("Access denied"))
+ );
+ }
+ const serviceRole = await getCarbonServiceRole();
+
+ const [methodTree, methodMaterials, methodOperations, partManufacturing] =
+ await Promise.all([
+ getMethodTree(serviceRole, makeMethod.data.id),
+ getMethodMaterialsByMakeMethod(serviceRole, makeMethod.data.id),
+ getMethodOperationsByMakeMethodId(serviceRole, makeMethod.data.id),
+ getItemManufacturing(serviceRole, itemId, companyId),
+ ]);
if (methodTree?.error) {
throw redirect(
path.to.partDetails(itemId),
@@ -120,6 +133,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
methods: (methodTree.data.length > 0
? flattenTree(methodTree.data[0])
: []) satisfies FlatTreeItem<Method>[],
+ partManufacturing: partManufacturing.data,
+ configurationParametersAndGroups: partManufacturing.data
+ ?.requiresConfiguration
+ ? await getConfigurationParameters(serviceRole, itemId, companyId)
+ : { groups: [], parameters: [] },
+ configurationRules: partManufacturing.data?.requiresConfiguration
+ ? await getConfigurationRules(serviceRole, itemId, companyId)
+ : [],
});
}
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index d85c326383..e929bf524a 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -764,11 +764,12 @@ serve(async (req: Request) => {
)
.eq("makeMethodId", node.data.materialMakeMethodId);
- const quoteOperations: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =
+ let quoteOperations: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =
[];
for await (const op of relatedOperations?.data ?? []) {
const [
processId,
+ workCenterId,
description,
setupTime,
setupUnit,
@@ -784,6 +785,11 @@ serve(async (req: Request) => {
field: "processId",
defaultValue: op.processId,
}),
+ getConfiguredValue({
+ id: op.id,
+ field: "workCenterId",
+ defaultValue: op.workCenterId,
+ }),
getConfiguredValue({
id: op.id,
field: "description",
@@ -836,7 +842,7 @@ serve(async (req: Request) => {
quoteLineId,
quoteMakeMethodId: parentQuoteMakeMethodId!,
processId,
- workCenterId: op.workCenterId,
+ workCenterId,
description,
setupTime,
setupUnit,
@@ -860,6 +866,37 @@ serve(async (req: Request) => {
});
}
+ const nodeLevelConfigurationKey = `${
+ node.data.materialMakeMethodId
+ }:${node.data.isRoot ? "undefined" : node.data.methodMaterialId}`;
+
+ const bopConfigurationKey = `billOfProcess:${nodeLevelConfigurationKey}`;
+ let bopConfiguration: string[] | null = null;
+
+ if (configurationCodeByField?.[bopConfigurationKey]) {
+ const mod = await importTypeScript(
+ configurationCodeByField[bopConfigurationKey]
+ );
+ bopConfiguration = await mod.configure(configuration);
+ }
+
+ if (bopConfiguration) {
+ // @ts-expect-error - we can't assign undefined to materialsWithConfiguredFields but we filter them in the next step
+ quoteOperations = bopConfiguration
+ .map((description, index) => {
+ const operation = quoteOperations.find(
+ (operation) => operation.description === description
+ );
+ if (operation) {
+ return {
+ ...operation,
+ order: index + 1,
+ };
+ }
+ })
+ .filter(Boolean);
+ }
+
let methodOperationsToQuoteOperations: Record<string, string> = {};
if (quoteOperations?.length > 0) {
const operationIds = await trx
@@ -907,41 +944,136 @@ serve(async (req: Request) => {
) ?? {};
}
- const mapMethodMaterialToQuoteMaterial = (
+ const mapMethodMaterialToQuoteMaterial = async (
child: MethodTreeItem
- ) => ({
- quoteId,
- quoteLineId,
- quoteMakeMethodId: parentQuoteMakeMethodId!,
- quoteOperationId:
- methodOperationsToQuoteOperations[child.data.operationId],
- itemId: child.data.itemId,
- itemReadableId: child.data.itemReadableId,
- itemType: child.data.itemType,
- methodType: child.data.methodType,
- order: child.data.order,
- description: child.data.description,
- quantity: child.data.quantity,
- unitOfMeasureCode: child.data.unitOfMeasureCode,
- unitCost: child.data.unitCost,
- companyId,
- createdBy: userId,
- customFields: {},
- });
+ ) => {
+ let [
+ itemId,
+ description,
+ quantity,
+ methodType,
+ unitOfMeasureCode,
+ ] = await Promise.all([
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "itemId",
+ defaultValue: child.data.itemId,
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "description",
+ defaultValue: child.data.description,
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "quantity",
+ defaultValue: child.data.quantity,
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "methodType",
+ defaultValue: child.data.methodType,
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "unitOfMeasureCode",
+ defaultValue: child.data.unitOfMeasureCode,
+ }),
+ ]);
- const madeChildren = node.children.filter(
- (child) => child.data.methodType === "Make"
- );
- const unmadeChildren = node.children.filter(
- (child) => child.data.methodType !== "Make"
- );
+ let itemReadableId = child.data.itemReadableId;
+ let itemType = child.data.itemType;
+ let unitCost = child.data.unitCost;
+
+ // TODO: if the methodType is Make and the default value is not Make, we need to do itemToQuoteMakeMethod for that material
+
+ if (itemId !== child.data.itemId) {
+ const item = await client
+ .from("item")
+ .select("readableId, type, name, itemCost(unitCost)")
+ .eq("id", itemId)
+ .single();
+ if (item.data) {
+ itemReadableId = item.data.readableId;
+ itemType = item.data.type;
+ unitCost =
+ item.data.itemCost[0]?.unitCost ?? child.data.unitCost;
+ if (description === child.data.description) {
+ description = item.data.name;
+ }
+ } else {
+ itemId = child.data.itemId;
+ }
+ }
- const madeMaterials = madeChildren.map(
- mapMethodMaterialToQuoteMaterial
+ return {
+ quoteId,
+ quoteLineId,
+ quoteMakeMethodId: parentQuoteMakeMethodId!,
+ quoteOperationId:
+ methodOperationsToQuoteOperations[child.data.operationId],
+ order: child.data.order,
+ itemId,
+ itemReadableId,
+ itemType,
+ methodType,
+ description,
+ quantity,
+ unitOfMeasureCode,
+ unitCost,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ };
+ };
+
+ let materialsWithConfiguredFields = await Promise.all(
+ node.children.map(mapMethodMaterialToQuoteMaterial)
);
- const pickedOrBoughtMaterials = unmadeChildren.map(
- mapMethodMaterialToQuoteMaterial
+
+ const bomConfigurationKey = `billOfMaterial:${nodeLevelConfigurationKey}`;
+ let bomConfiguration: string[] | null = null;
+
+ if (configurationCodeByField?.[bomConfigurationKey]) {
+ const mod = await importTypeScript(
+ configurationCodeByField[bomConfigurationKey]
+ );
+ bomConfiguration = await mod.configure(configuration);
+ }
+
+ if (bomConfiguration) {
+ // @ts-expect-error - we can't assign undefined to materialsWithConfiguredFields but we filter them in the next step
+ materialsWithConfiguredFields = bomConfiguration
+ .map((readableId, index) => {
+ const material = materialsWithConfiguredFields.find(
+ (material) => material.itemReadableId === readableId
+ );
+ if (material) {
+ return {
+ ...material,
+ order: index + 1,
+ };
+ }
+ })
+ .filter(Boolean);
+ }
+
+ const madeMaterials = materialsWithConfiguredFields.filter(
+ (material) => material.methodType === "Make"
);
+
+ const pickedOrBoughtMaterials =
+ materialsWithConfiguredFields.filter(
+ (material) => material.methodType !== "Make"
+ );
+
+ const madeChildren = madeMaterials.map((material, index) => {
+ const childIndex = materialsWithConfiguredFields.findIndex(
+ (m) => m.itemReadableId === material.itemReadableId
+ );
+ return node.children[childIndex];
+ });
+
if (madeMaterials.length > 0) {
const madeMaterialIds = await trx
.insertInto("quoteMaterial")