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
fix: multi-level bom get-method
Brad Barbin402f9a2e6af9
diff --git a/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx b/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsxindex cc2d608c7d..bba7694837 100644--- a/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx+++ b/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx@@ -98,6 +98,7 @@ const MakeMethodTools = ({const getMethodModal = useDisclosure();const saveMethodModal = useDisclosure();+ const [hasMethodParts, setHasMethodParts] = useState(true);const newVersionModal = useDisclosure();const activeMethodModal = useDisclosure();const itemLink = type && itemId ? getLinkToItemDetails(type, itemId) : null;@@ -268,6 +269,12 @@ const MakeMethodTools = ({<ModalBody><Hidden name="targetId" value={itemId} /><VStack spacing={4}>+ <Alert variant="destructive" className="mt-4">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ This will overwrite the existing manufacturing method+ </AlertTitle>+ </Alert><Itemname="sourceId"label="Source Method"@@ -292,20 +299,16 @@ const MakeMethodTools = ({</label></div>- <Alert variant="destructive" className="mt-4">- <LuTriangleAlert className="h-4 w-4" />- <AlertTitle>- This will overwrite the existing manufacturing method- </AlertTitle>- </Alert>- <AdvancedSection />+ <AdvancedSection onChange={setHasMethodParts} /></VStack></ModalBody><ModalFooter><Button onClick={getMethodModal.onClose} variant="secondary">Cancel</Button>- <Submit variant="destructive">Confirm</Submit>+ <Submit isDisabled={!hasMethodParts} variant="destructive">+ Confirm+ </Submit></ModalFooter></ValidatedForm></ModalContent>@@ -361,14 +364,14 @@ const MakeMethodTools = ({Include Inactive</label></div>- <AdvancedSection />+ <AdvancedSection onChange={setHasMethodParts} /></VStack></ModalBody><ModalFooter><Button onClick={saveMethodModal.onClose} variant="secondary">Cancel</Button>- <Submit>Confirm</Submit>+ <Submit isDisabled={!hasMethodParts}>Confirm</Submit></ModalFooter></ValidatedForm></ModalContent>@@ -459,14 +462,27 @@ const MakeMethodTools = ({);};-function AdvancedSection() {+function AdvancedSection({+ onChange+}: {+ onChange?: (hasSelection: boolean) => void;+}) {const [open, setOpen] = useState(false);+ const [billOfMaterial, setBillOfMaterial] = useState(true);const [billOfProcess, setBillOfProcess] = useState(true);const [parameters, setParameters] = useState(true);const [tools, setTools] = useState(true);const [steps, setSteps] = useState(true);const [workInstructions, setWorkInstructions] = useState(true);+ const hasSelection =+ billOfMaterial ||+ (billOfProcess && (parameters || tools || steps || workInstructions));++ useEffect(() => {+ onChange?.(hasSelection);+ }, [hasSelection, onChange]);+const processChildren = [{name: "parameters",@@ -500,7 +516,8 @@ function AdvancedSection() {<Checkboxid="billOfMaterial"name="billOfMaterial"- defaultChecked+ checked={billOfMaterial}+ onCheckedChange={(checked) => setBillOfMaterial(!!checked)}/><labelhtmlFor="billOfMaterial"diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsxindex 7f5658c031..45db07deec 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx@@ -118,6 +118,7 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {const getMethodModal = useDisclosure();const saveMethodModal = useDisclosure();+ const [hasMethodParts, setHasMethodParts] = useState(true);const isJobDetails = pathname === path.to.jobDetails(jobId);const isJobMethod =@@ -371,6 +372,14 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {)}<VStack spacing={4}>+ {hasMethods && (+ <Alert variant="destructive">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ This will overwrite the existing job method+ </AlertTitle>+ </Alert>+ )}<Itemname="sourceId"label="Source Method"@@ -392,15 +401,8 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {Include Inactive</label></div>- {hasMethods && (- <Alert variant="destructive">- <LuTriangleAlert className="h-4 w-4" />- <AlertTitle>- This will overwrite the existing job method- </AlertTitle>- </Alert>- )}- <AdvancedSection />++ <AdvancedSection onChange={setHasMethodParts} /></VStack></TabsContent><TabsContent value="quote">@@ -408,7 +410,7 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {<Hidden name="targetId" value={jobId} /><VStack spacing={4}><QuoteLineMethodForm />- <AdvancedSection />+ <AdvancedSection onChange={setHasMethodParts} /></VStack></TabsContent></Tabs>@@ -417,7 +419,10 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {<Button onClick={getMethodModal.onClose} variant="secondary">Cancel</Button>- <Submit variant={hasMethods ? "destructive" : "primary"}>+ <Submit+ isDisabled={!hasMethodParts}+ variant={hasMethods ? "destructive" : "primary"}+ >Confirm</Submit></ModalFooter>@@ -517,15 +522,8 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {Include Inactive</label></div>- {hasMethods && (- <Alert variant="destructive">- <LuTriangleAlert className="h-4 w-4" />- <AlertTitle>- This will overwrite the existing manufacturing method- </AlertTitle>- </Alert>- )}- <AdvancedSection />++ <AdvancedSection onChange={setHasMethodParts} /></VStack></ModalBody><ModalFooter>@@ -535,7 +533,9 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {<Submitvariant={hasMethods ? "destructive" : "primary"}isDisabled={- !selectedMakeMethod || !permissions.can("update", "parts")+ !selectedMakeMethod ||+ !permissions.can("update", "parts") ||+ !hasMethodParts}>Confirm@@ -611,14 +611,27 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {);};-function AdvancedSection() {+function AdvancedSection({+ onChange+}: {+ onChange?: (hasSelection: boolean) => void;+}) {const [open, setOpen] = useState(false);+ const [billOfMaterial, setBillOfMaterial] = useState(true);const [billOfProcess, setBillOfProcess] = useState(true);const [parameters, setParameters] = useState(true);const [tools, setTools] = useState(true);const [steps, setSteps] = useState(true);const [workInstructions, setWorkInstructions] = useState(true);+ const hasSelection =+ billOfMaterial ||+ (billOfProcess && (parameters || tools || steps || workInstructions));++ useEffect(() => {+ onChange?.(hasSelection);+ }, [hasSelection, onChange]);+const processChildren = [{name: "parameters",@@ -652,7 +665,8 @@ function AdvancedSection() {<Checkboxid="billOfMaterial"name="billOfMaterial"- defaultChecked+ checked={billOfMaterial}+ onCheckedChange={(checked) => setBillOfMaterial(!!checked)}/><labelhtmlFor="billOfMaterial"diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsxindex 55eeb98b3e..300a9b99b9 100644--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx@@ -21,10 +21,10 @@ import { useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { cva } from "class-variance-authority";import { AiOutlinePartition } from "react-icons/ai";-import { FaTasks } from "react-icons/fa";import {LuCalendarDays,LuCircleCheck,+ LuClock,LuEllipsisVertical,LuFlashlight,LuFlashlightOff,@@ -241,7 +241,7 @@ export function JobCard({ item, isOverlay, progressByItemId }: JobCardProps) {}progress={Math.min((item.progress ?? 0) * 100, 100)}/>- <FaTasks className="text-muted-foreground w-4 h-4" />+ <LuClock className="text-muted-foreground w-4 h-4" /></HStack>)}</CardHeader>diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsxindex f030a421e8..0df124c4e0 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx@@ -117,6 +117,7 @@ const QuoteMakeMethodTools = () => {const getMethodModal = useDisclosure();const saveMethodModal = useDisclosure();+ const [hasMethodParts, setHasMethodParts] = useState(true);const isQuoteLineDetails =lineId && pathname === path.to.quoteLine(quoteId, lineId);@@ -310,6 +311,14 @@ const QuoteMakeMethodTools = () => {<Hidden name="type" value="item" /><Hidden name="targetId" value={`${quoteId}:${lineId}`} /><VStack spacing={4}>+ {hasMethods && (+ <Alert variant="destructive">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ This will overwrite the existing quote method+ </AlertTitle>+ </Alert>+ )}<Itemname="sourceId"label="Source Method"@@ -331,15 +340,8 @@ const QuoteMakeMethodTools = () => {Include Inactive</label></div>- {hasMethods && (- <Alert variant="destructive">- <LuTriangleAlert className="h-4 w-4" />- <AlertTitle>- This will overwrite the existing quote method- </AlertTitle>- </Alert>- )}- <AdvancedSection />++ <AdvancedSection onChange={setHasMethodParts} /></VStack></TabsContent><TabsContent value="quote">@@ -353,6 +355,14 @@ const QuoteMakeMethodTools = () => {<Hidden name="type" value="method" /><Hidden name="targetId" value={methodId!} /><VStack spacing={4}>+ {hasMethods && (+ <Alert variant="destructive">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ This will overwrite the existing quote method+ </AlertTitle>+ </Alert>+ )}<Itemname="sourceId"label="Source Method"@@ -374,15 +384,8 @@ const QuoteMakeMethodTools = () => {Include Inactive</label></div>- {hasMethods && (- <Alert variant="destructive">- <LuTriangleAlert className="h-4 w-4" />- <AlertTitle>- This will overwrite the existing quote method- </AlertTitle>- </Alert>- )}- <AdvancedSection />++ <AdvancedSection onChange={setHasMethodParts} /></VStack></>)}@@ -391,7 +394,10 @@ const QuoteMakeMethodTools = () => {<Button onClick={getMethodModal.onClose} variant="secondary">Cancel</Button>- <Submit variant={hasMethods ? "destructive" : "primary"}>+ <Submit+ isDisabled={!hasMethodParts}+ variant={hasMethods ? "destructive" : "primary"}+ >Confirm</Submit></ModalFooter>@@ -495,7 +501,7 @@ const QuoteMakeMethodTools = () => {Include Inactive</label></div>- <AdvancedSection />+ <AdvancedSection onChange={setHasMethodParts} /></VStack></ModalBody><ModalFooter>@@ -503,7 +509,7 @@ const QuoteMakeMethodTools = () => {Cancel</Button><Submit- isDisabled={!selectedMakeMethod}+ isDisabled={!selectedMakeMethod || !hasMethodParts}variant={hasMethods ? "destructive" : "primary"}>Confirm@@ -576,14 +582,27 @@ const QuoteMakeMethodTools = () => {);};-function AdvancedSection() {+function AdvancedSection({+ onChange+}: {+ onChange?: (hasSelection: boolean) => void;+}) {const [open, setOpen] = useState(false);+ const [billOfMaterial, setBillOfMaterial] = useState(true);const [billOfProcess, setBillOfProcess] = useState(true);const [parameters, setParameters] = useState(true);const [tools, setTools] = useState(true);const [steps, setSteps] = useState(true);const [workInstructions, setWorkInstructions] = useState(true);+ const hasSelection =+ billOfMaterial ||+ (billOfProcess && (parameters || tools || steps || workInstructions));++ useEffect(() => {+ onChange?.(hasSelection);+ }, [hasSelection, onChange]);+const processChildren = [{name: "parameters",@@ -617,7 +636,8 @@ function AdvancedSection() {<Checkboxid="billOfMaterial"name="billOfMaterial"- defaultChecked+ checked={billOfMaterial}+ onCheckedChange={(checked) => setBillOfMaterial(!!checked)}/><labelhtmlFor="billOfMaterial"diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex 6be5a7a65d..71f8de786f 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -411,6 +411,13 @@ serve(async (req: Request) => {parts.billOfMaterial? trx.deleteFrom("jobMaterial").where("jobId", "=", jobId).execute(): Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx.updateTable("jobMaterial")+ .set({ jobOperationId: null })+ .where("jobId", "=", jobId)+ .execute()+ : Promise.resolve(),parts.billOfProcess? trx.deleteFrom("jobOperation").where("jobId", "=", jobId).execute(): Promise.resolve(),@@ -458,6 +465,19 @@ serve(async (req: Request) => {parentJobMakeMethodId: string | null,parentEstimatedQuantity: number) {+ console.log("[traverseMethod]", {+ isRoot: node.data.isRoot,+ itemId: node.data.itemId,+ methodType: node.data.methodType,+ materialMakeMethodId: node.data.materialMakeMethodId,+ childCount: node.children.length,+ childMethodTypes: node.children.map(c => ({+ itemId: c.data.itemId,+ methodType: c.data.methodType,+ })),+ parentJobMakeMethodId,+ });+// For root node, targetQuantity equals the job quantity (parentEstimatedQuantity passed in)// For children, targetQuantity = parentEstimatedQuantity * quantityPerParentconst targetQuantity = node.data.isRoot@@ -497,7 +517,8 @@ serve(async (req: Request) => {let methodOperationsToJobOperations: Record<string, string> = {};- if (parts.billOfProcess) {+ // For child nodes, always include operations regardless of parts flags+ if (!node.data.isRoot || parts.billOfProcess) {const relatedOperations = await client.from("methodOperation").select(@@ -606,7 +627,7 @@ serve(async (req: Request) => {processId,op.operationSupplierProcessId),- workInstruction: parts.workInstructions ? op.workInstruction : {},+ workInstruction: (!node.data.isRoot || parts.workInstructions) ? op.workInstruction : {},targetQuantity,operationQuantity,companyId,@@ -663,7 +684,7 @@ serve(async (req: Request) => {} = operation;if (- parts.tools &&+ (!node.data.isRoot || parts.tools) &&Array.isArray(methodOperationTool) &&methodOperationTool.length > 0) {@@ -690,7 +711,7 @@ serve(async (req: Request) => {});} else {if (- parts.parameters &&+ (!node.data.isRoot || parts.parameters) &&Array.isArray(methodOperationParameter) &&methodOperationParameter.length > 0) {@@ -715,7 +736,7 @@ serve(async (req: Request) => {}if (- parts.steps &&+ (!node.data.isRoot || parts.steps) &&Array.isArray(methodOperationStep) &&methodOperationStep.length > 0) {@@ -883,7 +904,7 @@ serve(async (req: Request) => {requiresSerialTracking,requiresBatchTracking,unitOfMeasureCode,- unitCost,+ unitCost: unitCost ?? 0,itemScrapPercentage,companyId,createdBy: userId,@@ -931,44 +952,48 @@ serve(async (req: Request) => {(material) => material.methodType !== "Make");- const madeChildren = madeMaterials.map((material, index) => {- const childIndex = materialsWithConfiguredFields.findIndex(- (m) => m.itemId === material.itemId- );- return node.children[childIndex];+ const madeChildren = node.children.filter(+ (child) => child.data.methodType === "Make"+ );++ console.log("[traverseMethod] materials", {+ totalChildren: materialsWithConfiguredFields.length,+ madeMaterialsCount: madeMaterials.length,+ madeChildrenCount: madeChildren.length,+ pickedOrBoughtCount: pickedOrBoughtMaterials.length,});if (madeMaterials.length > 0) {- const madeMaterialIds = await trx+ const madeMaterialsWithIds = madeMaterials.map((m) => ({+ ...m,+ id: nanoid(),+ }));++ await trx.insertInto("jobMaterial")- .values(madeMaterials)- .returning(["id"])+ .values(madeMaterialsWithIds).execute();- const jobMakeMethods = await trx- .selectFrom("jobMakeMethod")- .select(["id", "parentMaterialId"])- .where(- "parentMaterialId",- "in",- madeMaterialIds.map((m) => m.id)- )- .execute();+ for (const [index, child] of madeChildren.entries()) {+ const materialId = madeMaterialsWithIds[index].id;+ const newMakeMethodId = nanoid();- // Create proper mapping from parentMaterialId to jobMakeMethodId- const materialIdToJobMakeMethodId: Record<string, string> = {};- jobMakeMethods.forEach((jmm) => {- if (jmm.parentMaterialId && jmm.id) {- materialIdToJobMakeMethodId[jmm.parentMaterialId] = jmm.id;- }- });+ const updateResult = await trx+ .updateTable("jobMakeMethod")+ .set({ id: newMakeMethodId })+ .where("parentMaterialId", "=", materialId)+ .execute();++ console.log("[traverseMethod] processing made child", {+ index,+ materialId,+ newMakeMethodId,+ childItemId: child.data.itemId,+ parentItemId: itemId,+ willRecurse: child.data.itemId !== itemId,+ updateResult,+ });- // Use proper correlation instead of index-based assumption- for (const [index, child] of madeChildren.entries()) {- const materialId = madeMaterialIds[index]?.id;- const jobMakeMethodId = materialId- ? materialIdToJobMakeMethodId[materialId]- : null;// Get the total quantity (estimated + scrap) for this child material// This is what we pass to children for the cascadeconst material = madeMaterials[index];@@ -977,10 +1002,10 @@ serve(async (req: Request) => {(material?.scrapQuantity ?? 0);// prevent an infinite loop- if (child.data.itemId !== itemId && jobMakeMethodId) {+ if (child.data.itemId !== itemId) {await traverseMethod(child,- jobMakeMethodId,+ newMakeMethodId,childTotalForCascade || 1);}@@ -996,6 +1021,14 @@ serve(async (req: Request) => {} // end if (parts.billOfMaterial)}+ function logTree(node: MethodTreeItem, depth = 0) {+ console.log(" ".repeat(depth) + `[tree] ${node.data.itemId} (${node.data.methodType}, isRoot=${node.data.isRoot}, children=${node.children.length})`);+ for (const child of node.children) {+ logTree(child, depth + 1);+ }+ }+ logTree(methodTree);+// Start traversal with job quantity as the root's target/parent estimated quantityawait traverseMethod(methodTree,@@ -1120,6 +1153,13 @@ serve(async (req: Request) => {.where("jobMakeMethodId", "=", jobMakeMethodId).execute(): Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx.updateTable("jobMaterial")+ .set({ jobOperationId: null })+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .execute()+ : Promise.resolve(),parts.billOfProcess? trx.deleteFrom("jobOperation")@@ -1390,38 +1430,30 @@ serve(async (req: Request) => {}if (madeMaterials.length > 0) {- const madeMaterialIds = await trx+ const madeMaterialsWithIds = madeMaterials.map((m) => ({+ ...m,+ id: nanoid(),+ }));++ await trx.insertInto("jobMaterial")- .values(madeMaterials)- .returning(["id"])+ .values(madeMaterialsWithIds).execute();- const jobMakeMethods = await trx- .selectFrom("jobMakeMethod")- .select(["id", "parentMaterialId"])- .where(- "parentMaterialId",- "in",- madeMaterialIds.map((m) => m.id)- )- .execute();+ const madeChildren = node.children.filter(+ (child) => child.data.methodType === "Make"+ );- // Create proper mapping from parentMaterialId to jobMakeMethodId- const materialIdToJobMakeMethodId: Record<string, string> = {};- jobMakeMethods.forEach((jmm) => {- if (jmm.parentMaterialId && jmm.id) {- materialIdToJobMakeMethodId[jmm.parentMaterialId] = jmm.id;- }- });+ for (const [index, child] of madeChildren.entries()) {+ const materialId = madeMaterialsWithIds[index].id;+ const newMakeMethodId = nanoid();++ await trx+ .updateTable("jobMakeMethod")+ .set({ id: newMakeMethodId })+ .where("parentMaterialId", "=", materialId)+ .execute();- // Use proper correlation instead of index-based assumption- for (const [index, child] of node.children- .filter((child) => child.data.methodType === "Make")- .entries()) {- const materialId = madeMaterialIds[index]?.id;- const jobMakeMethodId = materialId- ? materialIdToJobMakeMethodId[materialId]- : null;// Get the total quantity (estimated + scrap) for this child material// This is what we pass to children for the cascadeconst material = madeMaterials[index];@@ -1430,10 +1462,10 @@ serve(async (req: Request) => {(material?.scrapQuantity ?? 0);// prevent an infinite loop- if (child.data.itemId !== itemId && jobMakeMethodId) {+ if (child.data.itemId !== itemId) {await traverseMethod(child,- jobMakeMethodId,+ newMakeMethodId,childTotalForCascade || 1);}@@ -1570,6 +1602,13 @@ serve(async (req: Request) => {.where("quoteLineId", "=", quoteLineId).execute(): Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx.updateTable("quoteMaterial")+ .set({ quoteOperationId: null })+ .where("quoteLineId", "=", quoteLineId)+ .execute()+ : Promise.resolve(),parts.billOfProcess? trx.deleteFrom("quoteOperation")@@ -1622,13 +1661,27 @@ serve(async (req: Request) => {node: MethodTreeItem,parentQuoteMakeMethodId: string | null) {+ console.log("[traverseMethod]", {+ isRoot: node.data.isRoot,+ itemId: node.data.itemId,+ methodType: node.data.methodType,+ materialMakeMethodId: node.data.materialMakeMethodId,+ childCount: node.children.length,+ childMethodTypes: node.children.map(c => ({+ itemId: c.data.itemId,+ methodType: c.data.methodType,+ })),+ parentQuoteMakeMethodId,+ });+let methodOperationsToQuoteOperations: Record<string, string> = {};const nodeLevelConfigurationKey = `${node.data.materialMakeMethodId}:${node.data.isRoot ? "undefined" : node.data.methodMaterialId}`;- if (parts.billOfProcess) {+ // For child nodes, always include operations regardless of parts flags+ if (!node.data.isRoot || parts.billOfProcess) {const relatedOperations = await client.from("methodOperation").select(@@ -1749,7 +1802,7 @@ serve(async (req: Request) => {op.operationSupplierProcessId),tags: op.tags ?? [],- workInstruction: parts.workInstructions ? op.workInstruction : {},+ workInstruction: (!node.data.isRoot || parts.workInstructions) ? op.workInstruction : {},companyId,createdBy: userId,customFields: {},@@ -1804,7 +1857,7 @@ serve(async (req: Request) => {} = operation;if (- parts.tools &&+ (!node.data.isRoot || parts.tools) &&Array.isArray(methodOperationTool) &&methodOperationTool.length > 0) {@@ -1824,7 +1877,7 @@ serve(async (req: Request) => {if (!procedureId) {if (- parts.parameters &&+ (!node.data.isRoot || parts.parameters) &&Array.isArray(methodOperationParameter) &&methodOperationParameter.length > 0) {@@ -1849,7 +1902,7 @@ serve(async (req: Request) => {}if (- parts.steps &&+ (!node.data.isRoot || parts.steps) &&Array.isArray(methodOperationStep) &&methodOperationStep.length > 0) {@@ -1978,7 +2031,7 @@ serve(async (req: Request) => {(child.data.shelfIds?.[quoteLocationId] as string) || null: null,unitOfMeasureCode,- unitCost,+ unitCost: unitCost ?? 0,companyId,createdBy: userId,customFields: {},@@ -2025,48 +2078,51 @@ serve(async (req: Request) => {(material) => material.methodType !== "Make");- const madeChildren = madeMaterials.map((material, index) => {- const childIndex = materialsWithConfiguredFields.findIndex(- (m) => m.itemId === material.itemId- );- return node.children[childIndex];+ const madeChildren = node.children.filter(+ (child) => child.data.methodType === "Make"+ );++ console.log("[traverseMethod] materials", {+ totalChildren: materialsWithConfiguredFields.length,+ madeMaterialsCount: madeMaterials.length,+ madeChildrenCount: madeChildren.length,+ pickedOrBoughtCount: pickedOrBoughtMaterials.length,});if (madeMaterials.length > 0) {- const madeMaterialIds = await trx+ const madeMaterialsWithIds = madeMaterials.map((m) => ({+ ...m,+ id: nanoid(),+ }));++ await trx.insertInto("quoteMaterial")- .values(madeMaterials)- .returning(["id"])+ .values(madeMaterialsWithIds).execute();- const quoteMakeMethods = await trx- .selectFrom("quoteMakeMethod")- .select(["id", "parentMaterialId"])- .where(- "parentMaterialId",- "in",- madeMaterialIds.map((m) => m.id)- )- .execute();+ for (const [index, child] of madeChildren.entries()) {+ const materialId = madeMaterialsWithIds[index].id;+ const newMakeMethodId = nanoid();- // Create proper mapping from parentMaterialId to quoteMakeMethodId- const materialIdToQuoteMakeMethodId: Record<string, string> = {};- quoteMakeMethods.forEach((qmm) => {- if (qmm.parentMaterialId && qmm.id) {- materialIdToQuoteMakeMethodId[qmm.parentMaterialId] = qmm.id;- }- });+ const updateResult = await trx+ .updateTable("quoteMakeMethod")+ .set({ id: newMakeMethodId })+ .where("parentMaterialId", "=", materialId)+ .execute();- // Use proper correlation instead of index-based assumption- for (const [index, child] of madeChildren.entries()) {- const materialId = madeMaterialIds[index]?.id;- const quoteMakeMethodId = materialId- ? materialIdToQuoteMakeMethodId[materialId]- : null;+ console.log("[traverseMethod] processing made child", {+ index,+ materialId,+ newMakeMethodId,+ childItemId: child.data.itemId,+ parentItemId: itemId,+ willRecurse: child.data.itemId !== itemId,+ updateResult,+ });// prevent an infinite loop- if (child.data.itemId !== itemId && quoteMakeMethodId) {- await traverseMethod(child, quoteMakeMethodId);+ if (child.data.itemId !== itemId) {+ await traverseMethod(child, newMakeMethodId);}}}@@ -2080,6 +2136,14 @@ serve(async (req: Request) => {} // end if (parts.billOfMaterial)}+ function logTree(node: MethodTreeItem, depth = 0) {+ console.log(" ".repeat(depth) + `[tree] ${node.data.itemId} (${node.data.methodType}, isRoot=${node.data.isRoot}, children=${node.children.length})`);+ for (const child of node.children) {+ logTree(child, depth + 1);+ }+ }+ logTree(methodTree);+await traverseMethod(methodTree, quoteMakeMethod.data.id);});@@ -2172,6 +2236,13 @@ serve(async (req: Request) => {.where("quoteMakeMethodId", "=", quoteMakeMethodId).execute(): Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx.updateTable("quoteMaterial")+ .set({ quoteOperationId: null })+ .where("quoteMakeMethodId", "=", quoteMakeMethodId)+ .execute()+ : Promise.resolve(),parts.billOfProcess? trx.deleteFrom("quoteOperation")@@ -2380,7 +2451,7 @@ serve(async (req: Request) => {quantity: child.data.quantity,shelfId: (child.data as any).shelfId || null, // @ts-ignore: shelfId field exists in database but types may not be updatedunitOfMeasureCode: child.data.unitOfMeasureCode,- unitCost: child.data.unitCost,+ unitCost: child.data.unitCost ?? 0,companyId,createdBy: userId,customFields: {},@@ -2400,40 +2471,29 @@ serve(async (req: Request) => {mapMethodMaterialToQuoteMaterial);if (madeMaterials.length > 0) {- const madeMaterialIds = await trx- .insertInto("quoteMaterial")- .values(madeMaterials)- .returning(["id"])- .execute();+ const madeMaterialsWithIds = madeMaterials.map((m) => ({+ ...m,+ id: nanoid(),+ }));- const quoteMakeMethods = await trx- .selectFrom("quoteMakeMethod")- .select(["id", "parentMaterialId"])- .where(- "parentMaterialId",- "in",- madeMaterialIds.map((m) => m.id)- )+ await trx+ .insertInto("quoteMaterial")+ .values(madeMaterialsWithIds).execute();- // Create proper mapping from parentMaterialId to quoteMakeMethodId- const materialIdToQuoteMakeMethodId: Record<string, string> = {};- quoteMakeMethods.forEach((qmm) => {- if (qmm.parentMaterialId && qmm.id) {- materialIdToQuoteMakeMethodId[qmm.parentMaterialId] = qmm.id;- }- });-- // Use proper correlation instead of index-based assumptionfor (const [index, child] of madeChildren.entries()) {- const materialId = madeMaterialIds[index]?.id;- const quoteMakeMethodId = materialId- ? materialIdToQuoteMakeMethodId[materialId]- : null;+ const materialId = madeMaterialsWithIds[index].id;+ const newMakeMethodId = nanoid();++ await trx+ .updateTable("quoteMakeMethod")+ .set({ id: newMakeMethodId })+ .where("parentMaterialId", "=", materialId)+ .execute();// prevent an infinite loop- if (child.data.itemId !== itemId && quoteMakeMethodId) {- await traverseMethod(child, quoteMakeMethodId);+ if (child.data.itemId !== itemId) {+ await traverseMethod(child, newMakeMethodId);}}}@@ -4072,6 +4132,13 @@ serve(async (req: Request) => {parts.billOfMaterial? trx.deleteFrom("jobMaterial").where("jobId", "=", jobId).execute(): Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx.updateTable("jobMaterial")+ .set({ jobOperationId: null })+ .where("jobId", "=", jobId)+ .execute()+ : Promise.resolve(),parts.billOfProcess? trx.deleteFrom("jobOperation").where("jobId", "=", jobId).execute(): Promise.resolve(),@@ -4466,6 +4533,13 @@ serve(async (req: Request) => {.where("quoteLineId", "=", targetQuoteLineId).execute(): Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx.updateTable("quoteMaterial")+ .set({ quoteOperationId: null })+ .where("quoteLineId", "=", targetQuoteLineId)+ .execute()+ : Promise.resolve(),parts.billOfProcess? trx.deleteFrom("quoteOperation")