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: add unit cost to quote methods
Brad Barbin62b071cad7fc
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.tsindex 8b3fed970c..392cd502f3 100644--- a/apps/carbon/app/modules/sales/sales.models.ts+++ b/apps/carbon/app/modules/sales/sales.models.ts@@ -134,6 +134,7 @@ export const quoteMaterialValidator = zdescription: z.string().min(1, { message: "Description is required" }),quoteOperationId: zfd.text(z.string().optional()),quantity: zfd.numeric(z.number().min(0)),+ unitCost: zfd.numeric(z.number().min(0)),unitOfMeasureCode: z.string().min(1, { message: "Unit of Measure is required" }),diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsxindex fa17b766e0..47f1c91c08 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx@@ -27,6 +27,7 @@ import {InputControlled,Item,Number,+ NumberControlled,Select,Submit,UnitOfMeasure,@@ -105,6 +106,7 @@ const initialMethodMaterial: Omit<Material, "quoteMakeMethodId" | "order"> & {methodType: "Buy" as const,description: "",quantity: 1,+ unitCost: 0,unitOfMeasureCode: "EA",};@@ -427,6 +429,7 @@ function MaterialForm({itemReadableId: string;methodType: MethodType;description: string;+ unitCost: number;unitOfMeasureCode: string;quantity: number;}>({@@ -434,6 +437,7 @@ function MaterialForm({itemReadableId: item.data.itemReadableId ?? "",methodType: item.data.methodType ?? "Buy",description: item.data.description ?? "",+ unitCost: item.data.unitCost ?? 0,unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",quantity: item.data.quantity ?? 1,});@@ -445,6 +449,7 @@ function MaterialForm({itemReadableId: "",methodType: "" as "Buy",quantity: 1,+ unitCost: 0,description: "",unitOfMeasureCode: "EA",});@@ -457,12 +462,19 @@ function MaterialForm({return;}- const item = await supabase- .from("item")- .select("name, readableId, unitOfMeasureCode, defaultMethodType")- .eq("id", itemId)- .eq("companyId", company.id)- .single();+ const [item, itemCost] = await await Promise.all([+ supabase+ .from("item")+ .select("name, readableId, unitOfMeasureCode, defaultMethodType")+ .eq("id", itemId)+ .eq("companyId", company.id)+ .single(),+ supabase+ .from("itemCost")+ .select("unitCost")+ .eq("itemId", itemId)+ .single(),+ ]);if (item.error) {toast.error("Failed to load item details");@@ -474,6 +486,7 @@ function MaterialForm({itemId,itemReadableId: item.data?.readableId ?? "",description: item.data?.name ?? "",+ unitCost: itemCost.data?.unitCost ?? 0,unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",methodType: item.data?.defaultMethodType ?? "Buy",}));@@ -507,6 +520,9 @@ function MaterialForm({<Hidden name="quoteMakeMethodId" /><Hidden name="itemReadableId" value={itemData.itemReadableId} /><Hidden name="order" />+ {itemData.methodType === "Make" && (+ <Hidden name="unitCost" value={itemData.unitCost} />+ )}<VStack className="pt-4"><div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3"><Select@@ -566,6 +582,14 @@ function MaterialForm({}))}/>+ {itemData.methodType !== "Make" && (+ <NumberControlled+ name="unitCost"+ label="Unit Cost"+ value={itemData.unitCost}+ minValue={0}+ />+ )}</div><motion.divdiff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsxnew file mode 100644index 0000000000..950b16b494--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx@@ -0,0 +1,416 @@+import {+ Button,+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Enumerable,+ HStack,+ Table,+ Tbody,+ Td,+ Tfoot,+ Th,+ Thead,+ Tr,+ VStack,+} from "@carbon/react";+import { useParams } from "@remix-run/react";+import { useCallback, useMemo, useState } from "react";+import type { Tree } from "~/components/TreeView";+import type { QuotationOperation, QuoteMethod } from "~/modules/sales";++type Costs = {+ materialCost: number;+ laborCost: number;+ overheadCost: number;+ outsideCost: number;+ setupHours: number;+ productionHours: number;+};++type Effect = (quantity: number) => number;+type CostEffects = {+ materialCost: Effect[];+ laborCost: Effect[];+ overheadCost: Effect[];+ setupHours: Effect[];+ productionHours: Effect[];+};++const defaultEffects: CostEffects = {+ materialCost: [],+ 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)) {+ effects.materialCost.push(+ (quantity) => data.unitCost * data.quantity * quantity+ );+ }++ 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 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,+ laborCost,+ overheadCost,+ outsideCost: 0,+ setupHours,+ productionHours,+ };+ },+ [costEffects]+ );++ return getCosts;+}++const QuoteLineCosting = ({+ methodTree,+ operations,+}: {+ methodTree?: Tree<QuoteMethod>;+ operations: QuotationOperation[];+}) => {+ const getLineCosts = useLineCosts({ methodTree, operations });+ const [quantities] = useState([1, 25, 50, 100]);++ const quantityCosts = quantities.map((quantity) => ({+ quantity,+ costs: getLineCosts(quantity),+ }));++ // TODO: factor in default currency or quote currency+ const formatter = useMemo(+ () =>+ new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }),+ []+ );++ return (+ <Card>+ <CardHeader>+ <CardTitle>Costing</CardTitle>+ </CardHeader>+ <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>+ {quantityCosts.map(({ quantity, costs }) => {+ return (+ <Td key={quantity.toString()} className="font-mono">+ <VStack spacing={0}>+ <span>+ {costs.materialCost+ ? formatter.format(costs.materialCost)+ : formatter.format(0)}+ </span>+ <span className="text-muted-foreground text-xs">+ {costs.materialCost && quantity > 0+ ? formatter.format(costs.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>+ {quantityCosts.map(({ quantity, costs }) => {+ return (+ <Td key={quantity.toString()} className="font-mono">+ <VStack spacing={0}>+ <span>+ {costs.overheadCost+ ? formatter.format(+ costs.overheadCost + costs.laborCost+ )+ : formatter.format(0)}+ </span>+ <span className="text-muted-foreground text-xs">+ {costs.overheadCost && quantity > 0+ ? formatter.format(+ (costs.overheadCost + costs.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>+ {quantityCosts.map(({ quantity, costs }) => {+ return (+ <Td key={quantity.toString()} className="font-mono">+ <VStack spacing={0}>+ <span>+ {costs.outsideCost+ ? formatter.format(costs.outsideCost)+ : formatter.format(0)}+ </span>+ <span className="text-muted-foreground text-xs">+ {costs.outsideCost && quantity > 0+ ? formatter.format(costs.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>+ {quantityCosts.map(({ quantity, costs }) => {+ const totalCost =+ // costs.materialCost ++ costs.laborCost + costs.overheadCost + costs.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" />+ {quantityCosts.map(({ quantity }) => (+ <Td key={quantity} className="font-mono">+ <Button variant="secondary">Add</Button>+ </Td>+ ))}+ </Tr>+ </Tfoot>+ </Table>+ </CardContent>+ </Card>+ );+};++export default QuoteLineCosting;diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsxnew file mode 100644index 0000000000..7763ec0506--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx@@ -0,0 +1,70 @@+import type { JSONContent } from "@carbon/react";+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Editor,+ toast,+ useDebounce,+} from "@carbon/react";+import { getLocalTimeZone, today } from "@internationalized/date";+import { useUser } from "~/hooks";+import { useSupabase } from "~/lib/supabase";+import type { QuotationLine } from "~/modules/sales";++const QuoteLineNotes = ({ line }: { line: QuotationLine }) => {+ const {+ id: userId,+ company: { id: companyId },+ } = useUser();+ const { supabase } = useSupabase();++ const onUploadImage = async (file: File) => {+ const fileName = `${companyId}/quote-line/${line.id}/${encodeURIComponent(+ file.name+ )}`;+ const result = await supabase?.storage+ .from("private")+ .upload(fileName, file);++ if (result?.error) {+ toast.error("Failed to upload image");+ throw new Error(result.error.message);+ }++ if (!result?.data) {+ throw new Error("Failed to upload image");+ }++ return `/file/preview/private/${result.data.path}`;+ };++ const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {+ await supabase+ ?.from("quoteLine")+ .update({+ notes: content,+ updatedAt: today(getLocalTimeZone()).toString(),+ updatedBy: userId,+ })+ .eq("id", line.id!);+ }, 3000);++ return (+ <Card>+ <CardHeader>+ <CardTitle>Internal Notes</CardTitle>+ </CardHeader>+ <CardContent>+ <Editor+ initialValue={(line.notes ?? {}) as JSONContent}+ onUpload={onUploadImage}+ onChange={onUpdateInternalNotes}+ />+ </CardContent>+ </Card>+ );+};++export default QuoteLineNotes;diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsxindex 255dd1dbf2..d2012079a3 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx@@ -18,6 +18,7 @@ import {InputControlled,Item,Number,+ NumberControlled,Select,Submit,UnitOfMeasure,@@ -60,6 +61,7 @@ const QuoteMaterialForm = ({itemReadableId: string;methodType: MethodType;description: string;+ unitCost: number;unitOfMeasureCode: string;quantity: number;}>({@@ -67,6 +69,7 @@ const QuoteMaterialForm = ({itemReadableId: initialValues.itemReadableId ?? "",methodType: initialValues.methodType ?? "Buy",description: initialValues.description ?? "",+ unitCost: initialValues.unitCost ?? 0,unitOfMeasureCode: initialValues.unitOfMeasureCode ?? "EA",quantity: initialValues.quantity ?? 1,});@@ -79,6 +82,7 @@ const QuoteMaterialForm = ({methodType: "" as "Buy",quantity: 1,description: "",+ unitCost: 0,unitOfMeasureCode: "EA",});};@@ -86,11 +90,18 @@ const QuoteMaterialForm = ({const onItemChange = async (itemId: string) => {if (!supabase) return;- const item = await supabase- .from("item")- .select("name, readableId, unitOfMeasureCode, defaultMethodType")- .eq("id", itemId)- .single();+ const [item, itemCost] = await await Promise.all([+ supabase+ .from("item")+ .select("name, readableId, unitOfMeasureCode, defaultMethodType")+ .eq("id", itemId)+ .single(),+ supabase+ .from("itemCost")+ .select("unitCost")+ .eq("itemId", itemId)+ .single(),+ ]);if (item.error) {toast.error("Failed to load item details");@@ -100,10 +111,11 @@ const QuoteMaterialForm = ({setItemData((d) => ({...d,itemId,- itemReadableId: initialValues?.itemReadableId ?? "",- description: initialValues?.description ?? "",- unitOfMeasureCode: initialValues?.unitOfMeasureCode ?? "EA",- methodType: initialValues?.methodType ?? "Buy",+ itemReadableId: item.data?.readableId ?? "",+ description: item.data?.name ?? "",+ unitCost: itemCost.data?.unitCost ?? 0,+ unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",+ methodType: item.data?.defaultMethodType ?? "Buy",}));};@@ -122,11 +134,29 @@ const QuoteMaterialForm = ({initialValues.methodType.toLowerCase(),initialValues.id!);- if (fetcher.data && location.pathname !== newPath) {+ if (+ fetcher.data?.methodType === "Make" &&+ !location.pathname.includes("make")+ ) {+ navigate(newPath);+ }++ if (+ fetcher.data?.methodType === "Buy" &&+ !location.pathname.includes("buy")+ ) {+ navigate(newPath);+ }++ if (+ fetcher.data?.methodType === "Pick" &&+ !location.pathname.includes("pick")+ ) {navigate(newPath);}}, [fetcher.data,+ initialValues,initialValues.id,initialValues.methodType,initialValues.quoteMaterialMakeMethodId,@@ -151,6 +181,9 @@ const QuoteMaterialForm = ({<CardContent><Hidden name="quoteMakeMethodId" /><Hidden name="itemReadableId" value={itemData.itemReadableId} />+ {itemData.methodType === "Make" && (+ <Hidden name="unitCost" value={itemData.unitCost} />+ )}<Hidden name="order" /><VStack className="pt-4"><div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">@@ -209,6 +242,14 @@ const QuoteMaterialForm = ({}))}/>+ {itemData.methodType !== "Make" && (+ <NumberControlled+ name="unitCost"+ label="Unit Cost"+ value={itemData.unitCost}+ minValue={0}+ />+ )}</div></VStack></CardContent>diff --git a/apps/carbon/app/modules/sales/ui/Quotes/index.ts b/apps/carbon/app/modules/sales/ui/Quotes/index.tsindex 4d22630b63..55d2c2f885 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/index.ts+++ b/apps/carbon/app/modules/sales/ui/Quotes/index.ts@@ -6,8 +6,10 @@ import QuoteBreadcrumbs from "./QuoteBreadcrumbs";import QuoteDocuments from "./QuoteDocuments";import QuoteForm from "./QuoteForm";import QuoteHeader from "./QuoteHeader";+import QuoteLineCosting from "./QuoteLineCosting";import QuoteLineDocuments from "./QuoteLineDocuments";import QuoteLineForm from "./QuoteLineForm";+import QuoteLineNotes from "./QuoteLineNotes";import QuoteMaterialForm from "./QuoteMaterialForm";import QuotesTable from "./QuotesTable";@@ -20,8 +22,10 @@ export {QuoteDocuments,QuoteForm,QuoteHeader,+ QuoteLineCosting,QuoteLineDocuments,QuoteLineForm,+ QuoteLineNotes,QuoteMaterialForm,QuotesTable,};diff --git a/apps/carbon/app/routes/x+/consumable+/new.tsx b/apps/carbon/app/routes/x+/consumable+/new.tsxindex 4bcaf0fb25..09144154e9 100644--- a/apps/carbon/app/routes/x+/consumable+/new.tsx+++ b/apps/carbon/app/routes/x+/consumable+/new.tsx@@ -9,10 +9,17 @@ import {import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Consumables",+ to: path.to.consumables,+ module: "items",+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/customer+/new.tsx b/apps/carbon/app/routes/x+/customer+/new.tsxindex fc2a53638c..645c8b1270 100644--- a/apps/carbon/app/routes/x+/customer+/new.tsx+++ b/apps/carbon/app/routes/x+/customer+/new.tsx@@ -9,10 +9,17 @@ import {import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Customers",+ to: path.to.customers,+ module: "sales",+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/fixture+/new.tsx b/apps/carbon/app/routes/x+/fixture+/new.tsxindex a756129136..ad8528f2ba 100644--- a/apps/carbon/app/routes/x+/fixture+/new.tsx+++ b/apps/carbon/app/routes/x+/fixture+/new.tsx@@ -5,10 +5,16 @@ import { FixtureForm, fixtureValidator, upsertFixture } from "~/modules/items";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Fixtures",+ to: path.to.fixtures,+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/material+/new.tsx b/apps/carbon/app/routes/x+/material+/new.tsxindex 014459bcb1..e90af8ed46 100644--- a/apps/carbon/app/routes/x+/material+/new.tsx+++ b/apps/carbon/app/routes/x+/material+/new.tsx@@ -9,10 +9,17 @@ import {import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Materials",+ to: path.to.materials,+ module: "items",+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/part+/new.tsx b/apps/carbon/app/routes/x+/part+/new.tsxindex 09dac85661..417b72ffcf 100644--- a/apps/carbon/app/routes/x+/part+/new.tsx+++ b/apps/carbon/app/routes/x+/part+/new.tsx@@ -5,10 +5,17 @@ import { PartForm, partValidator, upsertPart } from "~/modules/items";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Parts",+ to: path.to.parts,+ module: "items",+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx b/apps/carbon/app/routes/x+/purchase-invoice+/new.tsxindex de740c4e19..e9f18522f6 100644--- a/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx+++ b/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx@@ -15,10 +15,16 @@ import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import type { ListItem } from "~/types";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Purchasing",+ to: path.to.purchaseInvoices,+};+export async function loader({ request }: LoaderFunctionArgs) {// we don't use the client here -- if they have this permission, we'll upgrade to a service role if neededconst { companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/purchase-order+/new.tsx b/apps/carbon/app/routes/x+/purchase-order+/new.tsxindex 424e8b76ad..2d7213f705 100644--- a/apps/carbon/app/routes/x+/purchase-order+/new.tsx+++ b/apps/carbon/app/routes/x+/purchase-order+/new.tsx@@ -16,10 +16,16 @@ import { getNextSequence, rollbackNextSequence } from "~/modules/settings";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Orders",+ to: path.to.purchaseOrders,+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.buy.$materialId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.buy.$materialId.tsxindex 57f17bfa35..dc2eab65b3 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.buy.$materialId.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.buy.$materialId.tsx@@ -43,6 +43,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {quoteMakeMethodId: material.data.quoteMakeMethodId ?? "",quoteMaterialMakeMethodId: material.data.quoteMaterialMakeMethodId,quoteOperationId: material.data.quoteOperationId ?? undefined,+ unitCost: material.data.unitCost ?? 0,unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",},});diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex a3dda2d8b2..a6b30fdace 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -1,34 +1,21 @@-import type { JSONContent } from "@carbon/react";-import {- Card,- CardContent,- CardHeader,- CardTitle,- Editor,- toast,- useDebounce,-} from "@carbon/react";import { validationError, validator } from "@carbon/remix-validated-form";-import { getLocalTimeZone, today } from "@internationalized/date";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";import { json, redirect } from "@remix-run/node";import { Outlet, useLoaderData, useParams } from "@remix-run/react";+import { useMemo } from "react";import type { Tree } from "~/components/TreeView";-import { usePermissions, useRouteData, useUser } from "~/hooks";-import { useSupabase } from "~/lib/supabase";+import { usePermissions, useRouteData } from "~/hooks";import { CadModel } from "~/modules/items";-import type {- QuotationLine,- QuotationOperation,- QuoteMethod,-} from "~/modules/sales";+import type { QuoteMethod } from "~/modules/sales";import {getFilesByQuoteLineId,getQuoteLine,getQuoteOperationsByLine,quotationPricingValidator,+ QuoteLineCosting,QuoteLineDocuments,QuoteLineForm,+ QuoteLineNotes,quoteLineValidator,updateQuoteLinePrice,upsertQuoteLine,@@ -148,8 +135,9 @@ export default function QuoteLine() {path.to.quote(quoteId));- const methodTree = quoteData?.methods?.find(- (m) => m.data.quoteLineId === line.id+ const methodTree = useMemo(+ () => quoteData?.methods?.find((m) => m.data.quoteLineId === line.id),+ [quoteData, line.id]);const initialValues = {@@ -173,6 +161,9 @@ export default function QuoteLine() {<QuoteLineForm key={initialValues.id} initialValues={initialValues} />{permissions.is("employee") && (<>+ {line.methodType === "Make" && (+ <QuoteLineCosting methodTree={methodTree} operations={operations} />+ )}<div className="grid grid-cols-1 xl:grid-cols-2 w-full flex-grow gap-2 "><CadModelautodeskUrn={line?.autodeskUrn ?? null}@@ -189,7 +180,6 @@ export default function QuoteLine() {modelUpload={line ?? undefined}/></div>- <QuoteLineCosting methodTree={methodTree} operations={operations} /><QuoteLineNotes line={line} /><Outlet /></>@@ -197,78 +187,3 @@ export default function QuoteLine() {</>);}--const QuoteLineCosting = ({- methodTree,- operations,-}: {- methodTree?: Tree<QuoteMethod>;- operations: QuotationOperation[];-}) => {- return (- <Card>- <CardHeader>- <CardTitle>Costing</CardTitle>- </CardHeader>- <CardContent>- <div className="grid grid-cols-1 gap-2">- <pre>{JSON.stringify({ methodTree, operations }, null, 2)}</pre>- </div>- </CardContent>- </Card>- );-};--const QuoteLineNotes = ({ line }: { line: QuotationLine }) => {- const {- id: userId,- company: { id: companyId },- } = useUser();- const { supabase } = useSupabase();-- const onUploadImage = async (file: File) => {- const fileName = `${companyId}/quote-line/${line.id}/${encodeURIComponent(- file.name- )}`;- const result = await supabase?.storage- .from("private")- .upload(fileName, file);-- if (result?.error) {- toast.error("Failed to upload image");- throw new Error(result.error.message);- }-- if (!result?.data) {- throw new Error("Failed to upload image");- }-- return `/file/preview/private/${result.data.path}`;- };-- const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {- await supabase- ?.from("quoteLine")- .update({- notes: content,- updatedAt: today(getLocalTimeZone()).toString(),- updatedBy: userId,- })- .eq("id", line.id!);- }, 3000);-- return (- <Card>- <CardHeader>- <CardTitle>Internal Notes</CardTitle>- </CardHeader>- <CardContent>- <Editor- initialValue={(line.notes ?? {}) as JSONContent}- onUpload={onUploadImage}- onChange={onUpdateInternalNotes}- />- </CardContent>- </Card>- );-};diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsxindex acdcf8a4bc..e7037c866a 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx@@ -76,6 +76,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {quoteMakeMethodId: material.data.quoteMakeMethodId ?? "",quoteMaterialMakeMethodId: material.data.quoteMaterialMakeMethodId,quoteOperationId: material.data.quoteOperationId ?? undefined,+ unitCost: material.data.unitCost ?? 0,unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",},materials:diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.pick.$materialId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.pick.$materialId.tsxindex 949aa6ec4a..35bc764caf 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.pick.$materialId.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.pick.$materialId.tsx@@ -43,6 +43,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {quoteMakeMethodId: material.data.quoteMakeMethodId ?? "",quoteMaterialMakeMethodId: material.data.quoteMaterialMakeMethodId,quoteOperationId: material.data.quoteOperationId ?? undefined,+ unitCost: material.data.unitCost ?? 0,unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",},});diff --git a/apps/carbon/app/routes/x+/quote+/new.tsx b/apps/carbon/app/routes/x+/quote+/new.tsxindex bb2ffb5a73..52e421cb0e 100644--- a/apps/carbon/app/routes/x+/quote+/new.tsx+++ b/apps/carbon/app/routes/x+/quote+/new.tsx@@ -8,10 +8,17 @@ import { getNextSequence, rollbackNextSequence } from "~/modules/settings";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Quotes",+ to: path.to.quotes,+ module: "sales",+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/receipt+/$receiptId.tsx b/apps/carbon/app/routes/x+/receipt+/$receiptId.tsxindex 03a62ff678..f56c45e4de 100644--- a/apps/carbon/app/routes/x+/receipt+/$receiptId.tsx+++ b/apps/carbon/app/routes/x+/receipt+/$receiptId.tsx@@ -10,9 +10,15 @@ import {import { getNotes } from "~/modules/shared";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Receipts",+ to: path.to.receipts,+};+export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {view: "inventory",diff --git a/apps/carbon/app/routes/x+/receipt+/new.tsx b/apps/carbon/app/routes/x+/receipt+/new.tsxindex fab4fce5fd..56959c3613 100644--- a/apps/carbon/app/routes/x+/receipt+/new.tsx+++ b/apps/carbon/app/routes/x+/receipt+/new.tsx@@ -4,9 +4,15 @@ import type { ReceiptSourceDocument } from "~/modules/inventory";import { getUserDefaults } from "~/modules/users/users.server";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Receipts",+ to: path.to.receipts,+};+export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {create: "inventory",diff --git a/apps/carbon/app/routes/x+/sales-order+/new.tsx b/apps/carbon/app/routes/x+/sales-order+/new.tsxindex c0930a5843..51de39e08d 100644--- a/apps/carbon/app/routes/x+/sales-order+/new.tsx+++ b/apps/carbon/app/routes/x+/sales-order+/new.tsx@@ -13,10 +13,16 @@ import { getNextSequence, rollbackNextSequence } from "~/modules/settings";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Orders",+ to: path.to.salesOrders,+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/sales-rfq+/new.tsx b/apps/carbon/app/routes/x+/sales-rfq+/new.tsxindex a14dc0410f..d03a50baec 100644--- a/apps/carbon/app/routes/x+/sales-rfq+/new.tsx+++ b/apps/carbon/app/routes/x+/sales-rfq+/new.tsx@@ -13,10 +13,16 @@ import { getNextSequence, rollbackNextSequence } from "~/modules/settings";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "RFQs",+ to: path.to.salesRfqs,+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/supplier+/new.tsx b/apps/carbon/app/routes/x+/supplier+/new.tsxindex f8670a0d29..74165a49be 100644--- a/apps/carbon/app/routes/x+/supplier+/new.tsx+++ b/apps/carbon/app/routes/x+/supplier+/new.tsx@@ -9,10 +9,17 @@ import {import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Suppliers",+ to: path.to.suppliers,+ module: "purchasing",+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/apps/carbon/app/routes/x+/tool+/new.tsx b/apps/carbon/app/routes/x+/tool+/new.tsxindex a041301151..fc7c2411cc 100644--- a/apps/carbon/app/routes/x+/tool+/new.tsx+++ b/apps/carbon/app/routes/x+/tool+/new.tsx@@ -5,10 +5,17 @@ import { ToolForm, toolValidator, upsertTool } from "~/modules/items";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error } from "~/utils/result";+export const handle: Handle = {+ breadcrumb: "Tools",+ to: path.to.tools,+ module: "items",+};+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex a75729d553..c7bf761d37 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -25653,6 +25653,7 @@ export type Database = {itemReadableId: stringitemType: stringquantity: number+ unitCost: numbermethodType: Database["public"]["Enums"]["methodType"]parentMaterialId: stringorder: numberdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex a75729d553..c7bf761d37 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -25653,6 +25653,7 @@ export type Database = {itemReadableId: stringitemType: stringquantity: number+ unitCost: numbermethodType: Database["public"]["Enums"]["methodType"]parentMaterialId: stringorder: numberdiff --git a/packages/database/supabase/migrations/20240802010740_add-unit-cost-to-quote-methods.sql b/packages/database/supabase/migrations/20240802010740_add-unit-cost-to-quote-methods.sqlnew file mode 100644index 0000000000..ee06ec54c5--- /dev/null+++ b/packages/database/supabase/migrations/20240802010740_add-unit-cost-to-quote-methods.sql@@ -0,0 +1,77 @@+DROP FUNCTION get_quote_methods(text);+CREATE OR REPLACE FUNCTION get_quote_methods(qid TEXT)+RETURNS TABLE (+ "quoteId" TEXT,+ "quoteLineId" TEXT,+ "methodMaterialId" TEXT,+ "quoteMakeMethodId" TEXT,+ "quoteMaterialMakeMethodId" TEXT,+ "itemId" TEXT,+ "itemReadableId" TEXT,+ "itemType" TEXT,+ "quantity" NUMERIC,+ "unitCost" NUMERIC,+ "methodType" "methodType",+ "parentMaterialId" TEXT,+ "order" DOUBLE PRECISION,+ "isRoot" BOOLEAN+) AS $$+WITH RECURSIVE material AS (+ SELECT+ "quoteId",+ "quoteLineId",+ "id",+ "id" AS "quoteMakeMethodId",+ 'Make'::"methodType" AS "methodType",+ "id" AS "quoteMaterialMakeMethodId",+ "itemId",+ 'Part' AS "itemType",+ 1::NUMERIC(10,4) AS "quantity",+ 0::NUMERIC(10,4) AS "unitCost",+ "parentMaterialId",+ CAST(1 AS DOUBLE PRECISION) AS "order",+ TRUE AS "isRoot"+ FROM+ "quoteMakeMethod"+ WHERE+ "quoteId" = qid+ AND "parentMaterialId" IS NULL+ UNION+ SELECT+ child."quoteId",+ child."quoteLineId",+ child."id",+ child."quoteMakeMethodId",+ child."methodType",+ child."quoteMaterialMakeMethodId",+ child."itemId",+ child."itemType",+ child."quantity",+ child."unitCost",+ parent."id" AS "parentMaterialId",+ child."order",+ FALSE AS "isRoot"+ FROM+ "quoteMaterialWithMakeMethodId" child+ INNER JOIN material parent ON parent."quoteMaterialMakeMethodId" = child."quoteMakeMethodId"+)+SELECT+ material."quoteId",+ material."quoteLineId",+ material.id as "methodMaterialId",+ material."quoteMakeMethodId",+ material."quoteMaterialMakeMethodId",+ material."itemId",+ item."readableId" AS "itemReadableId",+ material."itemType",+ material."quantity",+ material."unitCost",+ material."methodType",+ material."parentMaterialId",+ material."order",+ material."isRoot"+FROM material+INNER JOIN item ON material."itemId" = item.id+WHERE material."quoteId" = qid+ORDER BY "order"+$$ LANGUAGE sql STABLE;\ No newline at end of file