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: download csv and json for quote bill of material

Brad Barbin73ffaea13fc2
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
index ea249748df..9f7b8b73c3 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
@@ -1,10 +1,15 @@
import {
+ Badge,
Button,
cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
DropdownMenuTrigger,
HStack,
IconButton,
@@ -21,10 +26,13 @@ import { prettifyKeyboardShortcut } from "@carbon/utils";
import { useNavigate, useParams } from "@remix-run/react";
import { useMemo, useRef, useState } from "react";
import {
+ LuBraces,
LuChevronDown,
LuCirclePlus,
+ LuDownload,
LuEllipsisVertical,
LuSearch,
+ LuTable,
LuTrash,
} from "react-icons/lu";
import { Empty, ItemThumbnail, MethodItemTypeIcon } from "~/components";
@@ -288,17 +296,6 @@ function QuoteLineItem({
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
- <DropdownMenuItem
- destructive
- disabled={isDisabled || !permissions.can("update", "sales")}
- onClick={(e) => {
- e.stopPropagation();
- onDelete(line);
- }}
- >
- <DropdownMenuIcon icon={<LuTrash />} />
- Delete Line
- </DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
@@ -320,11 +317,105 @@ function QuoteLineItem({
View Item Master
</DropdownMenuItem>
{line.methodType === "Make" && (
- <DropdownMenuItem onClick={searchDisclosure.onOpen}>
- <DropdownMenuIcon icon={<LuSearch />} />
- Search
- </DropdownMenuItem>
+ <>
+ <DropdownMenuItem onClick={searchDisclosure.onOpen}>
+ <DropdownMenuIcon icon={<LuSearch />} />
+ Search
+ </DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <DropdownMenuIcon icon={<LuDownload />} />
+ Download
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuItem asChild>
+ <a
+ href={path.to.api.quoteBillOfMaterialsCsv(
+ line.id!,
+ 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.quoteBillOfMaterialsCsv(
+ line.id!,
+ 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.quoteBillOfMaterials(
+ line.id!,
+ 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.quoteBillOfMaterials(
+ line.id!,
+ 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>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </>
)}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ destructive
+ disabled={isDisabled || !permissions.can("update", "sales")}
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete(line);
+ }}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Line
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</HStack>
diff --git a/apps/erp/app/routes/api+/items.methods.$id.bom.tsx b/apps/erp/app/routes/api+/items.methods.$id.bom.tsx
index e77d6e1368..efaa09ec79 100644
--- a/apps/erp/app/routes/api+/items.methods.$id.bom.tsx
+++ b/apps/erp/app/routes/api+/items.methods.$id.bom.tsx
@@ -13,7 +13,9 @@ export const config = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {});
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
const { id } = params;
const withOperations = request.url.includes("withOperations=true");
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 2b71a9582b..1d7ce5b16f 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
@@ -44,7 +44,9 @@ const operationHeaders = [
];
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {});
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
const { id } = params;
const withOperations = request.url.includes("withOperations=true");
diff --git a/apps/erp/app/routes/api+/sales.quote.line.$id.bom.tsx b/apps/erp/app/routes/api+/sales.quote.line.$id.bom.tsx
new file mode 100644
index 0000000000..d31db945e8
--- /dev/null
+++ b/apps/erp/app/routes/api+/sales.quote.line.$id.bom.tsx
@@ -0,0 +1,145 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { Database } from "@carbon/database";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { flattenTree } from "~/components/TreeView";
+import { getQuoteMethodTrees } from "~/modules/sales";
+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: "sales",
+ });
+
+ const { id } = params;
+ const withOperations = request.url.includes("withOperations=true");
+
+ if (!id) {
+ return { data: [], error: null };
+ }
+
+ const quote = await client
+ .from("quoteLine")
+ .select("quoteId, quantity")
+ .eq("id", id)
+ .single();
+ if (quote.error) {
+ return { data: [], error: "Failed to load quote line" };
+ }
+
+ const methodTrees = await getQuoteMethodTrees(client, quote.data?.quoteId);
+
+ if (methodTrees.error) {
+ return { data: [], error: methodTrees.error };
+ }
+
+ const methodTree = methodTrees.data.find((m) => m.data.quoteLineId === id);
+ const flattenedMethods = methodTree ? flattenTree(methodTree) : [];
+
+ const makeMethodIds = [
+ ...new Set(flattenedMethods.map((method) => method.data.quoteMakeMethodId)),
+ ];
+
+ let operationsByMakeMethodId: Record<
+ string,
+ Array<
+ Database["public"]["Tables"]["quoteOperation"]["Row"] & {
+ processName: string;
+ workCenterName: string | null;
+ }
+ >
+ > = {};
+
+ 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
+ );
+ }
+ }
+
+ console.log({ withOperations, operationsByMakeMethodId });
+
+ const bomIds = generateBomIds(flattenedMethods);
+
+ const result = flattenedMethods.map((node, index) => {
+ const total = calculateTotalQuantity(node, flattenedMethods);
+ 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.quoteMaterialMakeMethodId];
+ if (!operations) {
+ return { ...bomItem, operations: [] };
+ }
+
+ return {
+ ...bomItem,
+ operations: operations.map((operation) => {
+ const durations: Record<string, number> = (quote.data?.quantity ?? [])
+ .map((quantity) => {
+ const duration = makeDurations({
+ ...operation,
+ operationQuantity: quantity,
+ });
+ return [quantity, duration.duration];
+ })
+ .reduce((acc, [quantity, duration]) => {
+ acc[`totalDuration${quantity}`] = duration;
+ return acc;
+ }, {} as Record<string, number>);
+
+ 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,
+ ...durations,
+ };
+ }),
+ };
+ });
+
+ return { data: result, error: null };
+}
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
new file mode 100644
index 0000000000..f9a230479f
--- /dev/null
+++ b/apps/erp/app/routes/api+/sales.quote.line.$id.bom[.]csv.tsx
@@ -0,0 +1,195 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { Database } from "@carbon/database";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { flattenTree } from "~/components/TreeView";
+import { getQuoteMethodTrees } from "~/modules/sales";
+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",
+ "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",
+];
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { id } = params;
+ const withOperations = request.url.includes("withOperations=true");
+
+ if (!id) {
+ return new Response(bomHeaders.join(",") + "\n", {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": "attachment; filename=bom.csv",
+ },
+ });
+ }
+
+ const quote = await client
+ .from("quoteLine")
+ .select("quoteId, quantity")
+ .eq("id", id)
+ .single();
+ if (quote.error) {
+ return new Response(bomHeaders.join(",") + "\n", {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": "attachment; filename=bom.csv",
+ },
+ });
+ }
+
+ const methodTrees = await getQuoteMethodTrees(client, quote.data?.quoteId);
+
+ if (methodTrees.error) {
+ return new Response(bomHeaders.join(",") + "\n", {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": "attachment; filename=bom.csv",
+ },
+ });
+ }
+
+ const methodTree = methodTrees.data.find((m) => m.data.quoteLineId === id);
+ const flattenedMethods = methodTree ? flattenTree(methodTree) : [];
+
+ const makeMethodIds = [
+ ...new Set(flattenedMethods.map((method) => method.data.quoteMakeMethodId)),
+ ];
+
+ let operationsByMakeMethodId: Record<
+ string,
+ Array<
+ Database["public"]["Tables"]["quoteOperation"]["Row"] & {
+ processName: string;
+ workCenterName: string | null;
+ }
+ >
+ > = {};
+
+ 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
+ );
+ }
+ }
+
+ const bomIds = generateBomIds(flattenedMethods);
+
+ // Build headers including duration columns for each quantity
+ let headers = bomHeaders.join(",");
+ if (withOperations) {
+ headers += "," + operationHeaders.join(",");
+ // Add duration column for each quantity
+ if (quote.data?.quantity) {
+ quote.data.quantity.forEach((qty) => {
+ headers += `,Total Duration x ${qty} (ms)`;
+ });
+ }
+ }
+ headers += "\n";
+
+ let csv = headers;
+
+ flattenedMethods.forEach((node, index) => {
+ const total = calculateTotalQuantity(node, flattenedMethods);
+ 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.quoteMaterialMakeMethodId];
+ if (operations) {
+ operations.forEach((operation) => {
+ const durations: Record<string, number> = (quote.data?.quantity ?? [])
+ .map((quantity) => {
+ const duration = makeDurations({
+ ...operation,
+ operationQuantity: quantity,
+ });
+ return [quantity, duration.duration];
+ })
+ .reduce((acc, [quantity, duration]) => {
+ acc[`totalDuration${quantity}`] = duration;
+ return acc;
+ }, {} as Record<string, number>);
+
+ 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}`;
+
+ // Add duration values for each quantity
+ if (quote.data?.quantity) {
+ quote.data.quantity.forEach((qty) => {
+ csv += `,${durations[`totalDuration${qty}`] || 0}`;
+ });
+ }
+ csv += "\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.ts
index 4690bda81a..24a30d4b24 100644
--- a/apps/erp/app/utils/bom.ts
+++ b/apps/erp/app/utils/bom.ts
@@ -1,9 +1,10 @@
import type { FlatTreeItem } from "~/components/TreeView";
import type { Method } from "~/modules/items";
+import type { QuoteMethod } from "~/modules/sales/types";
export const calculateTotalQuantity = (
- node: FlatTreeItem<Method>,
- nodes: FlatTreeItem<Method>[]
+ node: FlatTreeItem<QuoteMethod> | FlatTreeItem<Method>,
+ nodes: FlatTreeItem<QuoteMethod>[] | FlatTreeItem<Method>[]
): number => {
// Create lookup map for faster parent finding
const nodeMap = new Map(nodes.map((n) => [n.id, n]));
@@ -20,7 +21,9 @@ export const calculateTotalQuantity = (
return quantity;
};
-export const generateBomIds = (nodes: FlatTreeItem<Method>[]): string[] => {
+export const generateBomIds = (
+ nodes: FlatTreeItem<QuoteMethod>[] | FlatTreeItem<Method>[]
+): string[] => {
const ids = new Array(nodes.length);
const levelCounters = new Map<number, number>();
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 472365a572..40e131dbd9 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -76,6 +76,20 @@ export const path = {
processes: `${api}/resources/processes`,
productionKpi: (key: string) =>
generatePath(`${api}/production/kpi/${key}`),
+ quoteBillOfMaterials: (
+ methodId: string,
+ withOperations: boolean = false
+ ) =>
+ generatePath(
+ `${api}/sales/quote/line/${methodId}/bom?withOperations=${withOperations}`
+ ),
+ quoteBillOfMaterialsCsv: (
+ methodId: string,
+ withOperations: boolean = false
+ ) =>
+ generatePath(
+ `${api}/sales/quote/line/${methodId}/bom.csv?withOperations=${withOperations}`
+ ),
quotes: `${api}/sales/quotes`,
quoteLines: (quoteId: string) =>
generatePath(`${api}/sales/quotes/${quoteId}/lines`),