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: include cost of subassemblies in bom export

Brad Barbin6c3ac68eb304
diff --git a/apps/erp/app/routes/api+/items.methods.$id.bom[.]csv.tsx b/apps/erp/app/routes/api+/items.methods.$id.bom[.]csv.tsx
index 97ea8d3431..c265d3d90e 100644
--- a/apps/erp/app/routes/api+/items.methods.$id.bom[.]csv.tsx
+++ b/apps/erp/app/routes/api+/items.methods.$id.bom[.]csv.tsx
@@ -5,7 +5,12 @@ import type { FlatTreeItem } from "~/components/TreeView";
import { flattenTree } from "~/components/TreeView";
import type { Method } from "~/modules/items";
import { getMethodTree } from "~/modules/items";
-import { calculateTotalQuantity, generateBomIds } from "~/utils/bom";
+import type { BomOperation } from "~/utils/bom";
+import {
+ calculateMadePartCosts,
+ calculateTotalQuantity,
+ generateBomIds
+} from "~/utils/bom";
import { makeDurations } from "~/utils/duration";
const bomHeaders = [
@@ -81,51 +86,79 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
...new Set(methods.map((method) => method.data.makeMethodId))
];
+ const methodOperations = await client
+ .from("methodOperation")
+ .select(
+ "*, ...process(processName:name), ...workCenter(workCenterName:name, laborRate, machineRate, overheadRate)"
+ )
+ .in("makeMethodId", makeMethodIds)
+ .eq("companyId", companyId);
+
let operationsByMakeMethodId: Record<
string,
Array<
Database["public"]["Tables"]["methodOperation"]["Row"] & {
processName: string;
workCenterName: string | null;
+ laborRate: number | null;
+ machineRate: number | null;
+ overheadRate: number | null;
}
>
> = {};
- if (withOperations) {
- const methodOperations = await client
- .from("methodOperation")
- .select(
- "*, ...process(processName:name), ...workCenter(workCenterName:name)"
- )
- .in("makeMethodId", makeMethodIds)
- .eq("companyId", companyId);
- if (methodOperations.data) {
- operationsByMakeMethodId = methodOperations.data.reduce(
- (acc, operation) => {
- acc[operation.makeMethodId] = [
- ...(acc[operation.makeMethodId] || []),
- operation
- ];
- return acc;
- },
- {} as typeof operationsByMakeMethodId
- );
- }
+ if (methodOperations.data) {
+ operationsByMakeMethodId = methodOperations.data.reduce(
+ (acc, operation) => {
+ acc[operation.makeMethodId] = [
+ ...(acc[operation.makeMethodId] || []),
+ operation
+ ];
+ return acc;
+ },
+ {} as typeof operationsByMakeMethodId
+ );
}
+ // Build BomOperation map for cost calculation
+ const bomOperationsByKey: Record<string, BomOperation[]> = {};
+ for (const [key, ops] of Object.entries(operationsByMakeMethodId)) {
+ bomOperationsByKey[key] = ops.map((op) => ({
+ operationType: op.operationType,
+ setupTime: op.setupTime,
+ setupUnit: op.setupUnit,
+ laborTime: op.laborTime,
+ laborUnit: op.laborUnit,
+ machineTime: op.machineTime,
+ machineUnit: op.machineUnit,
+ operationUnitCost: op.operationUnitCost,
+ operationMinimumCost: op.operationMinimumCost,
+ laborRate: op.laborRate ?? 0,
+ machineRate: op.machineRate ?? 0,
+ overheadRate: op.overheadRate ?? 0
+ }));
+ }
+
+ const computedCosts = calculateMadePartCosts(
+ methods,
+ bomOperationsByKey,
+ (node) => node.data.materialMakeMethodId
+ );
+
const bomIds = generateBomIds(methods);
let csv = headers;
methods.forEach((node, index) => {
const total = calculateTotalQuantity(node, methods);
- const totalCost = total * (node.data.unitCost || 0);
+ const unitCost = computedCosts.get(node.id) ?? node.data.unitCost ?? 0;
+ const totalCost = total * unitCost;
csv += `${bomIds[index]},${
node.data.itemReadableId
},"${node.data.description?.replace(/"/g, '""')}",${
node.data.quantity
- },${total},${node.data.unitCost},${totalCost},${
+ },${total},${unitCost},${totalCost},${
node.data.unitOfMeasureCode
},${node.data.methodType},${node.data.itemType},${node.level},${
node.data.version || ""
diff --git a/apps/erp/app/routes/api+/production.methods.$id.bom[.]csv.tsx b/apps/erp/app/routes/api+/production.methods.$id.bom[.]csv.tsx
index 77baca0cf8..24f66268e6 100644
--- a/apps/erp/app/routes/api+/production.methods.$id.bom[.]csv.tsx
+++ b/apps/erp/app/routes/api+/production.methods.$id.bom[.]csv.tsx
@@ -3,7 +3,12 @@ import type { LoaderFunctionArgs } from "react-router";
import { flattenTree } from "~/components/TreeView";
import type { JobOperation } from "~/modules/production";
import { getJobMethodTree } from "~/modules/production";
-import { calculateTotalQuantity, generateBomIds } from "~/utils/bom";
+import type { BomOperation } from "~/utils/bom";
+import {
+ calculateMadePartCosts,
+ calculateTotalQuantity,
+ generateBomIds
+} from "~/utils/bom";
import { makeDurations } from "~/utils/duration";
const bomHeaders = [
@@ -78,6 +83,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
...new Set(methods.map((method) => method.data.jobMakeMethodId))
];
+ const methodOperations = await client
+ .from("jobOperation")
+ .select(
+ "*, ...process(processName:name), ...workCenter(workCenterName:name), ...jobMakeMethod(parentMaterialId, item(readableIdWithRevision))"
+ )
+ .in("jobMakeMethodId", makeMethodIds)
+ .eq("companyId", companyId);
+
let operationsByMakeMethodId: Record<
string,
Array<
@@ -88,51 +101,68 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
>
> = {};
- if (withOperations) {
- const methodOperations = await client
- .from("jobOperation")
- .select(
- "*, ...process(processName:name), ...workCenter(workCenterName:name), ...jobMakeMethod(parentMaterialId, item(readableIdWithRevision))"
- )
- .in("jobMakeMethodId", makeMethodIds)
- .eq("companyId", companyId);
- if (methodOperations.data) {
- operationsByMakeMethodId = methodOperations.data.reduce<
- typeof operationsByMakeMethodId
- >((acc, operation) => {
- const transformedOperation = {
- ...operation,
- jobMakeMethod: operation.item
- ? {
- parentMaterialId: operation.parentMaterialId,
- item: {
- readableIdWithRevision: operation.item.readableIdWithRevision
- }
+ if (methodOperations.data) {
+ operationsByMakeMethodId = methodOperations.data.reduce<
+ typeof operationsByMakeMethodId
+ >((acc, operation) => {
+ const transformedOperation = {
+ ...operation,
+ jobMakeMethod: operation.item
+ ? {
+ parentMaterialId: operation.parentMaterialId,
+ item: {
+ readableIdWithRevision: operation.item.readableIdWithRevision
}
- : null
- };
- acc[operation.jobMakeMethodId ?? ""] = [
- ...(acc[operation.jobMakeMethodId ?? ""] || []),
- transformedOperation
- ];
- return acc;
- }, {});
- }
+ }
+ : null
+ };
+ acc[operation.jobMakeMethodId ?? ""] = [
+ ...(acc[operation.jobMakeMethodId ?? ""] || []),
+ transformedOperation
+ ];
+ return acc;
+ }, {});
}
+ // Build BomOperation map for cost calculation
+ const bomOperationsByKey: Record<string, BomOperation[]> = {};
+ for (const [key, ops] of Object.entries(operationsByMakeMethodId)) {
+ bomOperationsByKey[key] = ops.map((op) => ({
+ operationType: op.operationType,
+ setupTime: op.setupTime,
+ setupUnit: op.setupUnit,
+ laborTime: op.laborTime,
+ laborUnit: op.laborUnit,
+ machineTime: op.machineTime,
+ machineUnit: op.machineUnit,
+ operationUnitCost: op.operationUnitCost,
+ operationMinimumCost: op.operationMinimumCost,
+ laborRate: op.laborRate ?? 0,
+ machineRate: op.machineRate ?? 0,
+ overheadRate: op.overheadRate ?? 0
+ }));
+ }
+
+ const computedCosts = calculateMadePartCosts(
+ methods,
+ bomOperationsByKey,
+ (node) => node.data.jobMaterialMakeMethodId
+ );
+
const bomIds = generateBomIds(methods);
let csv = headers;
methods.forEach((node, index) => {
const total = calculateTotalQuantity(node, methods);
- const totalCost = total * (node.data.unitCost || 0);
+ const unitCost = computedCosts.get(node.id) ?? node.data.unitCost ?? 0;
+ const totalCost = total * unitCost;
csv += `${bomIds[index]},${
node.data.itemReadableId
},"${node.data.description?.replace(/"/g, '""')}",${
node.data.quantity
- },${total},${node.data.unitCost},${totalCost},,${node.data.methodType},${
+ },${total},${unitCost},${totalCost},,${node.data.methodType},${
node.data.itemType
},${node.level},${node.data.version || ""}\n`;
diff --git a/apps/erp/app/routes/api+/sales.quote.line.$id.bom[.]csv.tsx b/apps/erp/app/routes/api+/sales.quote.line.$id.bom[.]csv.tsx
index be028933e8..4b5e33842b 100644
--- a/apps/erp/app/routes/api+/sales.quote.line.$id.bom[.]csv.tsx
+++ b/apps/erp/app/routes/api+/sales.quote.line.$id.bom[.]csv.tsx
@@ -3,7 +3,12 @@ import type { Database } from "@carbon/database";
import type { LoaderFunctionArgs } from "react-router";
import { flattenTree } from "~/components/TreeView";
import { getQuoteMethodTrees } from "~/modules/sales";
-import { calculateTotalQuantity, generateBomIds } from "~/utils/bom";
+import type { BomOperation } from "~/utils/bom";
+import {
+ calculateMadePartCosts,
+ calculateTotalQuantity,
+ generateBomIds
+} from "~/utils/bom";
import { makeDurations } from "~/utils/duration";
const bomHeaders = [
@@ -83,6 +88,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
...new Set(flattenedMethods.map((method) => method.data.quoteMakeMethodId))
];
+ const quoteOperations = await client
+ .from("quoteOperation")
+ .select(
+ "*, ...process(processName:name), ...workCenter(workCenterName:name)"
+ )
+ .in("quoteMakeMethodId", makeMethodIds)
+ .eq("companyId", companyId);
+
let operationsByMakeMethodId: Record<
string,
Array<
@@ -93,28 +106,44 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
>
> = {};
- if (withOperations) {
- const quoteOperations = await client
- .from("quoteOperation")
- .select(
- "*, ...process(processName:name), ...workCenter(workCenterName:name)"
- )
- .in("quoteMakeMethodId", makeMethodIds)
- .eq("companyId", companyId);
- if (quoteOperations.data) {
- operationsByMakeMethodId = quoteOperations.data.reduce(
- (acc, operation) => {
- acc[operation.quoteMakeMethodId ?? ""] = [
- ...(acc[operation.quoteMakeMethodId ?? ""] || []),
- operation
- ];
- return acc;
- },
- {} as typeof operationsByMakeMethodId
- );
- }
+ if (quoteOperations.data) {
+ operationsByMakeMethodId = quoteOperations.data.reduce(
+ (acc, operation) => {
+ acc[operation.quoteMakeMethodId ?? ""] = [
+ ...(acc[operation.quoteMakeMethodId ?? ""] || []),
+ operation
+ ];
+ return acc;
+ },
+ {} as typeof operationsByMakeMethodId
+ );
}
+ // Build BomOperation map for cost calculation
+ const bomOperationsByKey: Record<string, BomOperation[]> = {};
+ for (const [key, ops] of Object.entries(operationsByMakeMethodId)) {
+ bomOperationsByKey[key] = ops.map((op) => ({
+ operationType: op.operationType,
+ setupTime: op.setupTime,
+ setupUnit: op.setupUnit,
+ laborTime: op.laborTime,
+ laborUnit: op.laborUnit,
+ machineTime: op.machineTime,
+ machineUnit: op.machineUnit,
+ operationUnitCost: op.operationUnitCost,
+ operationMinimumCost: op.operationMinimumCost,
+ laborRate: op.laborRate ?? 0,
+ machineRate: op.machineRate ?? 0,
+ overheadRate: op.overheadRate ?? 0
+ }));
+ }
+
+ const computedCosts = calculateMadePartCosts(
+ flattenedMethods,
+ bomOperationsByKey,
+ (node) => node.data.quoteMaterialMakeMethodId
+ );
+
const bomIds = generateBomIds(flattenedMethods);
// Build headers including duration columns for each quantity
@@ -134,13 +163,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
flattenedMethods.forEach((node, index) => {
const total = calculateTotalQuantity(node, flattenedMethods);
- const totalCost = total * (node.data.unitCost || 0);
+ const unitCost = computedCosts.get(node.id) ?? node.data.unitCost ?? 0;
+ const totalCost = total * unitCost;
csv += `${bomIds[index]},${
node.data.itemReadableId
},"${node.data.description?.replace(/"/g, '""')}",${
node.data.quantity
- },${total},${node.data.unitCost},${totalCost},${node.data.methodType},${
+ },${total},${unitCost},${totalCost},${node.data.methodType},${
node.data.itemType
},${node.level},${node.data.version || ""}\n`;
diff --git a/apps/erp/app/utils/bom.ts b/apps/erp/app/utils/bom.ts
index 46caa7a896..e7232d273b 100644
--- a/apps/erp/app/utils/bom.ts
+++ b/apps/erp/app/utils/bom.ts
@@ -3,6 +3,150 @@ import type { Method } from "~/modules/items";
import type { JobMethod } from "~/modules/production/types";
import type { QuoteMethod } from "~/modules/sales/types";
+export interface BomOperation {
+ operationType: string;
+ setupTime: number | null;
+ setupUnit: string;
+ laborTime: number | null;
+ laborUnit: string;
+ machineTime: number | null;
+ machineUnit: string;
+ operationUnitCost: number;
+ operationMinimumCost: number;
+ laborRate: number;
+ machineRate: number | null;
+ overheadRate: number;
+}
+
+export function normalizeTime(
+ time: number,
+ unit: string
+): { fixedHours: number; hoursPerUnit: number } {
+ let fixedHours = 0;
+ let hoursPerUnit = 0;
+ switch (unit) {
+ case "Total Hours":
+ fixedHours = time;
+ break;
+ case "Total Minutes":
+ fixedHours = time / 60;
+ break;
+ case "Hours/Piece":
+ hoursPerUnit = time;
+ break;
+ case "Hours/100 Pieces":
+ hoursPerUnit = time / 100;
+ break;
+ case "Hours/1000 Pieces":
+ hoursPerUnit = time / 1000;
+ break;
+ case "Minutes/Piece":
+ hoursPerUnit = time / 60;
+ break;
+ case "Minutes/100 Pieces":
+ hoursPerUnit = time / 100 / 60;
+ break;
+ case "Minutes/1000 Pieces":
+ hoursPerUnit = time / 1000 / 60;
+ break;
+ case "Pieces/Hour":
+ hoursPerUnit = 1 / time;
+ break;
+ case "Pieces/Minute":
+ hoursPerUnit = 1 / (time / 60);
+ break;
+ case "Seconds/Piece":
+ hoursPerUnit = time / 3600;
+ break;
+ }
+ return { fixedHours, hoursPerUnit };
+}
+
+function calculateOperationUnitCost(op: BomOperation): number {
+ if (op.operationType === "Outside") {
+ return Math.max(op.operationMinimumCost, op.operationUnitCost);
+ }
+
+ let cost = 0;
+
+ if (op.setupTime) {
+ const { fixedHours, hoursPerUnit } = normalizeTime(
+ op.setupTime,
+ op.setupUnit
+ );
+ const totalHours = fixedHours + hoursPerUnit;
+ cost += totalHours * (op.laborRate ?? 0);
+ cost += totalHours * (op.overheadRate ?? 0);
+ }
+
+ let laborTotalHours = 0;
+ let machineTotalHours = 0;
+
+ if (op.laborTime) {
+ const { fixedHours, hoursPerUnit } = normalizeTime(
+ op.laborTime,
+ op.laborUnit
+ );
+ laborTotalHours = fixedHours + hoursPerUnit;
+ cost += laborTotalHours * (op.laborRate ?? 0);
+ }
+
+ if (op.machineTime) {
+ const { fixedHours, hoursPerUnit } = normalizeTime(
+ op.machineTime,
+ op.machineUnit
+ );
+ machineTotalHours = fixedHours + hoursPerUnit;
+ cost += machineTotalHours * (op.machineRate ?? 0);
+ }
+
+ cost += Math.max(laborTotalHours, machineTotalHours) * (op.overheadRate ?? 0);
+
+ return cost;
+}
+
+export function calculateMadePartCosts<
+ TData extends { methodType: string; unitCost: number; quantity: number }
+>(
+ nodes: FlatTreeItem<TData>[],
+ operationsByKey: Record<string, BomOperation[]>,
+ getOperationKey: (node: FlatTreeItem<TData>) => string
+): Map<string, number> {
+ const costMap = new Map<string, number>();
+ const nodeMap = new Map(nodes.map((n) => [n.id, n]));
+
+ // Iterate in reverse (bottom-up since flattenTree is depth-first)
+ for (let i = nodes.length - 1; i >= 0; i--) {
+ const node = nodes[i];
+
+ if (node.data.methodType !== "Make") {
+ costMap.set(node.id, node.data.unitCost ?? 0);
+ continue;
+ }
+
+ // Sum children material costs
+ let materialCost = 0;
+ for (const childId of node.children) {
+ const child = nodeMap.get(childId);
+ if (!child) continue;
+ const childUnitCost = costMap.get(childId) ?? child.data.unitCost ?? 0;
+ materialCost += childUnitCost * (child.data.quantity ?? 0);
+ }
+
+ // Sum operation costs
+ let operationCost = 0;
+ const key = getOperationKey(node);
+ const ops = operationsByKey[key] ?? [];
+ for (const op of ops) {
+ operationCost += calculateOperationUnitCost(op);
+ }
+
+ costMap.set(node.id, materialCost + operationCost);
+ }
+
+ return costMap;
+}
+
export const calculateTotalQuantity = (
node:
| FlatTreeItem<QuoteMethod>