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: pull job method from quote line method

Brad Barbin5d6be5a51312
diff --git a/apps/carbon/app/components/Layout/Navigation/IconSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/PrimaryNavigation.tsx
similarity index 65%
rename from apps/carbon/app/components/Layout/Navigation/IconSidebar.tsx
rename to apps/carbon/app/components/Layout/Navigation/PrimaryNavigation.tsx
index 3379f2ddfd..e669303fc7 100644
--- a/apps/carbon/app/components/Layout/Navigation/IconSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/PrimaryNavigation.tsx
@@ -3,18 +3,16 @@ import { Link, useMatches } from "@remix-run/react";
import { noop } from "@tanstack/react-table";
import { forwardRef, type AnchorHTMLAttributes } from "react";
import { BsFillHexagonFill } from "react-icons/bs";
-import { LuUserCircle } from "react-icons/lu";
import { z } from "zod";
import { useOptimisticLocation, useUser } from "~/hooks";
import type { Authenticated, NavItem } from "~/types";
-import { path } from "~/utils/path";
import { useModules } from "./useModules";
export const ModuleHandle = z.object({
module: z.string(),
});
-const IconSidebar = () => {
+const PrimaryNavigation = () => {
const { company } = useUser();
const navigationPanel = useDisclosure();
@@ -37,7 +35,7 @@ const IconSidebar = () => {
<nav
data-state={navigationPanel.isOpen ? "expanded" : "collapsed"}
className={cn(
- "bg-background group py-2 z-10 h-full w-14 data-[state=expanded]:w-[13rem]",
+ "bg-background py-[3px] group z-10 h-full w-14 data-[state=expanded]:w-[13rem]",
"border-r border-border data-[state=expanded]:shadow-xl",
"transition-width duration-200",
"hide-scrollbar flex flex-col justify-between overflow-y-auto"
@@ -45,54 +43,37 @@ const IconSidebar = () => {
onMouseEnter={navigationPanel.onOpen}
onMouseLeave={navigationPanel.onClose}
>
- <VStack
- spacing={1}
- className="flex flex-col justify-between h-full px-2"
- >
- <VStack spacing={1}>
- <Button isIcon asChild variant="ghost" size="lg">
- <Link to="/">
- {company?.logo ? (
- <img
- src={company.logo}
- alt={`${company.name} logo`}
- className="w-full h-auto rounded"
- />
- ) : (
- <BsFillHexagonFill />
- )}
- </Link>
- </Button>
- {links.map((link) => {
- const m = getModule(link.to);
+ <VStack spacing={1} className="flex flex-col justify-start h-full px-2">
+ <Button isIcon asChild variant="ghost" size="lg">
+ <Link to="/">
+ {company?.logo ? (
+ <img
+ src={company.logo}
+ alt={`${company.name} logo`}
+ className="w-full h-auto rounded"
+ />
+ ) : (
+ <BsFillHexagonFill />
+ )}
+ </Link>
+ </Button>
- const moduleMatches = matchedModules.has(m);
+ {links.map((link) => {
+ const m = getModule(link.to);
- const isActive = currentModule === m || moduleMatches;
- return (
- <NavigationIconLink
- key={link.name}
- link={link}
- isActive={isActive}
- isOpen={navigationPanel.isOpen}
- onClick={navigationPanel.onClose}
- />
- );
- })}
- </VStack>
+ const moduleMatches = matchedModules.has(m);
- <VStack spacing={1}>
- <NavigationIconLink
- link={{
- to: path.to.profile,
- icon: LuUserCircle,
- name: "Account",
- }}
- isActive={matchedModules.has(getModule(path.to.profile))}
- isOpen={navigationPanel.isOpen}
- onClick={navigationPanel.onClose}
- />
- </VStack>
+ const isActive = currentModule === m || moduleMatches;
+ return (
+ <NavigationIconLink
+ key={link.name}
+ link={link}
+ isActive={isActive}
+ isOpen={navigationPanel.isOpen}
+ onClick={navigationPanel.onClose}
+ />
+ );
+ })}
</VStack>
</nav>
</div>
@@ -163,7 +144,7 @@ const NavigationIconLink = forwardRef<
);
NavigationIconLink.displayName = "NavigationIconLink";
-export default IconSidebar;
+export default PrimaryNavigation;
function getModule(link: string) {
return link.split("/")?.[2];
diff --git a/apps/carbon/app/components/Layout/Navigation/index.ts b/apps/carbon/app/components/Layout/Navigation/index.ts
index f2f011b114..733759a719 100644
--- a/apps/carbon/app/components/Layout/Navigation/index.ts
+++ b/apps/carbon/app/components/Layout/Navigation/index.ts
@@ -3,7 +3,7 @@ import ContentSidebar from "./ContentSidebar";
import DetailSidebar from "./DetailSidebar";
import DetailsTopbar from "./DetailsTopbar";
import GroupedContentSidebar from "./GroupedContentSidebar";
-import IconSidebar from "./IconSidebar";
+import PrimaryNavigation from "./PrimaryNavigation";
export {
CollapsibleSidebar,
@@ -11,5 +11,5 @@ export {
DetailSidebar,
DetailsTopbar,
GroupedContentSidebar,
- IconSidebar,
+ PrimaryNavigation,
};
diff --git a/apps/carbon/app/components/Layout/Navigation/useModules.tsx b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
index 2407ac1b10..4bde1981c3 100644
--- a/apps/carbon/app/components/Layout/Navigation/useModules.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
@@ -4,7 +4,6 @@ import {
LuCrown,
LuFactory,
LuFiles,
- LuLandmark,
LuSettings,
LuShield,
LuShoppingCart,
@@ -69,12 +68,12 @@ export function useModules() {
// to: path.to.messaging,
// icon: BiMessage,
// },
- {
- permission: "accounting",
- name: "Accounting",
- to: path.to.chartOfAccounts,
- icon: LuLandmark,
- },
+ // {
+ // permission: "accounting",
+ // name: "Accounting",
+ // to: path.to.chartOfAccounts,
+ // icon: LuLandmark,
+ // },
{
permission: "invoicing",
name: "Invoicing",
diff --git a/apps/carbon/app/components/Layout/index.ts b/apps/carbon/app/components/Layout/index.ts
index 1788099e48..62e673f499 100644
--- a/apps/carbon/app/components/Layout/index.ts
+++ b/apps/carbon/app/components/Layout/index.ts
@@ -5,7 +5,7 @@ import {
DetailSidebar,
DetailsTopbar,
GroupedContentSidebar,
- IconSidebar,
+ PrimaryNavigation,
} from "./Navigation";
import Topbar from "./Topbar";
@@ -17,6 +17,6 @@ export {
DetailSidebar,
DetailsTopbar,
GroupedContentSidebar,
- IconSidebar,
+ PrimaryNavigation,
Topbar,
};
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.ts
index d8188d8bab..e26d53204c 100644
--- a/apps/carbon/app/modules/items/items.models.ts
+++ b/apps/carbon/app/modules/items/items.models.ts
@@ -67,6 +67,7 @@ export const itemValidator = z.object({
unitOfMeasureCode: z
.string()
.min(1, { message: "Unit of Measure is required" }),
+
active: zfd.checkbox(),
});
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
index d1b10aa24e..e83850d844 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
@@ -14,12 +14,18 @@ import {
ModalFooter,
ModalHeader,
ModalTitle,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
toast,
useDisclosure,
+ useMount,
VStack,
} from "@carbon/react";
import { Link, useFetcher, useLocation, useParams } from "@remix-run/react";
-import { useEffect, useState } from "react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { useEffect, useMemo, useState } from "react";
import {
LuAlertTriangle,
LuDownload,
@@ -27,7 +33,13 @@ import {
LuUpload,
} from "react-icons/lu";
import { BreadcrumbItem, Breadcrumbs } from "~/components";
-import { Hidden, Item, Submit } from "~/components/Form";
+import {
+ Hidden,
+ Item,
+ Select,
+ SelectControlled,
+ Submit,
+} from "~/components/Form";
import type { Tree } from "~/components/TreeView";
import { usePermissions, useRouteData } from "~/hooks";
import { path } from "~/utils/path";
@@ -136,48 +148,63 @@ const JobBreadcrumbs = () => {
</ModalDescription>
</ModalHeader>
<ModalBody>
- {isJobMethod ? (
- <>
- <Hidden name="type" value="item" />
- <Hidden name="targetId" value={jobId} />
- </>
- ) : (
- <>
- <Hidden name="type" value="method" />
- <Hidden name="targetId" value={materialId!} />
- </>
- )}
-
- <VStack spacing={4}>
- <Item
- name="sourceId"
- label="Source Method"
- type={(routeData?.job.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">
- <LuAlertTriangle className="h-4 w-4" />
- <AlertTitle>
- This will overwrite the existing job method
- </AlertTitle>
- </Alert>
+ <Tabs defaultValue="item" className="w-full">
+ {isJobMethod && (
+ <TabsList className="grid w-full grid-cols-2 my-4">
+ <TabsTrigger value="item">Item</TabsTrigger>
+ <TabsTrigger value="quote">Quote</TabsTrigger>
+ </TabsList>
)}
- </VStack>
+ <TabsContent value="item">
+ {isJobMethod ? (
+ <>
+ <Hidden name="type" value="item" />
+ <Hidden name="targetId" value={jobId} />
+ </>
+ ) : (
+ <>
+ <Hidden name="type" value="method" />
+ <Hidden name="targetId" value={materialId!} />
+ </>
+ )}
+
+ <VStack spacing={4}>
+ <Item
+ name="sourceId"
+ label="Source Method"
+ type={(routeData?.job.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">
+ <LuAlertTriangle className="h-4 w-4" />
+ <AlertTitle>
+ This will overwrite the existing job method
+ </AlertTitle>
+ </Alert>
+ )}
+ </VStack>
+ </TabsContent>
+ <TabsContent value="quote">
+ <Hidden name="type" value="quoteLine" />
+ <Hidden name="targetId" value={jobId} />
+ <QuoteLineForm />
+ </TabsContent>
+ </Tabs>
</ModalBody>
<ModalFooter>
<Button onClick={getMethodModal.onClose} variant="secondary">
@@ -281,3 +308,85 @@ const JobBreadcrumbs = () => {
};
export default JobBreadcrumbs;
+
+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/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 8d4dc9f126..57c85b6baf 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -483,6 +483,17 @@ export async function getQuotes(
return query;
}
+export async function getQuotesList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("quote")
+ .select("id, quoteId")
+ .eq("companyId", companyId)
+ .order("createdAt", { ascending: false });
+}
+
export async function getQuoteAssembliesByLine(
client: SupabaseClient<Database>,
quoteLineId: string
@@ -526,6 +537,16 @@ export async function getQuoteLine(
return client.from("quoteLines").select("*").eq("id", quoteLineId).single();
}
+export async function getQuoteLinesList(
+ client: SupabaseClient<Database>,
+ quoteId: string
+) {
+ return client
+ .from("quoteLine")
+ .select("id, itemReadableId, description")
+ .eq("quoteId", quoteId);
+}
+
type QuoteMethod = NonNullable<
Awaited<ReturnType<typeof getQuoteMethodTreeArray>>["data"]
>[number];
diff --git a/apps/carbon/app/routes/api+/sales.quotes.$id.lines.ts b/apps/carbon/app/routes/api+/sales.quotes.$id.lines.ts
new file mode 100644
index 0000000000..0ec93b8877
--- /dev/null
+++ b/apps/carbon/app/routes/api+/sales.quotes.$id.lines.ts
@@ -0,0 +1,15 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { getQuoteLinesList } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth/auth.server";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { id } = params;
+ if (!id) return json({ data: [], error: null });
+
+ return json(await getQuoteLinesList(client, id));
+}
diff --git a/apps/carbon/app/routes/api+/sales.quotes.ts b/apps/carbon/app/routes/api+/sales.quotes.ts
new file mode 100644
index 0000000000..850c751ceb
--- /dev/null
+++ b/apps/carbon/app/routes/api+/sales.quotes.ts
@@ -0,0 +1,12 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { getQuotesList } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth/auth.server";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ return json(await getQuotesList(client, companyId));
+}
diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsx
index 71595c0f84..ea45b71e11 100644
--- a/apps/carbon/app/routes/x+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/_layout.tsx
@@ -6,7 +6,7 @@ import NProgress from "nprogress";
import { useEffect } from "react";
import { RealtimeDataProvider } from "~/components";
-import { IconSidebar, Topbar } from "~/components/Layout";
+import { PrimaryNavigation, Topbar } from "~/components/Layout";
import { AutodeskProvider } from "~/lib/autodesk";
import { SupabaseProvider, getSupabase } from "~/lib/supabase";
import { getCompanies, getCompanyIntegrations } from "~/modules/settings";
@@ -133,7 +133,7 @@ export default function AuthenticatedRoute() {
<div className="flex-none" />
<div className="h-screen min-h-[0px] basis-0 flex-1">
<div className="flex h-full">
- <IconSidebar />
+ <PrimaryNavigation />
<div className="flex w-full h-full">
<div className="w-full h-full flex-1 overflow-hidden">
<main className="h-full flex flex-col flex-1 max-w-[100vw] sm:max-w-[calc(100vw-56px)] overflow-x-hidden bg-muted">
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 9c983ff029..df9a9cd15c 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -35,6 +35,9 @@ export const path = {
materialForms: `${api}/items/forms`,
materialSubstances: `${api}/items/substances`,
processes: `${api}/resources/processes`,
+ quotes: `${api}/sales/quotes`,
+ quoteLines: (quoteId: string) =>
+ generatePath(`${api}/sales/quotes/${quoteId}/lines`),
rollback: (table: string, id: string) =>
generatePath(
`${api}/settings/sequence/rollback?table=${table}&currentSequence=${id}`
diff --git a/apps/developers/app/components/Navigation/IconSidebar.tsx b/apps/developers/app/components/Navigation/PrimaryNavigation.tsx
similarity index 98%
rename from apps/developers/app/components/Navigation/IconSidebar.tsx
rename to apps/developers/app/components/Navigation/PrimaryNavigation.tsx
index 7c3686b9b9..49e3ad6b61 100644
--- a/apps/developers/app/components/Navigation/IconSidebar.tsx
+++ b/apps/developers/app/components/Navigation/PrimaryNavigation.tsx
@@ -20,7 +20,7 @@ type NavLink = {
const links: NavLink[] = [];
-const IconSidebar = () => {
+const PrimaryNavigation = () => {
const { company } = useUser();
const navigationPanel = useDisclosure();
@@ -156,7 +156,7 @@ const NavigationIconLink = forwardRef<
);
NavigationIconLink.displayName = "NavigationIconLink";
-export default IconSidebar;
+export default PrimaryNavigation;
function getModule(link: string) {
return link.split("/")?.[2];
diff --git a/apps/developers/app/components/Navigation/index.ts b/apps/developers/app/components/Navigation/index.ts
index 06570f64f1..c35d36a69f 100644
--- a/apps/developers/app/components/Navigation/index.ts
+++ b/apps/developers/app/components/Navigation/index.ts
@@ -1,3 +1,3 @@
-import IconSidebar from "./IconSidebar";
+import PrimaryNavigation from "./PrimaryNavigation";
-export { IconSidebar };
+export { PrimaryNavigation };
diff --git a/apps/developers/app/routes/x+/_layout.tsx b/apps/developers/app/routes/x+/_layout.tsx
index afc6be5fd1..f6d9905fad 100644
--- a/apps/developers/app/routes/x+/_layout.tsx
+++ b/apps/developers/app/routes/x+/_layout.tsx
@@ -6,7 +6,7 @@ import NProgress from "nprogress";
import { useEffect } from "react";
import { Topbar } from "~/components/Layout";
-import { IconSidebar } from "~/components/Navigation";
+import { PrimaryNavigation } from "~/components/Navigation";
import { VERCEL_URL } from "~/config/env";
import { SupabaseProvider, getSupabase } from "~/lib/supabase";
import { getCompanies, getUser } from "~/services/auth/auth.server";
@@ -82,7 +82,7 @@ export default function AuthenticatedRoute() {
<div className="flex-none" />
<div className="h-screen min-h-[0px] basis-0 flex-1">
<div className="flex h-full">
- <IconSidebar />
+ <PrimaryNavigation />
<div className="flex w-full h-full">
<div className="w-full h-full flex-1 overflow-hidden">
<main className="h-full flex flex-col flex-1 max-w-[100vw] sm:max-w-[calc(100vw-56px)] overflow-x-hidden bg-muted">
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 5586ac3a4b..d1e1a61b29 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -1488,7 +1488,7 @@ serve(async (req: Request) => {
const [
jobMakeMethod,
- quoteMakeMethods,
+ quoteMakeMethod,
quoteMaterials,
quoteOperations,
] = await Promise.all([
@@ -1501,7 +1501,9 @@ serve(async (req: Request) => {
client
.from("quoteMakeMethod")
.select("*")
- .eq("quoteLineId", quoteLineId),
+ .is("parentMaterialId", null)
+ .eq("quoteLineId", quoteLineId)
+ .single(),
client
.from("quoteMaterial")
.select("*")
@@ -1517,110 +1519,141 @@ serve(async (req: Request) => {
}
if (
- quoteMakeMethods.error ||
+ quoteMakeMethod.error ||
quoteMaterials.error ||
quoteOperations.error
) {
throw new Error("Failed to fetch quote data");
}
+ const [quoteMethodTrees] = await Promise.all([
+ getQuoteMethodTree(client, quoteMakeMethod.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");
+
await db.transaction().execute(async (trx) => {
- // delete the existing jobMakeMethods where jobId is jobId and parentMaterialId is not null
- await trx
- .deleteFrom("jobMakeMethod")
- .where((eb) =>
- eb.and([
- eb("jobId", "=", jobId),
- eb("parentMaterialId", "is not", null),
- ])
- )
- .execute();
-
- // Delete existing jobMaterials for this job
- await trx
- .deleteFrom("jobMaterial")
- .where("jobId", "=", jobId)
- .execute();
-
- // Delete existing jobOperations for this job
- await trx
- .deleteFrom("jobOperation")
- .where("jobId", "=", jobId)
- .execute();
-
- // Copy quoteMakeMethods to jobMakeMethods
- const jobMakeMethodInserts = quoteMakeMethods.data.map((qmm) => {
- const {
- quoteId: _quoteId,
- quoteLineId: _quoteLineId,
- ...data
- } = qmm;
- if (qmm.parentMaterialId === null) {
- return {
- ...data,
- id: jobMakeMethod.data.id,
- jobId,
- createdBy: userId,
- };
- }
- return {
- ...data,
- jobId,
- createdBy: userId,
- };
- });
+ // Delete existing jobMakeMethods, jobMaterials, and jobOperations for this job
+ await Promise.all([
+ trx
+ .deleteFrom("jobMakeMethod")
+ .where((eb) =>
+ eb.and([
+ eb("jobId", "=", jobId),
+ eb("parentMaterialId", "is not", null),
+ ])
+ )
+ .execute(),
+ trx.deleteFrom("jobMaterial").where("jobId", "=", jobId).execute(),
+ trx.deleteFrom("jobOperation").where("jobId", "=", jobId).execute(),
+ ]);
- const insertedJobMakeMethods = await trx
- .insertInto("jobMakeMethod")
- .values(jobMakeMethodInserts)
- .returning(["id", "parentMaterialId"])
- .execute();
-
- // Create a map of quoteMakeMethodId to jobMakeMethodId
- const makeMethodIdMap = new Map(
- quoteMakeMethods.data.map((qmm, index) => [
- qmm.id,
- insertedJobMakeMethods[index].id,
- ])
- );
+ await traverseQuoteMethod(
+ quoteMethodTree,
+ async (node: QuoteMethodTreeItem) => {
+ const jobMaterialInserts: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =
+ [];
+ const jobMakeMethodInserts: Database["public"]["Tables"]["jobMakeMethod"]["Insert"][] =
+ [];
+
+ console.log({ node });
+ for await (const child of node.children) {
+ console.log({
+ child,
+ });
+
+ jobMaterialInserts.push({
+ id: child.id,
+ jobId,
+ itemId: child.data.itemId,
+ itemReadableId: child.data.itemReadableId,
+ itemType: child.data.itemType,
+ methodType: child.data.methodType,
+ order: child.data.order,
+ description: child.data.description,
+ jobMakeMethodId:
+ child.data.quoteMakeMethodId === quoteMakeMethod.data.id
+ ? jobMakeMethod.data.id
+ : child.data.quoteMakeMethodId,
+ quantity: child.data.quantity,
+ unitOfMeasureCode: child.data.unitOfMeasureCode,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ });
+
+ if (child.data.quoteMaterialMakeMethodId) {
+ jobMakeMethodInserts.push({
+ id: child.data.quoteMaterialMakeMethodId,
+ jobId,
+ parentMaterialId: child.id,
+ itemId: child.data.itemId,
+ quantityPerParent: child.data.quantity,
+ companyId,
+ createdBy: userId,
+ });
+ }
+ }
- // Copy quoteMaterials to jobMaterials
- const jobMaterialInserts = quoteMaterials.data.map((qm) => {
- const {
- quoteId: _quoteId,
- quoteLineId: _quoteLineId,
- ...data
- } = qm;
- return {
- ...data,
- jobId,
- jobMakeMethodId: makeMethodIdMap.get(qm.quoteMakeMethodId)!,
- createdBy: userId,
- };
- });
+ if (jobMaterialInserts.length > 0) {
+ await trx
+ .insertInto("jobMaterial")
+ .values(jobMaterialInserts)
+ .execute();
+ console.log(
+ `finished inserting ${jobMaterialInserts.length} materials`
+ );
+ }
- if (jobMakeMethodInserts.length > 0) {
- await trx
- .insertInto("jobMaterial")
- .values(jobMaterialInserts)
- .execute();
- }
+ if (jobMakeMethodInserts.length > 0) {
+ // we use an update instead of an insert because
+ // the trigger is creating a record automatically
+ for await (const insert of jobMakeMethodInserts) {
+ await trx
+ .updateTable("jobMakeMethod")
+ .set({
+ id: insert.id,
+ quantityPerParent: insert.quantityPerParent,
+ })
+ .where("jobId", "=", jobId)
+ .where("parentMaterialId", "=", insert.parentMaterialId)
+ .execute();
+ }
+ }
+ }
+ );
- // Copy quoteOperations to jobOperations
- const jobOperationInserts = quoteOperations.data.map((qo) => {
- const {
- quoteId: _quoteId,
- quoteLineId: _quoteLineId,
- quoteMakeMethodId,
- ...data
- } = qo;
- return {
- ...data,
+ const jobOperationInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =
+ quoteOperations.data.map((op) => ({
jobId,
- jobMakeMethodId: makeMethodIdMap.get(quoteMakeMethodId!)!,
+ jobMakeMethodId:
+ op.quoteMakeMethodId === quoteMakeMethod.data.id
+ ? jobMakeMethod.data.id
+ : op.quoteMakeMethodId,
+ processId: op.processId,
+ 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,
+ workInstruction: op.workInstruction,
+ companyId,
createdBy: userId,
- };
- });
+ customFields: {},
+ }));
if (jobOperationInserts.length > 0) {
await trx
@@ -1629,6 +1662,7 @@ serve(async (req: Request) => {
.execute();
}
});
+
break;
}
case "quoteMakeMethodToItem": {
@@ -1995,14 +2029,14 @@ function getQuoteMethodTreeArrayToTree(
return rootItems;
}
-function traverseQuoteMethod(
+async function traverseQuoteMethod(
node: QuoteMethodTreeItem,
- callback: (node: QuoteMethodTreeItem) => void
+ callback: (node: QuoteMethodTreeItem) => void | Promise<void>
) {
- callback(node);
+ await callback(node);
if (node.children) {
- for (const child of node.children) {
+ for await (const child of node.children) {
traverseQuoteMethod(child, callback);
}
}
diff --git a/packages/database/supabase/migrations/20240915192542_job-methods.sql b/packages/database/supabase/migrations/20240915192542_job-methods.sql
index a96b7759ac..b05d19be5c 100644
--- a/packages/database/supabase/migrations/20240915192542_job-methods.sql
+++ b/packages/database/supabase/migrations/20240915192542_job-methods.sql
@@ -507,4 +507,17 @@ SELECT
FROM material
INNER JOIN item ON material."itemId" = item.id
ORDER BY "order"
-$$ LANGUAGE sql STABLE;
\ No newline at end of file
+$$ LANGUAGE sql STABLE;
+
+DROP VIEW "quoteOperationsWithMakeMethods";
+COMMIT;
+ALTER TABLE "quoteOperation" DROP COLUMN "quotingRate";
+CREATE OR REPLACE VIEW "quoteOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ qo.*
+ FROM "quoteOperation" qo
+ INNER JOIN "quoteMakeMethod" qmm
+ ON qo."quoteMakeMethodId" = qmm.id
+ LEFT JOIN "makeMethod" mm
+ ON qmm."itemId" = mm."itemId";