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
- comment fixes. and FE validations
Gaurav Bhattaaa1eeee3bc9
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsxindex 4426aee469..761eb5cc3c 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx@@ -42,10 +42,9 @@ import {import type { PurchaseInvoice } from "~/modules/invoicing";import { purchaseInvoiceLineValidator } from "~/modules/invoicing";import { getSupplierPartPriceBreaks } from "~/modules/items";-import type { MethodItemType } from "~/modules/shared";+import { type MethodItemType, resolveSupplierPrice } from "~/modules/shared";import { useItems } from "~/stores";import { path } from "~/utils/path";-import { resolveSupplierPrice } from "~/utils/pricing";type PurchaseInvoiceLineFormProps = {initialValues: z.infer<typeof purchaseInvoiceLineValidator> & {diff --git a/apps/erp/app/modules/items/index.ts b/apps/erp/app/modules/items/index.tsindex 5c4a021c1b..7a8d32da13 100644--- a/apps/erp/app/modules/items/index.ts+++ b/apps/erp/app/modules/items/index.ts@@ -1,4 +1,3 @@export * from "./items.models";-export * from "./items.pricing";export * from "./items.service";export * from "./types";diff --git a/apps/erp/app/modules/items/items.pricing.ts b/apps/erp/app/modules/items/items.pricing.tsdeleted file mode 100644index c238182d69..0000000000--- a/apps/erp/app/modules/items/items.pricing.ts+++ /dev/null@@ -1,104 +0,0 @@-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/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 3a10d7deb4..979ff2da4a 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -13,6 +13,11 @@ import type {operationStepValidator,operationToolValidator} from "../shared";+import {+ lookupBuyPriceFromMap,+ type PriceBreak,+ type SupplierPriceMap+} from "../shared";import type {configurationParameterGroupOrderValidator,configurationParameterGroupValidator,@@ -3244,3 +3249,100 @@ export async function upsertTool(if (updateItem.error) return updateItem;return updateTool;}++/**+ * 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 5cbc97d9c2..9ff2d13ae6 100644--- a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx@@ -122,6 +122,10 @@ const SupplierPartForm = ({})));+ const hasInvalidPriceBreaks = priceBreaks.some(+ (pb) => pb.quantity <= 0 || pb.unitPrice <= 0+ );+const isEditing = initialValues.id !== undefined;const isDisabled = isEditing? !permissions.can("update", "parts")@@ -212,7 +216,11 @@ const SupplierPartForm = ({<DrawerFooter><HStack><Submit- isDisabled={isDisabled || fetcher.state !== "idle"}+ isDisabled={+ isDisabled ||+ hasInvalidPriceBreaks ||+ fetcher.state !== "idle"+ }isLoading={fetcher.state !== "idle"}withBlocker={false}>diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsxindex 1f4faa4ca0..8146bbb350 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx@@ -47,11 +47,10 @@ import {isPurchaseOrderLocked,purchaseOrderLineValidator} from "~/modules/purchasing";-import type { MethodItemType } from "~/modules/shared";+import { type MethodItemType, resolveSupplierPrice } 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 = {diff --git a/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx b/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsxindex 6357d171ba..9d3dae64e4 100644--- a/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx@@ -1,7 +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 { lookupBuyPriceFromMap, type SupplierPriceMap } from "~/modules/shared";import type {CostEffects,Costs,diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.tsindex 37440d06c6..aa7671a55d 100644--- a/apps/erp/app/modules/shared/shared.models.ts+++ b/apps/erp/app/modules/shared/shared.models.ts@@ -290,3 +290,16 @@ export const standardFactorType = ["Total Hours","Total Minutes"] as const;++export type PriceBreak = {+ quantity: number;+ unitPrice: number;+};++export type SupplierPriceMap = Record<+ string,+ {+ priceBreaks: PriceBreak[];+ fallbackUnitPrice: number | null;+ }+>;diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex bf5bced4d4..673f4b7c1d 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -6,7 +6,12 @@ import { FunctionRegion } from "@supabase/supabase-js";import type { GenericQueryFilters } from "~/utils/query";import { setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";-import type { approvalDocumentType, documentTypes } from "./shared.models";+import type {+ approvalDocumentType,+ documentTypes,+ PriceBreak,+ SupplierPriceMap+} from "./shared.models";import type {ApprovalFilters,ApprovalRequestForApproveCheck,@@ -1226,3 +1231,61 @@ export async function updateSavedViewOrder();return Promise.all(updatePromises);}++/**+ * 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/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsxindex 06eae9267f..c25c057cf6 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx@@ -8,6 +8,7 @@ import { redirect, useLoaderData, useNavigate, useParams } from "react-router";import type { ConsumableSummary } from "~/modules/items";import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";import { SupplierPartForm } from "~/modules/items/ui/Item";+import { getDatabaseClient } from "~/services/database.server";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";@@ -92,24 +93,32 @@ export async function action({ request, params }: ActionFunctionArgs) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;unitPrice: number;+ leadTime: 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- }))- );- }+ const db = getDatabaseClient();+ await db.transaction().execute(async (trx) => {+ await trx+ .deleteFrom("supplierPartPrice")+ .where("supplierPartId", "=", supplierPartId)+ .execute();+ if (priceBreaks.length > 0) {+ await trx+ .insertInto("supplierPartPrice")+ .values(+ priceBreaks.map((pb) => ({+ supplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ leadTime: pb.leadTime ?? 0,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ )+ .execute();+ }+ });}throw redirect(diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsxindex 0d78b76d52..037c9a1d07 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx@@ -50,6 +50,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;unitPrice: number;+ leadTime: number;}[];if (priceBreaks.length > 0) {await client.from("supplierPartPrice").insert(@@ -57,6 +58,7 @@ export async function action({ request, params }: ActionFunctionArgs) {supplierPartId: newSupplierPartId,quantity: pb.quantity,unitPrice: pb.unitPrice,+ leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,createdBy: userId,diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsxindex be74c963e0..cd83c2d9df 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx@@ -8,6 +8,7 @@ import { redirect, useLoaderData, useNavigate, useParams } from "react-router";import type { MaterialSummary } from "~/modules/items";import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";import { SupplierPartForm } from "~/modules/items/ui/Item";+import { getDatabaseClient } from "~/services/database.server";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";@@ -92,24 +93,32 @@ export async function action({ request, params }: ActionFunctionArgs) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;unitPrice: number;+ leadTime: 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- }))- );- }+ const db = getDatabaseClient();+ await db.transaction().execute(async (trx) => {+ await trx+ .deleteFrom("supplierPartPrice")+ .where("supplierPartId", "=", supplierPartId)+ .execute();+ if (priceBreaks.length > 0) {+ await trx+ .insertInto("supplierPartPrice")+ .values(+ priceBreaks.map((pb) => ({+ supplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ leadTime: pb.leadTime ?? 0,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ )+ .execute();+ }+ });}throw redirect(diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsxindex 2192c5e786..4dc2a4db3c 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx@@ -50,6 +50,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;unitPrice: number;+ leadTime: number;}[];if (priceBreaks.length > 0) {await client.from("supplierPartPrice").insert(@@ -57,6 +58,7 @@ export async function action({ request, params }: ActionFunctionArgs) {supplierPartId: newSupplierPartId,quantity: pb.quantity,unitPrice: pb.unitPrice,+ leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,createdBy: userId,diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsxindex 147b19c16d..aca7af31af 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx@@ -8,6 +8,7 @@ import { redirect, useLoaderData, useNavigate, useParams } from "react-router";import type { PartSummary } from "~/modules/items";import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";import { SupplierPartForm } from "~/modules/items/ui/Item";+import { getDatabaseClient } from "~/services/database.server";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";@@ -92,24 +93,32 @@ export async function action({ request, params }: ActionFunctionArgs) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;unitPrice: number;+ leadTime: 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- }))- );- }+ const db = getDatabaseClient();+ await db.transaction().execute(async (trx) => {+ await trx+ .deleteFrom("supplierPartPrice")+ .where("supplierPartId", "=", supplierPartId)+ .execute();+ if (priceBreaks.length > 0) {+ await trx+ .insertInto("supplierPartPrice")+ .values(+ priceBreaks.map((pb) => ({+ supplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ leadTime: pb.leadTime ?? 0,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ )+ .execute();+ }+ });}throw redirect(diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsxindex 95fb1fdf49..517b25e9b1 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx@@ -53,6 +53,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;unitPrice: number;+ leadTime: number;}[];if (priceBreaks.length > 0) {await client.from("supplierPartPrice").insert(@@ -60,6 +61,7 @@ export async function action({ request, params }: ActionFunctionArgs) {supplierPartId: newSupplierPartId,quantity: pb.quantity,unitPrice: pb.unitPrice,+ leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,createdBy: userId,diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsxindex f3dda2a839..d09ffa4e61 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx@@ -5,8 +5,8 @@ import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { getSupplierPriceBreaksForItems } from "~/modules/items";import { upsertQuoteLineMethod } from "~/modules/sales/sales.service";+import { lookupBuyPriceFromMap } from "~/modules/shared";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, {diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex 1426ec7f6d..935b808a3b 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -51,10 +51,9 @@ import {} from "~/modules/sales/ui/Quotes";import QuoteLinePricingHistory from "~/modules/sales/ui/Quotes/QuoteLinePricingHistory";import QuoteLineRiskRegister from "~/modules/sales/ui/Quotes/QuoteLineRiskRegister";-import { getTagsList } from "~/modules/shared";+import { getTagsList, type SupplierPriceMap } 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, {diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsxindex 976d60c9a7..631713ccec 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx@@ -11,9 +11,9 @@ import {upsertQuoteLineMethod,upsertQuoteLinePrices} from "~/modules/sales";+import { lookupBuyPriceFromMap } from "~/modules/shared";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { lookupBuyPriceFromMap } from "~/utils/pricing";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsxindex e1936581cb..5dc26ff22f 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx@@ -189,6 +189,7 @@ 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 5d0a247520..f6cf4dada7 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx@@ -8,6 +8,7 @@ import { redirect, useLoaderData, useNavigate, useParams } from "react-router";import type { ToolSummary } from "~/modules/items";import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";import { SupplierPartForm } from "~/modules/items/ui/Item";+import { getDatabaseClient } from "~/services/database.server";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";@@ -92,24 +93,32 @@ export async function action({ request, params }: ActionFunctionArgs) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;unitPrice: number;+ leadTime: 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- }))- );- }+ const db = getDatabaseClient();+ await db.transaction().execute(async (trx) => {+ await trx+ .deleteFrom("supplierPartPrice")+ .where("supplierPartId", "=", supplierPartId)+ .execute();+ if (priceBreaks.length > 0) {+ await trx+ .insertInto("supplierPartPrice")+ .values(+ priceBreaks.map((pb) => ({+ supplierPartId,+ quantity: pb.quantity,+ unitPrice: pb.unitPrice,+ leadTime: pb.leadTime ?? 0,+ sourceType: "Manual Entry" as const,+ companyId,+ createdBy: userId,+ updatedBy: userId+ }))+ )+ .execute();+ }+ });}throw redirect(diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsxindex 6a193d0283..579e45f7c4 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx@@ -53,6 +53,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;unitPrice: number;+ leadTime: number;}[];if (priceBreaks.length > 0) {await client.from("supplierPartPrice").insert(@@ -60,6 +61,7 @@ export async function action({ request, params }: ActionFunctionArgs) {supplierPartId: newSupplierPartId,quantity: pb.quantity,unitPrice: pb.unitPrice,+ leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,createdBy: userId,diff --git a/apps/erp/app/utils/pricing.ts b/apps/erp/app/utils/pricing.tsdeleted file mode 100644index 096a265dfa..0000000000--- a/apps/erp/app/utils/pricing.ts+++ /dev/null@@ -1,72 +0,0 @@-/** 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/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 9f4099dd9c..be699bc5bb 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -23250,6 +23250,9 @@ export default {{$ref: "#/parameters/rowFilter.supplierPartPrice.updatedAt",},+ {+ $ref: "#/parameters/rowFilter.supplierPartPrice.leadTime",+ },{$ref: "#/parameters/select",},@@ -23339,6 +23342,9 @@ export default {{$ref: "#/parameters/rowFilter.supplierPartPrice.updatedAt",},+ {+ $ref: "#/parameters/rowFilter.supplierPartPrice.leadTime",+ },{$ref: "#/parameters/preferReturn",},@@ -23382,6 +23388,9 @@ export default {{$ref: "#/parameters/rowFilter.supplierPartPrice.updatedAt",},+ {+ $ref: "#/parameters/rowFilter.supplierPartPrice.leadTime",+ },{$ref: "#/parameters/body.supplierPartPrice",},@@ -79514,6 +79523,7 @@ export default {"companyId","createdBy","createdAt",+ "leadTime",],properties: {supplierPartId: {@@ -79568,6 +79578,11 @@ export default {format: "timestamp with time zone",type: "string",},+ leadTime: {+ default: 0,+ format: "numeric",+ type: "number",+ },},type: "object",},@@ -111124,6 +111139,12 @@ export default {in: "query",type: "string",},+ "rowFilter.supplierPartPrice.leadTime": {+ name: "leadTime",+ required: false,+ in: "query",+ type: "string",+ },"body.contact": {name: "contact",description: "contact",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 4b0cc14c84..844dcf141e 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -36334,6 +36334,7 @@ export type Database = {companyId: stringcreatedAt: stringcreatedBy: string+ leadTime: numberquantity: numbersourceDocumentId: string | nullsourceType: Database["public"]["Enums"]["supplierPartPriceSourceType"]@@ -36346,6 +36347,7 @@ export type Database = {companyId: stringcreatedAt?: stringcreatedBy: string+ leadTime?: numberquantity?: numbersourceDocumentId?: string | nullsourceType?: Database["public"]["Enums"]["supplierPartPriceSourceType"]@@ -36358,6 +36360,7 @@ export type Database = {companyId?: stringcreatedAt?: stringcreatedBy?: string+ leadTime?: numberquantity?: numbersourceDocumentId?: string | nullsourceType?: Database["public"]["Enums"]["supplierPartPriceSourceType"]@@ -52101,14 +52104,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 4b0cc14c84..844dcf141e 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -36334,6 +36334,7 @@ export type Database = {companyId: stringcreatedAt: stringcreatedBy: string+ leadTime: numberquantity: numbersourceDocumentId: string | nullsourceType: Database["public"]["Enums"]["supplierPartPriceSourceType"]@@ -36346,6 +36347,7 @@ export type Database = {companyId: stringcreatedAt?: stringcreatedBy: string+ leadTime?: numberquantity?: numbersourceDocumentId?: string | nullsourceType?: Database["public"]["Enums"]["supplierPartPriceSourceType"]@@ -36358,6 +36360,7 @@ export type Database = {companyId?: stringcreatedAt?: stringcreatedBy?: string+ leadTime?: numberquantity?: numbersourceDocumentId?: string | nullsourceType?: Database["public"]["Enums"]["supplierPartPriceSourceType"]@@ -52101,14 +52104,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/migrations/20260226120000_supplier-part-price-lead-time.sql b/packages/database/supabase/migrations/20260226120000_supplier-part-price-lead-time.sqlnew file mode 100644index 0000000000..398170cf53--- /dev/null+++ b/packages/database/supabase/migrations/20260226120000_supplier-part-price-lead-time.sql@@ -0,0 +1,5 @@+-- Add lead time column to supplierPartPrice+-- Matches the NUMERIC(10,5) type used in supplierQuoteLinePrice.leadTime++ALTER TABLE "supplierPartPrice"+ADD COLUMN IF NOT EXISTS "leadTime" NUMERIC(10, 5) NOT NULL DEFAULT 0;