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: download csv and json for bill of material item master
Brad Barbinf46937f589c5
diff --git a/apps/erp/app/assets/icons/AlmostDoneIcon.tsx b/apps/erp/app/assets/icons/AlmostDoneIcon.tsxindex 921e44a27f..da9e451fea 100644--- a/apps/erp/app/assets/icons/AlmostDoneIcon.tsx+++ b/apps/erp/app/assets/icons/AlmostDoneIcon.tsx@@ -13,7 +13,7 @@ export function AlmostDoneIcon({ className }: { className?: string }) {cy="7"r="6"fill="none"- stroke="#26a544"+ stroke="#10b981"strokeWidth="2"strokeDasharray="3.14 0"strokeDashoffset="-0.7"@@ -23,7 +23,7 @@ export function AlmostDoneIcon({ className }: { className?: string }) {cy="7"r="2"fill="none"- stroke="#26a544"+ stroke="#10b981"strokeWidth="4"strokeDasharray="9.377654070965532 100"strokeDashoffset="0"diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsxindex 1b235e1518..e539f29afd 100644--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx@@ -1,6 +1,12 @@+/* eslint-disable react/jsx-no-undef */import {Badge,Copy,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuIcon,+ DropdownMenuItem,+ DropdownMenuTrigger,HStack,HoverCard,HoverCardContent,@@ -16,13 +22,14 @@ import {import { useOptimisticLocation } from "@carbon/remix";import { Link, useNavigate, useParams } from "@remix-run/react";import { useRef, useState } from "react";-import { CSVLink } from "react-csv";import {+ LuBraces,LuChevronDown,LuChevronRight,LuDownload,LuExternalLink,LuSearch,+ LuTable,} from "react-icons/lu";import { MethodIcon, MethodItemTypeIcon } from "~/components";import { OnshapeStatus } from "~/components/Icons";@@ -33,13 +40,14 @@ import { OnshapeSync } from "~/integrations/onshape/lib/OnshapeSync";import { type MethodItemType } from "~/modules/shared";import { useBom } from "~/stores";import { path } from "~/utils/path";-import type { MakeMethod, Method } from "../../types";+import type { MakeMethod, Method, MethodOperation } from "../../types";import { getLinkToItemDetails } from "./ItemForm";type BoMExplorerProps = {itemType: MethodItemType;makeMethod: MakeMethod;methods: FlatTreeItem<Method>[];+ operations: MethodOperation[];selectedId?: string;};@@ -60,17 +68,6 @@ const BoMExplorer = ({status: makeMethodStatus,} = makeMethod;- const csvData = methods.map((node) => ({- "Item ID": node.data.itemReadableId,- Description: node.data.description,- Quantity: node.data.quantity,- UOM: node.data.unitOfMeasureCode,- "Method Type": node.data.methodType,- "Item Type": node.data.itemType,- Level: node.level,- Version: node.data.version || "",- }));-const {nodes,getTreeProps,@@ -139,13 +136,78 @@ const BoMExplorer = ({onChange={(e) => setFilterText(e.target.value)}/></InputGroup>- <CSVLink- data={csvData}- filename={`bom-${makeMethod.id}-v${makeMethodVersion}.csv`}- className="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-secondary text-secondary-foreground hover:bg-secondary/80 h-9 w-9"- >- <LuDownload className="h-4 w-4" />- </CSVLink>++ <DropdownMenu>+ <DropdownMenuTrigger>+ <IconButton+ aria-label="Actions"+ variant="ghost"+ icon={<LuDownload />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem asChild>+ <a+ href={path.to.api.billOfMaterialsCsv(makeMethodId, false)}+ target="_blank"+ rel="noreferrer"+ >+ <DropdownMenuIcon icon={<LuTable />} />+ <div className="flex flex-grow items-center gap-4 justify-between">+ <span>BoM</span>+ <Badge variant="green" className="text-xs">+ CSV+ </Badge>+ </div>+ </a>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <a+ href={path.to.api.billOfMaterialsCsv(makeMethodId, true)}+ target="_blank"+ rel="noreferrer"+ >+ <DropdownMenuIcon icon={<LuTable />} />+ <div className="flex flex-grow items-center gap-4 justify-between">+ <span>BoM + BoP</span>+ <Badge variant="green" className="text-xs">+ CSV+ </Badge>+ </div>+ </a>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <a+ href={path.to.api.billOfMaterials(makeMethodId, false)}+ target="_blank"+ rel="noreferrer"+ >+ <DropdownMenuIcon icon={<LuBraces />} />+ <div className="flex flex-grow items-center gap-4 justify-between">+ <span>BoM</span>+ <Badge variant="outline" className="text-xs">+ JSON+ </Badge>+ </div>+ </a>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <a+ href={path.to.api.billOfMaterials(makeMethodId, true)}+ target="_blank"+ rel="noreferrer"+ >+ <DropdownMenuIcon icon={<LuBraces />} />+ <div className="flex flex-grow items-center gap-4 justify-between">+ <span>BoM + BoP</span>+ <Badge variant="outline" className="text-xs">+ JSON+ </Badge>+ </div>+ </a>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></HStack>{integrations.has("onshape") && (<OnshapeSyncdiff --git a/apps/erp/app/routes/api+/items.methods.$id.bom.tsx b/apps/erp/app/routes/api+/items.methods.$id.bom.tsxnew file mode 100644index 0000000000..e77d6e1368--- /dev/null+++ b/apps/erp/app/routes/api+/items.methods.$id.bom.tsx@@ -0,0 +1,133 @@+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 type { Method } from "~/modules/items";+import { getMethodTree } from "~/modules/items";+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, {});++ const { id } = params;+ const withOperations = request.url.includes("withOperations=true");++ if (!id) {+ return { data: [], error: null };+ }++ const methodTree = await getMethodTree(client, id);+ if (methodTree.error) {+ return { data: [], error: methodTree.error };+ }++ const methods = (+ methodTree.data.length > 0 ? flattenTree(methodTree.data[0]) : []+ ) satisfies FlatTreeItem<Method>[];++ const makeMethodIds = [+ ...new Set(methods.map((method) => method.data.makeMethodId)),+ ];++ let operationsByMakeMethodId: Record<+ string,+ Array<+ Database["public"]["Tables"]["methodOperation"]["Row"] & {+ processName: string;+ workCenterName: string | 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+ );+ }+ }++ 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,+ uom: node.data.unitOfMeasureCode,+ 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.materialMakeMethodId];+ 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+/items.methods.$id.bom[.]csv.tsx b/apps/erp/app/routes/api+/items.methods.$id.bom[.]csv.tsxnew file mode 100644index 0000000000..2b71a9582b--- /dev/null+++ b/apps/erp/app/routes/api+/items.methods.$id.bom[.]csv.tsx@@ -0,0 +1,170 @@+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 type { Method } from "~/modules/items";+import { getMethodTree } from "~/modules/items";+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, {});++ 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 getMethodTree(client, id);+ if (methodTree.error) {+ return new Response(headers, {+ headers: {+ "Content-Type": "text/csv",+ "Content-Disposition": "attachment; filename=bom.csv",+ },+ });+ }++ const methods = (+ methodTree.data.length > 0 ? flattenTree(methodTree.data[0]) : []+ ) satisfies FlatTreeItem<Method>[];++ const makeMethodIds = [+ ...new Set(methods.map((method) => method.data.makeMethodId)),+ ];++ let operationsByMakeMethodId: Record<+ string,+ Array<+ Database["public"]["Tables"]["methodOperation"]["Row"] & {+ processName: string;+ workCenterName: string | 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+ );+ }+ }++ 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.unitOfMeasureCode+ },${node.data.methodType},${node.data.itemType},${node.level},${+ node.data.version || ""+ }\n`;++ if (withOperations) {+ const operations =+ operationsByMakeMethodId[node.data.materialMakeMethodId];+ 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=bom.csv",+ },+ });+}diff --git a/apps/erp/app/utils/bom.ts b/apps/erp/app/utils/bom.tsnew file mode 100644index 0000000000..4690bda81a--- /dev/null+++ b/apps/erp/app/utils/bom.ts@@ -0,0 +1,48 @@+import type { FlatTreeItem } from "~/components/TreeView";+import type { Method } from "~/modules/items";++export const calculateTotalQuantity = (+ node: FlatTreeItem<Method>,+ nodes: FlatTreeItem<Method>[]+): number => {+ // Create lookup map for faster parent finding+ const nodeMap = new Map(nodes.map((n) => [n.id, n]));+ let quantity = node.data.quantity || 1;+ let currentNode = node;++ while (currentNode.parentId) {+ const parent = nodeMap.get(currentNode.parentId);+ if (!parent) break;+ quantity *= parent.data.quantity || 1;+ currentNode = parent;+ }++ return quantity;+};++export const generateBomIds = (nodes: FlatTreeItem<Method>[]): string[] => {+ const ids = new Array(nodes.length);+ const levelCounters = new Map<number, number>();++ nodes.forEach((node, index) => {+ const level = node.level;++ // Reset deeper level counters when moving to shallower level+ if (index > 0 && level <= nodes[index - 1].level) {+ for (const [key] of levelCounters) {+ if (key > level) levelCounters.delete(key);+ }+ }++ // Update counter for current level+ levelCounters.set(level, (levelCounters.get(level) || 0) + 1);++ // Build ID string from all level counters+ ids[index] = Array.from(+ { length: level + 1 },+ (_, i) => levelCounters.get(i) || 1+ ).join(".");+ });++ return ids;+};diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex c903bb96e8..472365a572 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -19,6 +19,14 @@ export const path = {autodeskUpload: `${api}/autodesk/upload`,batchNumbers: (itemId: string) =>generatePath(`${api}/inventory/batch-numbers?itemId=${itemId}`),+ billOfMaterials: (methodId: string, withOperations: boolean = false) =>+ generatePath(+ `${api}/items/methods/${methodId}/bom?withOperations=${withOperations}`+ ),+ billOfMaterialsCsv: (methodId: string, withOperations: boolean = false) =>+ generatePath(+ `${api}/items/methods/${methodId}/bom.csv?withOperations=${withOperations}`+ ),countries: `${api}/countries`,currencies: `${api}/accounting/currencies`,customerContacts: (id: string) =>diff --git a/apps/erp/tsconfig.json b/apps/erp/tsconfig.jsonindex a3209f8d54..6be6e78d8d 100644--- a/apps/erp/tsconfig.json+++ b/apps/erp/tsconfig.json@@ -5,8 +5,7 @@"**/*.tsx","app/modules/documents/documents.service.ts","app/types/global.d.ts",- "trigger.config.ts",- "../../packages/react/src/Copy.tsx"+ "trigger.config.ts"],"compilerOptions": {"lib": ["dom", "dom.iterable", "ESNext"],diff --git a/apps/mes/app/assets/icons/AlmostDoneIcon.tsx b/apps/mes/app/assets/icons/AlmostDoneIcon.tsxindex 921e44a27f..da9e451fea 100644--- a/apps/mes/app/assets/icons/AlmostDoneIcon.tsx+++ b/apps/mes/app/assets/icons/AlmostDoneIcon.tsx@@ -13,7 +13,7 @@ export function AlmostDoneIcon({ className }: { className?: string }) {cy="7"r="6"fill="none"- stroke="#26a544"+ stroke="#10b981"strokeWidth="2"strokeDasharray="3.14 0"strokeDashoffset="-0.7"@@ -23,7 +23,7 @@ export function AlmostDoneIcon({ className }: { className?: string }) {cy="7"r="2"fill="none"- stroke="#26a544"+ stroke="#10b981"strokeWidth="4"strokeDasharray="9.377654070965532 100"strokeDashoffset="0"diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsxindex 87cc239be8..ec9c979268 100644--- a/apps/mes/app/components/AppSidebar.tsx+++ b/apps/mes/app/components/AppSidebar.tsx@@ -47,6 +47,7 @@ import {} from "@carbon/react";import { Form, Link, useFetcher, useLocation } from "@remix-run/react";import { useRef, type ComponentProps } from "react";+import { BsFillHexagonFill } from "react-icons/bs";import { useMode, useUser } from "~/hooks";import type { action } from "~/root";import type { Location } from "~/services/types";@@ -54,7 +55,6 @@ import { ERP_URL, path } from "~/utils/path";import { AdjustInventory } from "./AdjustInventory";import { EndShift } from "./EndShift";import Feedback from "./Feedback";-import { BsFillHexagonFill } from "react-icons/bs";export function AppSidebar({activeEvents,diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.tsindex cd953ff61b..33fb82d3a5 100644--- a/packages/utils/src/themes.ts+++ b/packages/utils/src/themes.ts@@ -3,7 +3,7 @@ import template from "lodash.template";export const themes = [{name: "zinc",- label: "Carbon",+ label: "Zinc",activeColor: {light: "220 5.9% 10%",dark: "220 5.2% 33.9%",