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: get method for nested methods
Brad Barbin417395d4fca2
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.tsindex 15d96027f9..1ef8e33040 100644--- a/apps/carbon/app/modules/items/items.service.ts+++ b/apps/carbon/app/modules/items/items.service.ts@@ -115,9 +115,15 @@ export async function getConsumables(.select("*", {count: "exact",})- .eq("active", true).eq("companyId", companyId);+ const includeInactive = args?.filters?.some(+ (filter) => filter.column === "active" && filter.value === "false"+ );+ if (!includeInactive) {+ query = query.eq("active", true);+ }+if (args.search) {query = query.or(`id.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%`@@ -174,9 +180,16 @@ export async function getFixtures(.select("*", {count: "exact",})- .eq("active", true).eq("companyId", companyId);+ const includeInactive = args?.filters?.some(+ (filter) => filter.column === "active" && filter.value === "false"+ );++ if (!includeInactive) {+ query = query.eq("active", true);+ }+if (args.search) {query = query.or(`id.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%`@@ -383,9 +396,15 @@ export async function getMaterials(.select("*", {count: "exact",})- .eq("active", true).or(`companyId.eq.${companyId},companyId.is.null`);+ const includeInactive = args?.filters?.some(+ (filter) => filter.column === "active" && filter.value === "false"+ );+ if (!includeInactive) {+ query = query.eq("active", true);+ }+if (args.search) {query = query.or(`id.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%`@@ -633,9 +652,15 @@ export async function getParts(.select("*", {count: "exact",})- .eq("active", true).eq("companyId", companyId);+ const includeInactive = args?.filters?.some(+ (filter) => filter.column === "active" && filter.value === "false"+ );+ if (!includeInactive) {+ query = query.eq("active", true);+ }+if (args.search) {query = query.or(`id.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%`@@ -708,9 +733,15 @@ export async function getServices(.select("*", {count: "exact",})- .eq("active", true).eq("companyId", companyId);+ const includeInactive = args?.filters?.some(+ (filter) => filter.column === "active" && filter.value === "false"+ );++ if (!includeInactive) {+ query = query.eq("active", true);+ }if (args.search) {query = query.or(`name.ilike.%${args.search}%,description.ilike.%${args.search}%`@@ -801,9 +832,15 @@ export async function getTools(.select("*", {count: "exact",})- .eq("active", true).eq("companyId", companyId);+ const includeInactive = args?.filters?.some(+ (filter) => filter.column === "active" && filter.value === "false"+ );+ if (!includeInactive) {+ query = query.eq("active", true);+ }+if (args.search) {query = query.or(`id.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%`diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.tsindex 84be7f53de..84ab06c872 100644--- a/apps/carbon/app/modules/sales/sales.models.ts+++ b/apps/carbon/app/modules/sales/sales.models.ts@@ -59,6 +59,18 @@ export const customerTypeValidator = z.object({name: z.string().min(1, { message: "Name is required" }),});+export const getLineMethodValidator = z.object({+ type: z.enum(["line"]),+ itemId: z.string().min(1, { message: "Please select a source method" }),+ quoteId: z.string(),+ quoteLineId: z.string(),+});++export const getMethodValidator = z.object({+ quoteMaterialId: z.string().min(1, { message: "Quote Material is required" }),+ itemId: z.string().min(1, { message: "Please select a source method" }),+});+export const quoteLineStatusType = ["Draft","In Progress",diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.tsindex f820a6c84a..495c0ee393 100644--- a/apps/carbon/app/modules/sales/sales.service.ts+++ b/apps/carbon/app/modules/sales/sales.service.ts@@ -1,7 +1,7 @@import type { Database, Json } from "@carbon/database";import { getLocalTimeZone, today } from "@internationalized/date";import type { FileObject } from "@supabase/storage-js";-import type { SupabaseClient } from "@supabase/supabase-js";+import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import { getEmployeeJob } from "~/modules/resources";import type { GenericQueryFilters } from "~/utils/query";@@ -14,6 +14,7 @@ import type {customerStatusValidator,customerTypeValidator,customerValidator,+ getMethodValidator,quotationPricingValidator,quoteLineAdditionalChargesValidator,quoteLineValidator,@@ -1406,6 +1407,27 @@ export async function updateQuoteLinePrice(.eq("quoteLineId", quoteLinePrice.quoteLineId);}+export async function upsertQuoteLineMethod(+ client: SupabaseClient<Database>,+ lineMethod: {+ itemId: string;+ quoteId: string;+ quoteLineId: string;+ companyId: string;+ userId: string;+ }+) {+ return client.functions.invoke("get-method", {+ body: {+ type: "itemToQuoteLine",+ sourceId: lineMethod.itemId,+ targetId: `${lineMethod.quoteId}:${lineMethod.quoteLineId}`,+ companyId: lineMethod.companyId,+ userId: lineMethod.userId,+ },+ });+}+export async function upsertQuoteMaterial(client: SupabaseClient<Database>,quoteMaterial:@@ -1441,6 +1463,44 @@ export async function upsertQuoteMaterial(.single();}+export async function upsertQuoteMaterialMakeMethod(+ client: SupabaseClient<Database>,+ quoteMaterial: z.infer<typeof getMethodValidator> & {+ companyId: string;+ createdBy: string;+ }+) {+ const makeMethod = await client+ .from("quoteMakeMethod")+ .select("id")+ .eq("parentMaterialId", quoteMaterial.quoteMaterialId)+ .single();+ if (makeMethod.error) {+ return makeMethod;+ }++ console.log({ makeMethod });++ const { error } = await client.functions.invoke("get-method", {+ body: {+ type: "itemToQuoteMakeMethod",+ sourceId: quoteMaterial.itemId,+ targetId: makeMethod.data.id,+ companyId: quoteMaterial.companyId,+ userId: quoteMaterial.createdBy,+ },+ });++ if (error) {+ return {+ data: null,+ error: { message: "Failed to pull method" } as PostgrestError,+ };+ }++ return { data: null, error: null };+}+export async function upsertQuoteOperation(client: SupabaseClient<Database>,operation:diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsxindex a9c6ca6415..95b31427fb 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx@@ -1,6 +1,7 @@import {Alert,Button,+ Checkbox,HStack,Menubar,MenubarItem,@@ -17,26 +18,20 @@ import {} from "@carbon/react";import { ValidatedForm } from "@carbon/remix-validated-form";import { Link, useFetcher, useLocation, useParams } from "@remix-run/react";-import { useEffect } from "react";+import { useEffect, useState } from "react";import { LuDownload, LuUpload } from "react-icons/lu";import { RiProgress4Line } from "react-icons/ri";-import { z } from "zod";import { BreadcrumbItem, Breadcrumbs } from "~/components";import { Hidden, Item, Submit } from "~/components/Form";import type { Tree } from "~/components/TreeView";import { usePermissions, useRouteData } from "~/hooks";import { path } from "~/utils/path";+import { getLineMethodValidator, getMethodValidator } from "../../sales.models";import type { Quotation, QuotationLine, QuoteMethod } from "../../types";-const getMethodValidator = z.object({- itemId: z.string().min(1, { message: "Please select a source method" }),- quoteId: z.string(),- quoteLineId: z.string(),-});-const QuoteBreadcrumbs = () => {const permissions = usePermissions();- const { quoteId, lineId } = useParams();+ const { quoteId, lineId, methodId, materialId } = useParams();if (!quoteId) throw new Error("quoteId not found");const fetcher = useFetcher<{ error: string | null }>();@@ -62,7 +57,18 @@ const QuoteBreadcrumbs = () => {}}, [fetcher.data?.error]);+ const [includeInactive, setIncludeInactive] = useState<+ boolean | "indeterminate"+ >(false);+const getMethodModal = useDisclosure();+ const isQuoteLineMethod =+ pathname === path.to.quoteLineMethod(quoteId, lineId!, methodId!);+ const isQuoteMakeMethod =+ methodId &&+ materialId &&+ pathname ===+ path.to.quoteLineMaterialMake(quoteId, lineId!, methodId, materialId);return (<>@@ -88,7 +94,7 @@ const QuoteBreadcrumbs = () => {</Breadcrumbs>{line &&permissions.can("update", "sales") &&- pathname === path.to.quoteLine(quoteId, lineId!) && (+ (isQuoteLineMethod || isQuoteMakeMethod) && (<HStack spacing={0}><MenubarItemleftIcon={<LuDownload />}@@ -117,13 +123,10 @@ const QuoteBreadcrumbs = () => {method="post"fetcher={fetcher}action={path.to.quoteMethodGet}- validator={getMethodValidator}+ validator={+ isQuoteLineMethod ? getLineMethodValidator : getMethodValidator+ }onSubmit={getMethodModal.onClose}- defaultValues={{- quoteId,- quoteLineId: lineId,- itemId: line?.itemId,- }}><ModalHeader><ModalTitle>Get Method</ModalTitle>@@ -132,15 +135,40 @@ const QuoteBreadcrumbs = () => {</ModalDescription></ModalHeader><ModalBody>- <Hidden name="quoteId" value={quoteId} />- <Hidden name="quoteLineId" value={lineId} />+ {isQuoteLineMethod ? (+ <>+ <Hidden name="type" value="line" />+ <Hidden name="quoteId" value={quoteId} />+ <Hidden name="quoteLineId" value={lineId} />+ </>+ ) : (+ <>+ <Hidden name="type" value="method" />+ <Hidden name="quoteMaterialId" value={materialId!} />+ </>+ )}+<VStack spacing={4}><Itemname="itemId"label="Source Method"type={(line?.itemType ?? "Part") as "Part"}+ includeInactive={includeInactive === true}replenishmentSystem="Make"/>+ <div className="flex items-center space-x-2">+ <Checkbox+ id="include-inactive"+ checked={includeInactive}+ onCheckedChange={setIncludeInactive}+ />+ <label+ htmlFor="include-inactive"+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"+ >+ Include Inactive+ </label>+ </div>{hasMethods && (<Alert variant="destructive">This will overwrite the existing quote methoddiff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsxindex b945eb0c49..af538ab8a1 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx@@ -110,12 +110,12 @@ export default function QuoteMakeMethodRoute() {operations={[]}/><QuoteBillOfProcess- key={`bop:${methodId}`}+ key={JSON.stringify(operations)}quoteMakeMethodId={methodId}operations={operations}/><QuoteBillOfMaterial- key={`bom:${methodId}`}+ key={JSON.stringify(materials)}quoteMakeMethodId={methodId}materials={materials}operations={operations}diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsxindex 461fa1eba3..11880fdf27 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx@@ -78,12 +78,12 @@ export default function QuoteMakeMethodRoute() {return (<VStack spacing={2}><QuoteBillOfProcess- key={`bop:${methodId}`}+ key={JSON.stringify(operations)}quoteMakeMethodId={methodId}operations={operations}/><QuoteBillOfMaterial- key={`bom:${methodId}`}+ key={JSON.stringify(materials)}quoteMakeMethodId={methodId}materials={materials}operations={operations}diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsxindex 4de3f5cdb4..fc99988481 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx@@ -1,10 +1,11 @@import { validationError, validator } from "@carbon/remix-validated-form";import type { ActionFunctionArgs } from "@remix-run/node";import { redirect } from "@remix-run/node";+import { getSupabaseServiceRole } from "~/lib/supabase";import {- insertQuoteLinePrice,quoteLineValidator,upsertQuoteLine,+ upsertQuoteLineMethod,} from "~/modules/sales";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";@@ -15,7 +16,7 @@ import { error } from "~/utils/result";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {+ const { companyId, userId } = await requirePermissions(request, {create: "sales",});@@ -31,7 +32,8 @@ export async function action({ request, params }: ActionFunctionArgs) {const { id, ...data } = validation.data;- const createQuotationLine = await upsertQuoteLine(client, {+ const serviceRole = getSupabaseServiceRole();+ const createQuotationLine = await upsertQuoteLine(serviceRole, {...data,companyId,createdBy: userId,@@ -49,14 +51,23 @@ export async function action({ request, params }: ActionFunctionArgs) {}const quoteLineId = createQuotationLine.data.id;-- await insertQuoteLinePrice(client, {+ const upsertMethod = await upsertQuoteLineMethod(serviceRole, {quoteId,quoteLineId,- quantity: 1,- markupPercent: 15,- createdBy: userId,+ itemId: data.itemId,+ companyId,+ userId,});+ if (upsertMethod.error) {+ throw redirect(+ path.to.quoteLine(quoteId, quoteLineId),+ await flash(+ request,+ error(upsertMethod.error, "Failed to create quote line method.")+ )+ );+ }+throw redirect(path.to.quoteLine(quoteId, quoteLineId));}diff --git a/apps/carbon/app/routes/x+/quote+/methods.$quoteId.$lineId.material.$id.tsx b/apps/carbon/app/routes/x+/quote+/methods.$quoteId.$lineId.material.$id.tsxindex 28bab19cb3..8183f2590b 100644--- a/apps/carbon/app/routes/x+/quote+/methods.$quoteId.$lineId.material.$id.tsx+++ b/apps/carbon/app/routes/x+/quote+/methods.$quoteId.$lineId.material.$id.tsx@@ -1,5 +1,6 @@import { validationError, validator } from "@carbon/remix-validated-form";import { json, type ActionFunctionArgs } from "@remix-run/node";+import { getSupabaseServiceRole } from "~/lib/supabase";import { quoteMaterialValidator, upsertQuoteMaterial } from "~/modules/sales";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";@@ -9,7 +10,7 @@ import { error } from "~/utils/result";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {+ const { companyId, userId } = await requirePermissions(request, {create: "sales",});@@ -31,7 +32,8 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}- const updateQuoteMaterial = await upsertQuoteMaterial(client, {+ const serviceRole = getSupabaseServiceRole();+ const updateQuoteMaterial = await upsertQuoteMaterial(serviceRole, {quoteId,quoteLineId: lineId,...validation.data,diff --git a/apps/carbon/app/routes/x+/quote+/methods.$quoteId.$lineId.material.new.tsx b/apps/carbon/app/routes/x+/quote+/methods.$quoteId.$lineId.material.new.tsxindex d88d7c212d..c96b83994c 100644--- a/apps/carbon/app/routes/x+/quote+/methods.$quoteId.$lineId.material.new.tsx+++ b/apps/carbon/app/routes/x+/quote+/methods.$quoteId.$lineId.material.new.tsx@@ -1,6 +1,11 @@import { validationError, validator } from "@carbon/remix-validated-form";import { json, type ActionFunctionArgs } from "@remix-run/node";-import { quoteMaterialValidator, upsertQuoteMaterial } from "~/modules/sales";+import { getSupabaseServiceRole } from "~/lib/supabase";+import {+ quoteMaterialValidator,+ upsertQuoteMaterial,+ upsertQuoteMaterialMakeMethod,+} from "~/modules/sales";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";@@ -9,7 +14,7 @@ import { error } from "~/utils/result";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {+ const { companyId, userId } = await requirePermissions(request, {create: "sales",});@@ -30,7 +35,8 @@ export async function action({ request, params }: ActionFunctionArgs) {const { id, ...data } = validation.data;- const insertQuoteMaterial = await upsertQuoteMaterial(client, {+ const serviceRole = getSupabaseServiceRole();+ const insertQuoteMaterial = await upsertQuoteMaterial(serviceRole, {...data,quoteId,quoteLineId: lineId,@@ -63,5 +69,26 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ if (data.methodType === "Make") {+ const makeMethod = await upsertQuoteMaterialMakeMethod(serviceRole, {+ ...data,+ quoteMaterialId,+ companyId,+ createdBy: userId,+ });++ if (makeMethod.error) {+ return json(+ {+ id: quoteMaterialId,+ },+ await flash(+ request,+ error(makeMethod.error, "Failed to insert quote material make method")+ )+ );+ }+ }+return json({ id: quoteMaterialId });}diff --git a/apps/carbon/app/routes/x+/quote+/methods.get.tsx b/apps/carbon/app/routes/x+/quote+/methods.get.tsxindex f3c69d1942..2024ec2917 100644--- a/apps/carbon/app/routes/x+/quote+/methods.get.tsx+++ b/apps/carbon/app/routes/x+/quote+/methods.get.tsx@@ -1,6 +1,14 @@-import { type ActionFunctionArgs } from "@remix-run/node";+import { validationError, validator } from "@carbon/remix-validated-form";+import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";import { getSupabaseServiceRole } from "~/lib/supabase";+import {+ getLineMethodValidator,+ getMethodValidator,+ upsertQuoteLineMethod,+ upsertQuoteMaterialMakeMethod,+} from "~/modules/sales";import { requirePermissions } from "~/services/auth/auth.server";+import { path, requestReferrer } from "~/utils/path";export async function action({ request }: ActionFunctionArgs) {const { companyId, userId } = await requirePermissions(request, {@@ -8,26 +16,50 @@ export async function action({ request }: ActionFunctionArgs) {});const formData = await request.formData();- const itemId = formData.get("itemId") as string;- const quoteId = formData.get("quoteId") as string;- const quoteLineId = formData.get("quoteLineId") as string;+ const type = formData.get("type") as string;- if (!itemId || !quoteId || !quoteLineId) {- throw new Error("Missing required fields");- }+ const serviceRole = getSupabaseServiceRole();+ if (type === "line") {+ const validation = await validator(getLineMethodValidator).validate(+ formData+ );+ if (validation.error) {+ return validationError(validation.error);+ }- const supabaseServiceRole = getSupabaseServiceRole();- const { error } = await supabaseServiceRole.functions.invoke("get-method", {- body: {- type: "itemToQuoteLine",- sourceId: itemId,- targetId: `${quoteId}:${quoteLineId}`,+ const lineMethod = await upsertQuoteLineMethod(serviceRole, {+ ...validation.data,companyId,userId,- },- });+ });++ return json({+ error: lineMethod.error ? "Failed to get quote line method" : null,+ });+ }++ if (type === "method") {+ const validation = await validator(getMethodValidator).validate(formData);+ if (validation.error) {+ return validationError(validation.error);+ }++ const makeMethod = await upsertQuoteMaterialMakeMethod(serviceRole, {+ ...validation.data,+ companyId,+ createdBy: userId,+ });++ if (makeMethod.error) {+ return json({+ error: makeMethod.error+ ? "Failed to insert quote material make method"+ : null,+ });+ }++ throw redirect(requestReferrer(request) ?? path.to.quotes);+ }- return {- error: error ? "Failed to get method" : null,- };+ return json({ error: "Invalid type" }, { status: 400 });}diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex 6a44992755..87fb8e10b0 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -17,7 +17,7 @@ const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);const payloadValidator = z.object({- type: z.enum(["itemToQuoteLine"]),+ type: z.enum(["itemToQuoteLine", "itemToQuoteMakeMethod"]),sourceId: z.string(),targetId: z.string(),companyId: z.string(),@@ -34,6 +34,8 @@ serve(async (req: Request) => {const { type, sourceId, targetId, companyId, userId } =payloadValidator.parse(payload);+ console.log({ type, sourceId, targetId, companyId, userId });+const client = getSupabaseServiceRole(req.headers.get("Authorization"));switch (type) {@@ -99,7 +101,7 @@ serve(async (req: Request) => {// - quoteMakeMethod// - quoteMakeMethodOperation// - quoteMakeMethodMaterial- async function traverseMethodToQuote(+ async function traverseMethod(node: MethodTreeItem,parentQuoteMakeMethodId: string | null) {@@ -147,14 +149,6 @@ serve(async (req: Request) => {},{}) ?? {};-- console.log({- node: node.data.itemReadableId,- operationId: node.data.operationId,- quoteOperations,- operationIds,- methodOperationsToQuoteOperations,- });}const mapMethodMaterialToQuoteMaterial = (@@ -211,7 +205,10 @@ serve(async (req: Request) => {for (const [index, child] of madeChildren.entries()) {const makeMethodId = quoteMakeMethods[index].id ?? null;- await traverseMethodToQuote(child, makeMethodId);+ // prevent an infinite loop+ if (child.data.itemId !== itemId) {+ await traverseMethod(child, makeMethodId);+ }}}@@ -223,12 +220,187 @@ serve(async (req: Request) => {}}- console.log(methodTree);- await traverseMethodToQuote(methodTree, quoteMakeMethod.data.id);+ await traverseMethod(methodTree, quoteMakeMethod.data.id);});break;}+ case "itemToQuoteMakeMethod": {+ const quoteMakeMethodId = targetId;++ if (!quoteMakeMethodId) {+ throw new Error("Invalid targetId");+ }+ const itemId = sourceId;++ const [makeMethod, quoteMakeMethod] = await Promise.all([+ client.from("makeMethod").select("*").eq("itemId", itemId).single(),+ client+ .from("quoteMakeMethod")+ .select("*")+ .eq("id", quoteMakeMethodId)+ .single(),+ ]);++ if (makeMethod.error) {+ throw new Error("Failed to get make method");+ }++ if (quoteMakeMethod.error || !quoteMakeMethod.data) {+ throw new Error("Failed to get quote make method");+ }++ const [methodTrees] = await Promise.all([+ getMethodTree(client, makeMethod.data.id),+ ]);++ if (methodTrees.error) {+ throw new Error("Failed to get method tree");+ }++ const methodTree = methodTrees.data?.[0] as MethodTreeItem;+ if (!methodTree) throw new Error("Method tree not found");++ await db.transaction().execute(async (trx) => {+ // Delete existing quoteMakeMethodOperation, quoteMakeMethodMaterial+ await Promise.all([+ trx+ .deleteFrom("quoteMaterial")+ .where("quoteMakeMethodId", "=", quoteMakeMethodId)+ .execute(),+ trx+ .deleteFrom("quoteOperation")+ .where("quoteMakeMethodId", "=", quoteMakeMethodId)+ .execute(),+ ]);++ // traverse method tree and create:+ // - quoteMakeMethod+ // - quoteMakeMethodOperation+ // - quoteMakeMethodMaterial+ async function traverseMethod(+ node: MethodTreeItem,+ parentQuoteMakeMethodId: string | null+ ) {+ const relatedOperations = await client+ .from("methodOperation")+ .select("*, workCellType(quotingRate, laborRate, overheadRate)")+ .eq("makeMethodId", node.data.materialMakeMethodId);++ const quoteOperations =+ relatedOperations?.data?.map((op) => ({+ quoteId: quoteMakeMethod.data?.quoteId!,+ quoteLineId: quoteMakeMethod.data?.quoteLineId!,+ quoteMakeMethodId: parentQuoteMakeMethodId!,+ workCellTypeId: op.workCellTypeId,+ equipmentTypeId: op.equipmentTypeId,+ description: op.description,+ setupHours: op.setupHours,+ standardFactor: op.standardFactor,+ productionStandard: op.productionStandard,+ quotingRate: op.workCellType?.quotingRate ?? 0,+ laborRate: op.workCellType?.laborRate ?? 0,+ overheadRate: op.workCellType?.overheadRate ?? 0,+ order: op.order,+ operationOrder: op.operationOrder,+ companyId,+ createdBy: userId,+ customFields: {},+ })) ?? [];++ let methodOperationsToQuoteOperations: Record<string, string> = {};+ if (quoteOperations?.length > 0) {+ const operationIds = await trx+ .insertInto("quoteOperation")+ .values(quoteOperations)+ .returning(["id"])+ .execute();++ methodOperationsToQuoteOperations =+ relatedOperations.data?.reduce<Record<string, string>>(+ (acc, op, index) => {+ if (operationIds[index].id) {+ acc[op.id!] = operationIds[index].id!;+ }+ return acc;+ },+ {}+ ) ?? {};+ }++ const mapMethodMaterialToQuoteMaterial = (+ child: MethodTreeItem+ ) => ({+ quoteId: quoteMakeMethod.data?.quoteId!,+ quoteLineId: quoteMakeMethod.data?.quoteLineId!,+ quoteMakeMethodId: parentQuoteMakeMethodId!,+ quoteOperationId:+ methodOperationsToQuoteOperations[child.data.operationId],+ itemId: child.data.itemId,+ itemReadableId: child.data.itemReadableId,+ itemType: child.data.itemType,+ methodType: child.data.methodType,+ order: child.data.order,+ description: child.data.description,+ quantity: child.data.quantity,+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ unitCost: child.data.unitCost,+ companyId,+ createdBy: userId,+ customFields: {},+ });++ const madeChildren = node.children.filter(+ (child) => child.data.methodType === "Make"+ );+ const unmadeChildren = node.children.filter(+ (child) => child.data.methodType !== "Make"+ );++ const madeMaterials = madeChildren.map(+ mapMethodMaterialToQuoteMaterial+ );+ const pickedOrBoughtMaterials = unmadeChildren.map(+ mapMethodMaterialToQuoteMaterial+ );+ if (madeMaterials.length > 0) {+ const madeMaterialIds = await trx+ .insertInto("quoteMaterial")+ .values(madeMaterials)+ .returning(["id"])+ .execute();++ const quoteMakeMethods = await trx+ .selectFrom("quoteMakeMethod")+ .select(["id"])+ .where(+ "parentMaterialId",+ "in",+ madeMaterialIds.map((m) => m.id)+ )+ .execute();++ for (const [index, child] of madeChildren.entries()) {+ const makeMethodId = quoteMakeMethods[index].id ?? null;+ // prevent an infinite loop+ if (child.data.itemId !== itemId) {+ await traverseMethod(child, makeMethodId);+ }+ }+ }++ if (pickedOrBoughtMaterials.length > 0) {+ await trx+ .insertInto("quoteMaterial")+ .values(pickedOrBoughtMaterials)+ .execute();+ }+ }++ await traverseMethod(methodTree, quoteMakeMethod.data.id);+ });+ break;+ }default:throw new Error(`Invalid type ${type}`);}