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
refactor: merge quote line method route and quote line details route
Brad Barbin9ab3b7a1928b
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 14323f4dbe..5a34da420f 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -1416,7 +1416,11 @@ export async function upsertSupplier(})) {if ("createdBy" in supplier) {- return client.from("supplier").insert([supplier]).select("*").single();+ return client+ .from("supplier")+ .insert([supplier])+ .select("id, name")+ .single();}return client.from("supplier")diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 6d3cb299d4..9b266e26f5 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -861,6 +861,18 @@ export async function getQuoteMakeMethod(.single();}+export async function getRootQuoteMakeMethod(+ client: SupabaseClient<Database>,+ quoteLineId: string+) {+ return client+ .from("quoteMakeMethod")+ .select("*, ...item(itemType:type)")+ .eq("quoteLineId", quoteLineId)+ .is("parentMaterialId", null)+ .single();+}+export async function getQuoteMethodTrees(client: SupabaseClient<Database>,quoteId: string@@ -1574,7 +1586,11 @@ export async function upsertCustomer(})) {if ("createdBy" in customer) {- return client.from("customer").insert([customer]).select("id").single();+ return client+ .from("customer")+ .insert([customer])+ .select("id, name")+ .single();}return client.from("customer")diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsxindex 9fb3602610..f14f9172d4 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx@@ -108,25 +108,46 @@ const QuoteBoMExplorer = ({const params = useParams();const [searchParams, setSearchParams] = useSearchParams();const selectedMaterialId = searchParams.get("materialId");++ const explorerLineId = methods[0]?.data.quoteLineId;+ const isDetailsRouteForThisLine =+ params.quoteId &&+ params.lineId &&+ params.lineId === explorerLineId &&+ location.pathname === path.to.quoteLine(params.quoteId, params.lineId);+// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (!selectedMaterialId) {+ if (isDetailsRouteForThisLine) {+ const rootNode = methods.find((m) => m.data.isRoot);+ if (rootNode) {+ selectNode(rootNode.id);+ return;+ }+ }deselectAllNodes();return;}- if (selectedMaterialId) {- const node = methods.find(- (m) => m.data.methodMaterialId === selectedMaterialId- );- if (node?.id) selectNode(node?.id);+ const node = methods.find(+ (m) => m.data.methodMaterialId === selectedMaterialId+ );+ if (node?.id) {+ selectNode(node.id);} else if (params.methodId) {- const node = methods.find(+ const methodNode = methods.find((m) => m.data.quoteMaterialMakeMethodId === params.methodId);- if (node?.id) selectNode(node?.id);+ if (methodNode?.id) {+ selectNode(methodNode.id);+ } else {+ deselectAllNodes();+ }+ } else {+ deselectAllNodes();}- }, [selectedMaterialId, params.methodId]);+ }, [selectedMaterialId, params.methodId, location.pathname]);return (<VStack className="flex flex-1 w-full">@@ -393,11 +414,7 @@ function NodePreview({ node }: { node: FlatTreeItem<QuoteMethod> }) {function getNodePath(node: FlatTreeItem<QuoteMethod>) {return node.data.isRoot- ? path.to.quoteLineMethod(- node.data.quoteId,- node.data.quoteLineId,- node.data.quoteMaterialMakeMethodId- )+ ? path.to.quoteLine(node.data.quoteId, node.data.quoteLineId): node.data.methodType === "Make"? path.to.quoteLineMakeMethod(node.data.quoteId,diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsxindex c905a2225b..976462262a 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx@@ -125,20 +125,15 @@ export default function QuoteExplorer({ methods }: QuoteExplorerProps) {const optimisticDrags = useOptimisticDocumentDrag();- const linesByItemId = new Map<string, QuotationLine | OptimisticQuoteLine>(- quoteData?.lines?.map((line) => [line.itemId!, line]) ?? []+ const linesMap = new Map<string, QuotationLine | OptimisticQuoteLine>(+ quoteData?.lines?.map((line) => [line.id!, line]) ?? []);- // Merge pending items with existing itemsfor (let pendingItem of optimisticDrags) {- let existingItem = linesByItemId.get(pendingItem.itemId!);- let merged = existingItem- ? { ...existingItem, ...pendingItem }- : { ...pendingItem, quoteId };- linesByItemId.set(pendingItem.itemId!, merged);+ linesMap.set(pendingItem.itemId!, { ...pendingItem, quoteId });}- const linesToRender = Array.from(linesByItemId.values()).sort((a, b) =>+ const linesToRender = Array.from(linesMap.values()).sort((a, b) =>(a.itemReadableId ?? "").localeCompare(b.itemReadableId ?? ""));diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsxindex a33cefc1fc..e619b80189 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx@@ -113,7 +113,10 @@ const QuoteMakeMethodTools = () => {const getMethodModal = useDisclosure();const saveMethodModal = useDisclosure();+ const isQuoteLineDetails =+ lineId && pathname === path.to.quoteLine(quoteId, lineId);const isQuoteLineMethod =+ isQuoteLineDetails ||pathname === path.to.quoteLineMethod(quoteId, lineId!, methodId!);const isQuoteMakeMethod =methodId &&diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex e7762fdb4b..0fe39a3dff 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { JSONContent } from "@carbon/react";-import { Spinner } from "@carbon/react";+import { Spinner, VStack } from "@carbon/react";import { Fragment, Suspense, useMemo } from "react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import {@@ -23,11 +23,16 @@ import type {QuoteMethod} from "~/modules/sales";import {+ getConfigurationParametersByQuoteLineId,+ getModelByQuoteLineId,getOpportunityLineDocuments,getQuoteLine,getQuoteLinePrices,+ getQuoteMaterialsByMethodId,getQuoteOperationsByLine,+ getQuoteOperationsByMethodId,getRelatedPricesForQuoteLine,+ getRootQuoteMakeMethod,quoteLineValidator,upsertQuoteLine} from "~/modules/sales";@@ -36,18 +41,22 @@ import {OpportunityLineNotes} from "~/modules/sales/ui/Opportunity";import {+ QuoteBillOfMaterial,+ QuoteBillOfProcess,QuoteLineCosting,QuoteLineForm,QuoteLinePricing,+ QuoteMakeMethodTools,useLineCosts} from "~/modules/sales/ui/Quotes";import QuoteLinePricingHistory from "~/modules/sales/ui/Quotes/QuoteLinePricingHistory";import QuoteLineRiskRegister from "~/modules/sales/ui/Quotes/QuoteLineRiskRegister";+import { getTagsList } from "~/modules/shared";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";export const loader = async ({ request, params }: LoaderFunctionArgs) => {- const { companyId } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {view: "sales"});@@ -72,6 +81,50 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {const itemId = line.data.itemId!;+ const rootMethod = await getRootQuoteMakeMethod(serviceRole, lineId);++ const methodData = rootMethod.data+ ? await (async () => {+ const methodId = rootMethod.data.id;+ const [materials, methodOperations, tags] = await Promise.all([+ getQuoteMaterialsByMethodId(serviceRole, methodId),+ getQuoteOperationsByMethodId(serviceRole, methodId),+ getTagsList(client, companyId, "operation")+ ]);++ return {+ methodMaterials:+ materials?.data?.map((m) => ({+ ...m,+ itemType: m.itemType as "Part",+ unitOfMeasureCode: m.unitOfMeasureCode ?? "",+ quoteOperationId: m.quoteOperationId ?? undefined+ })) ?? [],+ methodOperations:+ methodOperations.data?.map((o) => ({+ ...o,+ description: o.description ?? "",+ workCenterId: o.workCenterId ?? undefined,+ laborRate: o.laborRate ?? 0,+ machineRate: o.machineRate ?? 0,+ operationSupplierProcessId:+ o.operationSupplierProcessId ?? undefined,+ quoteMakeMethodId: o.quoteMakeMethodId ?? methodId,+ workInstruction: o.workInstruction as JSONContent,+ tags: o.tags ?? []+ })) ?? [],+ configurationParameters: getConfigurationParametersByQuoteLineId(+ serviceRole,+ lineId,+ companyId+ ),+ model: getModelByQuoteLineId(serviceRole, lineId),+ tags: tags.data ?? [],+ rootMethodId: methodId+ };+ })()+ : null;+return {line: line.data,operations: operations?.data ?? [],@@ -82,7 +135,8 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {acc[price.quantity] = price;return acc;}, {}),- relatedPrices: getRelatedPricesForQuoteLine(serviceRole, itemId, quoteId)+ relatedPrices: getRelatedPricesForQuoteLine(serviceRole, itemId, quoteId),+ methodData};};@@ -128,8 +182,14 @@ export async function action({ request, params }: ActionFunctionArgs) {}export default function QuoteLine() {- const { line, operations, files, pricesByQuantity, relatedPrices } =- useLoaderData<typeof loader>();+ const {+ line,+ operations,+ files,+ pricesByQuantity,+ relatedPrices,+ methodData+ } = useLoaderData<typeof loader>();const permissions = usePermissions();const { quoteId, lineId } = useParams();if (!quoteId) throw new Error("Could not find quoteId");@@ -179,7 +239,36 @@ export default function QuoteLine() {return (<Fragment key={lineId}>+ <QuoteMakeMethodTools /><QuoteLineForm key={lineId} initialValues={initialValues} />+ <OpportunityLineNotes+ id={line.id}+ table="quoteLine"+ title="Notes"+ subTitle={line.itemReadableId ?? ""}+ internalNotes={line.internalNotes as JSONContent}+ externalNotes={line.externalNotes as JSONContent}+ />++ {methodData && (+ <VStack spacing={2}>+ <QuoteBillOfMaterial+ key={`bom:${methodData.rootMethodId}`}+ quoteMakeMethodId={methodData.rootMethodId}+ // @ts-ignore+ materials={methodData.methodMaterials}+ // @ts-expect-error+ operations={methodData.methodOperations}+ />+ <QuoteBillOfProcess+ key={`bop:${methodData.rootMethodId}`}+ quoteMakeMethodId={methodData.rootMethodId}+ // @ts-expect-error+ operations={methodData.methodOperations}+ tags={methodData.tags ?? []}+ />+ </VStack>+ )}{line.methodType === "Make" &&line.status !== "No Quote" &&@@ -227,14 +316,6 @@ export default function QuoteLine() {/></>)}- <OpportunityLineNotes- id={line.id}- table="quoteLine"- title="Notes"- subTitle={line.itemReadableId ?? ""}- internalNotes={line.internalNotes as JSONContent}- externalNotes={line.externalNotes as JSONContent}- /><Suspensefallback={@@ -257,17 +338,38 @@ export default function QuoteLine() {</Await></Suspense>- <CadModel- isReadOnly={!permissions.can("update", "sales")}- metadata={{- quoteLineId: line.id ?? undefined,- itemId: line.itemId ?? undefined- }}- modelPath={line?.modelPath ?? null}- title="CAD Model"- uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"- viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"- />+ {methodData ? (+ <Suspense fallback={null}>+ <Await resolve={methodData.model}>+ {(model) => (+ <CadModel+ key={`cad:${model?.itemId}`}+ isReadOnly={!permissions.can("update", "sales")}+ metadata={{+ quoteLineId: lineId ?? undefined,+ itemId: model?.itemId ?? undefined+ }}+ modelPath={model?.modelPath ?? null}+ title="CAD Model"+ uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"+ viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"+ />+ )}+ </Await>+ </Suspense>+ ) : (+ <CadModel+ isReadOnly={!permissions.can("update", "sales")}+ metadata={{+ quoteLineId: line.id ?? undefined,+ itemId: line.itemId ?? undefined+ }}+ modelPath={line?.modelPath ?? null}+ title="CAD Model"+ uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"+ viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"+ />+ )}<QuoteLineRiskRegister quoteLineId={lineId} itemId={line.itemId ?? ""} />diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsxindex 5f6981f35a..a4ef51fbc3 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx@@ -1,141 +1,11 @@-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import type { JSONContent } from "@carbon/react";-import { VStack } from "@carbon/react";-import { Suspense } from "react";import type { LoaderFunctionArgs } from "react-router";-import { Await, redirect, useLoaderData, useParams } from "react-router";-import { CadModel } from "~/components";-import { usePermissions } from "~/hooks";-import {- getConfigurationParametersByQuoteLineId,- getModelByQuoteLineId,- getQuoteMaterialsByMethodId,- getQuoteOperationsByMethodId-} from "~/modules/sales";-import {- QuoteBillOfMaterial,- QuoteBillOfProcess,- QuoteMakeMethodTools-} from "~/modules/sales/ui/Quotes";-import { getTagsList } from "~/modules/shared";+import { redirect } from "react-router";import { path } from "~/utils/path";-export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales"- });-- const { quoteId, lineId, methodId } = params;+export async function loader({ params }: LoaderFunctionArgs) {+ const { quoteId, lineId } = params;if (!quoteId) throw new Error("Could not find quoteId");if (!lineId) throw new Error("Could not find lineId");- if (!methodId) throw new Error("Could not find methodId");-- const [materials, operations, tags] = await Promise.all([- getQuoteMaterialsByMethodId(client, methodId),- getQuoteOperationsByMethodId(client, methodId),- getTagsList(client, companyId, "operation")- ]);-- if (materials.error) {- throw redirect(- path.to.quoteLine(quoteId, lineId),- await flash(- request,- error(materials.error, "Failed to load quote materials")- )- );- }-- if (operations.error) {- throw redirect(- path.to.quoteLine(quoteId, lineId),- await flash(- request,- error(operations.error, "Failed to load quote operations")- )- );- }-- return {- materials:- materials?.data.map((m) => ({- ...m,- itemType: m.itemType as "Part",- unitOfMeasureCode: m.unitOfMeasureCode ?? "",- quoteOperationId: m.quoteOperationId ?? undefined- })) ?? [],- operations:- operations.data?.map((o) => ({- ...o,- description: o.description ?? "",- workCenterId: o.workCenterId ?? undefined,- laborRate: o.laborRate ?? 0,- machineRate: o.machineRate ?? 0,- operationSupplierProcessId: o.operationSupplierProcessId ?? undefined,- quoteMakeMethodId: o.quoteMakeMethodId ?? methodId,- workInstruction: o.workInstruction as JSONContent,- tags: o.tags ?? []- })) ?? [],- configurationParameters: getConfigurationParametersByQuoteLineId(- client,- lineId,- companyId- ),- model: getModelByQuoteLineId(client, lineId),- tags: tags.data ?? []- };-}--export default function QuoteMakeMethodRoute() {- const { quoteId, lineId, methodId } = useParams();-- if (!quoteId) throw new Error("Could not find quoteId");- if (!lineId) throw new Error("Could not find lineId");- if (!methodId) throw new Error("Could not find methodId");-- const permissions = usePermissions();- const loaderData = useLoaderData<typeof loader>();- const { materials, operations, tags } = loaderData;-- return (- <VStack spacing={2}>- <QuoteMakeMethodTools />-- <QuoteBillOfMaterial- key={`bom:${methodId}`}- quoteMakeMethodId={methodId}- materials={materials}- // @ts-expect-error- operations={operations}- />- <QuoteBillOfProcess- key={`bop:${methodId}`}- quoteMakeMethodId={methodId}- // @ts-expect-error- operations={operations}- tags={tags ?? []}- />- <Suspense fallback={null}>- <Await resolve={loaderData.model}>- {(model) => (- <CadModel- key={`cad:${model?.itemId}`}- isReadOnly={!permissions.can("update", "sales")}- metadata={{- quoteLineId: lineId ?? undefined,- itemId: model?.itemId ?? undefined- }}- modelPath={model?.modelPath ?? null}- title="CAD Model"- uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"- viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"- />- )}- </Await>- </Suspense>- </VStack>- );+ throw redirect(path.to.quoteLine(quoteId, lineId));}diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsxindex 2cd4590af5..09c4fe8be8 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx@@ -48,7 +48,10 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ console.log(createQuotationLine);+if (createQuotationLine.error) {+ console.log(createQuotationLine);throw redirect(path.to.quote(quoteId),await flash(