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: copy quote lines

Brad Barbin67e7c1657ac2
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index e51748523d..2f521a94ec 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -33,10 +33,9 @@ import {
useParams,
} from "@remix-run/react";
import type {
- PostgrestResponse,
PostgrestSingleResponse,
} from "@supabase/supabase-js";
-import { Suspense, useEffect, useMemo, useState } from "react";
+import { Suspense, useEffect, useState } from "react";
import {
LuGitBranch,
LuGitFork,
@@ -50,8 +49,6 @@ import { ConfiguratorModal } from "~/components/Configurator/ConfiguratorForm";
import {
Hidden,
Item,
- Select,
- SelectControlled,
Submit,
} from "~/components/Form";
import type { Tree } from "~/components/TreeView";
@@ -66,6 +63,7 @@ import { path } from "~/utils/path";
import { getJobMethodValidator } from "../../production.models";
import type { Job, JobMakeMethod, JobMaterial, JobMethod } from "../../types";
import { labelSizes } from "@carbon/utils";
+import { QuoteLineMethodForm } from "~/modules/sales/ui/Quotes/QuoteLineMethodForm";
const JobMakeMethodTools = ({
makeMethod,
@@ -366,7 +364,7 @@ const JobMakeMethodTools = ({
<TabsContent value="quote">
<Hidden name="type" value="quoteLine" />
<Hidden name="targetId" value={jobId} />
- <QuoteLineForm />
+ <QuoteLineMethodForm />
</TabsContent>
</Tabs>
</ModalBody>
@@ -495,84 +493,3 @@ const JobMakeMethodTools = ({
export default JobMakeMethodTools;
-function QuoteLineForm() {
- const quoteFetcher =
- useFetcher<PostgrestResponse<{ id: string; quoteId: string }>>();
- const quoteLineFetcher = useFetcher<
- PostgrestResponse<{
- id: string;
- itemReadableId: string;
- description: string;
- }>
- >();
-
- // const quotesLoading = quoteFetcher.state === "loading";
- // const quoteLinesLoading = quoteLineFetcher.state === "loading";
- const [quote, setQuote] = useState<string | null>(null);
- const [quoteLine, setQuoteLine] = useState<string | null>(null);
-
- useMount(() => {
- quoteFetcher.load(path.to.api.quotes);
- });
-
- useEffect(() => {
- if (quote) {
- quoteLineFetcher.load(path.to.api.quoteLines(quote));
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [quote]);
-
- const quoteOptions = useMemo(
- () =>
- quoteFetcher.data?.data?.map((quote) => ({
- label: quote.quoteId,
- value: quote.id,
- })) ?? [],
- [quoteFetcher.data]
- );
-
- const quoteLineOptions = useMemo(
- () =>
- quoteLineFetcher.data?.data?.map((quoteLine) => ({
- label: quoteLine.itemReadableId,
- value: quoteLine.id,
- })) ?? [],
- [quoteLineFetcher.data]
- );
-
- return (
- <>
- <VStack spacing={4} className="w-full">
- <Select
- name="quoteId"
- label="Quote"
- options={quoteOptions}
- placeholder="Select a quote"
- onChange={(newValue) => {
- if (newValue) {
- setQuote(newValue.value);
- setQuoteLine(null);
- }
- }}
- />
- <SelectControlled
- name="quoteLineId"
- label="Quote Line"
- options={quoteLineOptions}
- placeholder="Select a quote line"
- isReadOnly={!quote}
- onChange={(newValue) => {
- if (newValue) {
- setQuoteLine(newValue.value);
- }
- }}
- />
- </VStack>
- <Hidden
- name="sourceId"
- className="-my-4"
- value={quoteLine ? `${quote}:${quoteLine}` : ""}
- />
- </>
- );
-}
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index 7cd65f6865..c8e825b16d 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -121,18 +121,13 @@ export const externalQuoteValidator = z.discriminatedUnion("type", [
}),
]);
-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" }),
+ type: z.enum(["item", "quoteLine", "method" ]),
+ sourceId: z.string(),
+ targetId: z.string(),
});
+
export const noQuoteReasonValidator = z.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }),
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 2d06dc4f4b..e9b87e2fe4 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -94,6 +94,22 @@ export async function convertQuoteToOrder(
});
}
+export async function copyQuoteLine(
+ client: SupabaseClient<Database>,
+ payload: z.infer<typeof getMethodValidator> & {
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke<{ copiedId: string }>("get-method", {
+ body: {
+ ...payload,
+ type: "quoteLineToQuoteLine",
+ },
+ });
+}
+
+
export async function deleteCustomer(
client: SupabaseClient<Database>,
customerId: string
@@ -1772,7 +1788,9 @@ export async function upsertMakeMethodFromQuoteLine(
export async function upsertMakeMethodFromQuoteMethod(
client: SupabaseClient<Database>,
- quoteMaterial: z.infer<typeof getMethodValidator> & {
+ quoteMaterial: {
+ quoteMaterialId: string;
+ itemId: string;
companyId: string;
createdBy: string;
}
@@ -2137,7 +2155,9 @@ export async function upsertQuoteMaterial(
export async function upsertQuoteMaterialMakeMethod(
client: SupabaseClient<Database>,
- quoteMaterial: z.infer<typeof getMethodValidator> & {
+ quoteMaterial: {
+ quoteMaterialId: string;
+ itemId: string;
companyId: string;
createdBy: string;
}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineMethodForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineMethodForm.tsx
new file mode 100644
index 0000000000..ec79e7393b
--- /dev/null
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineMethodForm.tsx
@@ -0,0 +1,88 @@
+import { SelectControlled, Hidden, Combobox } from "@carbon/form";
+import { useMount, VStack } from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { PostgrestResponse } from "@supabase/supabase-js";
+import { useState, useEffect, useMemo } from "react";
+import { path } from "~/utils/path";
+
+export function QuoteLineMethodForm() {
+ const quoteFetcher =
+ useFetcher<PostgrestResponse<{ id: string; quoteId: string }>>();
+ const quoteLineFetcher = useFetcher<
+ PostgrestResponse<{
+ id: string;
+ itemReadableId: string;
+ description: string;
+ }>
+ >();
+
+ // const quotesLoading = quoteFetcher.state === "loading";
+ // const quoteLinesLoading = quoteLineFetcher.state === "loading";
+ const [quote, setQuote] = useState<string | null>(null);
+ const [quoteLine, setQuoteLine] = useState<string | null>(null);
+
+ useMount(() => {
+ quoteFetcher.load(path.to.api.quotes);
+ });
+
+ useEffect(() => {
+ if (quote) {
+ quoteLineFetcher.load(path.to.api.quoteLines(quote));
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [quote]);
+
+ const quoteOptions = useMemo(
+ () =>
+ quoteFetcher.data?.data?.map((quote) => ({
+ label: quote.quoteId,
+ value: quote.id,
+ })) ?? [],
+ [quoteFetcher.data]
+ );
+
+ const quoteLineOptions = useMemo(
+ () =>
+ quoteLineFetcher.data?.data?.map((quoteLine) => ({
+ label: quoteLine.itemReadableId,
+ value: quoteLine.id,
+ })) ?? [],
+ [quoteLineFetcher.data]
+ );
+
+ return (
+ <>
+ <VStack spacing={4} className="w-full">
+ <Combobox
+ name="quoteId"
+ label="Quote"
+ options={quoteOptions}
+ placeholder="Select a quote"
+ onChange={(newValue) => {
+ if (newValue) {
+ setQuote(newValue.value);
+ setQuoteLine(null);
+ }
+ }}
+ />
+ <SelectControlled
+ name="quoteLineId"
+ label="Quote Line"
+ options={quoteLineOptions}
+ placeholder="Select a quote line"
+ isReadOnly={!quote}
+ onChange={(newValue) => {
+ if (newValue) {
+ setQuoteLine(newValue.value);
+ }
+ }}
+ />
+ </VStack>
+ <Hidden
+ name="sourceId"
+ className="-my-4"
+ value={quoteLine ? `${quote}:${quoteLine}` : ""}
+ />
+ </>
+ );
+}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
index 07d7fd7ad2..0fea45addb 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
@@ -15,6 +15,10 @@ import {
ModalFooter,
ModalHeader,
ModalTitle,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
toast,
useDisclosure,
useMount,
@@ -33,6 +37,7 @@ import {
LuGitFork,
LuGitMerge,
LuSettings,
+ LuSquareStack,
LuTriangleAlert,
} from "react-icons/lu";
import { ConfiguratorModal } from "~/components/Configurator/ConfiguratorForm";
@@ -46,8 +51,10 @@ import type {
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType } from "~/modules/shared/types";
import { path } from "~/utils/path";
-import { getLineMethodValidator, getMethodValidator } from "../../sales.models";
+import { getMethodValidator } from "../../sales.models";
import type { Quotation, QuotationLine, QuoteMethod } from "../../types";
+import { RiProgress4Line } from "react-icons/ri";
+import { QuoteLineMethodForm } from "./QuoteLineMethodForm";
const QuoteMakeMethodTools = () => {
const permissions = usePermissions();
@@ -218,9 +225,7 @@ const QuoteMakeMethodTools = () => {
method="post"
fetcher={fetcher}
action={path.to.quoteMethodGet}
- validator={
- isQuoteLineMethod ? getLineMethodValidator : getMethodValidator
- }
+ validator={getMethodValidator}
onSubmit={getMethodModal.onClose}
>
<ModalHeader>
@@ -231,48 +236,92 @@ const QuoteMakeMethodTools = () => {
</ModalHeader>
<ModalBody>
{isQuoteLineMethod ? (
- <>
- <Hidden name="type" value="line" />
- <Hidden name="quoteId" value={quoteId} />
- <Hidden name="quoteLineId" value={lineId} />
- </>
+ <Tabs defaultValue="item" className="w-full">
+ <TabsList className="grid w-full grid-cols-2 my-4">
+ <TabsTrigger value="item">
+ <LuSquareStack className="mr-2" /> Item
+ </TabsTrigger>
+ <TabsTrigger value="quote">
+ <RiProgress4Line className="mr-2" />
+ Quote
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="item">
+ <Hidden name="type" value="item" />
+ <Hidden name="targetId" value={`${quoteId}:${lineId}`} />
+ <VStack spacing={4}>
+ <Item
+ name="sourceId"
+ 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">
+ <LuTriangleAlert className="h-4 w-4" />
+ <AlertTitle>
+ This will overwrite the existing quote method
+ </AlertTitle>
+ </Alert>
+ )}
+ </VStack>
+ </TabsContent>
+ <TabsContent value="quote">
+ <Hidden name="type" value="quoteLine" />
+ <Hidden name="targetId" value={`${quoteId}:${lineId}`} />
+ <QuoteLineMethodForm />
+ </TabsContent>
+ </Tabs>
) : (
<>
<Hidden name="type" value="method" />
- <Hidden name="quoteMaterialId" value={materialId!} />
+ <Hidden name="targetId" value={materialId!} />
+ <VStack spacing={4}>
+ <Item
+ name="sourceId"
+ 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">
+ <LuTriangleAlert className="h-4 w-4" />
+ <AlertTitle>
+ This will overwrite the existing quote method
+ </AlertTitle>
+ </Alert>
+ )}
+ </VStack>
</>
)}
-
- <VStack spacing={4}>
- <Item
- name="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">
- <LuTriangleAlert className="h-4 w-4" />
- <AlertTitle>
- This will overwrite the existing quote method
- </AlertTitle>
- </Alert>
- )}
- </VStack>
</ModalBody>
<ModalFooter>
<Button onClick={getMethodModal.onClose} variant="secondary">
@@ -301,11 +350,9 @@ const QuoteMakeMethodTools = () => {
method="post"
fetcher={fetcher}
action={path.to.quoteMethodSave}
- validator={
- isQuoteLineMethod ? getLineMethodValidator : getMethodValidator
- }
+ validator={getMethodValidator}
defaultValues={{
- itemId: isQuoteLineMethod
+ sourceId: isQuoteLineMethod
? line?.itemId ?? undefined
: undefined,
}}
@@ -321,20 +368,19 @@ const QuoteMakeMethodTools = () => {
<ModalBody>
{isQuoteLineMethod ? (
<>
- <Hidden name="type" value="line" />
- <Hidden name="quoteId" value={quoteId} />
- <Hidden name="quoteLineId" value={lineId} />
+ <Hidden name="type" value="item" />
+ <Hidden name="sourceId" value={`${quoteId}:${lineId}`} />
</>
) : (
<>
<Hidden name="type" value="method" />
- <Hidden name="quoteMaterialId" value={materialId!} />
+ <Hidden name="sourceId" value={materialId!} />
</>
)}
<VStack spacing={4}>
<Item
- name="itemId"
+ name="targetId"
label="Target Method"
type={(line?.itemType ?? "Part") as "Part"}
includeInactive={includeInactive === true}
diff --git a/apps/erp/app/routes/x+/quote+/methods+/get.tsx b/apps/erp/app/routes/x+/quote+/methods+/get.tsx
index d462987eb7..05e1e887d4 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/get.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/get.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
import {
- getLineMethodValidator,
+ copyQuoteLine,
getMethodValidator,
upsertQuoteLineMethod,
upsertQuoteMaterialMakeMethod,
@@ -18,17 +18,24 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const type = formData.get("type") as string;
+
const serviceRole = getCarbonServiceRole();
- if (type === "line") {
- const validation = await validator(getLineMethodValidator).validate(
+ if (type === "item") {
+ const validation = await validator(getMethodValidator).validate(
formData
);
if (validation.error) {
return validationError(validation.error);
}
+ const [quoteId, quoteLineId] = validation.data.targetId.split(":");
+ const itemId = validation.data.sourceId;
+
+
const lineMethod = await upsertQuoteLineMethod(serviceRole, {
- ...validation.data,
+ itemId,
+ quoteId,
+ quoteLineId,
companyId,
userId,
});
@@ -38,14 +45,36 @@ export async function action({ request }: ActionFunctionArgs) {
});
}
+ if (type === "quoteLine") {
+ const validation = await validator(getMethodValidator).validate(formData);
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+
+ const copyLine = await copyQuoteLine(serviceRole, {
+ ...validation.data,
+ companyId,
+ userId,
+ });
+
+ return json({
+ error: copyLine.error ? "Failed to copy quote line" : null,
+ });
+ }
+
if (type === "method") {
const validation = await validator(getMethodValidator).validate(formData);
if (validation.error) {
return validationError(validation.error);
}
+ const quoteMaterialId = validation.data.targetId;
+ const itemId = validation.data.sourceId;
+
const makeMethod = await upsertQuoteMaterialMakeMethod(serviceRole, {
- ...validation.data,
+ itemId,
+ quoteMaterialId,
companyId,
createdBy: userId,
});
diff --git a/apps/erp/app/routes/x+/quote+/methods+/save.tsx b/apps/erp/app/routes/x+/quote+/methods+/save.tsx
index 59d51ea132..32ad56121f 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/save.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/save.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
import {
- getLineMethodValidator,
+
getMethodValidator,
upsertMakeMethodFromQuoteLine,
upsertMakeMethodFromQuoteMethod,
@@ -19,16 +19,22 @@ export async function action({ request }: ActionFunctionArgs) {
const type = formData.get("type") as string;
const serviceRole = getCarbonServiceRole();
- if (type === "line") {
- const validation = await validator(getLineMethodValidator).validate(
+
+ if (type === "item") {
+ const validation = await validator(getMethodValidator).validate(
formData
);
if (validation.error) {
return validationError(validation.error);
}
+ const [quoteId, quoteLineId] = validation.data.sourceId.split(":");
+ const itemId = validation.data.targetId;
+
const lineMethod = await upsertMakeMethodFromQuoteLine(serviceRole, {
- ...validation.data,
+ quoteId,
+ quoteLineId,
+ itemId,
companyId,
userId,
});
@@ -46,8 +52,12 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ const quoteMaterialId = validation.data.targetId;
+ const itemId = validation.data.sourceId;
+
const makeMethod = await upsertMakeMethodFromQuoteMethod(serviceRole, {
- ...validation.data,
+ quoteMaterialId,
+ itemId,
companyId,
createdBy: userId,
});
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 842967a1a2..4152d06a66 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -40,6 +40,7 @@ const payloadValidator = z.object({
"procedureToOperation",
"quoteLineToItem",
"quoteLineToJob",
+ "quoteLineToQuoteLine",
"quoteMakeMethodToItem",
]),
sourceId: z.string(),
@@ -3125,6 +3126,280 @@ serve(async (req: Request) => {
break;
}
+ case "quoteLineToQuoteLine": {
+ const [, sourceQuoteLineId] = (sourceId as string).split(":");
+ const [targetQuoteId, targetQuoteLineId] = (targetId as string).split(":");
+
+ console.log({
+ sourceQuoteLineId,
+ targetQuoteId,
+ targetQuoteLineId,
+ })
+
+ const [
+ targetQuoteMakeMethod,
+ sourceQuoteMakeMethod,
+ sourceQuoteMaterials,
+ sourceQuoteOperations,
+ ] = await Promise.all([
+ client
+ .from("quoteMakeMethod")
+ .select("*")
+ .eq("quoteLineId", targetQuoteLineId)
+ .is("parentMaterialId", null)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("quoteMakeMethod")
+ .select("*")
+ .is("parentMaterialId", null)
+ .eq("quoteLineId", sourceQuoteLineId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("quoteMaterial")
+ .select("*")
+ .eq("quoteLineId", sourceQuoteLineId)
+ .eq("companyId", companyId),
+ client
+ .from("quoteOperation")
+ .select(
+ "*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"
+ )
+ .eq("quoteLineId", sourceQuoteLineId)
+ .eq("companyId", companyId),
+ ]);
+
+ if (targetQuoteMakeMethod.error || !targetQuoteMakeMethod.data) {
+ console.error(targetQuoteMakeMethod.error);
+ throw new Error("Failed to get target quote make method");
+ }
+
+ if (
+ sourceQuoteMakeMethod.error ||
+ sourceQuoteMaterials.error ||
+ sourceQuoteOperations.error
+ ) {
+ throw new Error("Failed to source quote data");
+ }
+
+ const [quoteMethodTrees] = await Promise.all([
+ getQuoteMethodTree(client, sourceQuoteMakeMethod.data.id),
+ ]);
+
+ if (quoteMethodTrees.error) {
+ throw new Error("Failed to get method tree");
+ }
+
+ const quoteMethodTree = quoteMethodTrees
+ .data?.[0] as QuoteMethodTreeItem;
+ if (!quoteMethodTree) throw new Error("Method tree not found");
+
+ const quoteMaterialIdToQuoteMaterialId: Record<string, string> = {};
+ const quoteMakeMethodIdToQuoteMakeMethodId: Record<string, string> = {};
+
+ await db.transaction().execute(async (trx) => {
+ // Delete existing jobMakeMethods, jobMaterials, and jobOperations for this job
+ await Promise.all([
+ trx
+ .deleteFrom("quoteMakeMethod")
+ .where((eb) =>
+ eb.and([
+ eb("quoteLineId", "=", targetQuoteLineId),
+ eb("parentMaterialId", "is not", null),
+ ])
+ )
+ .execute(),
+ trx.deleteFrom("quoteMaterial").where("quoteLineId", "=", targetQuoteLineId).execute(),
+ trx.deleteFrom("quoteOperation").where("quoteLineId", "=", targetQuoteLineId).execute(),
+ ]);
+
+
+
+ await traverseQuoteMethod(
+ quoteMethodTree,
+ async (node: QuoteMethodTreeItem) => {
+ const quoteMaterialInserts: Database["public"]["Tables"]["quoteMaterial"]["Insert"][] =
+ [];
+ const quoteMakeMethodInserts: Database["public"]["Tables"]["quoteMakeMethod"]["Insert"][] =
+ [];
+
+ for await (const child of node.children) {
+ const newMaterialId = nanoid();
+ quoteMaterialIdToQuoteMaterialId[child.id] = newMaterialId;
+
+ quoteMaterialInserts.push({
+ id: newMaterialId,
+ quoteId: targetQuoteId,
+ quoteLineId: targetQuoteLineId,
+ itemId: child.data.itemId,
+ itemReadableId: child.data.itemReadableId,
+ itemType: child.data.itemType,
+ methodType: child.data.methodType,
+ order: child.data.order,
+ description: child.data.description,
+ quoteMakeMethodId:
+ child.data.quoteMakeMethodId === sourceQuoteMakeMethod.data.id
+ ? targetQuoteMakeMethod.data.id
+ : quoteMakeMethodIdToQuoteMakeMethodId[
+ child.data.quoteMakeMethodId
+ ],
+ quantity: child.data.quantity,
+ unitOfMeasureCode: child.data.unitOfMeasureCode,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ });
+
+ if (child.data.quoteMaterialMakeMethodId) {
+ const newMakeMethodId = nanoid();
+ quoteMakeMethodIdToQuoteMakeMethodId[
+ child.data.quoteMaterialMakeMethodId
+ ] = newMakeMethodId;
+ quoteMakeMethodInserts.push({
+ id: newMakeMethodId,
+ quoteId: targetQuoteId,
+ quoteLineId: targetQuoteLineId,
+ parentMaterialId: quoteMaterialIdToQuoteMaterialId[child.id],
+ itemId: child.data.itemId,
+ quantityPerParent: child.data.quantity,
+ companyId,
+ createdBy: userId,
+ });
+ }
+ }
+
+ if (quoteMaterialInserts.length > 0) {
+ await trx
+ .insertInto("quoteMaterial")
+ .values(quoteMaterialInserts)
+ .execute();
+ }
+
+ if (quoteMakeMethodInserts.length > 0) {
+ for await (const insert of quoteMakeMethodInserts) {
+ await trx
+ .updateTable("quoteMakeMethod")
+ .set({
+ id: insert.id,
+ quantityPerParent: insert.quantityPerParent,
+ })
+ .where("quoteLineId", "=", targetQuoteLineId)
+ .where("parentMaterialId", "=", insert.parentMaterialId)
+ .execute();
+ }
+ }
+ }
+ );
+
+ const quoteOperationInserts: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =
+ sourceQuoteOperations.data.map((op) => ({
+ quoteId: targetQuoteId,
+ quoteLineId: targetQuoteLineId,
+ quoteMakeMethodId:
+ op.quoteMakeMethodId === sourceQuoteMakeMethod.data.id
+ ? targetQuoteMakeMethod.data.id
+ : quoteMakeMethodIdToQuoteMakeMethodId[op.quoteMakeMethodId!],
+ processId: op.processId,
+ procedureId: op.procedureId,
+ workCenterId: op.workCenterId,
+ description: op.description,
+ setupTime: op.setupTime,
+ setupUnit: op.setupUnit,
+ laborTime: op.laborTime,
+ laborUnit: op.laborUnit,
+ machineTime: op.machineTime,
+ machineUnit: op.machineUnit,
+ order: op.order,
+ operationOrder: op.operationOrder,
+ operationType: op.operationType,
+ operationSupplierProcessId: op.operationSupplierProcessId,
+ tags: op.tags ?? [],
+ workInstruction: op.workInstruction,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ }));
+
+ if (quoteOperationInserts.length > 0) {
+ const operationIds = await trx
+ .insertInto("quoteOperation")
+ .values(quoteOperationInserts)
+ .returning(["id"])
+ .execute();
+
+ for (const [index, operation] of (
+ sourceQuoteOperations.data ?? []
+ ).entries()) {
+ const operationId = operationIds[index].id;
+ if (operationId) {
+ const {
+ quoteOperationTool,
+ quoteOperationParameter,
+ quoteOperationAttribute,
+ } = operation;
+
+ if (
+ Array.isArray(quoteOperationTool) &&
+ quoteOperationTool.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationTool")
+ .values(
+ quoteOperationTool.map((tool) => ({
+ toolId: tool.toolId,
+ quantity: tool.quantity,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
+
+
+ if (
+ Array.isArray(quoteOperationParameter) &&
+ quoteOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationParameter")
+ .values(
+ quoteOperationParameter.map((param) => ({
+ operationId,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
+
+ if (
+ Array.isArray(quoteOperationAttribute) &&
+ quoteOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationAttribute")
+ .values(
+ quoteOperationAttribute.map((attribute) => ({
+ ...attribute,
+ operationId,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
+ }
+
+ }
+ }
+ });
+
+ break;
+ }
case "quoteMakeMethodToItem": {
const quoteMakeMethodId = sourceId;
const itemId = targetId;