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
- comments fixes and improvements
Gaurav Bhatt9cec6d722798
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsxindex 91d772fedd..4426aee469 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx@@ -14,6 +14,7 @@ import {ModalCardHeader,ModalCardProvider,ModalCardTitle,+ useMount,VStack} from "@carbon/react";import { getItemReadableId } from "@carbon/utils";@@ -40,9 +41,11 @@ import {} from "~/hooks";import type { PurchaseInvoice } from "~/modules/invoicing";import { purchaseInvoiceLineValidator } from "~/modules/invoicing";+import { getSupplierPartPriceBreaks } from "~/modules/items";import type { MethodItemType } from "~/modules/shared";import { useItems } from "~/stores";import { path } from "~/utils/path";+import { resolveSupplierPrice } from "~/utils/pricing";type PurchaseInvoiceLineFormProps = {initialValues: z.infer<typeof purchaseInvoiceLineValidator> & {@@ -91,6 +94,8 @@ const PurchaseInvoiceLineForm = ({minimumOrderQuantity?: number;taxAmount: number;taxPercent: number;+ priceBreaks: Array<{ quantity: number; unitPrice: number }>;+ fallbackUnitPrice: number;}>({itemId: initialValues.itemId ?? "",description: initialValues.description ?? "",@@ -103,7 +108,9 @@ const PurchaseInvoiceLineForm = ({shelfId: initialValues.shelfId ?? "",minimumOrderQuantity: undefined,taxAmount: initialValues.supplierTaxAmount ?? 0,- taxPercent: initialValues.taxPercent ?? 0+ taxPercent: initialValues.taxPercent ?? 0,+ priceBreaks: [],+ fallbackUnitPrice: initialValues.supplierUnitPrice ?? 0});// update tax amount when quantity or unit price changes@@ -125,6 +132,32 @@ const PurchaseInvoiceLineForm = ({]);const isEditing = initialValues.id !== undefined;++ // Load price breaks+ useMount(() => {+ if (!isEditing || !initialValues.itemId) return;+ const supplierId = routeData?.purchaseInvoice?.supplierId;+ if (!supplierId) return;++ (async () => {+ const supplierPart = await carbon+ .from("supplierPart")+ .select("id")+ .eq("itemId", initialValues.itemId!)+ .eq("companyId", company.id)+ .eq("supplierId", supplierId)+ .maybeSingle();++ if (supplierPart?.data?.id) {+ const breaks = await getSupplierPartPriceBreaks(+ carbon,+ supplierPart.data.id+ );+ setItemData((d) => ({ ...d, priceBreaks: breaks }));+ }+ })();+ });+const isDisabled = !isEditable? true: isEditing@@ -149,7 +182,9 @@ const PurchaseInvoiceLineForm = ({shelfId: "",minimumOrderQuantity: undefined,taxAmount: 0,- taxPercent: 0+ taxPercent: 0,+ priceBreaks: [],+ fallbackUnitPrice: 0});};@@ -189,14 +224,27 @@ const PurchaseInvoiceLineForm = ({const itemCost = item?.data?.itemCost?.[0];const itemReplenishment = item?.data?.itemReplenishment;+ const exchangeRate = routeData?.purchaseInvoice?.exchangeRate ?? 1;+ const initialQty = supplierPart?.data?.minimumOrderQuantity ?? 1;+ const baseFallback =+ (supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0) /+ exchangeRate;++ const breaks = supplierPart?.data?.id+ ? await getSupplierPartPriceBreaks(carbon, supplierPart.data.id)+ : [];+ const resolvedPrice = resolveSupplierPrice(+ breaks,+ initialQty,+ baseFallback,+ exchangeRate+ );setItemData({itemId: itemId,description: item.data?.name ?? "",- quantity: supplierPart?.data?.minimumOrderQuantity ?? 1,- supplierUnitPrice:- (supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0) /- (routeData?.purchaseInvoice?.exchangeRate ?? 1),+ quantity: initialQty,+ supplierUnitPrice: resolvedPrice,supplierShippingCost: 0,purchaseUom:supplierPart?.data?.supplierUnitOfMeasureCode ??@@ -210,7 +258,9 @@ const PurchaseInvoiceLineForm = ({1,shelfId: inventory.data?.defaultShelfId ?? null,taxAmount: 0,- taxPercent: 0+ taxPercent: 0,+ priceBreaks: breaks,+ fallbackUnitPrice: baseFallback});if (item.data?.type) {@@ -357,9 +407,17 @@ const PurchaseInvoiceLineForm = ({label="Quantity"value={itemData.quantity}onChange={(value) => {+ const exchangeRate =+ routeData?.purchaseInvoice?.exchangeRate ?? 1;setItemData((d) => ({...d,- quantity: value+ quantity: value,+ supplierUnitPrice: resolveSupplierPrice(+ d.priceBreaks,+ value,+ d.fallbackUnitPrice,+ exchangeRate+ )}));}}/>diff --git a/apps/erp/app/modules/items/index.ts b/apps/erp/app/modules/items/index.tsindex 7a8d32da13..5c4a021c1b 100644--- a/apps/erp/app/modules/items/index.ts+++ b/apps/erp/app/modules/items/index.ts@@ -1,3 +1,4 @@export * from "./items.models";+export * from "./items.pricing";export * from "./items.service";export * from "./types";diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex 2473c3a2ce..b8fd191322 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -58,6 +58,12 @@ export const partManufacturingPolicies = [export const serviceType = ["Internal", "External"] as const;+export const supplierPartPriceSourceTypes = [+ "Quote",+ "Purchase Order",+ "Manual Entry"+] as const;+export const itemValidator = z.object({id: z.string().min(1, { message: "Item ID is required" }).max(255),readableId: zfd.text(z.string().optional()),@@ -526,10 +532,7 @@ export const supplierPartValidator = z.object({supplierUnitOfMeasureCode: zfd.text(z.string().optional()),minimumOrderQuantity: zfd.numeric(z.number().min(0)),conversionFactor: zfd.numeric(z.number().min(0)),- unitPrice: zfd.numeric(z.number().min(0).optional()),- lastPurchaseDate: z.string().optional(),- lastPOQuantity: zfd.numeric(z.number().min(0).optional()),- lastPOId: z.string().optional()+ unitPrice: zfd.numeric(z.number().min(0).optional())});export const toolValidator = itemValidator.merge(diff --git a/apps/erp/app/modules/items/items.pricing.ts b/apps/erp/app/modules/items/items.pricing.tsnew file mode 100644index 0000000000..c238182d69--- /dev/null+++ b/apps/erp/app/modules/items/items.pricing.ts@@ -0,0 +1,104 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import {+ lookupBuyPriceFromMap,+ type PriceBreak,+ type SupplierPriceMap+} from "~/utils/pricing";++/**+ * Batch pre-fetch supplier price breaks for multiple items.+ * Builds a SupplierPriceMap keyed by itemId, pooling price break+ * tiers from ALL suppliers for each item.+ *+ * Used by the quote loader to pre-load pricing data for BOM costing.+ */+export async function getSupplierPriceBreaksForItems(+ client: SupabaseClient<Database>,+ itemIds: string[]+): Promise<SupplierPriceMap> {+ if (!itemIds.length) return {};++ const supplierParts = await client+ .from("supplierPart")+ .select("id, itemId, unitPrice")+ .in("itemId", itemIds);++ if (!supplierParts.data?.length) return {};++ const supplierPartIds = supplierParts.data.map((sp) => sp.id);++ const prices = await client+ .from("supplierPartPrice")+ .select("supplierPartId, quantity, unitPrice")+ .in("supplierPartId", supplierPartIds)+ .order("quantity", { ascending: true });++ // Build a lookup from supplierPartId → itemId+ const spToItem = new Map<string, string>();+ for (const sp of supplierParts.data) {+ spToItem.set(sp.id, sp.itemId);+ }++ const result: SupplierPriceMap = {};++ // Initialize entries with fallback prices+ for (const sp of supplierParts.data) {+ if (!result[sp.itemId]) {+ result[sp.itemId] = { priceBreaks: [], fallbackUnitPrice: null };+ }+ const current = result[sp.itemId].fallbackUnitPrice;+ if (sp.unitPrice != null && (current === null || sp.unitPrice < current)) {+ result[sp.itemId].fallbackUnitPrice = sp.unitPrice;+ }+ }++ // Add price breaks+ for (const price of prices.data ?? []) {+ const itemId = spToItem.get(price.supplierPartId);+ if (itemId && result[itemId]) {+ result[itemId].priceBreaks.push({+ quantity: price.quantity,+ unitPrice: price.unitPrice+ });+ }+ }++ return result;+}++/**+ * Async price lookup across ALL suppliers for an item.+ * Delegates to getSupplierPriceBreaksForItems + lookupBuyPriceFromMap.+ *+ * Used in quote creation where the specific supplier isn't known.+ */+export async function lookupBuyPrice(+ client: SupabaseClient<Database>,+ itemId: string,+ qty: number,+ fallbackCost: number+): Promise<number> {+ const map = await getSupplierPriceBreaksForItems(client, [itemId]);+ return lookupBuyPriceFromMap(itemId, qty, map, fallbackCost);+}++/**+ * Fetch price breaks array for a specific supplier part.+ * Used by PO and Invoice forms to cache breaks in state.+ */+export async function getSupplierPartPriceBreaks(+ client: SupabaseClient<Database>,+ supplierPartId: string+): Promise<PriceBreak[]> {+ const result = await client+ .from("supplierPartPrice")+ .select("quantity, unitPrice")+ .eq("supplierPartId", supplierPartId)+ .order("quantity", { ascending: true });++ return (result.data ?? []).map((pb) => ({+ quantity: pb.quantity,+ unitPrice: pb.unitPrice+ }));+}diff --git a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsxindex d77d79faa6..c5796641ce 100644--- a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx@@ -1,20 +1,47 @@-import { useCarbon } from "@carbon/auth";import { ValidatedForm } from "@carbon/form";import {Button,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,Drawer,DrawerBody,DrawerContent,DrawerFooter,DrawerHeader,DrawerTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuIcon,+ DropdownMenuItem,+ DropdownMenuTrigger,HStack,+ IconButton,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr,toast,VStack} from "@carbon/react";-import { useEffect, useState } from "react";-import { useFetcher, useParams } from "react-router";+import {+ Carousel,+ CarouselContent,+ CarouselItem,+ CarouselNext,+ CarouselPrevious+} from "@carbon/react/Carousel";+import { formatDate } from "@carbon/utils";+import type { ColumnDef } from "@tanstack/react-table";+import { useCallback, useEffect, useMemo, useState } from "react";+import { LuEllipsisVertical, LuTrash } from "react-icons/lu";+import { Link, useFetcher, useParams } from "react-router";import type { z } from "zod";+import { EditableNumber } from "~/components/Editable";import {ConversionFactor,CustomFormFields,@@ -26,14 +53,42 @@ import {Supplier,UnitOfMeasure} from "~/components/Form";+import Grid from "~/components/Grid";import { useCurrencyFormatter, usePermissions, useUser } from "~/hooks";import { path } from "~/utils/path";import { supplierPartValidator } from "../../items.models";+type PriceBreak = {+ quantity: number;+ unitPrice: number;+ sourceType: string;+ sourceDocumentId: string | null;+ createdAt: string;+};++type PriceBreakRow = {+ quantity: number;+ unitPrice: number;+};++type PurchaseHistoryItem = {+ id: string;+ purchaseQuantity: number | null;+ unitPrice: number | null;+ purchaseOrderId: string;+ purchaseOrder: {+ purchaseOrderId: string;+ supplierId: string;+ orderDate: string | null;+ };+};+type SupplierPartFormProps = {initialValues: z.infer<typeof supplierPartValidator>;type: "Part" | "Service" | "Tool" | "Consumable" | "Material";unitOfMeasureCode: string;+ priceBreaks?: PriceBreak[];+ purchasingHistory?: PurchaseHistoryItem[];onClose: () => void;};@@ -41,11 +96,11 @@ const SupplierPartForm = ({initialValues,type,unitOfMeasureCode,+ priceBreaks: initialPriceBreaks = [],+ purchasingHistory = [],onClose}: SupplierPartFormProps) => {- const { carbon } = useCarbon();const permissions = usePermissions();- const formatter = useCurrencyFormatter();const { company } = useUser();const baseCurrency = company?.baseCurrencyCode ?? "USD";@@ -60,6 +115,13 @@ const SupplierPartForm = ({string | undefined>(initialValues.supplierUnitOfMeasureCode);+ const [priceBreaks, setPriceBreaks] = useState<PriceBreakRow[]>(+ initialPriceBreaks.map((pb) => ({+ quantity: pb.quantity,+ unitPrice: pb.unitPrice+ }))+ );+const isEditing = initialValues.id !== undefined;const isDisabled = isEditing? !permissions.can("update", "parts")@@ -68,29 +130,6 @@ const SupplierPartForm = ({const action = getAction(isEditing, type, itemId, initialValues.id);const fetcher = useFetcher<{ success: boolean; message: string }>();- // Fetch price breaks for existing supplier parts- const [priceBreaks, setPriceBreaks] = useState<- {- quantity: number;- unitPrice: number;- leadTime: number | null;- sourceType: string;- }[]- >([]);-- useEffect(() => {- if (!carbon || !isEditing || !initialValues.id) return;-- carbon- .from("supplierPartPrice")- .select("quantity, unitPrice, leadTime, sourceType")- .eq("supplierPartId", initialValues.id)- .order("quantity", { ascending: true })- .then(({ data }) => {- if (data?.length) setPriceBreaks(data);- });- }, [carbon, isEditing, initialValues.id]);-useEffect(() => {if (fetcher.data?.success) {onClose();@@ -123,6 +162,7 @@ const SupplierPartForm = ({<DrawerBody><Hidden name="id" /><Hidden name="itemId" />+ <Hidden name="priceBreaks" value={JSON.stringify(priceBreaks)} /><VStack spacing={4}><Supplier name="supplierId" label="Supplier" />@@ -136,64 +176,6 @@ const SupplierPartForm = ({currency: baseCurrency}}/>- {/* last purchase info (read-only) */}- {initialValues.lastPurchaseDate && (- <div className="text-sm text-muted-foreground bg-muted/50 rounded-md p-3 space-y-1">- <div className="font-medium text-foreground">- Last Purchase Info- </div>- <div>- Date:{" "}- {new Date(- initialValues.lastPurchaseDate- ).toLocaleDateString()}- </div>- {initialValues.lastPOQuantity != null && (- <div>- Quantity: {initialValues.lastPOQuantity.toLocaleString()}- </div>- )}- </div>- )}- {/* Show quantity price breaks if available */}- {priceBreaks.length > 0 && (- <div className="text-sm bg-muted/50 rounded-md p-3 space-y-2 w-full">- <div className="font-medium text-foreground">- Price Breaks- </div>- <table className="w-full text-sm">- <thead>- <tr className="text-muted-foreground border-b">- <th className="text-left py-1">Qty</th>- <th className="text-right py-1">Unit Price</th>- <th className="text-right py-1">Lead Time</th>- <th className="text-right py-1">Source</th>- </tr>- </thead>- <tbody>- {priceBreaks.map((pb) => (- <tr- key={pb.quantity}- className="border-b last:border-0"- >- <td className="py-1">- {pb.quantity.toLocaleString()}- </td>- <td className="text-right py-1">- {formatter.format(pb.unitPrice)}- </td>- <td className="text-right py-1">- {pb.leadTime != null ? `${pb.leadTime}d` : "—"}- </td>- <td className="text-right py-1 text-muted-foreground">- {pb.sourceType}- </td>- </tr>- ))}- </tbody>- </table>- </div>- )}<UnitOfMeasurename="supplierUnitOfMeasureCode"label="Unit of Measure"@@ -213,6 +195,16 @@ const SupplierPartForm = ({minValue={0}/><CustomFormFields table="partSupplier" />+ <PriceBreaks+ priceBreaks={priceBreaks}+ onChange={setPriceBreaks}+ baseCurrency={baseCurrency}+ isDisabled={isDisabled}+ />+ <PurchaseHistory+ history={purchasingHistory}+ baseCurrency={baseCurrency}+ /></VStack></DrawerBody><DrawerFooter>@@ -235,6 +227,197 @@ const SupplierPartForm = ({);};+function PurchaseHistory({+ history,+ baseCurrency+}: {+ history: PurchaseHistoryItem[];+ baseCurrency: string;+}) {+ if (history.length === 0) return null;++ return (+ <Card>+ <CardHeader>+ <CardTitle>Purchase History</CardTitle>+ <CardDescription>+ <span className="text-sm text-muted-foreground">+ {history.length} order{history.length !== 1 ? "s" : ""}+ </span>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Carousel className="w-full">+ <CarouselContent className="-ml-4">+ {history.map((line) => (+ <CarouselItem+ key={line.id}+ className="pl-4 basis-full lg:basis-1/2"+ >+ <Card className="w-full p-0">+ <CardContent className="p-4">+ <HStack className="flex justify-between">+ <Link+ to={path.to.purchaseOrder(line.purchaseOrderId)}+ className="text-sm font-medium hover:underline"+ >+ {line.purchaseOrder.purchaseOrderId}+ </Link>+ <span className="text-xs text-muted-foreground">+ {line.purchaseOrder.orderDate+ ? formatDate(line.purchaseOrder.orderDate)+ : "—"}+ </span>+ </HStack>+ <div className="my-4">+ <Table>+ <Thead>+ <Tr className="border-b border-border">+ <Th>+ <span className="font-medium">Quantity</span>+ </Th>+ <Th>+ <span className="font-medium">Price</span>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ <Tr>+ <Td>{line.purchaseQuantity}</Td>+ <Td>+ {new Intl.NumberFormat("en-US", {+ style: "currency",+ currency: baseCurrency+ }).format(line.unitPrice ?? 0)}+ </Td>+ </Tr>+ </Tbody>+ </Table>+ </div>+ </CardContent>+ </Card>+ </CarouselItem>+ ))}+ </CarouselContent>+ {history.length > 1 && (+ <div className="flex justify-between mt-4">+ <CarouselPrevious />+ <CarouselNext />+ </div>+ )}+ </Carousel>+ </CardContent>+ </Card>+ );+}++function PriceBreaks({+ priceBreaks,+ onChange,+ baseCurrency,+ isDisabled+}: {+ priceBreaks: PriceBreakRow[];+ onChange: React.Dispatch<React.SetStateAction<PriceBreakRow[]>>;+ baseCurrency: string;+ isDisabled: boolean;+}) {+ const formatter = useCurrencyFormatter();++ const removeRow = useCallback(+ (index: number) => {+ onChange((prev) => prev.filter((_, i) => i !== index));+ },+ [onChange]+ );++ const addRow = useCallback(() => {+ onChange((prev) => [...prev, { quantity: 0, unitPrice: 0 }]);+ }, [onChange]);++ const noOpMutation = useCallback(+ async (_accessorKey: string, _newValue: unknown, _row: PriceBreakRow) =>+ ({+ data: null,+ error: null,+ count: null,+ status: 200,+ statusText: "OK"+ }) as const,+ []+ );++ const editableComponents = useMemo(+ () => ({+ quantity: EditableNumber(noOpMutation),+ unitPrice: EditableNumber(noOpMutation, {+ formatOptions: { style: "currency", currency: baseCurrency }+ })+ }),+ [noOpMutation, baseCurrency]+ );++ const columns = useMemo<ColumnDef<PriceBreakRow>[]>(+ () => [+ {+ accessorKey: "quantity",+ header: "Quantity",+ cell: ({ row }) => (+ <HStack className="justify-between min-w-[80px]">+ <span>{row.original.quantity}</span>+ {!isDisabled && (+ <div className="relative w-6 h-5">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="Price break actions"+ icon={<LuEllipsisVertical />}+ size="md"+ className="absolute right-[-1px] top-[-6px]"+ variant="ghost"+ onClick={(e) => e.stopPropagation()}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem+ onClick={() => removeRow(row.index)}+ destructive+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ Delete Price Break+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ )}+ </HStack>+ )+ },+ {+ accessorKey: "unitPrice",+ header: "Unit Price",+ cell: ({ row }) => formatter.format(row.original.unitPrice)+ }+ ],+ [isDisabled, removeRow, formatter]+ );++ return (+ <div className="space-y-3 w-full">+ <span className="font-medium text-sm">Price Breaks</span>+ <Grid<PriceBreakRow>+ data={priceBreaks}+ columns={columns}+ canEdit={!isDisabled}+ editableComponents={editableComponents}+ onDataChange={onChange}+ onNewRow={!isDisabled ? addRow : undefined}+ contained={false}+ />+ </div>+ );+}+export default SupplierPartForm;function getAction(diff --git a/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsx b/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsxindex b030ecf8e8..35bd5e74c6 100644--- a/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsx+++ b/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsx@@ -19,8 +19,6 @@ type Part = Pick<| "minimumOrderQuantity"| "conversionFactor"| "customFields"- | "lastPurchaseDate"- | "lastPOQuantity">;type SupplierPartsProps = {@@ -63,24 +61,6 @@ const SupplierParts = ({renderTotal: true}},- {- accessorKey: "lastPurchaseDate",- header: "Last Purchase",- cell: (item) => {- const date = item.getValue<string>();- if (!date) return "—";- return new Date(date).toLocaleDateString();- }- },- {- accessorKey: "lastPOQuantity",- header: "Last PO Qty",- cell: (item) => {- const qty = item.getValue<number>();- if (qty == null) return "—";- return qty.toLocaleString();- }- },{accessorKey: "supplierUnitOfMeasureCode",header: "Unit of Measure",diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsxindex 8f9d1ed105..1f4faa4ca0 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx@@ -41,6 +41,7 @@ import {useRouteData,useUser} from "~/hooks";+import { getSupplierPartPriceBreaks } from "~/modules/items";import type { PurchaseOrder, PurchaseOrderLine } from "~/modules/purchasing";import {isPurchaseOrderLocked,@@ -50,6 +51,7 @@ import type { MethodItemType } from "~/modules/shared";import type { action } from "~/routes/x+/purchase-order+/$orderId.$lineId.details";import { useItems } from "~/stores";import { path } from "~/utils/path";+import { resolveSupplierPrice } from "~/utils/pricing";import DeletePurchaseOrderLine from "./DeletePurchaseOrderLine";type PurchaseOrderLineFormProps = {@@ -98,6 +100,8 @@ const PurchaseOrderLineForm = ({minimumOrderQuantity?: number;supplierTaxAmount: number;taxPercent: number;+ priceBreaks: Array<{ quantity: number; unitPrice: number }>;+ fallbackUnitPrice: number;}>({itemId: initialValues.itemId ?? "",description: initialValues.description ?? "",@@ -119,7 +123,9 @@ const PurchaseOrderLineForm = ({((initialValues.supplierUnitPrice ?? 0) *(initialValues.purchaseQuantity ?? 1) +(initialValues.supplierShippingCost ?? 0))- : 0+ : 0,+ priceBreaks: [],+ fallbackUnitPrice: initialValues.supplierUnitPrice ?? 0});// update tax amount when quantity or unit price changes@@ -141,6 +147,32 @@ const PurchaseOrderLineForm = ({]);const isEditing = initialValues.id !== undefined;++ // Load price breaks on mount when editing so quantity changes resolve correctly+ useMount(() => {+ if (!isEditing || !initialValues.itemId) return;+ const supplierId = routeData?.purchaseOrder?.supplierId;+ if (!supplierId) return;++ (async () => {+ const supplierPart = await carbon+ .from("supplierPart")+ .select("id")+ .eq("itemId", initialValues.itemId!)+ .eq("companyId", company.id)+ .eq("supplierId", supplierId)+ .maybeSingle();++ if (supplierPart?.data?.id) {+ const breaks = await getSupplierPartPriceBreaks(+ carbon,+ supplierPart.data.id+ );+ setItemData((d) => ({ ...d, priceBreaks: breaks }));+ }+ })();+ });+const isDisabled = isClosed? true: isEditing@@ -168,7 +200,9 @@ const PurchaseOrderLineForm = ({shelfId: "",minimumOrderQuantity: undefined,supplierTaxAmount: 0,- taxPercent: 0+ taxPercent: 0,+ priceBreaks: [],+ fallbackUnitPrice: 0});};@@ -208,14 +242,27 @@ const PurchaseOrderLineForm = ({const itemCost = item?.data?.itemCost?.[0];const itemReplenishment = item?.data?.itemReplenishment;+ const exchangeRate = routeData?.purchaseOrder?.exchangeRate ?? 1;+ const initialQty = supplierPart?.data?.minimumOrderQuantity ?? 1;+ const baseFallback =+ (supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0) /+ exchangeRate;++ const breaks = supplierPart?.data?.id+ ? await getSupplierPartPriceBreaks(carbon, supplierPart.data.id)+ : [];+ const resolvedPrice = resolveSupplierPrice(+ breaks,+ initialQty,+ baseFallback,+ exchangeRate+ );setItemData({itemId: itemId,description: item.data?.name ?? "",- purchaseQuantity: supplierPart?.data?.minimumOrderQuantity ?? 1,- supplierUnitPrice:- (supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0) /- (routeData?.purchaseOrder?.exchangeRate ?? 1),+ purchaseQuantity: initialQty,+ supplierUnitPrice: resolvedPrice,supplierShippingCost: 0,purchaseUom:supplierPart?.data?.supplierUnitOfMeasureCode ??@@ -229,7 +276,9 @@ const PurchaseOrderLineForm = ({1,shelfId: inventory.data?.defaultShelfId ?? null,supplierTaxAmount: 0,- taxPercent: 0+ taxPercent: 0,+ priceBreaks: breaks,+ fallbackUnitPrice: baseFallback});if (item.data?.type) {@@ -382,9 +431,17 @@ const PurchaseOrderLineForm = ({label="Quantity"value={itemData.purchaseQuantity}onChange={(value) => {+ const exchangeRate =+ routeData?.purchaseOrder?.exchangeRate ?? 1;setItemData((d) => ({...d,- purchaseQuantity: value+ purchaseQuantity: value,+ supplierUnitPrice: resolveSupplierPrice(+ d.priceBreaks,+ value,+ d.fallbackUnitPrice,+ exchangeRate+ )}));}}/>diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsxindex 035a132eec..b7aea0f97e 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx@@ -65,6 +65,7 @@ import type {} from "~/components/SortableList";import { SortableList, SortableListItem } from "~/components/SortableList";import { usePermissions, useRouteData, useUrlParams, useUser } from "~/hooks";+import { lookupBuyPrice as lookupBuyPriceAsync } from "~/modules/items";import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";import type { MethodItemType, MethodType } from "~/modules/shared";import type { Item as ItemType } from "~/stores";@@ -687,41 +688,10 @@ function MaterialForm({});};- const lookupBuyPrice = useCallback(+ const lookupBuyPriceFn = useCallback(async (itemId: string, qty: number, fallbackCost: number) => {if (!carbon) return fallbackCost;-- const supplierParts = await carbon- .from("supplierPart")- .select("id, unitPrice")- .eq("itemId", itemId);-- if (!supplierParts.data?.length) return fallbackCost;-- const supplierPartIds = supplierParts.data.map((sp) => sp.id);-- const priceBreak = await carbon- .from("supplierPartPrice")- .select("unitPrice")- .in("supplierPartId", supplierPartIds)- .lte("quantity", qty)- .order("unitPrice", { ascending: true })- .limit(1)- .single();-- if (priceBreak.data?.unitPrice != null) {- return priceBreak.data.unitPrice;- }-- const lowestSupplierPrice = supplierParts.data- .filter((sp) => sp.unitPrice != null)- .sort((a, b) => (a.unitPrice ?? 0) - (b.unitPrice ?? 0))[0];-- if (lowestSupplierPrice?.unitPrice != null) {- return lowestSupplierPrice.unitPrice;- }-- return fallbackCost;+ return lookupBuyPriceAsync(carbon, itemId, qty, fallbackCost);},[carbon]);@@ -754,7 +724,11 @@ function MaterialForm({const isBuyPart = item.data?.defaultMethodType === "Buy";if (isBuyPart) {- unitCost = await lookupBuyPrice(itemId, itemData.quantity ?? 1, unitCost);+ unitCost = await lookupBuyPriceFn(+ itemId,+ itemData.quantity ?? 1,+ unitCost+ );}setItemData((d) => ({@@ -787,7 +761,7 @@ function MaterialForm({.single();const fallbackCost = itemCost.data?.unitCost ?? 0;- const unitCost = await lookupBuyPrice(+ const unitCost = await lookupBuyPriceFn(itemData.itemId,newQty,fallbackCost@@ -795,7 +769,7 @@ function MaterialForm({setItemData((d) => ({ ...d, unitCost }));},- [carbon, itemData.methodType, itemData.itemId, lookupBuyPrice]+ [carbon, itemData.methodType, itemData.itemId, lookupBuyPriceFn]);const sourceDisclosure = useDisclosure();diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsxindex 59d85b7dd8..1a6f304608 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx@@ -67,7 +67,7 @@ const QuoteLinePricing = ({}) => {const permissions = usePermissions();- const isMade = line.methodType === "Make";+ const hasCalculatedCost = line.methodType !== "Pick";const quantities = line.quantity ?? [1];const { quoteId, lineId } = useParams();@@ -513,7 +513,7 @@ const QuoteLinePricing = ({})}</Tr>{isEmployee && (- <Tr className={cn(isMade && "[&>td]:bg-muted/60")}>+ <Tr className={cn(hasCalculatedCost && "[&>td]:bg-muted/60")}><Td className="border-r border-border group-hover:bg-muted/50"><HStack className="w-full justify-between "><span>Unit Cost</span>@@ -521,7 +521,7 @@ const QuoteLinePricing = ({</Td>{unitCostsByQuantity.map((cost, index) => {- return isMade ? (+ return hasCalculatedCost ? (<Td key={index} className="group-hover:bg-muted/50"><VStack spacing={0}><span>diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsxindex 0b12d98807..e2f3de2e9e 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx@@ -26,6 +26,7 @@ import {UnitOfMeasure} from "~/components/Form";import { usePermissions, useUrlParams } from "~/hooks";+import { lookupBuyPrice as lookupBuyPriceAsync } from "~/modules/items";import type { MethodItemType, MethodType } from "~/modules/shared";import { useItems } from "~/stores";import { path } from "~/utils/path";@@ -88,39 +89,7 @@ const QuoteMaterialForm = ({const lookupBuyPrice = useCallback(async (itemId: string, qty: number, fallbackCost: number) => {- if (!carbon) return fallbackCost;-- const supplierParts = await carbon- .from("supplierPart")- .select("id, unitPrice")- .eq("itemId", itemId);-- if (!supplierParts.data?.length) return fallbackCost;-- const supplierPartIds = supplierParts.data.map((sp) => sp.id);-- const priceBreak = await carbon- .from("supplierPartPrice")- .select("unitPrice")- .in("supplierPartId", supplierPartIds)- .lte("quantity", qty)- .order("unitPrice", { ascending: true })- .limit(1)- .single();-- if (priceBreak.data?.unitPrice != null) {- return priceBreak.data.unitPrice;- }-- const lowestSupplierPrice = supplierParts.data- .filter((sp) => sp.unitPrice != null)- .sort((a, b) => (a.unitPrice ?? 0) - (b.unitPrice ?? 0))[0];-- if (lowestSupplierPrice?.unitPrice != null) {- return lowestSupplierPrice.unitPrice;- }-- return fallbackCost;+ return lookupBuyPriceAsync(carbon, itemId, qty, fallbackCost);},[carbon]);diff --git a/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx b/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsxindex 5ca38a52fc..6357d171ba 100644--- a/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx@@ -1,6 +1,7 @@import { useCallback, useMemo } from "react";import { useParams } from "react-router";import type { Tree } from "~/components/TreeView";+import { lookupBuyPriceFromMap, type SupplierPriceMap } from "~/utils/pricing";import type {CostEffects,Costs,@@ -29,11 +30,13 @@ type EnhancedTree = Tree<QuoteMethod & { operations?: QuotationOperation[] }>;export function useLineCosts({methodTree: originalMethodTree,operations,- line+ line,+ supplierPriceMap = {}}: {methodTree?: Tree<QuoteMethod>;operations: QuotationOperation[];line: QuotationLine;+ supplierPriceMap?: SupplierPriceMap;}): (quantity: number) => Costs {const { quoteId, lineId } = useParams();if (!quoteId) throw new Error("Could not find quoteId");@@ -71,35 +74,74 @@ export function useLineCosts({const costEffects = useMemo<CostEffects>(() => {const effects = structuredClone(defaultEffects);+ function pushBuyCostEffect(+ itemId: string,+ itemType: string,+ quantity: number,+ unitCost: number,+ supplierPriceMap: SupplierPriceMap+ ) {+ const costFn = (outerQty: number) => {+ const requestedQty = quantity * outerQty;+ const resolved = lookupBuyPriceFromMap(+ itemId,+ requestedQty,+ supplierPriceMap,+ unitCost+ );+ return resolved * requestedQty;+ };+ switch (itemType) {+ case "Material":+ effects.materialCost.push(costFn);+ break;+ case "Part":+ effects.partCost.push(costFn);+ break;+ case "Tool":+ effects.toolCost.push(costFn);+ break;+ case "Consumable":+ effects.consumableCost.push(costFn);+ break;+ case "Service":+ effects.serviceCost.push(costFn);+ break;+ default:+ break;+ }+ }+function walkTree(tree: EnhancedTree) {const { data } = tree;- if (["Buy", "Pick"].includes(data.methodType)) {+ if (data.methodType === "Buy") {+ pushBuyCostEffect(+ data.itemId,+ data.itemType,+ data.quantity,+ data.unitCost,+ supplierPriceMap+ );+ } else if (data.methodType === "Pick") {+ // Pick items use static average cost+ const costFn = (quantity: number) =>+ data.unitCost * data.quantity * quantity;switch (data.itemType) {case "Material":- effects.materialCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );+ effects.materialCost.push(costFn);break;case "Part":- effects.partCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );+ effects.partCost.push(costFn);break;case "Tool":- effects.toolCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );+ effects.toolCost.push(costFn);break;case "Consumable":- effects.consumableCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );+ effects.consumableCost.push(costFn);break;case "Service":- effects.serviceCost.push(- (quantity) => data.unitCost * data.quantity * quantity- );+ effects.serviceCost.push(costFn);break;default:break;@@ -333,12 +375,26 @@ export function useLineCosts({if (methodTree && line.methodType === "Make") {walkTree(methodTree);+ } else if (line.methodType === "Buy") {+ pushBuyCostEffect(+ line.itemId ?? "",+ "Material",+ 1,+ line.unitCost ?? 0,+ supplierPriceMap+ );} else {effects.materialCost.push((quantity) => (line.unitCost ?? 0) * quantity);}return effects;- }, [methodTree, line.methodType, line.unitCost]);+ }, [+ methodTree,+ line.methodType,+ line.unitCost,+ line.itemId,+ supplierPriceMap+ ]);const getCosts = useCallback((quantity: number) => {diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsxindex 0de9e5985b..06eae9267f 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx@@ -19,21 +19,45 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { supplierPartId } = params;if (!supplierPartId) throw new Error("Could not find supplierPartId");- const supplierPart = await client- .from("supplierPart")- .select("*")- .eq("id", supplierPartId)- .eq("companyId", companyId)- .single();-- if (!supplierPart?.data) throw new Error("Could not find supplier part");-- return { supplierPart: supplierPart.data };+ const [supplierPartResult, priceBreaksResult] = await Promise.all([+ client+ .from("supplierPart")+ .select("*")+ .eq("id", supplierPartId)+ .eq("companyId", companyId)+ .single(),+ client+ .from("supplierPartPrice")+ .select("*")+ .eq("supplierPartId", supplierPartId)+ .order("quantity", { ascending: true })+ ]);++ if (!supplierPartResult?.data)+ throw new Error("Could not find supplier part");++ const supplierPart = supplierPartResult.data;++ const purchasingHistory = await client+ .from("purchaseOrderLine")+ .select(+ "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ )+ .eq("itemId", supplierPart.itemId)+ .eq("purchaseOrder.supplierId", supplierPart.supplierId)+ .order("createdAt", { ascending: false })+ .limit(10);++ return {+ supplierPart,+ priceBreaks: priceBreaksResult.data ?? [],+ purchasingHistory: purchasingHistory.data ?? []+ };}export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, userId, companyId } = await requirePermissions(request, {update: "parts"});@@ -42,6 +66,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!supplierPartId) throw new Error("Could not find supplierPartId");const formData = await request.formData();+const validation = await validator(supplierPartValidator).validate(formData);if (validation.error) {@@ -62,6 +87,31 @@ export async function action({ request, params }: ActionFunctionArgs) {return { success: false, message: "Failed to update supplier part" };}+ const priceBreaksRaw = formData.get("priceBreaks");+ if (priceBreaksRaw) {+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {+ quantity: number;+ unitPrice: number;+ }[];+ await client+ .from("supplierPartPrice")+ .delete()+ .eq("supplierPartId", supplierPartId);+ if (priceBreaks.length > 0) {+ await client.from("supplierPartPrice").insert(+ priceBreaks.map((pb) => ({+ supplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ );+ }+ }+throw redirect(path.to.consumablePurchasing(itemId),await flash(request, success("Supplier part updated"))@@ -70,7 +120,8 @@ export async function action({ request, params }: ActionFunctionArgs) {export default function EditConsumableSupplierRoute() {const { itemId } = useParams();- const { supplierPart } = useLoaderData<typeof loader>();+ const { supplierPart, priceBreaks, purchasingHistory } =+ useLoaderData<typeof loader>();if (!itemId) throw new Error("itemId not found");@@ -89,10 +140,7 @@ export default function EditConsumableSupplierRoute() {unitPrice: supplierPart.unitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,- conversionFactor: supplierPart.conversionFactor ?? 1,- lastPurchaseDate: supplierPart.lastPurchaseDate,- lastPOQuantity: supplierPart.lastPOQuantity,- lastPOId: supplierPart.lastPOId+ conversionFactor: supplierPart.conversionFactor ?? 1};return (@@ -100,6 +148,8 @@ export default function EditConsumableSupplierRoute() {type="Consumable"initialValues={initialValues}unitOfMeasureCode={routeData?.consumableSummary?.unitOfMeasureCode ?? ""}+ priceBreaks={priceBreaks}+ purchasingHistory={purchasingHistory}onClose={onClose}/>);diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsxindex 2244eb75eb..0d78b76d52 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx@@ -44,6 +44,28 @@ export async function action({ request, params }: ActionFunctionArgs) {};}+ const newSupplierPartId = createConsumableSupplier.data?.id;+ const priceBreaksRaw = formData.get("priceBreaks");+ if (newSupplierPartId && priceBreaksRaw) {+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {+ quantity: number;+ unitPrice: number;+ }[];+ if (priceBreaks.length > 0) {+ await client.from("supplierPartPrice").insert(+ priceBreaks.map((pb) => ({+ supplierPartId: newSupplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ );+ }+ }+throw redirect(path.to.consumablePurchasing(itemId),await flash(request, success("Consumable supplier created"))diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsxindex b3952e41b0..be74c963e0 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx@@ -19,21 +19,45 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { supplierPartId } = params;if (!supplierPartId) throw new Error("Could not find supplierPartId");- const supplierPart = await client- .from("supplierPart")- .select("*")- .eq("id", supplierPartId)- .eq("companyId", companyId)- .single();-- if (!supplierPart?.data) throw new Error("Could not find supplier part");-- return { supplierPart: supplierPart.data };+ const [supplierPartResult, priceBreaksResult] = await Promise.all([+ client+ .from("supplierPart")+ .select("*")+ .eq("id", supplierPartId)+ .eq("companyId", companyId)+ .single(),+ client+ .from("supplierPartPrice")+ .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")+ .eq("supplierPartId", supplierPartId)+ .order("quantity", { ascending: true })+ ]);++ if (!supplierPartResult?.data)+ throw new Error("Could not find supplier part");++ const supplierPart = supplierPartResult.data;++ const purchasingHistory = await client+ .from("purchaseOrderLine")+ .select(+ "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ )+ .eq("itemId", supplierPart.itemId)+ .eq("purchaseOrder.supplierId", supplierPart.supplierId)+ .order("createdAt", { ascending: false })+ .limit(10);++ return {+ supplierPart,+ priceBreaks: priceBreaksResult.data ?? [],+ purchasingHistory: purchasingHistory.data ?? []+ };}export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, userId, companyId } = await requirePermissions(request, {update: "parts"});@@ -42,6 +66,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!supplierPartId) throw new Error("Could not find supplierPartId");const formData = await request.formData();+const validation = await validator(supplierPartValidator).validate(formData);if (validation.error) {@@ -62,6 +87,31 @@ export async function action({ request, params }: ActionFunctionArgs) {return { success: false, message: "Failed to update supplier part" };}+ const priceBreaksRaw = formData.get("priceBreaks");+ if (priceBreaksRaw) {+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {+ quantity: number;+ unitPrice: number;+ }[];+ await client+ .from("supplierPartPrice")+ .delete()+ .eq("supplierPartId", supplierPartId);+ if (priceBreaks.length > 0) {+ await client.from("supplierPartPrice").insert(+ priceBreaks.map((pb) => ({+ supplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ );+ }+ }+throw redirect(path.to.materialPurchasing(itemId),await flash(request, success("Supplier part updated"))@@ -70,7 +120,8 @@ export async function action({ request, params }: ActionFunctionArgs) {export default function EditMaterialSupplierRoute() {const { itemId } = useParams();- const { supplierPart } = useLoaderData<typeof loader>();+ const { supplierPart, priceBreaks, purchasingHistory } =+ useLoaderData<typeof loader>();if (!itemId) throw new Error("itemId not found");@@ -89,10 +140,7 @@ export default function EditMaterialSupplierRoute() {unitPrice: supplierPart.unitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,- conversionFactor: supplierPart.conversionFactor ?? 1,- lastPurchaseDate: supplierPart.lastPurchaseDate,- lastPOQuantity: supplierPart.lastPOQuantity,- lastPOId: supplierPart.lastPOId+ conversionFactor: supplierPart.conversionFactor ?? 1};return (@@ -100,6 +148,8 @@ export default function EditMaterialSupplierRoute() {type="Material"initialValues={initialValues}unitOfMeasureCode={routeData?.materialSummary?.unitOfMeasureCode ?? ""}+ priceBreaks={priceBreaks}+ purchasingHistory={purchasingHistory}onClose={onClose}/>);diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsxindex 595035913d..2192c5e786 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx@@ -44,6 +44,28 @@ export async function action({ request, params }: ActionFunctionArgs) {};}+ const newSupplierPartId = createMaterialSupplier.data?.id;+ const priceBreaksRaw = formData.get("priceBreaks");+ if (newSupplierPartId && priceBreaksRaw) {+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {+ quantity: number;+ unitPrice: number;+ }[];+ if (priceBreaks.length > 0) {+ await client.from("supplierPartPrice").insert(+ priceBreaks.map((pb) => ({+ supplierPartId: newSupplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ );+ }+ }+throw redirect(path.to.materialPurchasing(itemId),await flash(request, success("Material supplier created"))diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsxindex 4fbeb2a876..147b19c16d 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx@@ -19,21 +19,45 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { supplierPartId } = params;if (!supplierPartId) throw new Error("Could not find supplierPartId");- const supplierPart = await client- .from("supplierPart")- .select("*")- .eq("id", supplierPartId)- .eq("companyId", companyId)- .single();-- if (!supplierPart?.data) throw new Error("Could not find supplier part");-- return { supplierPart: supplierPart.data };+ const [supplierPartResult, priceBreaksResult] = await Promise.all([+ client+ .from("supplierPart")+ .select("*")+ .eq("id", supplierPartId)+ .eq("companyId", companyId)+ .single(),+ client+ .from("supplierPartPrice")+ .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")+ .eq("supplierPartId", supplierPartId)+ .order("quantity", { ascending: true })+ ]);++ if (!supplierPartResult?.data)+ throw new Error("Could not find supplier part");++ const supplierPart = supplierPartResult.data;++ const purchasingHistory = await client+ .from("purchaseOrderLine")+ .select(+ "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ )+ .eq("itemId", supplierPart.itemId)+ .eq("purchaseOrder.supplierId", supplierPart.supplierId)+ .order("createdAt", { ascending: false })+ .limit(10);++ return {+ supplierPart,+ priceBreaks: priceBreaksResult.data ?? [],+ purchasingHistory: purchasingHistory.data ?? []+ };}export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, userId, companyId } = await requirePermissions(request, {update: "parts"});@@ -42,6 +66,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!supplierPartId) throw new Error("Could not find supplierPartId");const formData = await request.formData();+const validation = await validator(supplierPartValidator).validate(formData);if (validation.error) {@@ -62,6 +87,31 @@ export async function action({ request, params }: ActionFunctionArgs) {return { success: false, message: "Failed to update supplier part" };}+ const priceBreaksRaw = formData.get("priceBreaks");+ if (priceBreaksRaw) {+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {+ quantity: number;+ unitPrice: number;+ }[];+ await client+ .from("supplierPartPrice")+ .delete()+ .eq("supplierPartId", supplierPartId);+ if (priceBreaks.length > 0) {+ await client.from("supplierPartPrice").insert(+ priceBreaks.map((pb) => ({+ supplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ );+ }+ }+throw redirect(path.to.partPurchasing(itemId),await flash(request, success("Supplier part updated"))@@ -70,7 +120,8 @@ export async function action({ request, params }: ActionFunctionArgs) {export default function EditPartSupplierRoute() {const { itemId } = useParams();- const { supplierPart } = useLoaderData<typeof loader>();+ const { supplierPart, priceBreaks, purchasingHistory } =+ useLoaderData<typeof loader>();if (!itemId) throw new Error("itemId not found");@@ -89,10 +140,7 @@ export default function EditPartSupplierRoute() {unitPrice: supplierPart.unitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,- conversionFactor: supplierPart.conversionFactor ?? 1,- lastPurchaseDate: supplierPart.lastPurchaseDate,- lastPOQuantity: supplierPart.lastPOQuantity,- lastPOId: supplierPart.lastPOId+ conversionFactor: supplierPart.conversionFactor ?? 1};return (@@ -100,6 +148,8 @@ export default function EditPartSupplierRoute() {type="Part"initialValues={initialValues}unitOfMeasureCode={routeData?.partSummary?.unitOfMeasureCode ?? ""}+ priceBreaks={priceBreaks}+ purchasingHistory={purchasingHistory}onClose={onClose}/>);diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsxindex acd5871f1d..95fb1fdf49 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx@@ -47,6 +47,28 @@ export async function action({ request, params }: ActionFunctionArgs) {};}+ const newSupplierPartId = createPartSupplier.data?.id;+ const priceBreaksRaw = formData.get("priceBreaks");+ if (newSupplierPartId && priceBreaksRaw) {+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {+ quantity: number;+ unitPrice: number;+ }[];+ if (priceBreaks.length > 0) {+ await client.from("supplierPartPrice").insert(+ priceBreaks.map((pb) => ({+ supplierPartId: newSupplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ );+ }+ }+throw redirect(path.to.partPurchasing(itemId),await flash(request, success("Part supplier created"))diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsxindex 24be58fcca..f3dda2a839 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx@@ -3,8 +3,10 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";+import { getSupplierPriceBreaksForItems } from "~/modules/items";import { upsertQuoteLineMethod } from "~/modules/sales/sales.service";import { path, requestReferrer } from "~/utils/path";+import { lookupBuyPriceFromMap } from "~/utils/pricing";export async function action({ request, params }: ActionFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {@@ -60,6 +62,36 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, error("Failed to update quote line method")));}++ // Fix BOM material costs: replace average cost with price break values+ const buyMaterials = await serviceRole+ .from("quoteMaterial")+ .select("id, itemId, unitCost")+ .eq("quoteLineId", lineId)+ .eq("methodType", "Buy");++ const buyItemIds = [+ ...new Set((buyMaterials.data ?? []).map((m) => m.itemId))+ ];+ const priceMap = await getSupplierPriceBreaksForItems(+ serviceRole,+ buyItemIds+ );++ for (const mat of buyMaterials.data ?? []) {+ const price = lookupBuyPriceFromMap(+ mat.itemId,+ 1,+ priceMap,+ mat.unitCost+ );+ if (price !== mat.unitCost) {+ await serviceRole+ .from("quoteMaterial")+ .update({ unitCost: price })+ .eq("id", mat.id);+ }+ }} else {throw new Error("No configuration provided");}diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex 0fe39a3dff..1426ec7f6d 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -54,6 +54,7 @@ import QuoteLineRiskRegister from "~/modules/sales/ui/Quotes/QuoteLineRiskRegistimport { getTagsList } from "~/modules/shared";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";+import type { SupplierPriceMap } from "~/utils/pricing";export const loader = async ({ request, params }: LoaderFunctionArgs) => {const { client, companyId } = await requirePermissions(request, {@@ -205,6 +206,7 @@ export default function QuoteLine() {const quoteData = useRouteData<{methods: Tree<QuoteMethod>[];quote: Quotation;+ supplierPriceMap: SupplierPriceMap;}>(path.to.quote(quoteId));const methodTree = useMemo(@@ -215,7 +217,8 @@ export default function QuoteLine() {const getLineCosts = useLineCosts({methodTree,operations: operations as QuotationOperation[],- line+ line,+ supplierPriceMap: quoteData?.supplierPriceMap ?? {}});const initialValues = {diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsxindex 09c4fe8be8..976d60c9a7 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx@@ -4,13 +4,16 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";+import { getSupplierPriceBreaksForItems } from "~/modules/items";import {quoteLineValidator,upsertQuoteLine,- upsertQuoteLineMethod+ upsertQuoteLineMethod,+ upsertQuoteLinePrices} from "~/modules/sales";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";+import { lookupBuyPriceFromMap } from "~/utils/pricing";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -62,6 +65,27 @@ export async function action({ request, params }: ActionFunctionArgs) {}const quoteLineId = createQuotationLine.data.id;++ if (d.methodType === "Buy") {+ const quantities = d.quantity ?? [1];+ const priceMap = await getSupplierPriceBreaksForItems(serviceRole, [+ d.itemId+ ]);+ await upsertQuoteLinePrices(+ serviceRole,+ quoteId,+ quoteLineId,+ quantities.map((qty) => ({+ quoteLineId,+ quantity: qty,+ unitPrice: lookupBuyPriceFromMap(d.itemId, qty, priceMap, 0),+ leadTime: 0,+ discountPercent: 0,+ createdBy: userId+ }))+ );+ }+if (d.methodType === "Make") {const upsertMethod = await upsertQuoteLineMethod(serviceRole, {quoteId,@@ -81,6 +105,36 @@ export async function action({ request, params }: ActionFunctionArgs) {));}++ // Fix BOM material costs: replace average cost with price break values+ const buyMaterials = await serviceRole+ .from("quoteMaterial")+ .select("id, itemId, unitCost")+ .eq("quoteLineId", quoteLineId)+ .eq("methodType", "Buy");++ const buyItemIds = [+ ...new Set((buyMaterials.data ?? []).map((m) => m.itemId))+ ];+ const bomPriceMap = await getSupplierPriceBreaksForItems(+ serviceRole,+ buyItemIds+ );++ for (const mat of buyMaterials.data ?? []) {+ const price = lookupBuyPriceFromMap(+ mat.itemId,+ 1,+ bomPriceMap,+ mat.unitCost+ );+ if (price !== mat.unitCost) {+ await serviceRole+ .from("quoteMaterial")+ .update({ unitCost: price })+ .eq("id", mat.id);+ }+ }}throw redirect(path.to.quoteLine(quoteId, quoteLineId));diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.tsxindex 5af6929841..fbad0d4410 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.tsx@@ -16,6 +16,7 @@ import {} from "react-router";import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";import { getCurrencyByCode } from "~/modules/accounting";+import { getSupplierPriceBreaksForItems } from "~/modules/items";import type { SalesOrderLine } from "~/modules/sales";import {getCustomer,@@ -140,11 +141,33 @@ export async function loader({ request, params }: LoaderFunctionArgs) {? customer.data.defaultCc: (companySettings.data?.defaultCustomerCc ?? []);+ // Collect all Buy item IDs from method trees + top-level Buy lines+ const methodTrees = methods.data ?? [];+ const buyItemIds = new Set<string>();+ function collectBuyItems(tree: (typeof methodTrees)[number]) {+ if (tree.data.methodType === "Buy" && tree.data.itemId) {+ buyItemIds.add(tree.data.itemId);+ }+ tree.children?.forEach(collectBuyItems);+ }+ methodTrees.forEach(collectBuyItems);+ // Also include top-level Buy lines (non-Make lines)+ for (const line of lines.data ?? []) {+ if (line.methodType === "Buy" && line.itemId) {+ buyItemIds.add(line.itemId);+ }+ }++ const supplierPriceMap = await getSupplierPriceBreaksForItems(+ client,+ Array.from(buyItemIds)+ );+return {quote: quote.data,customer: customer.data,lines: lines.data ?? [],- methods: methods.data ?? [],+ methods: methodTrees,files: opportunityDocuments,prices: prices.data ?? [],shipment: shipment.data,@@ -152,7 +175,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {opportunity: opportunity.data,exchangeRate,salesOrderLines: salesOrderLines?.data ?? null,- defaultCc+ defaultCc,+ supplierPriceMap};}diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsxindex 5dc26ff22f..e1936581cb 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx@@ -189,7 +189,6 @@ export async function action(args: ActionFunctionArgs) {supplierPartId,quantity: price.quantity ?? 1,unitPrice: unitPriceInInventoryUnit,- leadTime: price.leadTime ?? 0,sourceType: "Quote",sourceDocumentId: id,companyId,diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsxindex 0d51fec0dc..5d0a247520 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx@@ -19,21 +19,45 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { supplierPartId } = params;if (!supplierPartId) throw new Error("Could not find supplierPartId");- const supplierPart = await client- .from("supplierPart")- .select("*")- .eq("id", supplierPartId)- .eq("companyId", companyId)- .single();-- if (!supplierPart?.data) throw new Error("Could not find supplier part");-- return { supplierPart: supplierPart.data };+ const [supplierPartResult, priceBreaksResult] = await Promise.all([+ client+ .from("supplierPart")+ .select("*")+ .eq("id", supplierPartId)+ .eq("companyId", companyId)+ .single(),+ client+ .from("supplierPartPrice")+ .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")+ .eq("supplierPartId", supplierPartId)+ .order("quantity", { ascending: true })+ ]);++ if (!supplierPartResult?.data)+ throw new Error("Could not find supplier part");++ const supplierPart = supplierPartResult.data;++ const purchasingHistory = await client+ .from("purchaseOrderLine")+ .select(+ "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ )+ .eq("itemId", supplierPart.itemId)+ .eq("purchaseOrder.supplierId", supplierPart.supplierId)+ .order("createdAt", { ascending: false })+ .limit(10);++ return {+ supplierPart,+ priceBreaks: priceBreaksResult.data ?? [],+ purchasingHistory: purchasingHistory.data ?? []+ };}export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, userId, companyId } = await requirePermissions(request, {update: "parts"});@@ -42,6 +66,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!supplierPartId) throw new Error("Could not find supplierPartId");const formData = await request.formData();+const validation = await validator(supplierPartValidator).validate(formData);if (validation.error) {@@ -62,6 +87,31 @@ export async function action({ request, params }: ActionFunctionArgs) {return { success: false, message: "Failed to update supplier part" };}+ const priceBreaksRaw = formData.get("priceBreaks");+ if (priceBreaksRaw) {+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {+ quantity: number;+ unitPrice: number;+ }[];+ await client+ .from("supplierPartPrice")+ .delete()+ .eq("supplierPartId", supplierPartId);+ if (priceBreaks.length > 0) {+ await client.from("supplierPartPrice").insert(+ priceBreaks.map((pb) => ({+ supplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ );+ }+ }+throw redirect(path.to.toolPurchasing(itemId),await flash(request, success("Supplier part updated"))@@ -70,7 +120,8 @@ export async function action({ request, params }: ActionFunctionArgs) {export default function EditToolSupplierRoute() {const { itemId } = useParams();- const { supplierPart } = useLoaderData<typeof loader>();+ const { supplierPart, priceBreaks, purchasingHistory } =+ useLoaderData<typeof loader>();if (!itemId) throw new Error("itemId not found");@@ -89,10 +140,7 @@ export default function EditToolSupplierRoute() {unitPrice: supplierPart.unitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,- conversionFactor: supplierPart.conversionFactor ?? 1,- lastPurchaseDate: supplierPart.lastPurchaseDate,- lastPOQuantity: supplierPart.lastPOQuantity,- lastPOId: supplierPart.lastPOId+ conversionFactor: supplierPart.conversionFactor ?? 1};return (@@ -100,6 +148,8 @@ export default function EditToolSupplierRoute() {type="Tool"initialValues={initialValues}unitOfMeasureCode={routeData?.toolSummary?.unitOfMeasureCode ?? ""}+ priceBreaks={priceBreaks}+ purchasingHistory={purchasingHistory}onClose={onClose}/>);diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsxindex 67a7e40929..6a193d0283 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx@@ -47,6 +47,28 @@ export async function action({ request, params }: ActionFunctionArgs) {};}+ const newSupplierPartId = createToolSupplier.data?.id;+ const priceBreaksRaw = formData.get("priceBreaks");+ if (newSupplierPartId && priceBreaksRaw) {+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {+ quantity: number;+ unitPrice: number;+ }[];+ if (priceBreaks.length > 0) {+ await client.from("supplierPartPrice").insert(+ priceBreaks.map((pb) => ({+ supplierPartId: newSupplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ );+ }+ }+throw redirect(path.to.toolPurchasing(itemId),await flash(request, success("Tool supplier created"))diff --git a/apps/erp/app/utils/pricing.ts b/apps/erp/app/utils/pricing.tsnew file mode 100644index 0000000000..096a265dfa--- /dev/null+++ b/apps/erp/app/utils/pricing.ts@@ -0,0 +1,72 @@+/** Shape of a single price break tier */+export type PriceBreak = {+ quantity: number;+ unitPrice: number;+};++/** Pre-fetched supplier price data keyed by itemId */+export type SupplierPriceMap = Record<+ string,+ {+ priceBreaks: PriceBreak[];+ fallbackUnitPrice: number | null;+ }+>;++/**+ * Core sync lookup: given price break tiers and a requested quantity,+ * return the unit price from the highest qualifying tier+ * (where tier.quantity <= requestedQty). Falls back to fallbackPrice.+ */+export function lookupPriceFromBreaks(+ priceBreaks: PriceBreak[],+ requestedQty: number,+ fallbackPrice: number+): number {+ const eligible = priceBreaks.filter((pb) => pb.quantity <= requestedQty);+ if (eligible.length) {+ return eligible.reduce((best, pb) =>+ pb.quantity > best.quantity ? pb : best+ ).unitPrice;+ }+ return fallbackPrice;+}++/**+ * Map-aware wrapper: look up itemId in a SupplierPriceMap, then resolve+ * via lookupPriceFromBreaks. Used by useLineCosts for BOM tree costing.+ */+export function lookupBuyPriceFromMap(+ itemId: string,+ requestedQty: number,+ priceMap: SupplierPriceMap,+ fallbackCost: number+): number {+ const entry = priceMap[itemId];+ if (!entry) return fallbackCost;+ return lookupPriceFromBreaks(+ entry.priceBreaks,+ requestedQty,+ entry.fallbackUnitPrice ?? fallbackCost+ );+}++/**+ * Resolve the best supplier unit price for a quantity, applying exchange+ * rate conversion.+ */+export function resolveSupplierPrice(+ priceBreaks: PriceBreak[],+ quantity: number,+ fallbackUnitPrice: number,+ exchangeRate: number+): number {+ if (!priceBreaks.length) return fallbackUnitPrice;+ return (+ lookupPriceFromBreaks(+ priceBreaks,+ quantity,+ fallbackUnitPrice * exchangeRate+ ) / exchangeRate+ );+}diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.tsindex 6e993a9f7b..7036913f42 100644--- a/packages/database/supabase/functions/convert/index.ts+++ b/packages/database/supabase/functions/convert/index.ts@@ -1508,9 +1508,6 @@ serve(async (req: Request) => {(selectedLine.supplierUnitPrice /(exchangeRate === 0 ? 1 : exchangeRate)) /(line.conversionFactor ?? 1);- const quantityInInventoryUnits =- selectedLine.quantity * (line.conversionFactor ?? 1);-supplierPartMap.set(key, {companyId,supplierId: quote.data?.supplierId!,@@ -1520,9 +1517,6 @@ serve(async (req: Request) => {itemId: line.itemId!,createdBy: userId,unitPrice: unitPriceInInventoryUnit,- lastPurchaseDate: new Date().toISOString(),- lastPOQuantity: quantityInInventoryUnits,- lastPOId: insertedPurchaseOrderId,});});@@ -1540,9 +1534,6 @@ serve(async (req: Request) => {.doUpdateSet((eb) => ({supplierPartId: eb.ref("excluded.supplierPartId"),unitPrice: eb.ref("excluded.unitPrice"),- lastPurchaseDate: eb.ref("excluded.lastPurchaseDate"),- lastPOQuantity: eb.ref("excluded.lastPOQuantity"),- lastPOId: eb.ref("excluded.lastPOId"),}))).execute();@@ -1588,7 +1579,7 @@ serve(async (req: Request) => {quantity: selectedLine.quantity,unitPrice: unitPriceInInventoryUnit,leadTime: selectedLine.leadTime ?? 0,- sourceType: "PurchaseOrder",+ sourceType: "Purchase Order",sourceDocumentId: insertedPurchaseOrderId,companyId,createdBy: userId,diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 92a33a0a0c..b0e44c58be 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -36106,9 +36106,6 @@ export type Database = {customFields: Json | nullid: stringitemId: string- lastPOId: string | null- lastPOQuantity: number | null- lastPurchaseDate: string | nullminimumOrderQuantity: number | nullsupplierId: stringsupplierPartId: string | null@@ -36127,9 +36124,6 @@ export type Database = {customFields?: Json | nullid?: stringitemId: string- lastPOId?: string | null- lastPOQuantity?: number | null- lastPurchaseDate?: string | nullminimumOrderQuantity?: number | nullsupplierId: stringsupplierPartId?: string | null@@ -36148,9 +36142,6 @@ export type Database = {customFields?: Json | nullid?: stringitemId?: string- lastPOId?: string | null- lastPOQuantity?: number | null- lastPurchaseDate?: string | nullminimumOrderQuantity?: number | nullsupplierId?: stringsupplierPartId?: string | null@@ -36336,27 +36327,6 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},- {- foreignKeyName: "supplierPart_lastPOId_fkey"- columns: ["lastPOId"]- isOneToOne: false- referencedRelation: "purchaseOrder"- referencedColumns: ["id"]- },- {- foreignKeyName: "supplierPart_lastPOId_fkey"- columns: ["lastPOId"]- isOneToOne: false- referencedRelation: "purchaseOrderLocations"- referencedColumns: ["id"]- },- {- foreignKeyName: "supplierPart_lastPOId_fkey"- columns: ["lastPOId"]- isOneToOne: false- referencedRelation: "purchaseOrders"- referencedColumns: ["id"]- },]}supplierPartPrice: {@@ -36364,10 +36334,9 @@ export type Database = {companyId: stringcreatedAt: stringcreatedBy: string- leadTime: number | nullquantity: numbersourceDocumentId: string | null- sourceType: string+ sourceType: Database["public"]["Enums"]["supplierPartPriceSourceType"]supplierPartId: stringunitPrice: numberupdatedAt: string | null@@ -36377,10 +36346,9 @@ export type Database = {companyId: stringcreatedAt?: stringcreatedBy: string- leadTime?: number | nullquantity?: numbersourceDocumentId?: string | null- sourceType?: string+ sourceType?: Database["public"]["Enums"]["supplierPartPriceSourceType"]supplierPartId: stringunitPrice: numberupdatedAt?: string | null@@ -36390,10 +36358,9 @@ export type Database = {companyId?: stringcreatedAt?: stringcreatedBy?: string- leadTime?: number | nullquantity?: numbersourceDocumentId?: string | null- sourceType?: string+ sourceType?: Database["public"]["Enums"]["supplierPartPriceSourceType"]supplierPartId?: stringunitPrice?: numberupdatedAt?: string | null@@ -57851,6 +57818,7 @@ export type Database = {| "Finance Charge Memo"| "Reminder"| "Refund"+ supplierPartPriceSourceType: "Quote" | "Purchase Order" | "Manual Entry"supplierQuoteStatus:| "Active"| "Expired"@@ -59006,6 +58974,7 @@ export const Constants = {"Reminder","Refund",],+ supplierPartPriceSourceType: ["Quote", "Purchase Order", "Manual Entry"],supplierQuoteStatus: ["Active","Expired",diff --git a/packages/database/supabase/migrations/20260129150000_quantity-price-breaks.sql b/packages/database/supabase/migrations/20260129150000_quantity-price-breaks.sqlindex 9d2be8ed3b..c25419dd1c 100644--- a/packages/database/supabase/migrations/20260129150000_quantity-price-breaks.sql+++ b/packages/database/supabase/migrations/20260129150000_quantity-price-breaks.sql@@ -1,31 +1,20 @@--- Add pricing fields to supplierPart table and create supplierPartPrice child table--- This enables quantity-based pricing for customer quote material costing---- ============================================================================--- Part 1: Add "last price" fields to supplierPart (backward compat / quick ref)--- ============================================================================--ALTER TABLE "supplierPart"-ADD COLUMN IF NOT EXISTS "unitPrice" NUMERIC(15, 5),-ADD COLUMN IF NOT EXISTS "lastPurchaseDate" TIMESTAMP WITH TIME ZONE,-ADD COLUMN IF NOT EXISTS "lastPOQuantity" NUMERIC(20, 2),-ADD COLUMN IF NOT EXISTS "lastPOId" TEXT;+-- Add unit price to supplierPart and create supplierPartPrice child table+-- for quantity-based pricing used in quote material costingALTER TABLE "supplierPart"-ADD CONSTRAINT "supplierPart_lastPOId_fkey"-FOREIGN KEY ("lastPOId") REFERENCES "purchaseOrder"("id")-ON DELETE SET NULL ON UPDATE CASCADE;+ADD COLUMN IF NOT EXISTS "unitPrice" NUMERIC(15, 5);--- ============================================================================--- Part 2: Create supplierPartPrice child table (quantity scales)--- ============================================================================+CREATE TYPE "supplierPartPriceSourceType" AS ENUM (+ 'Quote',+ 'Purchase Order',+ 'Manual Entry'+);CREATE TABLE "supplierPartPrice" ("supplierPartId" TEXT NOT NULL,"quantity" NUMERIC(20, 2) NOT NULL DEFAULT 1,"unitPrice" NUMERIC(15, 5) NOT NULL,- "leadTime" NUMERIC(10, 5) DEFAULT 0,- "sourceType" TEXT NOT NULL DEFAULT 'Quote',+ "sourceType" "supplierPartPriceSourceType" NOT NULL DEFAULT 'Quote',"sourceDocumentId" TEXT,"companyId" TEXT NOT NULL,"createdBy" TEXT NOT NULL,@@ -43,54 +32,39 @@ CREATE TABLE "supplierPartPrice" (CONSTRAINT "supplierPartPrice_createdBy_fkey"FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "supplierPartPrice_updatedBy_fkey"- FOREIGN KEY ("updatedBy") REFERENCES "user"("id"),- CONSTRAINT "supplierPartPrice_sourceType_check"- CHECK ("sourceType" IN ('Quote', 'PurchaseOrder', 'Manual'))+ FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));--- RLS: same access patterns as supplierPartALTER TABLE "supplierPartPrice" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees with part/purchasing_view can view supplier part prices" ON "supplierPartPrice"- FOR SELECT- USING (- (- has_company_permission('parts_view', "companyId") OR- has_company_permission('purchasing_view', "companyId")- )- AND has_role('employee', "companyId")- );--CREATE POLICY "Employees with parts_create can create supplier part prices" ON "supplierPartPrice"- FOR INSERT- WITH CHECK (- has_role('employee', "companyId") AND- has_company_permission('parts_create', "companyId")- );+CREATE POLICY "SELECT" ON "public"."supplierPartPrice"+FOR SELECT USING (+ "companyId" = ANY (+ SELECT DISTINCT unnest(ARRAY(+ SELECT unnest(get_companies_with_employee_permission('parts_view'))+ UNION+ SELECT unnest(get_companies_with_employee_permission('purchasing_view'))+ ))+ )+);-CREATE POLICY "Employees with parts_update can update supplier part prices" ON "supplierPartPrice"- FOR UPDATE- USING (- has_role('employee', "companyId") AND- has_company_permission('parts_update', "companyId")- );+CREATE POLICY "INSERT" ON "public"."supplierPartPrice"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('parts_create'))::text[]+ )+);-CREATE POLICY "Employees with parts_delete can delete supplier part prices" ON "supplierPartPrice"- FOR DELETE- USING (- has_role('employee', "companyId") AND- has_company_permission('parts_delete', "companyId")- );+CREATE POLICY "UPDATE" ON "public"."supplierPartPrice"+FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('parts_update'))::text[]+ )+);--- Suppliers can view their own supplier part prices-CREATE POLICY "Suppliers can view their own supplier part prices" ON "supplierPartPrice"- FOR SELECT- USING (- has_role('supplier', "companyId") AND- has_company_permission('parts_view', "companyId") AND- "supplierPartId" IN (- SELECT "id" FROM "supplierPart" WHERE "supplierId" IN (- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()- )- )- );+CREATE POLICY "DELETE" ON "public"."supplierPartPrice"+FOR DELETE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('parts_delete'))::text[]+ )+);