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: refactor quote pricing to use a pricing table and a single price for a line
Brad Barbin625822b54d3e
diff --git a/apps/carbon/app/components/Editable/EditableQuotationLineQuantity.tsx b/apps/carbon/app/components/Editable/EditableQuotationLineQuantity.tsxdeleted file mode 100644index 67a61b1530..0000000000--- a/apps/carbon/app/components/Editable/EditableQuotationLineQuantity.tsx+++ /dev/null@@ -1,92 +0,0 @@-/* eslint-disable react/display-name */-import type { Database } from "@carbon/database";-import { Input, NumberField } from "@carbon/react";-import type {- PostgrestSingleResponse,- SupabaseClient,-} from "@supabase/supabase-js";-import type { FocusEvent, KeyboardEvent } from "react";--import type { EditableTableCellComponentProps } from "~/components/Editable";-import type { QuotationLineQuantity } from "~/modules/sales";-import { getLinePriceUpdate } from "~/modules/sales";-import { type LinePriceEffects } from "~/modules/sales/ui/Quotation/useQuotation";--const EditableQuotationLineQuantity =- (- mutation: (- accessorKey: string,- newValue: string,- row: QuotationLineQuantity- ) => Promise<PostgrestSingleResponse<unknown>>,- options: {- client?: SupabaseClient<Database>;- effects: LinePriceEffects;- isMade: boolean;- }- ) =>- ({- value,- row,- accessorKey,- onError,- onUpdate,- }: EditableTableCellComponentProps<QuotationLineQuantity>) => {- const updateNumber = async (newValue: string) => {- const quantity = Number(newValue);- const { client, effects, isMade } = options;-- const update = isMade- ? getLinePriceUpdate(quantity, effects)- : {- materialCost:- row.quantity === 0- ? row.materialCost * quantity- : (row.materialCost / row.quantity) * quantity,- };-- // this is the optimistic update on the FE- onUpdate({ quantity, ...update });-- const mutation = await client- ?.from("quoteLineQuantity")- .update({ quantity, ...update })- .eq("id", row.id!);-- if (!mutation || mutation.error) {- onError();- onUpdate({ ...row });- }- };-- const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {- // only run the update if they click enter- if (event.key === "Enter" || event.key === "Tab") {- if (event.currentTarget.value !== value) {- updateNumber(event.currentTarget.value);- }- }- };-- // run update if focus is lost- const onBlur = (event: FocusEvent<HTMLInputElement>) => {- if (event.currentTarget.value !== value) {- updateNumber(event.currentTarget.value);- }- };-- return (- <NumberField defaultValue={value as number}>- <Input- size="sm"- className="w-full rounded-none ring-offset-0"- autoFocus- onKeyDown={onKeyDown}- onBlur={onBlur}- />- </NumberField>- );- };--EditableQuotationLineQuantity.displayName = "EditableQuotationLineQuantity";-export default EditableQuotationLineQuantity;diff --git a/apps/carbon/app/components/Editable/index.ts b/apps/carbon/app/components/Editable/index.tsindex d819db2aff..cf9535b570 100644--- a/apps/carbon/app/components/Editable/index.ts+++ b/apps/carbon/app/components/Editable/index.ts@@ -2,7 +2,6 @@ import EditableList from "./EditableList";import EditableNumber from "./EditableNumber";import EditablePurchaseInvoiceLineNumber from "./EditablePurchaseInvoiceLineNumber";import EditablePurchaseOrderLineNumber from "./EditablePurchaseOrderLineNumber";-import EditableQuotationLineQuantity from "./EditableQuotationLineQuantity";import EditableQuotationMaterial from "./EditableQuotationMaterial";import EditableText from "./EditableText";@@ -12,7 +11,6 @@ export {EditableNumber,EditablePurchaseInvoiceLineNumber,EditablePurchaseOrderLineNumber,- EditableQuotationLineQuantity,EditableQuotationMaterial,EditableText,};diff --git a/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsxindex 965a9d639f..a82f8ec988 100644--- a/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx+++ b/apps/carbon/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx@@ -8,7 +8,7 @@ import {ModalOverlay,ModalTitle,} from "@carbon/react";-import { Form } from "@remix-run/react";+import { useFetcher } from "@remix-run/react";type ConfirmDeleteProps = {action?: string;@@ -27,6 +27,8 @@ const ConfirmDelete = ({onCancel,onSubmit,}: ConfirmDeleteProps) => {+ const fetcher = useFetcher();+ const isLoading = fetcher.state !== "idle";return (<Modalopen={isOpen}@@ -46,11 +48,11 @@ const ConfirmDelete = ({<Button variant="secondary" className="mr-3" onClick={onCancel}>Cancel</Button>- <Form method="post" action={action} onSubmit={onSubmit}>- <Button variant="destructive" type="submit">+ <fetcher.Form method="post" action={action} onSubmit={onSubmit}>+ <Button variant="destructive" type="submit" isLoading={isLoading}>Delete</Button>- </Form>+ </fetcher.Form></ModalFooter></ModalContent></Modal>diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.tsindex 344a1b9e34..5eddb9390e 100644--- a/apps/carbon/app/modules/sales/sales.models.ts+++ b/apps/carbon/app/modules/sales/sales.models.ts@@ -121,6 +121,15 @@ export const quotationOperationValidator = z.object({overheadRate: zfd.numeric(z.number().min(0)),});+export const quotationPricingValidator = z.object({+ quantity: zfd.numeric(z.number()),+ unitCost: zfd.numeric(z.number()),+ leadTime: zfd.numeric(z.number().int().nonnegative()),+ discountPercent: zfd.numeric(z.number().nonnegative()),+ markupPercent: zfd.numeric(z.number().nonnegative()),+ extendedPrice: zfd.numeric(z.number()),+});+export const quotationLineValidator = z.object({id: zfd.text(z.string().optional()),quoteId: z.string(),diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.tsindex 7e0fb6ecc9..321dd92a31 100644--- a/apps/carbon/app/modules/sales/sales.service.ts+++ b/apps/carbon/app/modules/sales/sales.service.ts@@ -16,6 +16,7 @@ import type {quotationLineValidator,quotationMaterialValidator,quotationOperationValidator,+ quotationPricingValidator,quotationValidator,} from "./sales.models";@@ -78,13 +79,6 @@ export async function deleteQuoteLine(return client.from("quoteLine").delete().eq("id", quoteLineId);}-export async function deleteQuoteLineQuantity(- client: SupabaseClient<Database>,- id: string-) {- return client.from("quoteLineQuantity").delete().eq("id", id);-}-export async function deleteQuoteMaterial(client: SupabaseClient<Database>,quoteMaterialId: string@@ -369,23 +363,23 @@ export async function getQuoteCustomerDetails(.single();}-export async function getQuoteLineQuantities(+export async function getQuoteLinePrice(client: SupabaseClient<Database>,quoteLineId: string) {return client- .from("quoteLineQuantity")+ .from("quoteLinePrice").select("*").eq("quoteLineId", quoteLineId)- .order("createdAt");+ .single();}-export async function getQuoteLineQuantitiesByQuoteId(+export async function getQuoteLinePricesByQuoteId(client: SupabaseClient<Database>,quoteId: string) {return client- .from("quoteLineQuantity")+ .from("quoteLinePrice").select("*").eq("quoteId", quoteId).order("createdAt");@@ -523,22 +517,24 @@ export async function insertCustomerLocation(.single();}-export async function insertQuoteLineQuantity(+export async function insertQuoteLinePrice(client: SupabaseClient<Database>,- quoteLineQuantity: {+ quoteLinePrice: {quoteId: string;quoteLineId: string;quantity?: number;- materialCost?: number;+ markupPercent?: number;+ unitCost?: number;createdBy: string;}) {- const quoteLine = await getQuoteLine(client, quoteLineQuantity.quoteLineId);+ const quoteLine = await getQuoteLine(client, quoteLinePrice.quoteLineId);if (quoteLine.error) {return quoteLine;}- let materialCost = 0;+ let unitCost = 0;+if (quoteLine.data?.replenishmentSystem === "Buy") {const partId = quoteLine.data?.partId;const [partCost] = await Promise.all([@@ -549,13 +545,17 @@ export async function insertQuoteLineQuantity(return partCost;}- materialCost = partCost.data?.unitCost;+ unitCost = partCost.data?.unitCost;}- return client.from("quoteLineQuantity").insert([+ const totalCost = unitCost * (quoteLinePrice.quantity ?? 0);++ return client.from("quoteLinePrice").insert([{- ...quoteLineQuantity,- materialCost,+ ...quoteLinePrice,+ unitCost,+ extendedPrice:+ totalCost + totalCost * ((quoteLinePrice?.markupPercent ?? 0) / 100),},]);}@@ -834,6 +834,20 @@ export async function upsertQuoteLine(return client.from("quoteLine").insert([quotationLine]).select("*").single();}+export async function updateQuoteLinePrice(+ client: SupabaseClient<Database>,+ quoteLinePrice: z.infer<typeof quotationPricingValidator> & {+ quoteId: string;+ quoteLineId: string;+ updatedBy: string;+ }+) {+ return client+ .from("quoteLinePrice")+ .update(sanitize(quoteLinePrice))+ .eq("quoteLineId", quoteLinePrice.quoteLineId);+}+export async function upsertQuoteMaterial(client: SupabaseClient<Database>,quotationMaterial:diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.tsindex 93f671ba5b..5aefe6f20e 100644--- a/apps/carbon/app/modules/sales/types.ts+++ b/apps/carbon/app/modules/sales/types.ts@@ -8,7 +8,6 @@ import type {getCustomerTypes,getQuoteAssembly,getQuoteExternalDocuments,- getQuoteLineQuantities,getQuoteLines,getQuoteMaterials,getQuoteOperation,@@ -55,10 +54,6 @@ export type QuotationLine = NonNullable<Awaited<ReturnType<typeof getQuoteLines>>["data"]>[number];-export type QuotationLineQuantity = NonNullable<- Awaited<ReturnType<typeof getQuoteLineQuantities>>["data"]->[number];-export type QuotationMaterial = NonNullable<Awaited<ReturnType<typeof getQuoteMaterials>>["data"]>[number];diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationExplorer.tsxindex d652963826..e07f8381dc 100644--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationExplorer.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationExplorer.tsx@@ -76,7 +76,7 @@ const QuotationExplorerItem = (<Buttonvariant={isActive ? "primary" : "ghost"}className={cn(- "w-full justify-between",+ "font-mono w-full justify-between",!isActive && "text-muted-foreground")}asChild@@ -148,7 +148,7 @@ const QuotationExplorerItem = (return (<Buttonvariant="ghost"- className="w-full justify-between text-muted-foreground"+ className="font-mono w-full justify-between text-muted-foreground"asChild><Link@@ -168,7 +168,7 @@ const QuotationExplorerItem = (<Buttonvariant={isActive ? "primary" : "ghost"}className={cn(- "w-full justify-between",+ "font-mono w-full justify-between",!isActive && "text-muted-foreground")}asChild@@ -437,8 +437,6 @@ const QuotationExplorer = () => {{});- console.log({ collapsedNodes });-const openNode = (id: string) => {const collapsed = { [id]: false };let currentId = id;@@ -468,10 +466,10 @@ const QuotationExplorer = () => {return (<div className="w-full" role="group" key={`${node.id}:${node.type}`}><HStack- className="items-stretch w-full"+ className="items-stretch w-full border-l border-border"spacing={0}style={{- paddingLeft: `calc(${0.5 * level}rem)`,+ paddingLeft: `calc(${0.75 * level}rem)`,}}><IconButtondiff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsxindex f348bb49de..e08c84e0ea 100644--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx@@ -151,6 +151,7 @@ const QuotationLineForm = ({ initialValues }: QuotationLineFormProps) => {</CardAction></HStack><CardContent>+ <Hidden name="intent" value="line" /><Hidden name="id" /><Hidden name="quoteId" /><Hidden name="unitOfMeasureCode" value={partData?.uom} />diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineQuantities.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineQuantities.tsxdeleted file mode 100644index f277590bd6..0000000000--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineQuantities.tsx+++ /dev/null@@ -1,277 +0,0 @@-import {- Card,- CardContent,- CardHeader,- CardTitle,- DropdownMenu,- DropdownMenuContent,- DropdownMenuIcon,- DropdownMenuItem,- DropdownMenuTrigger,- HStack,- IconButton,-} from "@carbon/react";-import { Form, Outlet, useNavigate, useParams } from "@remix-run/react";-import type { ColumnDef } from "@tanstack/react-table";-import { useCallback, useMemo, useRef } from "react";-import { IoMdTrash } from "react-icons/io";-import { MdMoreHoriz } from "react-icons/md";-import {- EditableNumber,- EditableQuotationLineQuantity,-} from "~/components/Editable";-import Grid from "~/components/Grid";-import { usePermissions, useRealtime, useUser } from "~/hooks";-import { useSupabase } from "~/lib/supabase";-import {- useQuotation,- useQuotationLinePriceEffects,- type QuotationLine,- type QuotationLineQuantity,-} from "~/modules/sales";-import { path } from "~/utils/path";--type QuotationLineQuantitiesProps = {- quotationLine: QuotationLine;- quotationLineQuantities: QuotationLineQuantity[];-};--const QuotationLineQuantities = ({- quotationLine,- quotationLineQuantities,-}: QuotationLineQuantitiesProps) => {- const { id, lineId } = useParams();- if (!id) throw new Error("id not found");- if (!lineId) throw new Error("lineId not found");-- useRealtime("quoteLineQuantity", `quoteLineId=eq.${lineId}`);-- const navigate = useNavigate();-- const [quotation] = useQuotation();- const linePriceEffects = useQuotationLinePriceEffects();-- // TODO: use the currency of the quote- const formatter = new Intl.NumberFormat("en-US", {- style: "currency",- currency: "USD",- });-- const { id: userId } = useUser();- const { supabase } = useSupabase();- const permissions = usePermissions();-- const canEdit = permissions.can("update", "sales");- const canDelete = permissions.can("delete", "sales");-- const onCellEdit = useCallback(- async (id: string, value: unknown, row: QuotationLineQuantity) => {- if (!supabase) throw new Error("Supabase client not found");- return await supabase- .from("quoteLineQuantity")- .update({- [id]: value,- updatedBy: userId,- })- .eq("id", row.id!);- },- [supabase, userId]- );-- const isEditable = ["Draft"].includes(quotation?.quote?.status ?? "");- const isMade = quotationLine.replenishmentSystem === "Make";-- const columns = useMemo<ColumnDef<QuotationLineQuantity>[]>(() => {- const _columns: ColumnDef<QuotationLineQuantity>[] = [- {- header: "Line",- cell: ({ row }) => (- <HStack className="justify-between">- <span>{row.index + 1}</span>- <div className="relative w-6 h-5">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label="Edit quotation line"- icon={<MdMoreHoriz />}- size="md"- className="absolute right-[-1px] top-[-6px]"- variant="ghost"- onClick={(e) => e.stopPropagation()}- />- </DropdownMenuTrigger>- <DropdownMenuContent>- <DropdownMenuItem- onClick={() => navigate(`${row.original.id}/delete`)}- disabled={!isEditable || !canDelete}- >- <DropdownMenuIcon icon={<IoMdTrash />} />- Delete Line- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- </HStack>- ),- },-- {- accessorKey: "quantity",- header: "Quantity",- cell: (item) => item.getValue(),- },- {- accessorKey: "unitCostBase",- header: "Unit Cost",- cell: ({ row }) => formatter.format(getUnitCost(row.original)),- },- {- accessorKey: "unitTaxAmount",- header: "Unit Tax",- cell: (item) => formatter.format(item.getValue<number>()),- },- {- header: "Extended Cost",- cell: ({ row }) =>- formatter.format(- row.original.quantity *- (getUnitCost(row.original) + row.original.unitTaxAmount)- ),- },- {- accessorKey: "markupPercentage",- header: "Markup %",- cell: (item) => item.getValue() + "%",- },- {- accessorKey: "discountPercentage",- header: "Discount %",- cell: (item) => item.getValue() + "%",- },- {- header: "Extended Price",- cell: ({ row }) =>- formatter.format(- row.original.quantity *- (getUnitCost(row.original) + row.original.unitTaxAmount) *- (1 - row.original.discountPercentage / 100) *- (1 + row.original.markupPercentage / 100)- ),- },- {- accessorKey: "leadTime",- header: "Lead Time",- cell: (item) => item.getValue(),- },- ];-- if (isMade) {- _columns.push(- {- accessorKey: "setupHours",- header: "Setup Hours",- cell: (item) => item.getValue(),- },- {- accessorKey: "productionHours",- header: "Production Hours",- cell: (item) => item.getValue(),- }- );- }-- _columns.push({- accessorKey: "materialCost",- header: "Material Cost",- cell: (item) => formatter.format(item.getValue<number>()),- });-- if (isMade) {- _columns.push(- {- header: "Labor + Overhead Cost",- cell: ({ row }) =>- formatter.format(- row.original.laborCost + row.original.overheadCost- ),- },- {- accessorKey: "additionalCost",- header: "Additional Cost",- cell: (item) => formatter.format(item.getValue<number>()),- }- );- }-- return _columns;- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [navigate, quotationLine.replenishmentSystem, isEditable, canDelete]);-- const editableComponents = useMemo(() => {- const editableCells = {- quantity: EditableQuotationLineQuantity(onCellEdit, {- client: supabase,- effects: linePriceEffects.effects[lineId],- isMade,- }),- additionalCost: EditableNumber(onCellEdit, { minValue: 0 }),- discountPercentage: EditableNumber(onCellEdit, { minValue: 0 }),- markupPercentage: EditableNumber(onCellEdit, { minValue: 0 }),- unitTaxAmount: EditableNumber(onCellEdit, { minValue: 0 }),- leadTime: EditableNumber(onCellEdit, { minValue: 0 }),- };- if (!isMade) {- // @ts-expect-error- editableCells.materialCost = EditableNumber(onCellEdit, { minValue: 0 });- }- return editableCells;- }, [isMade, lineId, linePriceEffects.effects, onCellEdit, supabase]);-- const newRowButtonRef = useRef<HTMLButtonElement>(null);-- return (- <>- <Card- className="w-full"- style={{ height: 196 + quotationLineQuantities.length * 44 }}- >- <HStack className="justify-between items-start">- <CardHeader>- <CardTitle>Line Prices</CardTitle>- </CardHeader>- </HStack>-- <CardContent>- <Grid<QuotationLineQuantity>- data={quotationLineQuantities}- canEdit={canEdit && isEditable}- columns={columns}- // @ts-ignore- editableComponents={editableComponents}- onNewRow={- canEdit && isEditable- ? () => newRowButtonRef.current?.click()- : undefined- }- />- <Form method="post" action={path.to.newQuoteLineQuantity(id, lineId)}>- <button type="submit" ref={newRowButtonRef} className="sr-only" />- </Form>- </CardContent>- </Card>- <Outlet />- </>- );-};--export default QuotationLineQuantities;--function getUnitCost(line: QuotationLineQuantity) {- return line.quantity- ? (line.materialCost +- line.laborCost +- line.overheadCost +- line.additionalCost) /- line.quantity- : 0;-}diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationPricing.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationPricing.tsxnew file mode 100644index 0000000000..ea2d24f105--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationPricing.tsx@@ -0,0 +1,365 @@+import {+ Button,+ Card,+ CardContent,+ CardFooter,+ CardHeader,+ CardTitle,+ Enumerable,+ HStack,+ Table,+ Tbody,+ Td,+ Tfoot,+ Th,+ Thead,+ Tr,+ VStack,+} from "@carbon/react";+import { ValidatedForm } from "@carbon/remix-validated-form";+import { useParams } from "@remix-run/react";+import { useMemo, useState } from "react";+import type { z } from "zod";+import { Hidden, Number, NumberControlled, Submit } from "~/components/Form";+import {+ getLinePriceUpdate,+ quotationPricingValidator,+ useQuotationLinePriceEffects,+} from "~/modules/sales";+import { path } from "~/utils/path";++type QuotationPricingProps = {+ initialValues: z.infer<typeof quotationPricingValidator>;+ isMade: boolean;+};++export default function QuotationPricing({+ initialValues,+ isMade,+}: QuotationPricingProps) {+ const linePriceEffects = useQuotationLinePriceEffects();++ const { id, lineId } = useParams();+ if (!id) throw new Error("id not found");+ if (!lineId) throw new Error("lineId not found");++ const [quantities] = useState([1, 25, 50, 100]);+ const [state, setState] = useState({+ quantity: initialValues.quantity ?? 1,+ unitCost: initialValues.unitCost ?? 0,+ discountPercent: initialValues.discountPercent ?? 0,+ markupPercent: initialValues.markupPercent ?? 0,+ extendedPrice: initialValues.extendedPrice ?? 0,+ });++ const quantityPriceEffects = useMemo(+ () =>+ quantities.map((quantity) => {+ const effects = linePriceEffects.effects[lineId];+ return {+ quantity,+ effects: getLinePriceUpdate(quantity, effects),+ };+ }),+ [lineId, linePriceEffects.effects, quantities]+ );++ const onAdd = ({+ quantity,+ effects,+ }: (typeof quantityPriceEffects)[number]) => {+ const totalCost =+ effects.materialCost ++ effects.laborCost ++ effects.overheadCost ++ effects.outsideCost;+ const unitCost = totalCost / quantity;++ setState((prevState) => ({+ ...prevState,+ quantity,+ unitCost,+ extendedPrice:+ totalCost ++ totalCost * (prevState.markupPercent / 100) -+ totalCost * (prevState.discountPercent / 100),+ }));+ };++ // TODO: factor in default currency, po currency and exchange rate+ const formatter = useMemo(+ () =>+ new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }),+ []+ );++ return (+ <>+ {isMade && (+ <Card>+ <HStack className="justify-between items-start">+ <CardHeader>+ <CardTitle>Costing</CardTitle>+ </CardHeader>+ {/* <CardAction>+ <IconButton+ variant="secondary"+ icon={<BsThreeDotsVertical />}+ aria-label="Options"+ />+ </CardAction> */}+ </HStack>+ <CardContent>+ <Table>+ <Thead>+ <Tr>+ <Th />+ {quantities.map((quantity) => (+ <Th key={quantity.toString()} className="font-mono">+ {quantity}+ </Th>+ ))}+ </Tr>+ </Thead>+ <Tbody>+ <Tr>+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Total Raw Material</span>+ <Enumerable value="Material" />+ </HStack>+ </Td>+ {quantityPriceEffects.map(({ quantity, effects }) => {+ return (+ <Td key={quantity.toString()} className="font-mono">+ <VStack spacing={0}>+ <span>+ {effects.materialCost+ ? formatter.format(effects.materialCost)+ : formatter.format(0)}+ </span>+ <span className="text-muted-foreground text-xs">+ {effects.materialCost && quantity > 0+ ? formatter.format(+ effects.materialCost / quantity+ )+ : formatter.format(0)}+ </span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr>+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Total Labor & Overhead</span>+ <Enumerable value="Labor" />+ </HStack>+ </Td>+ {quantityPriceEffects.map(({ quantity, effects }) => {+ return (+ <Td key={quantity.toString()} className="font-mono">+ <VStack spacing={0}>+ <span>+ {effects.overheadCost+ ? formatter.format(+ effects.overheadCost + effects.laborCost+ )+ : formatter.format(0)}+ </span>+ <span className="text-muted-foreground text-xs">+ {effects.overheadCost && quantity > 0+ ? formatter.format(+ (effects.overheadCost + effects.laborCost) /+ quantity+ )+ : formatter.format(0)}+ </span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr>+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Total Outside Processing</span>+ <Enumerable value="Subcontract" />+ </HStack>+ </Td>+ {quantityPriceEffects.map(({ quantity, effects }) => {+ return (+ <Td key={quantity.toString()} className="font-mono">+ <VStack spacing={0}>+ <span>+ {effects.outsideCost+ ? formatter.format(effects.outsideCost)+ : formatter.format(0)}+ </span>+ <span className="text-muted-foreground text-xs">+ {effects.outsideCost && quantity > 0+ ? formatter.format(effects.outsideCost / quantity)+ : formatter.format(0)}+ </span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr className="font-bold">+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Total Cost</span>+ </HStack>+ </Td>+ {quantityPriceEffects.map(({ quantity, effects }) => {+ const totalCost =+ effects.materialCost ++ effects.laborCost ++ effects.overheadCost ++ effects.outsideCost;+ return (+ <Td key={quantity.toString()} className="font-mono">+ <VStack spacing={0}>+ <span>+ {totalCost+ ? formatter.format(totalCost)+ : formatter.format(0)}+ </span>+ <span className="text-muted-foreground text-xs">+ {totalCost && quantity > 0+ ? formatter.format(totalCost / quantity)+ : formatter.format(0)}+ </span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ </Tbody>+ <Tfoot>+ <Tr className="font-bold">+ <Td className="border-r border-border" />+ {quantityPriceEffects.map((quantityEffect) => (+ <Td key={quantityEffect.quantity} className="font-mono">+ <Button+ variant="secondary"+ onClick={() => onAdd(quantityEffect)}+ >+ Add+ </Button>+ </Td>+ ))}+ </Tr>+ </Tfoot>+ </Table>+ </CardContent>+ </Card>+ )}++ <ValidatedForm+ validator={quotationPricingValidator}+ defaultValues={initialValues}+ method="post"+ action={path.to.quoteLine(id, lineId)}+ className="w-full"+ >+ <Card>+ <CardHeader>+ <CardTitle>Pricing</CardTitle>+ </CardHeader>+ <CardContent>+ <Hidden name="intent" value="pricing" />+ <div className="grid w-full gap-x-8 gap-y-2 grid-cols-1 lg:grid-cols-3">+ <NumberControlled+ name="quantity"+ label="Quantity"+ value={state.quantity}+ onChange={(quantity) =>+ setState((prevState) => ({+ ...prevState,+ quantity,+ extendedPrice:+ prevState.unitCost *+ quantity *+ (1 + prevState.markupPercent / 100) -+ prevState.unitCost *+ quantity *+ (prevState.discountPercent / 100),+ }))+ }+ />+ <NumberControlled+ name="unitCost"+ label="Unit Cost"+ value={state.unitCost}+ onChange={(unitCost) =>+ setState((prevState) => ({+ ...prevState,+ unitCost,+ extendedPrice:+ unitCost *+ prevState.quantity *+ (1 + prevState.markupPercent / 100) -+ unitCost *+ prevState.quantity *+ (prevState.discountPercent / 100),+ }))+ }+ formatOptions={{ style: "currency", currency: "USD" }}+ />+ <Number name="leadTime" label="Lead Time (Days)" />+ <NumberControlled+ name="discountPercent"+ label="Discount %"+ value={state.discountPercent}+ onChange={(discountPercent) =>+ setState((prevState) => ({+ ...prevState,+ discountPercent,+ extendedPrice:+ prevState.unitCost *+ prevState.quantity *+ (1 + prevState.markupPercent / 100) -+ prevState.unitCost *+ prevState.quantity *+ (discountPercent / 100),+ }))+ }+ />+ <NumberControlled+ name="markupPercent"+ label="Markup %"+ value={state.markupPercent}+ onChange={(markupPercent) =>+ setState((prevState) => ({+ ...prevState,+ markupPercent,+ extendedPrice:+ prevState.unitCost *+ prevState.quantity *+ (1 + markupPercent / 100) -+ prevState.unitCost *+ prevState.quantity *+ (prevState.discountPercent / 100),+ }))+ }+ />+ <NumberControlled+ name="extendedPrice"+ label="Extended Price"+ value={state.extendedPrice}+ isReadOnly+ formatOptions={{ style: "currency", currency: "USD" }}+ />+ </div>+ </CardContent>+ <CardFooter>+ <Submit>Save</Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ </>+ );+}diff --git a/apps/carbon/app/modules/sales/ui/Quotation/index.ts b/apps/carbon/app/modules/sales/ui/Quotation/index.tsindex f21505e0ac..8241ba39ba 100644--- a/apps/carbon/app/modules/sales/ui/Quotation/index.ts+++ b/apps/carbon/app/modules/sales/ui/Quotation/index.ts@@ -3,17 +3,15 @@ import QuotationDocuments from "./QuotationDocuments";import QuotationExplorer from "./QuotationExplorer";import QuotationForm from "./QuotationForm";import QuotationLineForm from "./QuotationLineForm";-import QuotationLineQuantities from "./QuotationLineQuantities";import QuotationMaterialForm from "./QuotationMaterialForm";import QuotationMaterialLines from "./QuotationMaterialLines";import QuotationOperationForm from "./QuotationOperationForm";-+import QuotationPricing from "./QuotationPricing";import QuotationStatus from "./QuotationStatus";import {getLinePriceUpdate,useQuotation,useQuotationLinePriceEffects,- useQuotationLinePriceEffectsUpdate,} from "./useQuotation";export {QuotationAssemblyForm,@@ -21,13 +19,12 @@ export {QuotationExplorer,QuotationForm,QuotationLineForm,- QuotationLineQuantities,QuotationMaterialForm,QuotationMaterialLines,QuotationOperationForm,+ QuotationPricing,QuotationStatus,getLinePriceUpdate,useQuotation,useQuotationLinePriceEffects,- useQuotationLinePriceEffectsUpdate,};diff --git a/apps/carbon/app/modules/sales/ui/Quotation/useQuotation.tsx b/apps/carbon/app/modules/sales/ui/Quotation/useQuotation.tsxindex bf9c86b918..d01ea4aeee 100644--- a/apps/carbon/app/modules/sales/ui/Quotation/useQuotation.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotation/useQuotation.tsx@@ -1,9 +1,6 @@-import type { Database } from "@carbon/database";import { useStore as useValue } from "@nanostores/react";-import type { SupabaseClient } from "@supabase/supabase-js";-import { atom, computed, task } from "nanostores";+import { atom, computed } from "nanostores";import { useNanoStore } from "~/hooks";-import logger from "~/lib/logger";import type {Quotation,QuotationAssembly,@@ -13,7 +10,6 @@ import type {} from "~/modules/sales";type QuoteStore = {- client?: SupabaseClient<Database>;quote?: Quotation;lines: QuotationLine[];assemblies: QuotationAssembly[];@@ -32,7 +28,6 @@ export type LinePriceEffects = {};const $quotationStore = atom<QuoteStore>({- client: undefined,quote: undefined,lines: [],assemblies: [],@@ -40,8 +35,6 @@ const $quotationStore = atom<QuoteStore>({materials: [],});-const defaultLinePriceEffectsResult = {} as Record<string, LinePriceEffects>;-const $quotationLinePriceEffects = computed($quotationStore, (store) => {const assembliesByLineId = store.assemblies?.reduce<Record<string, QuotationAssembly[]>@@ -226,53 +219,11 @@ const $quotationLinePriceEffects = computed($quotationStore, (store) => {}, {});return {- client: store.client,quoteId: store.quote?.id ?? "",effects: linePriceEffects,};});-const $quotationLinePriceEffectsUpdate = computed(- $quotationLinePriceEffects,- (store) =>- task(async () => {- if (!store.quoteId || !store.client) return defaultLinePriceEffectsResult;-- const quoteLineQuantities = await store.client- .from("quoteLineQuantity")- .select("*")- .eq("quoteId", store.quoteId);-- if (quoteLineQuantities.error) {- logger.error(quoteLineQuantities.error);- return defaultLinePriceEffectsResult;- }-- if (!quoteLineQuantities.data || !quoteLineQuantities.data.length) {- return defaultLinePriceEffectsResult;- }-- for await (const lineQuantity of quoteLineQuantities.data) {- const quantity = lineQuantity.quantity ?? 0;- const effects = store.effects[lineQuantity.quoteLineId];-- // skip updates for parts that aren't make- if (!effects) continue;-- const update = getLinePriceUpdate(quantity, effects);-- const { error } = await store.client- .from("quoteLineQuantity")- .update(update)- .eq("id", lineQuantity.id);-- if (error) {- logger.error(error);- }- }- })-);-export function getLinePriceUpdate(quantity: number,effects: LinePriceEffects@@ -306,6 +257,7 @@ export function getLinePriceUpdate(materialCost,laborCost,overheadCost,+ outsideCost: 0,setupHours,productionHours,};@@ -314,5 +266,3 @@ export function getLinePriceUpdate(export const useQuotation = () => useNanoStore<QuoteStore>($quotationStore);export const useQuotationLinePriceEffects = () =>useValue($quotationLinePriceEffects);-export const useQuotationLinePriceEffectsUpdate = () =>- useValue($quotationLinePriceEffectsUpdate);diff --git a/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx b/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsxindex 7c99bc4c78..30c32afb3f 100644--- a/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx+++ b/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx@@ -4,9 +4,8 @@ import { type LoaderFunctionArgs } from "@remix-run/node";import logger from "~/lib/logger";import {getQuote,- getQuoteLineQuantitiesByQuoteId,- getQuoteLines,getQuoteCustomerDetails,+ getQuoteLines,} from "~/modules/sales";import { getCompany } from "~/modules/settings";import { requirePermissions } from "~/services/auth";@@ -19,17 +18,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { id } = params;if (!id) throw new Error("Could not find id");- const [- company,- quote,- quoteLines,- quoteLineQuantitiesByQuoteId,- quoteLocations,- ] = await Promise.all([+ const [company, quote, quoteLines, quoteLocations] = await Promise.all([getCompany(client),getQuote(client, id),getQuoteLines(client, id),- getQuoteLineQuantitiesByQuoteId(client, id),getQuoteCustomerDetails(client, id),]);@@ -45,20 +37,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {logger.error(quoteLines.error);}- if (quoteLineQuantitiesByQuoteId.error) {- logger.error(quoteLineQuantitiesByQuoteId.error);- }-if (quoteLocations.error) {logger.error(quoteLocations.error);}- if (- company.error ||- quote.error ||- quoteLocations.error ||- quoteLines.error- ) {+ if (company.error || quote.error || quoteLocations.error) {throw new Error("Failed to load quote");}@@ -66,8 +49,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {<QuotePDFcompany={company.data}quote={quote.data}- quoteLines={quoteLines.data}- quoteLineQuantities={quoteLineQuantitiesByQuoteId.data}+ quoteLines={quoteLines.data ?? []}quoteCustomerDetails={quoteLocations.data}/>);diff --git a/apps/carbon/app/routes/x+/_index.tsx b/apps/carbon/app/routes/x+/_index.tsxindex f350d54116..94b452d2dd 100644--- a/apps/carbon/app/routes/x+/_index.tsx+++ b/apps/carbon/app/routes/x+/_index.tsx@@ -11,7 +11,7 @@ export default function AppIndexRoute() {const user = useUser();const modules = useModules();return (- <div className="p-8 w-full">+ <div className="p-8 w-full h-full bg-muted"><Heading size="h3">Hello, {user.firstName}</Heading><Subheading>{formatDate(today(getLocalTimeZone()).toString(), {diff --git a/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.details.$quantityId.delete.tsx b/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.details.$quantityId.delete.tsxdeleted file mode 100644index 6170c0171b..0000000000--- a/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.details.$quantityId.delete.tsx+++ /dev/null@@ -1,65 +0,0 @@-import { json, redirect, useNavigate, useParams } from "@remix-run/react";--import type { ActionFunctionArgs } from "@remix-run/node";-import { ConfirmDelete } from "~/components/Modals";-import { useRouteData } from "~/hooks";-import type { QuotationLineQuantity } from "~/modules/sales";-import { deleteQuoteLineQuantity } from "~/modules/sales";-import { requirePermissions } from "~/services/auth";-import { flash } from "~/services/session.server";-import { assertIsPost } from "~/utils/http";-import { path } from "~/utils/path";-import { error } from "~/utils/result";--export async function action({ request, params }: ActionFunctionArgs) {- assertIsPost(request);- const { client } = await requirePermissions(request, {- update: "sales",- });-- const { id: quoteId, lineId: quoteLineId, quantityId } = params;- if (!quoteId) throw new Error("Could not find quoteId");- if (!quoteLineId) throw new Error("Could not find quoteLineId");- if (!quantityId) throw new Error("Could not find quantityId");-- const deleteLineQuantity = await deleteQuoteLineQuantity(client, quantityId);-- if (deleteLineQuantity.error) {- return json(- path.to.quoteLine(quoteId, quoteLineId),- await flash(- request,- error(deleteLineQuantity.error, "Failed to update quote assembly")- )- );- }-- return redirect(path.to.quoteLine(quoteId, quoteLineId));-}--export default function DeleteQuoteLineQuantity() {- const navigate = useNavigate();-- const { id, lineId, quantityId } = useParams();- if (!id) throw new Error("id not found");- if (!lineId) throw new Error("lineId not found");- if (!quantityId) throw new Error("quantityId not found");-- const routeData = useRouteData<{- quotationLineQuantities: QuotationLineQuantity[];- }>(path.to.quoteLine(id, lineId));-- const quoteLineQuantity = routeData?.quotationLineQuantities.find(- (quantity) => quantity.id === quantityId- );- if (!routeData?.quotationLineQuantities || !quoteLineQuantity)- throw new Error("quote line quantity not found");-- return (- <ConfirmDelete- name="Line"- text={`Are you sure you want to delete this line? This cannot be undone.`}- onCancel={() => navigate(path.to.quoteLine(id, lineId))}- />- );-}diff --git a/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.details.tsx b/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.details.tsxindex 682e58c026..5789e8a29e 100644--- a/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.details.tsx+++ b/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.details.tsx@@ -1,38 +1,15 @@-import {- Button,- Card,- CardAction,- CardContent,- CardFooter,- CardHeader,- CardTitle,- Enumerable,- HStack,- IconButton,- Table,- Tbody,- Td,- Tfoot,- Th,- Thead,- Tr,- VStack,-} from "@carbon/react";-import {- ValidatedForm,- validationError,- validator,-} from "@carbon/remix-validated-form";+import { validationError, validator } from "@carbon/remix-validated-form";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";import { json, redirect } from "@remix-run/node";-import { useLoaderData } from "@remix-run/react";-import { BsThreeDotsVertical } from "react-icons/bs";-import { z } from "zod";-import { Number, Submit } from "~/components/Form";+import { Outlet, useLoaderData } from "@remix-run/react";import {QuotationLineForm,+ QuotationPricing,getQuoteLine,+ getQuoteLinePrice,quotationLineValidator,+ quotationPricingValidator,+ updateQuoteLinePrice,upsertQuoteLine,} from "~/modules/sales";import { requirePermissions } from "~/services/auth";@@ -51,10 +28,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { lineId } = params;if (!lineId) throw notFound("lineId not found");- const [quotationLine] = await Promise.all([getQuoteLine(client, lineId)]);+ const [quotationLine, quotationLinePricing] = await Promise.all([+ getQuoteLine(client, lineId),+ getQuoteLinePrice(client, lineId),+ ]);return json({quotationLine: quotationLine?.data ?? null,+ quotationLinePricing: quotationLinePricing?.data,});}@@ -69,39 +50,71 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!lineId) throw new Error("Could not find lineId");const formData = await request.formData();- const validation = await validator(quotationLineValidator).validate(formData);-- if (validation.error) {- return validationError(validation.error);- }-- const { id, ...data } = validation.data;+ const intent = formData.get("intent");- const updateQuotationLine = await upsertQuoteLine(client, {- id: lineId,- ...data,- updatedBy: userId,- customFields: setCustomFields(formData),- });+ if (intent === "line") {+ const validation = await validator(quotationLineValidator).validate(+ formData+ );- if (updateQuotationLine.error) {- return redirect(- path.to.quoteLine(quoteId, lineId),- await flash(- request,- error(updateQuotationLine.error, "Failed to update quote line")- )+ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const updateQuotationLine = await upsertQuoteLine(client, {+ id: lineId,+ ...data,+ updatedBy: userId,+ customFields: setCustomFields(formData),+ });++ if (updateQuotationLine.error) {+ return redirect(+ path.to.quoteLine(quoteId, lineId),+ await flash(+ request,+ error(updateQuotationLine.error, "Failed to update quote line")+ )+ );+ }+ } else if (intent === "pricing") {+ const validation = await validator(quotationPricingValidator).validate(+ formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const updateLinePrice = await updateQuoteLinePrice(client, {+ quoteId,+ quoteLineId: lineId,+ ...validation.data,+ updatedBy: userId,+ });++ if (updateLinePrice.error) {+ return redirect(+ path.to.quoteLine(quoteId, lineId),+ await flash(+ request,+ error(updateLinePrice.error, "Failed to update quote line price")+ )+ );+ }}return redirect(path.to.quoteLine(quoteId, lineId));}export default function EditQuotationLineRoute() {- const { quotationLine } = useLoaderData<typeof loader>();+ const { quotationLine, quotationLinePricing } =+ useLoaderData<typeof loader>();if (!quotationLine) throw new Error("Could not find quotation line");- const initialValues = {+ const lineInitialValues = {id: quotationLine?.id ?? undefined,quoteId: quotationLine?.quoteId ?? "",partId: quotationLine?.partId ?? "",@@ -116,231 +129,27 @@ export default function EditQuotationLineRoute() {...getCustomFields(quotationLine?.customFields),};+ const pricingInitialValues = {+ quantity: quotationLinePricing?.quantity ?? 1,+ unitCost: quotationLinePricing?.unitCost ?? 0,+ leadTime: quotationLinePricing?.leadTime ?? 0,+ discountPercent: quotationLinePricing?.discountPercent ?? 0,+ markupPercent: quotationLinePricing?.markupPercent ?? 0,+ extendedPrice: quotationLinePricing?.extendedPrice ?? 0,+ };+return (<>- <QuotationLineForm key={initialValues.id} initialValues={initialValues} />- <QuotationCostingTable />- <QuotationLinePrice />+ <QuotationLineForm+ key={`${lineInitialValues.id}-line`}+ initialValues={lineInitialValues}+ />+ <QuotationPricing+ key={`${lineInitialValues.id}-pricing`}+ initialValues={pricingInitialValues}+ isMade={quotationLine?.replenishmentSystem === "Make"}+ />+ <Outlet /></>);}--export function QuotationCostingTable() {- return (- <Card>- <HStack className="justify-between items-start">- <CardHeader>- <CardTitle>Costing</CardTitle>- </CardHeader>- <CardAction>- <IconButton- variant="secondary"- icon={<BsThreeDotsVertical />}- aria-label="Options"- />- </CardAction>- </HStack>- <CardContent>- <Table>- <Thead>- <Tr>- <Th className="font-mono"></Th>- <Th className="font-mono">1</Th>- <Th className="font-mono">25</Th>- <Th className="font-mono">50</Th>- <Th className="font-mono">100</Th>- </Tr>- </Thead>- <Tbody>- <Tr>- <Td className="border-r border-border">- <HStack className="w-full justify-between ">- <span>Total Raw Material</span>- <Enumerable value="Material" />- </HStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$3.00</span>- <span className="text-muted-foreground text-xs">$3.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$75.00</span>- <span className="text-muted-foreground text-xs">$3.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$150.00</span>- <span className="text-muted-foreground text-xs">$3.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$300.00</span>- <span className="text-muted-foreground text-xs">$3.00</span>- </VStack>- </Td>- </Tr>- <Tr>- <Td className="border-r border-border">- <HStack className="w-full justify-between ">- <span>Total Labor & Overhead</span>- <Enumerable value="Labor" />- </HStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$3.00</span>- <span className="text-muted-foreground text-xs">$3.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$75.00</span>- <span className="text-muted-foreground text-xs">$3.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$150.00</span>- <span className="text-muted-foreground text-xs">$3.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$300.00</span>- <span className="text-muted-foreground text-xs">$3.00</span>- </VStack>- </Td>- </Tr>- <Tr>- <Td className="border-r border-border">- <HStack className="w-full justify-between ">- <span>Total Outside Processing</span>- <Enumerable value="Subcontract" />- </HStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$0.00</span>- <span className="text-muted-foreground text-xs">$0.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$0.00</span>- <span className="text-muted-foreground text-xs">$0.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$0.00</span>- <span className="text-muted-foreground text-xs">$0.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$0.00</span>- <span className="text-muted-foreground text-xs">$0.00</span>- </VStack>- </Td>- </Tr>- <Tr className="font-bold">- <Td className="border-r border-border">- <HStack className="w-full justify-between ">- <span>Total Cost</span>- </HStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$6.00</span>- <span className="text-muted-foreground text-xs">$6.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$150.00</span>- <span className="text-muted-foreground text-xs">$6.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$300.00</span>- <span className="text-muted-foreground text-xs">$6.00</span>- </VStack>- </Td>- <Td className="font-mono">- <VStack spacing={0}>- <span>$600.00</span>- <span className="text-muted-foreground text-xs">$6.00</span>- </VStack>- </Td>- </Tr>- </Tbody>- <Tfoot>- <Tr className="font-bold">- <Td className="border-r border-border"></Td>- <Td className="font-mono text-center">- <Button size="sm" variant="secondary">- Add- </Button>- </Td>- <Td className="font-mono text-center">- <Button size="sm" variant="secondary">- Add- </Button>- </Td>- <Td className="font-mono text-center">- <Button size="sm" variant="secondary">- Add- </Button>- </Td>- <Td className="font-mono text-center">- <Button size="sm" variant="secondary">- Add- </Button>- </Td>- </Tr>- </Tfoot>- </Table>- </CardContent>- </Card>- );-}--export function QuotationLinePrice() {- return (- <ValidatedForm validator={z.object({})} className="w-full">- <Card>- <CardHeader>- <CardTitle>Pricing</CardTitle>- </CardHeader>- <CardContent>- <div className="grid w-full gap-x-8 gap-y-2 grid-cols-1 lg:grid-cols-3">- <Number name="quantity" label="Quantity" />- <Number- name="unitCost"- label="Unit Cost"- formatOptions={{ style: "currency", currency: "USD" }}- />- <Number name="leadTime" label="Lead Time (Days)" />- <Number name="discountPercent" label="Discount %" />- <Number name="markupPercent" label="Markup %" />- <Number- name="extendedPrice"- label="Extended Price"- isReadOnly- formatOptions={{ style: "currency", currency: "USD" }}- />- </div>- </CardContent>- <CardFooter>- <Submit>Save</Submit>- </CardFooter>- </Card>- </ValidatedForm>- );-}diff --git a/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.new.tsx b/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.new.tsxdeleted file mode 100644index 3cefea7d7c..0000000000--- a/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.new.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { redirect, type ActionFunctionArgs } from "@remix-run/node";-import { insertQuoteLineQuantity } from "~/modules/sales";-import { requirePermissions } from "~/services/auth";-import { flash } from "~/services/session.server";-import { assertIsPost } from "~/utils/http";-import { path } from "~/utils/path";-import { error } from "~/utils/result";--export async function action({ request, params }: ActionFunctionArgs) {- assertIsPost(request);- const { client, userId } = await requirePermissions(request, {- create: "sales",- });-- const { id: quoteId, lineId: quoteLineId } = params;- if (!quoteId) throw new Error("Could not find quoteId");- if (!quoteLineId) throw new Error("Could not find quoteLineId");-- const createQuoteQuantity = await insertQuoteLineQuantity(client, {- quoteId,- quoteLineId: quoteLineId,- createdBy: userId,- });-- if (createQuoteQuantity.error) {- return redirect(- path.to.quoteLine(quoteId, quoteLineId),- await flash(- request,- error(- createQuoteQuantity.error,- "Failed to create quote line quantity."- )- )- );- }-- return redirect(path.to.quoteLine(quoteId, quoteLineId));-}diff --git a/apps/carbon/app/routes/x+/quote+/$id.new.tsx b/apps/carbon/app/routes/x+/quote+/$id.new.tsxindex a00d8698a2..0128b3969a 100644--- a/apps/carbon/app/routes/x+/quote+/$id.new.tsx+++ b/apps/carbon/app/routes/x+/quote+/$id.new.tsx@@ -4,7 +4,7 @@ import { redirect } from "@remix-run/node";import { useParams } from "@remix-run/react";import {QuotationLineForm,- insertQuoteLineQuantity,+ insertQuoteLinePrice,quotationLineValidator,upsertQuoteLine,} from "~/modules/sales";@@ -51,26 +51,14 @@ export async function action({ request, params }: ActionFunctionArgs) {const quoteLineId = createQuotationLine.data.id;- const createQuoteQuantity = await insertQuoteLineQuantity(client, {+ await insertQuoteLinePrice(client, {quoteId,quoteLineId,quantity: 1,+ markupPercent: 15,createdBy: userId,});- if (createQuoteQuantity.error) {- return redirect(- path.to.quoteLine(quoteId, quoteLineId),- await flash(- request,- error(- createQuoteQuantity.error,- "Failed to create quote line quantity."- )- )- );- }-return redirect(path.to.quoteLine(quoteId, quoteLineId));}diff --git a/apps/carbon/app/routes/x+/quote+/$id.tsx b/apps/carbon/app/routes/x+/quote+/$id.tsxindex 95f86cce82..cb7246f32a 100644--- a/apps/carbon/app/routes/x+/quote+/$id.tsx+++ b/apps/carbon/app/routes/x+/quote+/$id.tsx@@ -30,7 +30,6 @@ import {getQuoteMaterials,getQuoteOperations,useQuotation,- useQuotationLinePriceEffectsUpdate,} from "~/modules/sales";import QuotationReleaseModal from "~/modules/sales/ui/Quotation/QuotationReleaseModal";@@ -112,11 +111,9 @@ export default function QuotationRoute() {const releaseDisclosure = useDisclosure();const [quote, setQuote] = useQuotation();- useQuotationLinePriceEffectsUpdate();useEffect(() => {setQuote({- client: supabase,quote: quotation,lines: quotationLines,assemblies: quotationAssemblies,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 75478d7bec..affad4d0f6 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -8939,135 +8939,132 @@ export type Database = {},]}- quoteLineQuantity: {+ quoteLinePrice: {Row: {- additionalCost: numbercreatedAt: stringcreatedBy: string- discountPercentage: number- extendedCost: number+ discountPercent: number+ extendedPrice: numberid: string- laborCost: numberleadTime: number- markupPercentage: number- materialCost: number- overheadCost: number- productionHours: number+ markupPercent: numberquantity: numberquoteId: stringquoteLineId: string- scrapPercentage: number- setupHours: number- unitCostBase: number- unitTaxAmount: number+ unitCost: numberupdatedAt: string | nullupdatedBy: string | null}Insert: {- additionalCost?: numbercreatedAt?: stringcreatedBy: string- discountPercentage?: number- extendedCost?: number+ discountPercent?: number+ extendedPrice?: numberid?: string- laborCost?: numberleadTime?: number- markupPercentage?: number- materialCost?: number- overheadCost?: number- productionHours?: number+ markupPercent?: numberquantity?: numberquoteId: stringquoteLineId: string- scrapPercentage?: number- setupHours?: number- unitCostBase?: number- unitTaxAmount?: number+ unitCost?: numberupdatedAt?: string | nullupdatedBy?: string | null}Update: {- additionalCost?: numbercreatedAt?: stringcreatedBy?: string- discountPercentage?: number- extendedCost?: number+ discountPercent?: number+ extendedPrice?: numberid?: string- laborCost?: numberleadTime?: number- markupPercentage?: number- materialCost?: number- overheadCost?: number- productionHours?: number+ markupPercent?: numberquantity?: numberquoteId?: stringquoteLineId?: string- scrapPercentage?: number- setupHours?: number- unitCostBase?: number- unitTaxAmount?: number+ unitCost?: numberupdatedAt?: string | nullupdatedBy?: string | null}Relationships: [{- foreignKeyName: "quoteLineQuantity_createdBy_fkey"+ foreignKeyName: "quoteLinePrice_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_createdBy_fkey"+ foreignKeyName: "quoteLinePrice_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_createdBy_fkey"+ foreignKeyName: "quoteLinePrice_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_createdBy_fkey"+ foreignKeyName: "quoteLinePrice_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},{- foreignKeyName: "quoteLineQuantity_quoteLineId_fkey"+ foreignKeyName: "quoteLinePrice_quoteId_fkey"+ columns: ["quoteId"]+ isOneToOne: false+ referencedRelation: "quote"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteLinePrice_quoteId_fkey"+ columns: ["quoteId"]+ isOneToOne: false+ referencedRelation: "quoteCustomerDetails"+ referencedColumns: ["quoteId"]+ },+ {+ foreignKeyName: "quoteLinePrice_quoteId_fkey"+ columns: ["quoteId"]+ isOneToOne: false+ referencedRelation: "quotes"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteLinePrice_quoteLineId_fkey"columns: ["quoteLineId"]isOneToOne: falsereferencedRelation: "quoteLine"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_updatedBy_fkey"+ foreignKeyName: "quoteLinePrice_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_updatedBy_fkey"+ foreignKeyName: "quoteLinePrice_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_updatedBy_fkey"+ foreignKeyName: "quoteLinePrice_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_updatedBy_fkey"+ foreignKeyName: "quoteLinePrice_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "userDefaults"diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 75478d7bec..affad4d0f6 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -8939,135 +8939,132 @@ export type Database = {},]}- quoteLineQuantity: {+ quoteLinePrice: {Row: {- additionalCost: numbercreatedAt: stringcreatedBy: string- discountPercentage: number- extendedCost: number+ discountPercent: number+ extendedPrice: numberid: string- laborCost: numberleadTime: number- markupPercentage: number- materialCost: number- overheadCost: number- productionHours: number+ markupPercent: numberquantity: numberquoteId: stringquoteLineId: string- scrapPercentage: number- setupHours: number- unitCostBase: number- unitTaxAmount: number+ unitCost: numberupdatedAt: string | nullupdatedBy: string | null}Insert: {- additionalCost?: numbercreatedAt?: stringcreatedBy: string- discountPercentage?: number- extendedCost?: number+ discountPercent?: number+ extendedPrice?: numberid?: string- laborCost?: numberleadTime?: number- markupPercentage?: number- materialCost?: number- overheadCost?: number- productionHours?: number+ markupPercent?: numberquantity?: numberquoteId: stringquoteLineId: string- scrapPercentage?: number- setupHours?: number- unitCostBase?: number- unitTaxAmount?: number+ unitCost?: numberupdatedAt?: string | nullupdatedBy?: string | null}Update: {- additionalCost?: numbercreatedAt?: stringcreatedBy?: string- discountPercentage?: number- extendedCost?: number+ discountPercent?: number+ extendedPrice?: numberid?: string- laborCost?: numberleadTime?: number- markupPercentage?: number- materialCost?: number- overheadCost?: number- productionHours?: number+ markupPercent?: numberquantity?: numberquoteId?: stringquoteLineId?: string- scrapPercentage?: number- setupHours?: number- unitCostBase?: number- unitTaxAmount?: number+ unitCost?: numberupdatedAt?: string | nullupdatedBy?: string | null}Relationships: [{- foreignKeyName: "quoteLineQuantity_createdBy_fkey"+ foreignKeyName: "quoteLinePrice_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_createdBy_fkey"+ foreignKeyName: "quoteLinePrice_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_createdBy_fkey"+ foreignKeyName: "quoteLinePrice_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_createdBy_fkey"+ foreignKeyName: "quoteLinePrice_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},{- foreignKeyName: "quoteLineQuantity_quoteLineId_fkey"+ foreignKeyName: "quoteLinePrice_quoteId_fkey"+ columns: ["quoteId"]+ isOneToOne: false+ referencedRelation: "quote"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteLinePrice_quoteId_fkey"+ columns: ["quoteId"]+ isOneToOne: false+ referencedRelation: "quoteCustomerDetails"+ referencedColumns: ["quoteId"]+ },+ {+ foreignKeyName: "quoteLinePrice_quoteId_fkey"+ columns: ["quoteId"]+ isOneToOne: false+ referencedRelation: "quotes"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteLinePrice_quoteLineId_fkey"columns: ["quoteLineId"]isOneToOne: falsereferencedRelation: "quoteLine"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_updatedBy_fkey"+ foreignKeyName: "quoteLinePrice_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_updatedBy_fkey"+ foreignKeyName: "quoteLinePrice_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_updatedBy_fkey"+ foreignKeyName: "quoteLinePrice_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "quoteLineQuantity_updatedBy_fkey"+ foreignKeyName: "quoteLinePrice_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "userDefaults"diff --git a/packages/database/supabase/migrations/20240329034816_quote-pricing.sql b/packages/database/supabase/migrations/20240329034816_quote-pricing.sqlnew file mode 100644index 0000000000..2cafcd6886--- /dev/null+++ b/packages/database/supabase/migrations/20240329034816_quote-pricing.sql@@ -0,0 +1,24 @@+ALTER publication supabase_realtime DROP TABLE "quoteLineQuantity";+DROP TABLE "quoteLineQuantity";++CREATE TABLE "quoteLinePrice" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "quoteId" TEXT NOT NULL,+ "quoteLineId" TEXT NOT NULL,+ "quantity" NUMERIC(10,5) NOT NULL DEFAULT 1,+ "unitCost" NUMERIC(10,5) NOT NULL DEFAULT 0,+ "leadTime" NUMERIC(10,5) NOT NULL DEFAULT 0,+ "discountPercent" NUMERIC(10,5) NOT NULL DEFAULT 0,+ "markupPercent" NUMERIC(10,5) NOT NULL DEFAULT 0,+ "extendedPrice" NUMERIC(10,5) NOT NULL DEFAULT 0,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "quoteLinePrice_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "quoteLinePrice_quoteId_fkey" FOREIGN KEY ("quoteId") REFERENCES "quote" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteLinePrice_quoteLineId_fkey" FOREIGN KEY ("quoteLineId") REFERENCES "quoteLine" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteLinePrice_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "quoteLinePrice_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);\ No newline at end of filediff --git a/packages/documents/src/pdf/QuotePDF.tsx b/packages/documents/src/pdf/QuotePDF.tsxindex 9019029a38..3c433ffacf 100644--- a/packages/documents/src/pdf/QuotePDF.tsx+++ b/packages/documents/src/pdf/QuotePDF.tsx@@ -2,15 +2,11 @@ import type { Database } from "@carbon/database";import { StyleSheet, Text, View } from "@react-pdf/renderer";import type { PDF } from "../types";-import { QuoteSummary, Template, QuoteHeader } from "./components";-import { getExtendedPrice, getUnitCost } from "../utils/quote";+import { QuoteHeader, QuoteSummary, Template } from "./components";interface QuotePDFProps extends PDF {quote: Database["public"]["Views"]["quotes"]["Row"];quoteLines: Database["public"]["Tables"]["quoteLine"]["Row"][];- quoteLineQuantities:- | Database["public"]["Tables"]["quoteLineQuantity"]["Row"][]- | null;quoteCustomerDetails: Database["public"]["Views"]["quoteCustomerDetails"]["Row"];}@@ -19,7 +15,6 @@ const QuotePDF = ({meta,quote,quoteLines,- quoteLineQuantities,quoteCustomerDetails,title = "Quote",}: QuotePDFProps) => {@@ -63,7 +58,7 @@ const QuotePDF = ({<Text style={{ fontSize: 9, opacity: 0.8 }}>{line.partId}</Text></View><View style={styles.quantityTable}>- {quoteLineQuantities &&+ {/* {quoteLineQuantities &"eLineQuantities.map((quantity) =>quantity.quoteLineId === line.id ? (<View style={styles.quantityRow} key={quantity.id}>@@ -81,7 +76,7 @@ const QuotePDF = ({</View></View>) : null- )}+ )} */}</View></View>))}