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: add calculated bom id to bom explorers and job traveler
Brad Barbin03162191fd34
diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsxindex b887b8118a..a9fd16a001 100644--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx@@ -22,7 +22,7 @@ import {VStack} from "@carbon/react";import { useOptimisticLocation } from "@carbon/remix";-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import {LuBraces,LuChevronDown,@@ -42,6 +42,7 @@ import type { FlatTreeItem } from "~/components/TreeView";import { LevelLine, TreeView, useTree } from "~/components/TreeView";import { useIntegrations } from "~/hooks/useIntegrations";import { type MethodItemType } from "~/modules/shared";+import { generateBomIds } from "~/utils/bom";import { path } from "~/utils/path";import type { MakeMethod, Method, MethodOperation } from "../../types";import { getLinkToItemDetails } from "./ItemForm";@@ -103,6 +104,13 @@ const BoMExplorer = ({isEager: true});+ // Generate hierarchical BOM IDs (1, 1.1, 1.1.1, etc.)+ const bomIds = useMemo(() => generateBomIds(methods), [methods]);+ const bomIdMap = useMemo(+ () => new Map(methods.map((node, index) => [node.id, bomIds[index]])),+ [methods, bomIds]+ );+const navigate = useNavigate();const location = useOptimisticLocation();@@ -326,19 +334,16 @@ const BoMExplorer = ({<div className="flex w-full items-center justify-between gap-2"><div className="flex items-center gap-2 overflow-x-hidden">- <MethodIcon- type={- // node.data.isRoot ? "Method" :- node.data.methodType- }- isKit={node.data.kit}- className="h-4 min-h-4 w-4 min-w-4 flex-shrink-0"- />+ {bomIdMap.get(node.id) && (+ <Badge variant="outline">+ {bomIdMap.get(node.id)}+ </Badge>+ )}<NodeText node={node} /></div><div className="flex items-center gap-1">{node.data.isRoot ? (- <Badge variant="outline" className="text-xs">+ <Badge variant="outline">V{makeMethodVersion}</Badge>) : (@@ -390,16 +395,17 @@ function NodeData({ node }: { node: FlatTreeItem<Method> }) {return (<HStack spacing={1}><Badge className="text-xs" variant="outline">+ <MethodIcon+ type={+ // node.data.isRoot ? "Method" :+ node.data.methodType+ }+ isKit={node.data.kit}+ className="mr-2"+ />{node.data.quantity}</Badge>-- {onShapeState ? (- <OnshapeStatus status={onShapeState} />- ) : (- <Badge variant="secondary">- <MethodItemTypeIcon type={node.data.itemType} />- </Badge>- )}+ {onShapeState && <OnshapeStatus status={onShapeState} />}</HStack>);}diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsxindex 521286ff10..e3fc43d333 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx@@ -18,7 +18,7 @@ import {Spinner,VStack} from "@carbon/react";-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import {LuBraces,LuChevronDown,@@ -42,6 +42,7 @@ import { LevelLine, TreeView, useTree } from "~/components/TreeView";import { useOptimisticLocation } from "~/hooks";import { useIntegrations } from "~/hooks/useIntegrations";import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";+import { generateBomIds } from "~/utils/bom";import { path } from "~/utils/path";import type { JobMethod } from "../../production.service";@@ -63,6 +64,13 @@ const JobBoMExplorer = ({ method }: JobBoMExplorerProps) => {const isLoading = getMethodFetcher?.state === "loading";+ // Generate hierarchical BOM IDs (1, 1.1, 1.1.1, etc.)+ const bomIds = useMemo(() => generateBomIds(method), [method]);+ const bomIdMap = useMemo(+ () => new Map(method.map((node, index) => [node.id, bomIds[index]])),+ [method, bomIds]+ );+const {nodes,getTreeProps,@@ -289,16 +297,16 @@ const JobBoMExplorer = ({ method }: JobBoMExplorerProps) => {<div className="flex w-full items-center justify-between gap-2"><div className="flex items-center gap-2 overflow-x-hidden">- <MethodIcon- type={node.data.methodType}- isKit={node.data.kit}- className="h-4 min-h-4 w-4 min-w-4 flex-shrink-0"- />+ {bomIdMap.get(node.id) && (+ <Badge variant="outline">+ {bomIdMap.get(node.id)}+ </Badge>+ )}<NodeText node={node} /></div><div className="flex items-center gap-1">{node.data.isRoot ? (- <Badge variant="outline" className="text-xs">+ <Badge variant="outline">V{node.data.version}</Badge>) : (@@ -344,15 +352,17 @@ function NodeData({ node }: { node: FlatTreeItem<JobMethod> }) {return (<HStack spacing={1}><Badge className="text-xs" variant="outline">+ <MethodIcon+ type={+ // node.data.isRoot ? "Method" :+ node.data.methodType+ }+ isKit={node.data.kit}+ className="mr-2"+ />{node.data.quantity}</Badge>- {onShapeState ? (- <OnshapeStatus status={onShapeState} />- ) : (- <Badge variant="secondary">- <MethodItemTypeIcon type={node.data.itemType} />- </Badge>- )}+ {onShapeState && <OnshapeStatus status={onShapeState} />}</HStack>);}diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsxindex 2c0ea2fe20..9fb3602610 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx@@ -13,7 +13,7 @@ import {Spinner,VStack} from "@carbon/react";-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import {LuChevronDown,LuChevronRight,@@ -34,6 +34,7 @@ import { LevelLine, TreeView, useTree } from "~/components/TreeView";import { useOptimisticLocation } from "~/hooks";import { useIntegrations } from "~/hooks/useIntegrations";import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";+import { generateBomIds } from "~/utils/bom";import { path } from "~/utils/path";import type { QuoteMethod } from "../../types";@@ -62,6 +63,13 @@ const QuoteBoMExplorer = ({getMethodFetcher.formData?.get("quoteLineId") ===methods?.[0].data.quoteLineId;+ // Generate hierarchical BOM IDs (1, 1.1, 1.1.1, etc.)+ const bomIds = useMemo(() => generateBomIds(methods), [methods]);+ const bomIdMap = useMemo(+ () => new Map(methods.map((node, index) => [node.id, bomIds[index]])),+ [methods, bomIds]+ );+const {nodes,getTreeProps,@@ -215,21 +223,16 @@ const QuoteBoMExplorer = ({<div className="flex w-full items-center justify-between gap-2"><div className="flex items-center gap-2 overflow-x-hidden">- <MethodIcon- type={- // node.data.isRoot ? "Method" :- node.data.methodType- }- isKit={node.data.kit}- className="h-4 min-h-4 w-4 min-w-4 flex-shrink-0"- />+ {bomIdMap.get(node.id) && (+ <Badge variant="outline">+ {bomIdMap.get(node.id)}+ </Badge>+ )}<NodeText node={node} /></div><div className="flex items-center gap-1">{node.data.isRoot ? (- <Badge variant="outline" className="text-xs">- V{node.data.version}- </Badge>+ <Badge variant="outline">V{node.data.version}</Badge>) : (<NodeData node={node} />)}@@ -251,7 +254,13 @@ const QuoteBoMExplorer = ({export default QuoteBoMExplorer;-function NodeText({ node }: { node: FlatTreeItem<QuoteMethod> }) {+function NodeText({+ node,+ bomId+}: {+ node: FlatTreeItem<QuoteMethod>;+ bomId?: string;+}) {return (<div className="flex items-center gap-1"><span className="font-medium text-sm truncate">@@ -272,15 +281,18 @@ function NodeData({ node }: { node: FlatTreeItem<QuoteMethod> }) {return (<HStack spacing={1}><Badge className="text-xs" variant="outline">+ <MethodIcon+ type={+ // node.data.isRoot ? "Method" :+ node.data.methodType+ }+ isKit={node.data.kit}+ className="mr-2"+ />{node.data.quantity}</Badge>- {onShapeState ? (- <OnshapeStatus status={onShapeState} />- ) : (- <Badge variant="secondary">- <MethodItemTypeIcon type={node.data.itemType} />- </Badge>- )}++ {onShapeState && <OnshapeStatus status={onShapeState} />}</HStack>);}diff --git a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsxindex c5b0fe0f09..b1ff68dbab 100644--- a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx+++ b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx@@ -2,6 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { JobTravelerPageContent } from "@carbon/documents/pdf";import type { JSONContent } from "@carbon/react";+import { flattenTree, generateBomIds } from "@carbon/utils";import {Document,Font,@@ -12,6 +13,7 @@ import {import { type LoaderFunctionArgs } from "react-router";import {getJob,+ getJobMethodTree,getJobOperationsByMethodId,getTrackedEntityByJobId} from "~/modules/production/production.service";@@ -65,6 +67,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// Get job notes if they existconst jobNotes = job.data.notes as JSONContent | undefined;+ // Compute BOM IDs for all make methods+ const bomIdMap = new Map<string, string>();+ const methodTree = await getJobMethodTree(serviceRole, jobId);+ if (!methodTree.error && methodTree.data?.length > 0) {+ const flatMethods = flattenTree(methodTree.data[0]);+ const bomIds = generateBomIds(flatMethods);+ flatMethods.forEach((node, index) => {+ bomIdMap.set(node.data.jobMaterialMakeMethodId, bomIds[index]);+ });+ }+// For each make method, get operations and item dataconst makeMethodsWithData = await Promise.all(jobMakeMethods.data.map(async (makeMethod) => {@@ -118,7 +131,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {operations: operations.data,item: item.data,thumbnail,- batchNumber+ batchNumber,+ bomId: bomIdMap.get(makeMethod.id)};}));@@ -175,6 +189,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {customer={customer.data}item={data.item}batchNumber={data.batchNumber}+ bomId={data.bomId}notes={index === 0 ? jobNotes : undefined}thumbnail={data.thumbnail}methodRevision={data.makeMethod.version?.toString()}diff --git a/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsxindex 4087dfda13..dde2065c17 100644--- a/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx@@ -2,11 +2,13 @@ import { getCarbonServiceRole } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { JobTravelerPDF } from "@carbon/documents/pdf";import type { JSONContent } from "@carbon/react";+import { flattenTree, generateBomIds } from "@carbon/utils";import { renderToStream } from "@react-pdf/renderer";import { type LoaderFunctionArgs } from "react-router";import {getJob,getJobMakeMethodById,+ getJobMethodTree,getJobOperationsByMethodId,getTrackedEntityByJobId} from "~/modules/production/production.service";@@ -85,6 +87,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// Get job notes if they existconst jobNotes = job.data.notes as JSONContent | undefined;+ // Compute BOM ID for this make method+ let bomId: string | undefined;+ const methodTree = await getJobMethodTree(serviceRole, job.data.id!);+ if (!methodTree.error && methodTree.data?.length > 0) {+ const flatMethods = flattenTree(methodTree.data[0]);+ const bomIds = generateBomIds(flatMethods);+ // Find the node matching this make method+ const nodeIndex = flatMethods.findIndex(+ (node) => node.data.jobMaterialMakeMethodId === id+ );+ if (nodeIndex >= 0) {+ bomId = bomIds[nodeIndex];+ }+ }+// Get thumbnail if it existslet thumbnail: string | null = null;if (item.data.thumbnailPath || item.data.modelUpload?.thumbnailPath) {@@ -105,6 +122,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {customer={customer.data}item={item.data}batchNumber={batchNumber}+ bomId={bomId}locale={locale}meta={{author: "Carbon",diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsxindex eb2f9a718d..e1332e9038 100644--- a/apps/mes/app/routes/x+/operation.$operationId.tsx+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx@@ -9,6 +9,7 @@ import {getJobFiles,getJobMakeMethod,getJobMaterialsByOperationId,+ getJobMethodBomIdMap,getJobOperationById,getJobOperationProcedure,getKanbanByJobId,@@ -65,7 +66,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const [thumbnailPath, trackedEntities, jobMakeMethod, kanban] =+ const [thumbnailPath, trackedEntities, jobMakeMethod, kanban, bomIdMap] =await Promise.all([getThumbnailPathByItemId(serviceRole, operation.data?.[0].itemId),getTrackedEntitiesByMakeMethodId(@@ -73,7 +74,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {operation.data?.[0].jobMakeMethodId),getJobMakeMethod(serviceRole, operation.data?.[0].jobMakeMethodId),- getKanbanByJobId(serviceRole, job.data.id)+ getKanbanByJobId(serviceRole, job.data.id),+ getJobMethodBomIdMap(serviceRole, job.data.id!)]);// If no trackedEntityId is provided in the URL but trackedEntities exist,@@ -96,6 +98,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}return {+ bomIdMap: Object.fromEntries(bomIdMap),events: events.data ?? [],quantities: (quantities.data ?? []).reduce((acc, curr) => {@@ -149,9 +152,12 @@ export default function OperationRoute() {thumbnailPath,trackedEntities,workCenter,- nonConformanceActions+ nonConformanceActions,+ bomIdMap} = useLoaderData<typeof loader>();+ console.log({ bomIdMap });+return (<JobOperationkey={`job-operation-${operationId}`}diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 61135a4c87..ca69c6c585 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -1,6 +1,11 @@import type { Database } from "@carbon/database";import type { JSONContent } from "@carbon/react";-import type { TrackedActivityAttributes } from "@carbon/utils";+import {+ type FlatTree,+ flattenTree,+ generateBomIds,+ type TrackedActivityAttributes+} from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";import type { z } from "zod";@@ -877,3 +882,78 @@ export async function startProductionEvent(return client.from("productionEvent").insert(data).select("*");}++type JobMethod = {+ id: string;+ methodMaterialId: string;+ parentMaterialId: string | null;+ [key: string]: unknown;+};++type JobMethodTreeItem = {+ id: string;+ data: JobMethod;+ children: JobMethodTreeItem[];+};++function arrayToTree(items: JobMethod[]): JobMethodTreeItem[] {+ const rootItems: JobMethodTreeItem[] = [];+ const lookup: { [id: string]: JobMethodTreeItem } = {};++ for (const item of items) {+ const itemId = item.methodMaterialId;+ const parentId = item.parentMaterialId;++ if (!Object.prototype.hasOwnProperty.call(lookup, itemId)) {+ // @ts-expect-error - building tree incrementally+ lookup[itemId] = { id: itemId, children: [] };+ }++ lookup[itemId].data = item;++ const treeItem = lookup[itemId];++ if (parentId === null || parentId === undefined) {+ rootItems.push(treeItem);+ } else {+ if (!Object.prototype.hasOwnProperty.call(lookup, parentId)) {+ // @ts-expect-error - building tree incrementally+ lookup[parentId] = { id: parentId, children: [] };+ }+ lookup[parentId].children.push(treeItem);+ }+ }+ return rootItems;+}++/**+ * Fetches the job method tree and generates BOM IDs.+ * Returns a map of methodMaterialId to hierarchical BOM ID (e.g., "1.2.3").+ */+export async function getJobMethodBomIdMap(+ client: SupabaseClient<Database>,+ jobId: string+): Promise<Map<string, string>> {+ const result = await client.rpc("get_job_method", { jid: jobId });++ if (result.error || !result.data?.length) {+ return new Map();+ }++ const tree = arrayToTree(result.data as JobMethod[]);+ if (tree.length === 0) {+ return new Map();+ }++ // Flatten tree and generate BOM IDs+ const flatMethods: FlatTree<JobMethod> = flattenTree(tree[0]);+ const bomIds = generateBomIds(flatMethods);++ // Create map of methodMaterialId to BOM ID+ const bomIdMap = new Map<string, string>();+ flatMethods.forEach((node, index) => {+ bomIdMap.set(node.data.methodMaterialId, bomIds[index]);+ });++ return bomIdMap;+}diff --git a/packages/documents/src/pdf/JobTravelerPDF.tsx b/packages/documents/src/pdf/JobTravelerPDF.tsxindex f29ca45418..18f073629b 100644--- a/packages/documents/src/pdf/JobTravelerPDF.tsx+++ b/packages/documents/src/pdf/JobTravelerPDF.tsx@@ -22,6 +22,7 @@ interface JobTravelerProps extends PDF {customer: Database["public"]["Tables"]["customer"]["Row"] | null;item: Database["public"]["Tables"]["item"]["Row"];batchNumber: string | undefined;+ bomId?: string;notes?: JSONContent;thumbnail?: string | null;}@@ -103,18 +104,20 @@ type JobHeaderProps = {customer: Database["public"]["Tables"]["customer"]["Row"] | null;item: Database["public"]["Tables"]["item"]["Row"];batchNumber?: string;+ bomId?: string;thumbnail?: string | null;methodRevision?: string | null;};const JobHeader = ({+ batchNumber,+ bomId,company,- job,customer,item,- batchNumber,- thumbnail,- methodRevision+ job,+ methodRevision,+ thumbnail}: JobHeaderProps) => {const getTargetInfo = () => {if (job.salesOrderId && job.salesOrderLineId) {@@ -241,6 +244,7 @@ export const JobTravelerPageContent = ({customer,item,batchNumber,+ bomId,notes,thumbnail,methodRevision@@ -250,9 +254,7 @@ export const JobTravelerPageContent = ({const subtitle = batchNumber? batchNumber: (item.name ?? item.readableIdWithRevision);- const tertiaryTitle = batchNumber- ? `${item.name ?? item.readableIdWithRevision}`- : undefined;+ const tertiaryTitle = `Assembly ${bomId}`;return (<View style={tw("flex flex-col")}>@@ -274,6 +276,7 @@ export const JobTravelerPageContent = ({customer={customer}item={item}batchNumber={batchNumber}+ bomId={bomId}thumbnail={thumbnail}methodRevision={methodRevision}/>@@ -494,6 +497,7 @@ const JobTravelerPDF = ({customer,item,batchNumber,+ bomId,meta,notes,thumbnail,@@ -515,6 +519,7 @@ const JobTravelerPDF = ({customer={customer}item={item}batchNumber={batchNumber}+ bomId={bomId}notes={notes}thumbnail={thumbnail}methodRevision={jobMakeMethod.version?.toString()}diff --git a/packages/utils/src/bom.ts b/packages/utils/src/bom.tsnew file mode 100644index 0000000000..489ff15d4b--- /dev/null+++ b/packages/utils/src/bom.ts@@ -0,0 +1,90 @@+/**+ * Tree and BOM (Bill of Materials) utility types and functions+ */++/** A tree structure */+export type Tree<TData> = {+ id: string;+ children?: Tree<TData>[];+ data: TData;+};++/** A tree but flattened so it can easily be used for DOM elements */+export type FlatTreeItem<TData> = {+ id: string;+ parentId: string | undefined;+ children: string[];+ hasChildren: boolean;+ /** The indentation level, the root is 0 */+ level: number;+ data: TData;+};++export type FlatTree<TData> = FlatTreeItem<TData>[];++/**+ * Flattens a tree structure into an array of FlatTreeItems.+ * Preserves parent-child relationships and calculates the level (depth) of each node.+ */+export function flattenTree<TData>(tree: Tree<TData>): FlatTree<TData> {+ const flatTree: FlatTree<TData> = [];++ function flattenNode(+ node: Tree<TData>,+ parentId: string | undefined,+ level: number+ ) {+ const children = node.children?.map((child) => child.id) ?? [];+ flatTree.push({+ id: node.id,+ parentId,+ children,+ hasChildren: children.length > 0,+ level,+ data: node.data+ });++ node.children?.forEach((child) => {+ flattenNode(child, node.id, level + 1);+ });+ }++ flattenNode(tree, undefined, 0);++ return flatTree;+}++/**+ * Generates hierarchical BOM IDs for a flattened tree.+ * Root node gets "1", children get "1.1", "1.2", etc.+ * Grandchildren get "1.1.1", "1.1.2", etc.+ *+ * @param nodes - A flattened tree with level information+ * @returns An array of BOM IDs in the same order as the input nodes+ */+export function generateBomIds<TData>(nodes: FlatTreeItem<TData>[]): string[] {+ const ids = new Array<string>(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/packages/utils/src/index.ts b/packages/utils/src/index.tsindex aa8d31bc42..fbf9cc8840 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -1,6 +1,7 @@export * from "./accounting";export * from "./address";export * from "./arrays";+export * from "./bom";export * from "./color";export * from "./const";export * from "./date";