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: pricing card
Brad Barbin64f098d72a91
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.tsindex 063795ccee..7490eb635f 100644--- a/apps/carbon/app/modules/sales/sales.service.ts+++ b/apps/carbon/app/modules/sales/sales.service.ts@@ -599,25 +599,14 @@ export async function getSalesOrderExternalDocuments(.list(`${companyId}/sales/external/${salesOrderId}`);}-/*export async function getSalesOrderInternalDocuments(- client: SupabaseClient<Database>,- companyId: string,- salesOrderId: string-) {- return client.storage- .from("private")- .list(`${companyId}/sales/internal/${salesOrderId}`);-}*/--export async function getQuoteLinePrice(+export async function getQuoteLinePrices(client: SupabaseClient<Database>,quoteLineId: string) {return client.from("quoteLinePrice").select("*")- .eq("quoteLineId", quoteLineId)- .single();+ .eq("quoteLineId", quoteLineId);}export async function getQuoteLinePricesByQuoteId(@@ -1351,6 +1340,29 @@ export async function upsertQuoteLineAdditionalCharges(return client.from("quoteLine").update(update).eq("id", lineId);}+export async function upsertQuoteLinePrices(+ client: SupabaseClient<Database>,+ lineId: string,+ quoteLinePrices: {+ quoteId: string;+ quoteLineId: string;+ unitPrice: number;+ leadTime: number;+ quantity: number;+ createdBy: string;+ }[]+) {+ const deletePrices = await client+ .from("quoteLinePrice")+ .delete()+ .eq("quoteLineId", lineId);+ if (deletePrices.error) {+ return deletePrices;+ }++ return client.from("quoteLinePrice").insert(quoteLinePrices);+}+export async function updateQuoteLinePrice(client: SupabaseClient<Database>,quoteLinePrice: z.infer<typeof quotationPricingValidator> & {diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.tsindex 6a90e0c3e4..e21d76da71 100644--- a/apps/carbon/app/modules/sales/types.ts+++ b/apps/carbon/app/modules/sales/types.ts@@ -1,4 +1,5 @@import type { Database } from "@carbon/database";+import type { QuantityEffect } from "../shared";import type {getCustomer,getCustomerContacts,@@ -7,6 +8,7 @@ import type {getCustomerStatuses,getCustomerTypes,getQuoteDocuments,+ getQuoteLinePrices,getQuoteLines,getQuoteMakeMethod,getQuoteMaterials,@@ -19,6 +21,33 @@ import type {getSalesRFQs,} from "./sales.service";+export type Costs = {+ materialCost: number;+ partCost: number;+ toolCost: number;+ fixtureCost: number;+ consumableCost: number;+ serviceCost: number;+ laborCost: number;+ overheadCost: number;+ outsideCost: number;+ setupHours: number;+ productionHours: number;+};++export type CostEffects = {+ materialCost: QuantityEffect[];+ partCost: QuantityEffect[];+ toolCost: QuantityEffect[];+ fixtureCost: QuantityEffect[];+ consumableCost: QuantityEffect[];+ serviceCost: QuantityEffect[];+ laborCost: QuantityEffect[];+ overheadCost: QuantityEffect[];+ setupHours: QuantityEffect[];+ productionHours: QuantityEffect[];+};+export type Customer = NonNullable<Awaited<ReturnType<typeof getCustomers>>["data"]>[number];@@ -71,6 +100,10 @@ export type QuotationOperation = NonNullable<Awaited<ReturnType<typeof getQuoteOperation>>["data"]>;+export type QuotationPrice = NonNullable<+ Awaited<ReturnType<typeof getQuoteLinePrices>>["data"]+>[number];+export type QuotationStatusType = Database["public"]["Enums"]["quoteStatus"];export type SalesOrder = NonNullable<diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsxindex 59061499db..9dc41e0eb2 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx@@ -17,341 +17,35 @@ import {Tfoot,Th,Thead,+ Tooltip,+ TooltipContent,+ TooltipTrigger,Tr,VStack,} from "@carbon/react";import { useFetcher, useParams } from "@remix-run/react";import { useCallback, useMemo } from "react";-import { LuPlus, LuTrash } from "react-icons/lu";+import { LuInfo, LuPlus, LuTrash } from "react-icons/lu";import type { z } from "zod";-import type { Tree } from "~/components/TreeView";-import {- quoteLineAdditionalChargesValidator,- type QuotationOperation,- type QuoteMethod,-} from "~/modules/sales";import { MethodItemTypeIcon } from "~/modules/shared";import { path } from "~/utils/path";--type Costs = {- materialCost: number;- partCost: number;- toolCost: number;- fixtureCost: number;- consumableCost: number;- serviceCost: number;- laborCost: number;- overheadCost: number;- outsideCost: number;- setupHours: number;- productionHours: number;-};--type Effect = (quantity: number) => number;-type CostEffects = {- materialCost: Effect[];- partCost: Effect[];- toolCost: Effect[];- fixtureCost: Effect[];- consumableCost: Effect[];- serviceCost: Effect[];- laborCost: Effect[];- overheadCost: Effect[];- setupHours: Effect[];- productionHours: Effect[];-};--const defaultEffects: CostEffects = {- materialCost: [],- partCost: [],- toolCost: [],- fixtureCost: [],- consumableCost: [],- serviceCost: [],- laborCost: [],- overheadCost: [],- setupHours: [],- productionHours: [],-};--type EnhancedTree = Tree<QuoteMethod & { operations?: QuotationOperation[] }>;--function useLineCosts({- methodTree: originalMethodTree,- operations,-}: {- methodTree?: Tree<QuoteMethod>;- operations: QuotationOperation[];-}): (quantity: number) => Costs {- const { quoteId, lineId } = useParams();- if (!quoteId) throw new Error("Could not find quoteId");- if (!lineId) throw new Error("Could not find lineId");-- // TODO: instead of walking the tree twice (once for the quantities/operations and once for the effects)- // we could do it all in one pass-- const methodTree = useMemo<EnhancedTree>(() => {- if (!originalMethodTree || !originalMethodTree.id) {- return {} as Tree<QuoteMethod>;- }-- const tree = structuredClone(originalMethodTree);- function walkTree(tree: EnhancedTree, parentQuantity: number) {- // multiply quantity by parent quantity- tree.data.quantity = tree.data.quantity * parentQuantity;- tree.data.operations = operations.filter(- (o) => o.quoteMakeMethodId === tree.data.quoteMaterialMakeMethodId- );-- if (tree.children) {- for (const child of tree.children) {- walkTree(child, tree.data.quantity);- }- }- }-- walkTree(tree, 1);-- return tree;- }, [operations, originalMethodTree]);-- const costEffects = useMemo<CostEffects>(() => {- const effects = defaultEffects;-- function walkTree(tree: EnhancedTree) {- const { data } = tree;-- if (["Buy", "Pick"].includes(data.methodType)) {- switch (data.itemType) {- case "Material":- effects.materialCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );- break;- case "Part":- effects.partCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );- break;- case "Tool":- effects.toolCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );- break;- case "Fixture":- effects.fixtureCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );- break;- case "Consumable":- effects.consumableCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );- break;- case "Service":- effects.serviceCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );- break;- default:- break;- }- }-- data.operations?.forEach((operation) => {- if (operation.setupHours) {- // setupHours don't depend on quantity- effects.setupHours.push((quantity) => {- return operation.setupHours;- });- if (operation.quotingRate) {- effects.overheadCost.push((quantity) => {- return operation.setupHours * (operation.quotingRate ?? 0);- });- } else {- effects.laborCost.push((quantity) => {- return operation.setupHours * (operation.laborRate ?? 0);- });- effects.overheadCost.push((quantity) => {- return operation.setupHours * (operation.overheadRate ?? 0);- });- }- }-- if (operation.productionStandard) {- // normalize production standard to hours- let hoursPerProductionStandard = 0;- switch (operation.standardFactor) {- case "Total Hours":- case "Hours/Piece":- hoursPerProductionStandard = operation.productionStandard;- break;- case "Hours/100 Pieces":- hoursPerProductionStandard = operation.productionStandard / 100;- break;- case "Hours/1000 Pieces":- hoursPerProductionStandard = operation.productionStandard / 1000;- break;- case "Total Minutes":- case "Minutes/Piece":- hoursPerProductionStandard = operation.productionStandard / 60;- break;- case "Minutes/100 Pieces":- hoursPerProductionStandard =- operation.productionStandard / 100 / 60;- break;- case "Minutes/1000 Pieces":- hoursPerProductionStandard =- operation.productionStandard / 1000 / 60;- break;- case "Pieces/Hour":- hoursPerProductionStandard = 1 / operation.productionStandard;- break;- case "Pieces/Minute":- hoursPerProductionStandard =- 1 / (operation.productionStandard / 60);- break;- case "Seconds/Piece":- hoursPerProductionStandard = operation.productionStandard / 3600;- break;- default:- break;- }-- effects.productionHours.push((quantity) => {- return hoursPerProductionStandard * quantity * data.quantity;- });- if (operation.quotingRate) {- effects.overheadCost.push((quantity) => {- return (- hoursPerProductionStandard *- quantity *- data.quantity *- (operation.quotingRate ?? 0)- );- });- } else {- effects.laborCost.push((quantity) => {- return (- hoursPerProductionStandard *- quantity *- data.quantity *- (operation.laborRate ?? 0)- );- });- effects.overheadCost.push((quantity) => {- return (- hoursPerProductionStandard *- quantity *- data.quantity *- (operation.overheadRate ?? 0)- );- });- }- }- });-- if (tree.children) {- for (const child of tree.children) {- walkTree(child);- }- }- }-- walkTree(methodTree);-- return effects;- }, [methodTree]);-- const getCosts = useCallback(- (quantity: number) => {- const materialCost = costEffects.materialCost.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- const partCost = costEffects.partCost.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- const toolCost = costEffects.toolCost.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- const fixtureCost = costEffects.fixtureCost.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- const consumableCost = costEffects.consumableCost.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- const serviceCost = costEffects.serviceCost.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- const laborCost = costEffects.laborCost.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- const overheadCost = costEffects.overheadCost.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- const setupHours = costEffects.setupHours.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- const productionHours = costEffects.productionHours.reduce(- (acc, effect) => acc + effect(quantity),- 0- );-- return {- materialCost,- partCost,- toolCost,- fixtureCost,- consumableCost,- serviceCost,- laborCost,- overheadCost,- outsideCost: 0,- setupHours,- productionHours,- };- },- [costEffects]- );-- return getCosts;-}+import { quoteLineAdditionalChargesValidator } from "../../sales.models";+import type { Costs } from "../../types";const QuoteLineCosting = ({- methodTree,- operations,quantities,additionalCharges: additionalChargesJson,+ getLineCosts,}: {- methodTree?: Tree<QuoteMethod>;- operations: QuotationOperation[];quantities: number[];additionalCharges?: Json;+ getLineCosts: (quantity: number) => Costs;}) => {const { quoteId, lineId } = useParams();if (!quoteId) throw new Error("Could not find quoteId");if (!lineId) throw new Error("Could not find lineId");const fetcher = useFetcher<{ id: string }>();- const getLineCosts = useLineCosts({ methodTree, operations });const quantityCosts = quantities.map((quantity) => ({quantity,@@ -452,7 +146,7 @@ const QuoteLineCosting = ({</Tr></Thead><Tbody>- <Tr className="font-bold">+ <Tr><Td className="border-r border-border"><HStack className="w-full justify-between "><span>Total Material Cost</span>@@ -489,7 +183,17 @@ const QuoteLineCosting = ({<Tr><Td className="border-r border-border pl-10"><HStack className="w-full justify-between ">- <span className="whitespace-nowrap">Part Cost</span>+ <span className="whitespace-nowrap flex items-center justify-start gap-2">+ Part Cost{" "}+ <Tooltip>+ <TooltipTrigger>+ <LuInfo className="w-4 h-4" />+ </TooltipTrigger>+ <TooltipContent>+ Includes bought and picked parts+ </TooltipContent>+ </Tooltip>+ </span><Badge variant="secondary"><MethodItemTypeIcon type="Part" /></Badge>diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsxindex ac91340fb4..f948b4064b 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx@@ -181,7 +181,6 @@ const QuoteLineForm = ({)}</HStack><ModalCardBody>- <Hidden name="intent" value="line" /><Hidden name="id" /><Hidden name="quoteId" /><Hiddendiff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsxnew file mode 100644index 0000000000..2646204e53--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx@@ -0,0 +1,339 @@+import type { Json } from "@carbon/database";+import {+ Button,+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ HStack,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ Tr,+ VStack,+} from "@carbon/react";+import { useFetcher, useParams } from "@remix-run/react";+import { useMemo } from "react";+import { LuInfo, LuRefreshCcw } from "react-icons/lu";+import type { z } from "zod";+import { path } from "~/utils/path";+import { quoteLineAdditionalChargesValidator } from "../../sales.models";+import type { Costs, QuotationPrice } from "../../types";++const QuoteLinePricing = ({+ quantities,+ additionalCharges: additionalChargesJson,+ pricesByQuantity,+ getLineCosts,+}: {+ quantities: number[];+ additionalCharges?: Json;+ pricesByQuantity: Record<number, QuotationPrice>;+ getLineCosts: (quantity: number) => Costs;+}) => {+ const { quoteId, lineId } = useParams();+ if (!quoteId) throw new Error("Could not find quoteId");+ if (!lineId) throw new Error("Could not find lineId");++ const fetcher = useFetcher<{ id: string }>();++ // TODO: factor in default currency or quote currency+ const formatter = useMemo(+ () =>+ new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }),+ []+ );++ const additionalCharges = useMemo(() => {+ if (fetcher.formAction === path.to.quoteLineCost(quoteId, lineId)) {+ // get the optimistic update+ return JSON.parse(+ (fetcher.formData?.get("additionalCharges") as string) ?? "{}"+ ) as z.infer<typeof quoteLineAdditionalChargesValidator>;+ }+ const parsedAdditionalCharges =+ quoteLineAdditionalChargesValidator.safeParse(additionalChargesJson);++ return parsedAdditionalCharges.success ? parsedAdditionalCharges.data : {};+ }, [+ additionalChargesJson,+ fetcher.formAction,+ fetcher.formData,+ lineId,+ quoteId,+ ]);++ const additionalChargesByQuantity = quantities.map((quantity) => {+ const charges = Object.values(additionalCharges).reduce((acc, charge) => {+ const amount = charge.amounts?.[quantity] ?? 0;+ return acc + amount;+ }, 0);+ return charges;+ });++ const unitCostsByQuantity = quantities.map((quantity, index) => {+ const costs = getLineCosts(quantity);+ const totalCost =+ (costs.materialCost ++ costs.partCost ++ costs.toolCost ++ costs.fixtureCost ++ costs.consumableCost ++ costs.serviceCost ++ costs.laborCost ++ costs.overheadCost ++ costs.outsideCost ++ additionalChargesByQuantity[index]) /+ quantity;+ return totalCost;+ });++ const netPricesByQuantity = quantities.map((quantity, index) => {+ const price = pricesByQuantity[quantity]?.unitPrice ?? 0;+ const discount = (pricesByQuantity[quantity]?.discountPercent ?? 0) / 100;+ const netPrice = price * (1 - discount / 100);+ return netPrice;+ });++ const onRecalculate = () => {+ const formData = new FormData();+ formData.append("unitCostsByQuantity", JSON.stringify(unitCostsByQuantity));+ formData.append("quantities", JSON.stringify(quantities));+ fetcher.submit(formData, {+ method: "post",+ action: path.to.quoteLineRecaluclatePrice(quoteId, lineId),+ });+ };++ return (+ <Card>+ <HStack className="justify-between">+ <CardHeader>+ <CardTitle>Pricing</CardTitle>+ </CardHeader>+ <CardAction>+ <Button+ variant="secondary"+ leftIcon={<LuRefreshCcw />}+ onClick={onRecalculate}+ isLoading={+ fetcher.state === "loading" &&+ fetcher.formAction ===+ path.to.quoteLineRecaluclatePrice(quoteId, lineId)+ }+ isDisabled={+ fetcher.state === "loading" &&+ fetcher.formAction ===+ path.to.quoteLineRecaluclatePrice(quoteId, lineId)+ }+ >+ Recalculate+ </Button>+ </CardAction>+ </HStack>+ <CardContent>+ <Table>+ <Thead>+ <Tr>+ <Th className="w-[300px]" />+ {quantities.map((quantity) => (+ <Th key={quantity.toString()}>{quantity}</Th>+ ))}+ </Tr>+ </Thead>+ <Tbody>+ <Tr className="[&>td]:bg-muted/80 [&>td]:group-hover:bg-muted/70">+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Unit Cost</span>+ </HStack>+ </Td>+ {unitCostsByQuantity.map((cost, index) => {+ return (+ <Td key={index}>+ <VStack spacing={0}>+ <span>{formatter.format(cost ?? 0)}</span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr>+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Unit Price</span>+ </HStack>+ </Td>+ {quantities.map((quantity) => {+ const price = pricesByQuantity[quantity]?.unitPrice;+ return (+ <Td key={quantity.toString()}>+ <VStack spacing={0}>+ <span>{formatter.format(price ?? 0)}</span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr>+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Lead Time</span>+ </HStack>+ </Td>+ {quantities.map((quantity) => {+ const leadTime = pricesByQuantity[quantity]?.leadTime ?? 0;+ return (+ <Td key={quantity.toString()}>+ <VStack spacing={0}>+ <span>{leadTime} days</span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr>+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Discount Percent</span>+ </HStack>+ </Td>+ {quantities.map((quantity, index) => {+ const discount = pricesByQuantity[quantity]?.discountPercent;++ return (+ <Td key={index}>+ <VStack spacing={0}>+ <span>{(discount ?? 0).toFixed(2)}%</span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr className="[&>td]:bg-muted/80 [&>td]:group-hover:bg-muted/70">+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Net Price</span>+ </HStack>+ </Td>+ {netPricesByQuantity.map((price, index) => {+ return (+ <Td key={index}>+ <VStack spacing={0}>+ <span>{formatter.format(price)}</span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr className="[&>td]:bg-muted/80 [&>td]:group-hover:bg-muted/70">+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span className="flex items-center justify-start gap-2">+ Markup Percent+ <Tooltip>+ <TooltipTrigger>+ <LuInfo className="w-4 h-4" />+ </TooltipTrigger>+ <TooltipContent>(Price - Cost) / Cost</TooltipContent>+ </Tooltip>+ </span>+ </HStack>+ </Td>+ {netPricesByQuantity.map((price, index) => {+ const cost = unitCostsByQuantity[index];+ const markup = ((price - cost) / cost) * 100;+ return (+ <Td key={index}>+ <VStack spacing={0}>+ {Number.isFinite(markup) ? (+ <span>{(markup ?? 0).toFixed(2)}%</span>+ ) : (+ <span>-</span>+ )}+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr className="[&>td]:bg-muted/80 [&>td]:group-hover:bg-muted/70">+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span className="flex items-center justify-start gap-2">+ Profit Percent+ <Tooltip>+ <TooltipTrigger>+ <LuInfo className="w-4 h-4" />+ </TooltipTrigger>+ <TooltipContent>(Price - Cost) / Price</TooltipContent>+ </Tooltip>+ </span>+ </HStack>+ </Td>+ {netPricesByQuantity.map((price, index) => {+ const cost = unitCostsByQuantity[index];+ const profit = ((price - cost) / price) * 100;+ return (+ <Td key={index}>+ <VStack spacing={0}>+ {Number.isFinite(profit) ? (+ <span>{profit.toFixed(2)}%</span>+ ) : (+ <span>-</span>+ )}+ </VStack>+ </Td>+ );+ })}+ </Tr>++ <Tr className="[&>td]:bg-muted/80 [&>td]:group-hover:bg-muted/70">+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Total Profit</span>+ </HStack>+ </Td>+ {quantities.map((quantity, index) => {+ const price = netPricesByQuantity[index];+ const cost = unitCostsByQuantity[index];+ const profit = (price - cost) * quantity;+ return (+ <Td key={index}>+ <VStack spacing={0}>+ <span>{formatter.format(profit)}</span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ <Tr className="font-bold">+ <Td className="border-r border-border">+ <HStack className="w-full justify-between ">+ <span>Total Price</span>+ </HStack>+ </Td>+ {quantities.map((quantity, index) => {+ const price = netPricesByQuantity[index];+ return (+ <Td key={index}>+ <VStack spacing={0}>+ <span>{formatter.format(price * quantity)}</span>+ </VStack>+ </Td>+ );+ })}+ </Tr>+ </Tbody>+ </Table>+ </CardContent>+ </Card>+ );+};++export default QuoteLinePricing;diff --git a/apps/carbon/app/modules/sales/ui/Quotes/index.ts b/apps/carbon/app/modules/sales/ui/Quotes/index.tsindex 55d2c2f885..966fcaecd3 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/index.ts+++ b/apps/carbon/app/modules/sales/ui/Quotes/index.ts@@ -10,8 +10,10 @@ import QuoteLineCosting from "./QuoteLineCosting";import QuoteLineDocuments from "./QuoteLineDocuments";import QuoteLineForm from "./QuoteLineForm";import QuoteLineNotes from "./QuoteLineNotes";+import QuoteLinePricing from "./QuoteLinePricing";import QuoteMaterialForm from "./QuoteMaterialForm";import QuotesTable from "./QuotesTable";+import { useLineCosts } from "./useLineCosts";export {DeleteQuoteLine,@@ -26,6 +28,8 @@ export {QuoteLineDocuments,QuoteLineForm,QuoteLineNotes,+ QuoteLinePricing,QuoteMaterialForm,QuotesTable,+ useLineCosts,};diff --git a/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx b/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsxnew file mode 100644index 0000000000..9325e4e1d3--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/useLineCosts.tsx@@ -0,0 +1,283 @@+import { useParams } from "@remix-run/react";+import { useCallback, useMemo } from "react";+import type { Tree } from "~/components/TreeView";+import type {+ CostEffects,+ Costs,+ QuotationOperation,+ QuoteMethod,+} from "../../types";++const defaultEffects: CostEffects = {+ materialCost: [],+ partCost: [],+ toolCost: [],+ fixtureCost: [],+ consumableCost: [],+ serviceCost: [],+ laborCost: [],+ overheadCost: [],+ setupHours: [],+ productionHours: [],+};++type EnhancedTree = Tree<QuoteMethod & { operations?: QuotationOperation[] }>;++export function useLineCosts({+ methodTree: originalMethodTree,+ operations,+}: {+ methodTree?: Tree<QuoteMethod>;+ operations: QuotationOperation[];+}): (quantity: number) => Costs {+ const { quoteId, lineId } = useParams();+ if (!quoteId) throw new Error("Could not find quoteId");+ if (!lineId) throw new Error("Could not find lineId");++ // TODO: instead of walking the tree twice (once for the quantities/operations and once for the effects)+ // we could do it all in one pass++ const methodTree = useMemo<EnhancedTree>(() => {+ if (!originalMethodTree || !originalMethodTree.id) {+ return {} as Tree<QuoteMethod>;+ }++ const tree = structuredClone(originalMethodTree);+ function walkTree(tree: EnhancedTree, parentQuantity: number) {+ // multiply quantity by parent quantity+ tree.data.quantity = tree.data.quantity * parentQuantity;+ tree.data.operations = operations.filter(+ (o) => o.quoteMakeMethodId === tree.data.quoteMaterialMakeMethodId+ );++ if (tree.children) {+ for (const child of tree.children) {+ walkTree(child, tree.data.quantity);+ }+ }+ }++ walkTree(tree, 1);++ return tree;+ }, [operations, originalMethodTree]);++ const costEffects = useMemo<CostEffects>(() => {+ const effects = structuredClone(defaultEffects);++ function walkTree(tree: EnhancedTree) {+ const { data } = tree;++ if (["Buy", "Pick"].includes(data.methodType)) {+ switch (data.itemType) {+ case "Material":+ effects.materialCost.push(+ (quantity) => data.unitCost * data.quantity * quantity+ );+ break;+ case "Part":+ effects.partCost.push(+ (quantity) => data.unitCost * data.quantity * quantity+ );+ break;+ case "Tool":+ effects.toolCost.push(+ (quantity) => data.unitCost * data.quantity * quantity+ );+ break;+ case "Fixture":+ effects.fixtureCost.push(+ (quantity) => data.unitCost * data.quantity * quantity+ );+ break;+ case "Consumable":+ effects.consumableCost.push(+ (quantity) => data.unitCost * data.quantity * quantity+ );+ break;+ case "Service":+ effects.serviceCost.push(+ (quantity) => data.unitCost * data.quantity * quantity+ );+ break;+ default:+ break;+ }+ }++ data.operations?.forEach((operation) => {+ if (operation.setupHours) {+ // setupHours don't depend on quantity+ effects.setupHours.push((quantity) => {+ return operation.setupHours;+ });+ if (operation.quotingRate) {+ effects.overheadCost.push((quantity) => {+ return operation.setupHours * (operation.quotingRate ?? 0);+ });+ } else {+ effects.laborCost.push((quantity) => {+ return operation.setupHours * (operation.laborRate ?? 0);+ });+ effects.overheadCost.push((quantity) => {+ return operation.setupHours * (operation.overheadRate ?? 0);+ });+ }+ }++ if (operation.productionStandard) {+ // normalize production standard to hours+ let hoursPerProductionStandard = 0;+ switch (operation.standardFactor) {+ case "Total Hours":+ case "Hours/Piece":+ hoursPerProductionStandard = operation.productionStandard;+ break;+ case "Hours/100 Pieces":+ hoursPerProductionStandard = operation.productionStandard / 100;+ break;+ case "Hours/1000 Pieces":+ hoursPerProductionStandard = operation.productionStandard / 1000;+ break;+ case "Total Minutes":+ case "Minutes/Piece":+ hoursPerProductionStandard = operation.productionStandard / 60;+ break;+ case "Minutes/100 Pieces":+ hoursPerProductionStandard =+ operation.productionStandard / 100 / 60;+ break;+ case "Minutes/1000 Pieces":+ hoursPerProductionStandard =+ operation.productionStandard / 1000 / 60;+ break;+ case "Pieces/Hour":+ hoursPerProductionStandard = 1 / operation.productionStandard;+ break;+ case "Pieces/Minute":+ hoursPerProductionStandard =+ 1 / (operation.productionStandard / 60);+ break;+ case "Seconds/Piece":+ hoursPerProductionStandard = operation.productionStandard / 3600;+ break;+ default:+ break;+ }++ effects.productionHours.push((quantity) => {+ return hoursPerProductionStandard * quantity * data.quantity;+ });+ if (operation.quotingRate) {+ effects.overheadCost.push((quantity) => {+ return (+ hoursPerProductionStandard *+ quantity *+ data.quantity *+ (operation.quotingRate ?? 0)+ );+ });+ } else {+ effects.laborCost.push((quantity) => {+ return (+ hoursPerProductionStandard *+ quantity *+ data.quantity *+ (operation.laborRate ?? 0)+ );+ });+ effects.overheadCost.push((quantity) => {+ return (+ hoursPerProductionStandard *+ quantity *+ data.quantity *+ (operation.overheadRate ?? 0)+ );+ });+ }+ }+ });++ if (tree.children) {+ for (const child of tree.children) {+ walkTree(child);+ }+ }+ }++ walkTree(methodTree);++ return effects;+ }, [methodTree]);++ const getCosts = useCallback(+ (quantity: number) => {+ const materialCost = costEffects.materialCost.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ const partCost = costEffects.partCost.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ const toolCost = costEffects.toolCost.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ const fixtureCost = costEffects.fixtureCost.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ const consumableCost = costEffects.consumableCost.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ const serviceCost = costEffects.serviceCost.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ const laborCost = costEffects.laborCost.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ const overheadCost = costEffects.overheadCost.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ const setupHours = costEffects.setupHours.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ const productionHours = costEffects.productionHours.reduce(+ (acc, effect) => acc + effect(quantity),+ 0+ );++ return {+ materialCost,+ partCost,+ toolCost,+ fixtureCost,+ consumableCost,+ serviceCost,+ laborCost,+ overheadCost,+ outsideCost: 0,+ setupHours,+ productionHours,+ };+ },+ [costEffects]+ );++ return getCosts;+}diff --git a/apps/carbon/app/modules/shared/types.ts b/apps/carbon/app/modules/shared/types.tsindex 1f15d4837b..cea82ef954 100644--- a/apps/carbon/app/modules/shared/types.ts+++ b/apps/carbon/app/modules/shared/types.ts@@ -51,3 +51,5 @@ export const standardFactorType = [] as const;export type StandardFactor = (typeof standardFactorType)[number];++export type QuantityEffect = (quantity: number) => number;diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex 7a91fd3a60..d2d9de347b 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -6,19 +6,20 @@ import { Fragment, useMemo } from "react";import type { Tree } from "~/components/TreeView";import { usePermissions, useRealtime, useRouteData } from "~/hooks";import { CadModel } from "~/modules/items";-import type { QuoteMethod } from "~/modules/sales";+import type { QuotationPrice, QuoteMethod } from "~/modules/sales";import {getFilesByQuoteLineId,getQuoteLine,+ getQuoteLinePrices,getQuoteOperationsByLine,- quotationPricingValidator,QuoteLineCosting,QuoteLineDocuments,QuoteLineForm,QuoteLineNotes,+ QuoteLinePricing,quoteLineValidator,- updateQuoteLinePrice,upsertQuoteLine,+ useLineCosts,} from "~/modules/sales";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";@@ -36,10 +37,11 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {if (!quoteId) throw new Error("Could not find quoteId");if (!lineId) throw new Error("Could not find lineId");- const [line, operations, files] = await Promise.all([+ const [line, operations, files, prices] = await Promise.all([getQuoteLine(client, lineId),getQuoteOperationsByLine(client, lineId),getFilesByQuoteLineId(client, companyId, lineId),+ getQuoteLinePrices(client, lineId),]);if (line.error) {@@ -53,6 +55,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {line: line.data,operations: operations?.data ?? [],files: files?.data ?? [],+ pricesByQuantity: (prices?.data ?? []).reduce<+ Record<number, QuotationPrice>+ >((acc, price) => {+ acc[price.quantity] = price;+ return acc;+ }, {}),});};@@ -67,65 +75,38 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!lineId) throw new Error("Could not find lineId");const formData = await request.formData();- const intent = formData.get("intent");-- if (intent === "line") {- const validation = await validator(quoteLineValidator).validate(formData);-- 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) {- throw 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) {- throw redirect(- path.to.quoteLine(quoteId, lineId),- await flash(- request,- error(updateLinePrice.error, "Failed to update quote line price")- )- );- }+ const validation = await validator(quoteLineValidator).validate(formData);++ 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) {+ throw redirect(+ path.to.quoteLine(quoteId, lineId),+ await flash(+ request,+ error(updateQuotationLine.error, "Failed to update quote line")+ )+ );}throw redirect(path.to.quoteLine(quoteId, lineId));}export default function QuoteLine() {- const { line, operations, files } = useLoaderData<typeof loader>();+ const { line, operations, files, pricesByQuantity } =+ useLoaderData<typeof loader>();const permissions = usePermissions();const { quoteId, lineId } = useParams();if (!quoteId) throw new Error("Could not find quoteId");@@ -144,6 +125,11 @@ export default function QuoteLine() {[quoteData, line.id]);+ const getLineCosts = useLineCosts({+ methodTree,+ operations,+ });+const initialValues = {...line,id: line.id ?? undefined,@@ -184,12 +170,17 @@ export default function QuoteLine() {</div>{line.methodType === "Make" && (<QuoteLineCosting- methodTree={methodTree}- operations={operations}quantities={line.quantity ?? [1]}additionalCharges={line.additionalCharges ?? {}}+ getLineCosts={getLineCosts}/>)}+ <QuoteLinePricing+ quantities={line.quantity ?? [1]}+ additionalCharges={line.additionalCharges ?? {}}+ pricesByQuantity={pricesByQuantity}+ getLineCosts={getLineCosts}+ /><QuoteLineNotes line={line} /><Outlet /></Fragment>diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsxnew file mode 100644index 0000000000..4102499d92--- /dev/null+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx@@ -0,0 +1,62 @@+import { json, type ActionFunctionArgs } from "@remix-run/node";+import { z } from "zod";+import { upsertQuoteLinePrices } from "~/modules/sales";+import { requirePermissions } from "~/services/auth/auth.server";+import { assertIsPost } from "~/utils/http";++const numberArrayValidator = z.array(z.number());++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);++ const { client, userId } = await requirePermissions(request, {+ update: "sales",+ });++ const { quoteId, lineId } = params;+ if (!quoteId) throw new Error("Could not find quoteId");+ if (!lineId) throw new Error("Could not find lineId");++ const formData = await request.formData();++ const unitCostsByQuantity = numberArrayValidator.safeParse(+ JSON.parse((formData.get("unitCostsByQuantity") ?? "[]") as string)+ );++ const quantities = numberArrayValidator.safeParse(+ JSON.parse((formData.get("quantities") ?? "[]") as string)+ );++ if (unitCostsByQuantity.success === false) {+ return json(+ { data: null, errors: unitCostsByQuantity.error.errors?.[0].message },+ { status: 400 }+ );+ }++ if (quantities.success === false) {+ return json(+ { data: null, errors: quantities.error.errors?.[0].message },+ { status: 400 }+ );+ }++ const inserts = unitCostsByQuantity.data.map((unitCost, index) => ({+ quoteId,+ quoteLineId: lineId,+ quantity: quantities.data[index],+ unitPrice: unitCost * 1.15,+ leadTime: 0,+ createdBy: userId,+ }));++ const insertLinePrices = await upsertQuoteLinePrices(client, lineId, inserts);+ if (insertLinePrices.error) {+ return json(+ { data: null, error: insertLinePrices.error.message },+ { status: 400 }+ );+ }++ return json({ data: null, error: null });+}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex 225761982e..b9504ef71e 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -582,7 +582,8 @@ export const path = {quoteOperation: (quoteId: string, lineId: string, id: string) =>generatePath(`${x}/quote/methods/${quoteId}/${lineId}/operation/${id}`),quoteOperationsOrder: `${x}/quote/methods/operation/order`,-+ quoteLineRecaluclatePrice: (quoteId: string, lineId: string) =>+ generatePath(`${x}/quote/${quoteId}/${lineId}/recalculate-price`),quoteRelease: (id: string) => generatePath(`${x}/quote/${id}/release`),quotes: `${x}/sales/quotes`,receipt: (id: string) => generatePath(`${x}/receipt/${id}`),diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 9f3377f512..57555e8070 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -13067,13 +13067,10 @@ export type Database = {}quoteLinePrice: {Row: {- additionalCharges: Json | nullcreatedAt: stringcreatedBy: stringdiscountPercent: number- extendedPrice: numberleadTime: number- markupPercent: numberquantity: numberquoteId: stringquoteLineId: string@@ -13083,13 +13080,10 @@ export type Database = {updatedBy: string | null}Insert: {- additionalCharges?: Json | nullcreatedAt?: stringcreatedBy: stringdiscountPercent?: number- extendedPrice?: numberleadTime?: number- markupPercent?: numberquantity?: numberquoteId: stringquoteLineId: string@@ -13099,13 +13093,10 @@ export type Database = {updatedBy?: string | null}Update: {- additionalCharges?: Json | nullcreatedAt?: stringcreatedBy?: stringdiscountPercent?: number- extendedPrice?: numberleadTime?: number- markupPercent?: numberquantity?: numberquoteId?: stringquoteLineId?: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 9f3377f512..57555e8070 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -13067,13 +13067,10 @@ export type Database = {}quoteLinePrice: {Row: {- additionalCharges: Json | nullcreatedAt: stringcreatedBy: stringdiscountPercent: number- extendedPrice: numberleadTime: number- markupPercent: numberquantity: numberquoteId: stringquoteLineId: string@@ -13083,13 +13080,10 @@ export type Database = {updatedBy: string | null}Insert: {- additionalCharges?: Json | nullcreatedAt?: stringcreatedBy: stringdiscountPercent?: number- extendedPrice?: numberleadTime?: number- markupPercent?: numberquantity?: numberquoteId: stringquoteLineId: string@@ -13099,13 +13093,10 @@ export type Database = {updatedBy?: string | null}Update: {- additionalCharges?: Json | nullcreatedAt?: stringcreatedBy?: stringdiscountPercent?: number- extendedPrice?: numberleadTime?: number- markupPercent?: numberquantity?: numberquoteId?: stringquoteLineId?: stringdiff --git a/packages/database/supabase/migrations/20240802114117_quote-line-quantities.sql b/packages/database/supabase/migrations/20240802114117_quote-line-quantities.sqlindex e4b7023a5f..66aee0bd8b 100644--- a/packages/database/supabase/migrations/20240802114117_quote-line-quantities.sql+++ b/packages/database/supabase/migrations/20240802114117_quote-line-quantities.sql@@ -22,6 +22,8 @@ COMMIT;ALTER TABLE "quoteLinePrice"DROP COLUMN "id",+ DROP COLUMN "markupPercent",+ DROP COLUMN "extendedPrice",+ DROP COLUMN "unitCost",ADD COLUMN "unitPrice" NUMERIC(10,5) NOT NULL DEFAULT 0,- ADD COLUMN "additionalCharges" JSONB DEFAULT '{}',ADD CONSTRAINT "quoteLinePrice_pkey" PRIMARY KEY ("quoteLineId", "quantity");diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.tsindex 4699919650..b6664fc7bb 100644--- a/packages/utils/src/themes.ts+++ b/packages/utils/src/themes.ts@@ -421,8 +421,8 @@ export const themes = [name: "violet",label: "Violet",activeColor: {- light: "262.1 83.3% 57.8%",- dark: "263.4 70% 50.4%",+ light: "252.1 83.3% 47.8%",+ dark: "253.4 70% 40.4%",},cssVars: {light: {@@ -432,7 +432,7 @@ export const themes = ["card-foreground": "224 71.4% 4.1%",popover: "0 0% 100%","popover-foreground": "224 71.4% 4.1%",- primary: "262.1 83.3% 57.8%",+ primary: "252.1 83.3% 47.8%","primary-foreground": "210 20% 98%",secondary: "220 14.3% 95.9%","secondary-foreground": "220.9 39.3% 11%",@@ -453,7 +453,7 @@ export const themes = ["card-foreground": "210 20% 98%",popover: "224 41.4 8.9%","popover-foreground": "210 20% 98%",- primary: "263.4 70% 50.4%",+ primary: "253.4 70% 40.4%","primary-foreground": "210 20% 98%",secondary: "215 27.9% 16.9%","secondary-foreground": "210 20% 98%",