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: add api endpoints for downloading bom from job

Brad Barbin1bffc5283508
diff --git a/apps/erp/app/routes/api+/production.methods.$id.bom.tsx b/apps/erp/app/routes/api+/production.methods.$id.bom.tsx
new file mode 100644
index 0000000000..6c4f8d24a9
--- /dev/null
+++ b/apps/erp/app/routes/api+/production.methods.$id.bom.tsx
@@ -0,0 +1,135 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { Database } from "@carbon/database";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import type { FlatTreeItem } from "~/components/TreeView";
+import { flattenTree } from "~/components/TreeView";
+import { getJobMethodTree } from "~/modules/production";
+import type { JobMethod } from "~/modules/production/types";
+import { calculateTotalQuantity, generateBomIds } from "~/utils/bom";
+import { makeDurations } from "~/utils/duration";
+
+export const config = {
+ runtime: "nodejs",
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { id } = params;
+ const withOperations = request.url.includes("withOperations=true");
+
+ if (!id) {
+ return { data: [], error: null };
+ }
+
+ const methodTree = await getJobMethodTree(client, id);
+ if (methodTree.error) {
+ return { data: [], error: methodTree.error };
+ }
+
+ const methods = (
+ methodTree.data.length > 0 ? flattenTree(methodTree.data[0]) : []
+ ) satisfies FlatTreeItem<JobMethod>[];
+
+ const makeMethodIds = [
+ ...new Set(methods.map((method) => method.data.jobMakeMethodId)),
+ ];
+
+ let operationsByMakeMethodId: Record<
+ string,
+ Array<
+ Database["public"]["Tables"]["jobOperation"]["Row"] & {
+ processName: string;
+ workCenterName: string | null;
+ }
+ >
+ > = {};
+
+ if (withOperations) {
+ const methodOperations = await client
+ .from("jobOperation")
+ .select(
+ "*, ...process(processName:name), ...workCenter(workCenterName:name)"
+ )
+ .in("jobMakeMethodId", makeMethodIds)
+ .eq("companyId", companyId);
+ if (methodOperations.data) {
+ operationsByMakeMethodId = methodOperations.data.reduce(
+ (acc, operation) => {
+ acc[operation.jobMakeMethodId ?? ""] = [
+ ...(acc[operation.jobMakeMethodId ?? ""] || []),
+ operation,
+ ];
+ return acc;
+ },
+ {} as typeof operationsByMakeMethodId
+ );
+ }
+ }
+
+ const bomIds = generateBomIds(methods);
+
+ const result = methods.map((node, index) => {
+ const total = calculateTotalQuantity(node, methods);
+ const totalCost = total * (node.data.unitCost || 0);
+
+ const bomItem = {
+ id: bomIds[index],
+ itemId: node.data.itemReadableId,
+ description: node.data.description,
+ quantity: node.data.quantity,
+ total,
+ unitCost: node.data.unitCost,
+ totalCost,
+ methodType: node.data.methodType,
+ itemType: node.data.itemType,
+ level: node.level,
+ version: node.data.version || null,
+ };
+
+ if (!withOperations) {
+ return bomItem;
+ }
+
+ const operations =
+ operationsByMakeMethodId[node.data.jobMaterialMakeMethodId];
+ if (!operations) {
+ return { ...bomItem, operations: [] };
+ }
+
+ return {
+ ...bomItem,
+ operations: operations.map((operation) => {
+ const op1 = makeDurations({ ...operation, operationQuantity: total });
+ const op100 = makeDurations({
+ ...operation,
+ operationQuantity: total * 100,
+ });
+ const op1000 = makeDurations({
+ ...operation,
+ operationQuantity: total * 1000,
+ });
+
+ return {
+ description: operation.description,
+ process: operation.processName,
+ workCenter: operation.workCenterName,
+ operationType: operation.operationType,
+ setupTime: operation.setupTime,
+ setupUnit: operation.setupUnit,
+ laborTime: operation.laborTime,
+ laborUnit: operation.laborUnit,
+ machineTime: operation.machineTime,
+ machineUnit: operation.machineUnit,
+ totalDurationX1: op1.duration,
+ totalDurationX100: op100.duration,
+ totalDurationX1000: op1000.duration,
+ };
+ }),
+ };
+ });
+
+ return { data: result, error: null };
+}
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
new file mode 100644
index 0000000000..9fd77c2b96
--- /dev/null
+++ b/apps/erp/app/routes/api+/production.methods.$id.bom[.]csv.tsx
@@ -0,0 +1,179 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { flattenTree } from "~/components/TreeView";
+import type { JobOperation } from "~/modules/production";
+import { getJobMethodTree } from "~/modules/production";
+import { calculateTotalQuantity, generateBomIds } from "~/utils/bom";
+import { makeDurations } from "~/utils/duration";
+
+export const config = {
+ runtime: "nodejs",
+};
+
+const bomHeaders = [
+ "ID",
+ "Item ID",
+ "Description",
+ "Quantity",
+ "Total",
+ "Unit Cost",
+ "Total Cost",
+ "UOM",
+ "Method Type",
+ "Item Type",
+ "Level",
+ "Version",
+];
+
+const operationHeaders = [
+ "Operation",
+ "Process",
+ "Work Center",
+ "Operation Type",
+ "Setup Time",
+ "Setup Unit",
+ "Labor Time",
+ "Labor Unit",
+ "Machine Time",
+ "Machine Unit",
+ "Total Duration x 1 (ms)",
+ "Total Duration x 100 (ms)",
+ "Total Duration x 1000 (ms)",
+];
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { id } = params;
+ const withOperations = request.url.includes("withOperations=true");
+
+ const headers =
+ (withOperations
+ ? [...bomHeaders, ...operationHeaders].join(",")
+ : bomHeaders.join(",")) + "\n";
+
+ if (!id) {
+ return new Response(headers, {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": "attachment; filename=bom.csv",
+ },
+ });
+ }
+
+ const methodTree = await getJobMethodTree(client, id);
+ if (methodTree.error) {
+ return new Response(headers, {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": "attachment; filename=bom.csv",
+ },
+ });
+ }
+
+ const fileName = `${methodTree.data[0].data.itemReadableId}-bom.csv`;
+
+ const methods =
+ methodTree.data.length > 0 ? flattenTree(methodTree.data[0]) : [];
+
+ const makeMethodIds = [
+ ...new Set(methods.map((method) => method.data.jobMakeMethodId)),
+ ];
+
+ let operationsByMakeMethodId: Record<
+ string,
+ Array<
+ JobOperation & {
+ processName: string;
+ workCenterName: string | null;
+ }
+ >
+ > = {};
+
+ 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,
+ },
+ }
+ : null,
+ };
+ acc[operation.jobMakeMethodId ?? ""] = [
+ ...(acc[operation.jobMakeMethodId ?? ""] || []),
+ transformedOperation,
+ ];
+ return acc;
+ }, {});
+ }
+ }
+
+ const bomIds = generateBomIds(methods);
+
+ let csv = headers;
+
+ methods.forEach((node, index) => {
+ const total = calculateTotalQuantity(node, methods);
+ const totalCost = total * (node.data.unitCost || 0);
+
+ csv += `${bomIds[index]},${
+ node.data.itemReadableId
+ },"${node.data.description?.replace(/"/g, '""')}",${
+ node.data.quantity
+ },${total},${node.data.unitCost},${totalCost},,${node.data.methodType},${
+ node.data.itemType
+ },${node.level},${node.data.version || ""}\n`;
+
+ if (withOperations) {
+ const operations =
+ operationsByMakeMethodId[node.data.jobMaterialMakeMethodId];
+ if (operations) {
+ operations.forEach((operation) => {
+ const op1 = makeDurations({ ...operation, operationQuantity: total });
+ const op100 = makeDurations({
+ ...operation,
+ operationQuantity: total * 100,
+ });
+ const op1000 = makeDurations({
+ ...operation,
+ operationQuantity: total * 1000,
+ });
+
+ csv += Array(bomHeaders.length).fill(",").join("");
+ csv += `${operation.description},${operation.processName},${
+ operation.workCenterName ?? ""
+ },${operation.operationType},${operation.setupTime},${
+ operation.setupUnit
+ },${operation.laborTime},${operation.laborUnit},${
+ operation.machineTime
+ },${operation.machineUnit},${op1.duration},${op100.duration},${
+ op1000.duration
+ }\n`;
+ });
+ }
+ }
+ });
+
+ return new Response(csv, {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": `attachment; filename=${fileName}`,
+ },
+ });
+}