Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: quote markup categories
Brad Barbin2c8a5f3217de
diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.tsindex 930ac44d3d..471fac2692 100644--- a/apps/erp/app/hooks/index.ts+++ b/apps/erp/app/hooks/index.ts@@ -16,6 +16,7 @@ import { usePercentFormatter } from "./usePercentFormatter";import { usePermissions } from "./usePermissions";import { useRealtime } from "./useRealtime";import { useScrollPosition } from "./useScrollPosition";+import { useSettings } from "./useSettings";import { useUser } from "./useUser";export {@@ -33,6 +34,7 @@ export {useRealtime,useRouteData,useScrollPosition,+ useSettings,useUrlParams,useUser};diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.tsindex c59e2024ca..5b70ea9d47 100644--- a/apps/erp/app/modules/sales/sales.models.ts+++ b/apps/erp/app/modules/sales/sales.models.ts@@ -190,6 +190,24 @@ export const quoteLineAdditionalChargesValidator = z.record(}));+export const costCategoryKeys = [+ "materialCost",+ "partCost",+ "toolCost",+ "consumableCost",+ "serviceCost",+ "laborCost",+ "machineCost",+ "overheadCost",+ "outsideCost"+] as const;++export type CostCategoryKey = (typeof costCategoryKeys)[number];++export const quoteLineCategoryMarkupsValidator = z+ .record(z.number().min(0))+ .default({});+export const quoteLineValidator = z.object({id: zfd.text(z.string().optional()),quoteId: z.string(),diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex c87342b7ef..d93fec5e1d 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -2246,6 +2246,7 @@ export async function upsertQuoteLinePrices(discountPercent: number;quantity: number;createdBy: string;+ categoryMarkups?: Record<string, number>;}[]) {const existingPrices = await client@@ -2282,6 +2283,7 @@ export async function upsertQuoteLinePrices({discountPercent: number;leadTime: number;+ categoryMarkups: unknown;}>>((acc, price) => {@@ -2290,29 +2292,19 @@ export async function upsertQuoteLinePrices(}, {});const pricesWithExistingDiscountsAndLeadTimes = quoteLinePrices.map((p) => {- if (p.quantity in pricesByQuantity) {- return {- ...p,- unitPrice: Number(- // Round the unit price to the precision of the quote line- p.unitPrice.toFixed(- quoteLineUnitPricePrecision.data?.unitPricePrecision ?? 2- )- ),- discountPercent: pricesByQuantity[p.quantity].discountPercent,- leadTime: pricesByQuantity[p.quantity].leadTime,- quoteId: quoteId,- exchangeRate: quoteExchangeRate.data?.exchangeRate ?? 1- };- }+ const existing = pricesByQuantity[p.quantity];+ const roundedUnitPrice = Number(+ p.unitPrice.toFixed(+ quoteLineUnitPricePrecision.data?.unitPricePrecision ?? 2+ )+ );+return {...p,- unitPrice: Number(- // Round the unit price to the precision of the quote line- p.unitPrice.toFixed(- quoteLineUnitPricePrecision.data?.unitPricePrecision ?? 2- )- ),+ unitPrice: roundedUnitPrice,+ discountPercent: existing?.discountPercent ?? p.discountPercent,+ leadTime: existing?.leadTime ?? p.leadTime,+ categoryMarkups: p.categoryMarkups ?? existing?.categoryMarkups ?? {},quoteId: quoteId,exchangeRate: quoteExchangeRate.data?.exchangeRate ?? 1};@@ -2323,6 +2315,424 @@ export async function upsertQuoteLinePrices(.insert(pricesWithExistingDiscountsAndLeadTimes);}+async function buildCostEffects(+ client: SupabaseClient<Database>,+ quoteLineId: string+) {+ const { getSupplierPriceBreaksForItems } = await import(+ "~/modules/items/items.service"+ );+ const { lookupBuyPriceFromMap } = await import(+ "~/modules/shared/shared.service"+ );+ const { costCategoryKeys } = await import("~/modules/sales/sales.models");++ const operationsResult = await client+ .from("quoteOperation")+ .select("*")+ .eq("quoteLineId", quoteLineId);++ const operations = operationsResult.data ?? [];++ // Fix Buy material costs+ const buyMaterials = await client+ .from("quoteMaterial")+ .select("id, itemId, unitCost")+ .eq("quoteLineId", quoteLineId)+ .eq("methodType", "Buy");++ const buyItemIds = [+ ...new Set((buyMaterials.data ?? []).map((m) => m.itemId))+ ];+ const priceMap = await getSupplierPriceBreaksForItems(client, buyItemIds);++ for (const mat of buyMaterials.data ?? []) {+ const price = lookupBuyPriceFromMap(mat.itemId, 1, priceMap, mat.unitCost);+ if (price !== mat.unitCost) {+ await client+ .from("quoteMaterial")+ .update({ unitCost: price })+ .eq("id", mat.id);+ }+ }++ // Build method tree+ const rootMethod = await client+ .from("quoteMakeMethod")+ .select("id")+ .eq("quoteLineId", quoteLineId)+ .is("parentMaterialId", null)+ .single();++ if (rootMethod.error) return null;++ const treeResult = await client.rpc("get_quote_methods_by_method_id", {+ mid: rootMethod.data.id+ });++ if (treeResult.error || !treeResult.data) return null;++ type TreeNode = {+ id: string;+ data: (typeof treeResult.data)[number];+ children: TreeNode[];+ };++ const rootItems: TreeNode[] = [];+ const lookup: Record<string, TreeNode> = {};++ for (const item of treeResult.data) {+ const itemId = item.methodMaterialId;+ const parentId = item.parentMaterialId;++ if (!lookup[itemId]) {+ lookup[itemId] = {+ id: itemId,+ children: [],+ data: item+ };+ } else {+ lookup[itemId].data = item;+ }++ if (!parentId) {+ rootItems.push(lookup[itemId]);+ } else {+ if (!lookup[parentId]) {+ lookup[parentId] = {+ id: parentId,+ children: [],+ data: {} as (typeof treeResult.data)[number]+ };+ }+ lookup[parentId].children.push(lookup[itemId]);+ }+ }++ type CostEffects = Record<string, ((qty: number) => number)[]>;+ const effects: CostEffects = {};+ for (const key of costCategoryKeys) {+ effects[key] = [];+ }++ function normalizeTime(+ time: number,+ unit: string+ ): { fixedHours: number; hoursPerUnit: number } {+ let fixedHours = 0;+ let hoursPerUnit = 0;+ switch (unit) {+ case "Total Hours":+ fixedHours = time;+ break;+ case "Total Minutes":+ fixedHours = time / 60;+ break;+ case "Hours/Piece":+ hoursPerUnit = time;+ break;+ case "Hours/100 Pieces":+ hoursPerUnit = time / 100;+ break;+ case "Hours/1000 Pieces":+ hoursPerUnit = time / 1000;+ break;+ case "Minutes/Piece":+ hoursPerUnit = time / 60;+ break;+ case "Minutes/100 Pieces":+ hoursPerUnit = time / 100 / 60;+ break;+ case "Minutes/1000 Pieces":+ hoursPerUnit = time / 1000 / 60;+ break;+ case "Pieces/Hour":+ hoursPerUnit = 1 / time;+ break;+ case "Pieces/Minute":+ hoursPerUnit = 1 / (time / 60);+ break;+ case "Seconds/Piece":+ hoursPerUnit = time / 3600;+ break;+ }+ return { fixedHours, hoursPerUnit };+ }++ function pushBuyCostEffect(+ itemId: string,+ itemType: string,+ quantity: number,+ unitCost: number+ ) {+ const costFn = (outerQty: number) => {+ const requestedQty = quantity * outerQty;+ return (+ lookupBuyPriceFromMap(itemId, requestedQty, priceMap, unitCost) *+ requestedQty+ );+ };+ const key =+ itemType === "Material"+ ? "materialCost"+ : itemType === "Part"+ ? "partCost"+ : itemType === "Tool"+ ? "toolCost"+ : itemType === "Consumable"+ ? "consumableCost"+ : itemType === "Service"+ ? "serviceCost"+ : null;+ if (key) effects[key].push(costFn);+ }++ function walkTree(node: TreeNode, parentQuantity: number) {+ const d = node.data;+ const qty = d.quantity * parentQuantity;++ if (d.methodType === "Buy") {+ pushBuyCostEffect(d.itemId, d.itemType, qty, d.unitCost);+ } else if (d.methodType === "Pick") {+ const costFn = (outerQty: number) => d.unitCost * qty * outerQty;+ const key =+ d.itemType === "Material"+ ? "materialCost"+ : d.itemType === "Part"+ ? "partCost"+ : d.itemType === "Tool"+ ? "toolCost"+ : d.itemType === "Consumable"+ ? "consumableCost"+ : d.itemType === "Service"+ ? "serviceCost"+ : null;+ if (key) effects[key].push(costFn);+ }++ const nodeOps = operations.filter(+ (o) => o.quoteMakeMethodId === d.quoteMaterialMakeMethodId+ );++ for (const op of nodeOps) {+ if (op.operationType === "Inside") {+ if (op.setupTime) {+ const { fixedHours, hoursPerUnit } = normalizeTime(+ op.setupTime,+ op.setupUnit+ );+ effects.laborCost.push((outerQty) => {+ return (+ hoursPerUnit * outerQty * qty * (op.laborRate ?? 0) ++ fixedHours * (op.laborRate ?? 0)+ );+ });+ effects.overheadCost.push((outerQty) => {+ return (+ hoursPerUnit * outerQty * qty * (op.overheadRate ?? 0) ++ fixedHours * (op.overheadRate ?? 0)+ );+ });+ }++ let laborFixedHours = 0;+ let laborHoursPerUnit = 0;+ let machineFixedHours = 0;+ let machineHoursPerUnit = 0;++ if (op.laborTime) {+ const n = normalizeTime(op.laborTime, op.laborUnit);+ laborFixedHours = n.fixedHours;+ laborHoursPerUnit = n.hoursPerUnit;+ effects.laborCost.push((outerQty) => {+ return (+ laborHoursPerUnit * outerQty * qty * (op.laborRate ?? 0) ++ laborFixedHours * (op.laborRate ?? 0)+ );+ });+ }++ if (op.machineTime) {+ const n = normalizeTime(op.machineTime, op.machineUnit);+ machineFixedHours = n.fixedHours;+ machineHoursPerUnit = n.hoursPerUnit;+ effects.machineCost.push((outerQty) => {+ return (+ machineHoursPerUnit * outerQty * qty * (op.machineRate ?? 0) ++ machineFixedHours * (op.machineRate ?? 0)+ );+ });+ }++ const hpu = Math.max(laborHoursPerUnit, machineHoursPerUnit);+ const fh = Math.max(laborFixedHours, machineFixedHours);+ effects.overheadCost.push((outerQty) => {+ if (hpu * outerQty * qty > fh) {+ return hpu * outerQty * qty * (op.overheadRate ?? 0);+ }+ return fh * (op.overheadRate ?? 0);+ });+ } else if (op.operationType === "Outside") {+ effects.outsideCost.push((outerQty) => {+ const cost = op.operationUnitCost * qty * outerQty;+ return Math.max(op.operationMinimumCost, cost);+ });+ }+ }++ for (const child of node.children) {+ walkTree(child, qty);+ }+ }++ for (const root of rootItems) {+ walkTree(root, 1);+ }++ return { effects, costCategoryKeys };+}++export async function calculatePricesForQuantities(+ client: SupabaseClient<Database>,+ quoteId: string,+ quoteLineId: string,+ quantities: number[],+ userId: string+) {+ if (!quantities.length) return;++ const { costCategoryKeys } = await import("~/modules/sales/sales.models");++ // 1. Parallel fetch+ const [settingsResult, quoteResult, lineResult] = await Promise.all([+ client.from("companySettings").select("quoteLineCategoryMarkups").single(),+ client.from("quote").select("exchangeRate").eq("id", quoteId).single(),+ client+ .from("quoteLine")+ .select("unitPricePrecision")+ .eq("id", quoteLineId)+ .single()+ ]);++ if (settingsResult.error || quoteResult.error || lineResult.error) return;++ const exchangeRate = quoteResult.data.exchangeRate ?? 1;+ const precision = lineResult.data.unitPricePrecision ?? 2;++ // Parse default markups (settings stores decimals, convert to whole numbers)+ const rawMarkups =+ (settingsResult.data.quoteLineCategoryMarkups as Record<string, number>) ??+ {};+ const defaultMarkups: Record<string, number> = {};+ for (const [key, value] of Object.entries(rawMarkups)) {+ defaultMarkups[key] = value * 100;+ }++ // 2. Build cost effects+ const result = await buildCostEffects(client, quoteLineId);+ if (!result) return;++ const { effects } = result;++ // 3. Compute prices for each quantity+ const priceRows = quantities.map((qty) => {+ const categoryCosts: Record<string, number> = {};+ for (const key of costCategoryKeys) {+ const total = effects[key].reduce((acc, fn) => acc + fn(qty), 0);+ categoryCosts[key] = qty > 0 ? total / qty : 0;+ }++ const unitPrice = costCategoryKeys.reduce((sum, key) => {+ const cost = categoryCosts[key] ?? 0;+ const markup = defaultMarkups[key] ?? 0;+ return sum + cost * (1 + markup / 100);+ }, 0);++ return {+ quoteId,+ quoteLineId,+ quantity: qty,+ unitPrice: Number(unitPrice.toFixed(precision)),+ categoryMarkups: defaultMarkups,+ exchangeRate,+ createdBy: userId,+ leadTime: 0,+ discountPercent: 0+ };+ });++ // 4. Insert price rows+ await client.from("quoteLinePrice").insert(priceRows);+}++export async function recalculateQuoteLinePrices(+ client: SupabaseClient<Database>,+ quoteId: string,+ quoteLineId: string,+ userId: string+) {+ const { costCategoryKeys } = await import("~/modules/sales/sales.models");++ // 1. Fetch existing price rows+ const existingPrices = await client+ .from("quoteLinePrice")+ .select("*")+ .eq("quoteLineId", quoteLineId);++ if (!existingPrices.data?.length) return;++ // 2. Fetch line precision+ const lineResult = await client+ .from("quoteLine")+ .select("unitPricePrecision")+ .eq("id", quoteLineId)+ .single();++ const precision = lineResult.data?.unitPricePrecision ?? 2;++ // 3. Build cost effects+ const result = await buildCostEffects(client, quoteLineId);+ if (!result) return;++ const { effects } = result;++ // 4. Recompute prices using each row's stored categoryMarkups+ const updatedRows = existingPrices.data.map((row) => {+ const qty = row.quantity;+ const markups = (row.categoryMarkups as Record<string, number>) ?? {};++ const categoryCosts: Record<string, number> = {};+ for (const key of costCategoryKeys) {+ const total = effects[key].reduce((acc, fn) => acc + fn(qty), 0);+ categoryCosts[key] = qty > 0 ? total / qty : 0;+ }++ const unitPrice = costCategoryKeys.reduce((sum, key) => {+ const cost = categoryCosts[key] ?? 0;+ const markup = markups[key] ?? 0;+ return sum + cost * (1 + markup / 100);+ }, 0);++ return {+ quoteId: row.quoteId,+ quoteLineId: row.quoteLineId,+ quantity: row.quantity,+ unitPrice: Number(unitPrice.toFixed(precision)),+ categoryMarkups: markups,+ exchangeRate: row.exchangeRate,+ createdBy: row.createdBy,+ updatedBy: userId,+ leadTime: row.leadTime,+ discountPercent: row.discountPercent+ };+ });++ // 5. Delete existing and re-insert with updated prices+ await client.from("quoteLinePrice").delete().eq("quoteLineId", quoteLineId);++ await client.from("quoteLinePrice").insert(updatedRows);+}+export async function upsertQuoteLineMethod(client: SupabaseClient<Database>,lineMethod: {diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsxindex 1a6f304608..0eafe2e3cc 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx@@ -33,6 +33,7 @@ import { getLocalTimeZone, today } from "@internationalized/date";import { useCallback, useEffect, useMemo, useState } from "react";import {LuChevronDown,+ LuChevronRight,LuCirclePlus,LuInfo,LuRefreshCcw,@@ -43,10 +44,16 @@ import {useCurrencyFormatter,usePermissions,useRouteData,+ useSettings,useUser} from "~/hooks";import { path } from "~/utils/path";-import { quoteLineAdditionalChargesValidator } from "../../sales.models";+import {+ type CostCategoryKey,+ costCategoryKeys,+ quoteLineAdditionalChargesValidator,+ quoteLineCategoryMarkupsValidator+} from "../../sales.models";import type {Costs,Quotation,@@ -54,6 +61,18 @@ import type {QuotationPrice} from "../../types";+const categoryLabels: Record<CostCategoryKey, string> = {+ materialCost: "Material",+ partCost: "Part",+ toolCost: "Tool",+ consumableCost: "Consumable",+ serviceCost: "Service",+ laborCost: "Labor",+ machineCost: "Machine",+ overheadCost: "Overhead",+ outsideCost: "Outside"+};+const QuoteLinePricing = ({line,pricesByQuantity,@@ -82,6 +101,8 @@ const QuoteLinePricing = ({taxPercent: line.taxPercent ?? 0});+ const [showCategoryMarkups, setShowCategoryMarkups] = useState(false);+useEffect(() => {setEditableFields((prev) => ({...prev,@@ -97,6 +118,34 @@ const QuoteLinePricing = ({line.taxPercent]);+ const settings = useSettings();+ const defaultCategoryMarkups = useMemo(() => {+ const raw = quoteLineCategoryMarkupsValidator.parse(+ (settings as Record<string, unknown>).quoteLineCategoryMarkups ?? {}+ );+ // Settings stores decimals (0.5 = 50%), but quote line markups use whole numbers (50 = 50%)+ const converted: Record<string, number> = {};+ for (const [key, value] of Object.entries(raw)) {+ converted[key] = value * 100;+ }+ return converted;+ }, [settings]);++ const categoryMarkupsByQuantity = useMemo(() => {+ const result: Record<number, Record<string, number>> = {};+ for (const quantity of quantities) {+ const priceMarkups = quoteLineCategoryMarkupsValidator.parse(+ (editableFields.prices[quantity] as Record<string, unknown>)+ ?.categoryMarkups ?? {}+ );+ result[quantity] =+ Object.keys(priceMarkups).length > 0+ ? priceMarkups+ : defaultCategoryMarkups;+ }+ return result;+ }, [editableFields.prices, quantities, defaultCategoryMarkups]);+const unitPricePrecision = line.unitPricePrecision ?? 2;const routeData = useRouteData<{@@ -211,22 +260,40 @@ const QuoteLinePricing = ({[additionalCharges, carbon, lineId]);- const unitCostsByQuantity = quantities.map((quantity, index) => {+ const costsByQuantity = quantities.map((quantity) => {const costs = getLineCosts(quantity);- const totalCost =- (costs.consumableCost +- costs.laborCost +- costs.machineCost +- costs.materialCost +- costs.overheadCost +- costs.partCost +- costs.serviceCost +- costs.toolCost +- costs.outsideCost) /- quantity;- return totalCost;+ return {+ materialCost: costs.materialCost / quantity,+ partCost: costs.partCost / quantity,+ toolCost: costs.toolCost / quantity,+ consumableCost: costs.consumableCost / quantity,+ serviceCost: costs.serviceCost / quantity,+ laborCost: costs.laborCost / quantity,+ machineCost: costs.machineCost / quantity,+ overheadCost: costs.overheadCost / quantity,+ outsideCost: costs.outsideCost / quantity+ };});+ const unitCostsByQuantity = costsByQuantity.map((costs) =>+ Object.values(costs).reduce((sum, v) => sum + v, 0)+ );++ const computeUnitPriceFromMarkups = (+ categoryCosts: Record<CostCategoryKey, number>,+ markups: Record<string, number>+ ): number => {+ return costCategoryKeys.reduce((sum, key) => {+ const cost = categoryCosts[key] ?? 0;+ const markup = markups[key] ?? 0;+ return sum + cost * (1 + markup / 100);+ }, 0);+ };++ const visibleCategories = costCategoryKeys.filter((key: CostCategoryKey) =>+ costsByQuantity.some((costs) => costs[key] > 0)+ );+const netPricesByQuantity = quantities.map((quantity, index) => {const price = editableFields.prices[quantity]?.unitPrice ?? 0;const discount = editableFields.prices[quantity]?.discountPercent ?? 0;@@ -235,10 +302,33 @@ const QuoteLinePricing = ({});const onRecalculate = (markup: number) => {+ const newMarkups: Record<string, number> = {};+ for (const key of costCategoryKeys) {+ newMarkups[key] = markup;+ }++ const newCategoryMarkupsByQuantity: Record<+ string,+ Record<string, number>+ > = {};+ for (const quantity of quantities) {+ newCategoryMarkupsByQuantity[quantity] = newMarkups;+ }++ const unitPricesByQuantity = costsByQuantity.map((costs) =>+ computeUnitPriceFromMarkups(costs, newMarkups)+ );+const formData = new FormData();- formData.append("markup", markup.toString());- formData.append("unitCostsByQuantity", JSON.stringify(unitCostsByQuantity));+ formData.append(+ "unitPricesByQuantity",+ JSON.stringify(unitPricesByQuantity)+ );formData.append("quantities", JSON.stringify(quantities));+ formData.append(+ "categoryMarkupsByQuantity",+ JSON.stringify(newCategoryMarkupsByQuantity)+ );fetcher.submit(formData, {method: "post",action: path.to.quoteLineRecalculatePrice(quoteId, lineId)@@ -281,6 +371,54 @@ const QuoteLinePricing = ({[carbon, line.itemId]);+ const onUpdateCategoryMarkup = useCallback(+ async (category: CostCategoryKey, quantity: number, value: number) => {+ const existingMarkups = categoryMarkupsByQuantity[quantity] ?? {};+ const newMarkups = {+ ...existingMarkups,+ [category]: value+ };++ const quantityIndex = quantities.indexOf(quantity);+ const categoryCosts = costsByQuantity[quantityIndex];+ const unitPrice = computeUnitPriceFromMarkups(categoryCosts, newMarkups);++ setEditableFields((prev) => ({+ ...prev,+ prices: {+ ...prev.prices,+ [quantity]: {+ ...prev.prices[quantity],+ categoryMarkups: newMarkups,+ unitPrice+ }+ }+ }));++ const priceUpdate = await carbon+ ?.from("quoteLinePrice")+ .update({+ categoryMarkups: newMarkups,+ unitPrice+ })+ .eq("quoteLineId", lineId)+ .eq("quantity", quantity);++ if (priceUpdate?.error) {+ console.error(priceUpdate.error);+ toast.error("Failed to update category markups");+ }+ },+ [+ categoryMarkupsByQuantity,+ carbon,+ lineId,+ costsByQuantity,+ quantities,+ quoteId+ ]+ );+const onUpdatePrice = useCallback(async (key: "leadTime" | "unitPrice" | "discountPercent" | "shippingCost",@@ -561,6 +699,7 @@ const QuoteLinePricing = ({})}</Tr>)}+{isEmployee && (<Tr><Td className="border-r border-border">@@ -612,6 +751,91 @@ const QuoteLinePricing = ({})}</Tr>)}+ {isEmployee && hasCalculatedCost && (+ <>+ <Tr>+ <Td className="border-r border-border">+ <Button+ variant="ghost"+ className="-ml-3"+ rightIcon={+ showCategoryMarkups ? (+ <LuChevronDown />+ ) : (+ <LuChevronRight />+ )+ }+ onClick={() =>+ setShowCategoryMarkups(!showCategoryMarkups)+ }+ >+ Markup by Category+ </Button>+ </Td>+ {quantities.map((quantity) => (+ <Td key={quantity.toString()} />+ ))}+ </Tr>+ {showCategoryMarkups &&+ visibleCategories.map((category: CostCategoryKey) => {+ return (+ <Tr key={category}>+ <Td className="border-r border-border pl-8">+ <span>{categoryLabels[category]}</span>+ </Td>+ {quantities.map((quantity, index) => {+ const categoryCost =+ costsByQuantity[index]?.[category] ?? 0;+ const markupValue =+ categoryMarkupsByQuantity[quantity]?.[category] ??+ 0;+ return (+ <Td key={quantity.toString()}>+ {categoryCost > 0 ? (+ <VStack spacing={0}>+ <NumberField+ value={markupValue / 100}+ formatOptions={{+ style: "percent",+ maximumFractionDigits: 2+ }}+ minValue={0}+ onChange={(value) => {+ const percent = value * 100;+ if (+ Number.isFinite(percent) &&+ percent !== markupValue+ ) {+ onUpdateCategoryMarkup(+ category,+ quantity,+ percent+ );+ }+ }}+ >+ <NumberInput+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"+ isDisabled={!isEditable}+ size="sm"+ min={0}+ />+ </NumberField>+ <span className="text-xs text-muted-foreground">+ {unitPriceFormatter.format(categoryCost)}+ </span>+ </VStack>+ ) : (+ <span className="text-muted-foreground">-</span>+ )}+ </Td>+ );+ })}+ </Tr>+ );+ })}+ </>+ )}<Tr><Td className="border-r border-border"><HStack className="w-full justify-between ">diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex a6f89ba2a8..36d56f09a3 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -242,3 +242,14 @@ export const webhookValidator = zexport const jobTravelerSettingsValidator = z.object({jobTravelerIncludeWorkInstructions: zfd.checkbox()});++export const quoteLineCategoryMarkupsSettingsValidator = z.object({+ materialCost: zfd.numeric(z.number().min(0).default(0)),+ partCost: zfd.numeric(z.number().min(0).default(0)),+ toolCost: zfd.numeric(z.number().min(0).default(0)),+ consumableCost: zfd.numeric(z.number().min(0).default(0)),+ laborCost: zfd.numeric(z.number().min(0).default(0)),+ machineCost: zfd.numeric(z.number().min(0).default(0)),+ overheadCost: zfd.numeric(z.number().min(0).default(0)),+ outsideCost: zfd.numeric(z.number().min(0).default(0))+});diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex a7b0fc7d4e..7f83a278d9 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -729,6 +729,17 @@ export async function updateDefaultCustomerCc(.eq("id", companyId);}+export async function updateQuoteLineCategoryMarkups(+ client: SupabaseClient<Database>,+ companyId: string,+ quoteLineCategoryMarkups: Record<string, number>+) {+ return client+ .from("companySettings")+ .update(sanitize({ quoteLineCategoryMarkups }))+ .eq("id", companyId);+}+export async function updateSequence(client: SupabaseClient<Database>,table: string,diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex 935b808a3b..3c01316548 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -23,6 +23,7 @@ import type {QuoteMethod} from "~/modules/sales";import {+ calculatePricesForQuantities,getConfigurationParametersByQuoteLineId,getModelByQuoteLineId,getOpportunityLineDocuments,@@ -178,6 +179,32 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ if (d.methodType === "Make" && d.quantity?.length) {+ const serviceRole = getCarbonServiceRole();+ const existingPrices = await serviceRole+ .from("quoteLinePrice")+ .select("quantity")+ .eq("quoteLineId", lineId);++ const existingQuantities = new Set(+ (existingPrices.data ?? []).map((p) => p.quantity)+ );++ const addedQuantities = d.quantity.filter(+ (q) => !existingQuantities.has(q)+ );++ if (addedQuantities.length > 0) {+ await calculatePricesForQuantities(+ serviceRole,+ quoteId,+ lineId,+ addedQuantities,+ userId+ );+ }+ }+throw redirect(path.to.quoteLine(quoteId, lineId));}diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsxindex dfbc32d29d..43ed74e314 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx@@ -20,18 +20,21 @@ export async function action({ request, params }: ActionFunctionArgs) {const formData = await request.formData();- const markup = Number.parseInt((formData.get("markup") as string) ?? "15");- const unitCostsByQuantity = numberArrayValidator.safeParse(- JSON.parse((formData.get("unitCostsByQuantity") ?? "[]") as string)+ const unitPricesByQuantity = numberArrayValidator.safeParse(+ JSON.parse((formData.get("unitPricesByQuantity") ?? "[]") as string));const quantities = numberArrayValidator.safeParse(JSON.parse((formData.get("quantities") ?? "[]") as string));- if (unitCostsByQuantity.success === false) {+ const categoryMarkupsByQuantity = JSON.parse(+ (formData.get("categoryMarkupsByQuantity") as string) ?? "{}"+ ) as Record<string, Record<string, number>>;++ if (unitPricesByQuantity.success === false) {return data(- { data: null, errors: unitCostsByQuantity.error.errors?.[0].message },+ { data: null, errors: unitPricesByQuantity.error.errors?.[0].message },{ status: 400 });}@@ -43,14 +46,18 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- const inserts = unitCostsByQuantity.data.map((unitCost, index) => ({- quoteLineId: lineId,- quantity: quantities.data[index],- unitPrice: unitCost * (1 + markup / 100),- discountPercent: 0,- leadTime: 0,- createdBy: userId- }));+ const inserts = unitPricesByQuantity.data.map((unitPrice, index) => {+ const quantity = quantities.data[index];+ return {+ quoteLineId: lineId,+ quantity,+ unitPrice,+ discountPercent: 0,+ leadTime: 0,+ createdBy: userId,+ categoryMarkups: categoryMarkupsByQuantity[quantity] ?? undefined+ };+ });const insertLinePrices = await upsertQuoteLinePrices(client,diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsxindex 631713ccec..30dfe74d86 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx@@ -105,36 +105,6 @@ 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+/methods+/$quoteId.$lineId.material.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsxindex 1f6c800379..934b377136 100644--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx@@ -4,7 +4,11 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";-import { quoteMaterialValidator, upsertQuoteMaterial } from "~/modules/sales";+import {+ quoteMaterialValidator,+ recalculateQuoteLinePrices,+ upsertQuoteMaterial+} from "~/modules/sales";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -66,6 +70,8 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);+return {id: quoteMaterialId,methodType: updateQuoteMaterial.data.methodType,diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsxindex a78d9c1a9e..0c93c06e88 100644--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx@@ -1,17 +1,26 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";-import { deleteQuoteMaterial } from "~/modules/sales";+import {+ deleteQuoteMaterial,+ recalculateQuoteLinePrices+} from "~/modules/sales";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client } = await requirePermissions(request, {+ const { client, userId } = await requirePermissions(request, {delete: "sales"});- const { id } = params;+ const { quoteId, lineId, id } = params;+ if (!quoteId) {+ throw new Error("quoteId not found");+ }+ if (!lineId) {+ throw new Error("lineId not found");+ }if (!id) {throw new Error("id not found");}@@ -29,5 +38,8 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ const serviceRole = getCarbonServiceRole();+ await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);+return {};}diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsxindex 7ef9a5a53e..00eb441c2a 100644--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx@@ -6,6 +6,7 @@ import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import {quoteMaterialValidator,+ recalculateQuoteLinePrices,upsertQuoteMaterial,upsertQuoteMaterialMakeMethod} from "~/modules/sales";@@ -103,6 +104,8 @@ export async function action({ request, params }: ActionFunctionArgs) {}}+ await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);+return {id: quoteMaterialId,success: true,diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsxindex 0a768dc7c3..f96e4a890a 100644--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx@@ -1,10 +1,14 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";-import { quoteOperationValidator, upsertQuoteOperation } from "~/modules/sales";+import {+ quoteOperationValidator,+ recalculateQuoteLinePrices,+ upsertQuoteOperation+} from "~/modules/sales";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -67,6 +71,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ const serviceRole = getCarbonServiceRole();+ await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);+return {id: quoteOperationId,success: true,diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsxindex bdea27006e..e054a46b87 100644--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx@@ -1,10 +1,14 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";-import { quoteOperationValidator, upsertQuoteOperation } from "~/modules/sales";+import {+ quoteOperationValidator,+ recalculateQuoteLinePrices,+ upsertQuoteOperation+} from "~/modules/sales";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -63,6 +67,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ const serviceRole = getCarbonServiceRole();+ await recalculateQuoteLinePrices(serviceRole, quoteId, lineId, userId);+return {id: quoteOperationId,success: true,diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.delete.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.delete.tsxindex 8fec5d5ec9..be93f0d269 100644--- a/apps/erp/app/routes/x+/quote+/methods+/operation.delete.tsx+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.delete.tsx@@ -1,9 +1,11 @@+import { getCarbonServiceRole } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";+import { recalculateQuoteLinePrices } from "~/modules/sales";export async function action({ request }: ActionFunctionArgs) {- const { client } = await requirePermissions(request, {+ const { client, userId } = await requirePermissions(request, {delete: "sales"});@@ -19,6 +21,13 @@ export async function action({ request }: ActionFunctionArgs) {);}+ // Fetch the operation's quoteId/quoteLineId before deleting+ const op = await client+ .from("quoteOperation")+ .select("quoteId, quoteLineId")+ .eq("id", id)+ .single();+const { error } = await client.from("quoteOperation").delete().eq("id", id);if (error) {@@ -30,5 +39,15 @@ export async function action({ request }: ActionFunctionArgs) {);}+ if (op.data) {+ const serviceRole = getCarbonServiceRole();+ await recalculateQuoteLinePrices(+ serviceRole,+ op.data.quoteId,+ op.data.quoteLineId,+ userId+ );+ }+return { success: true };}diff --git a/apps/erp/app/routes/x+/settings+/sales.tsx b/apps/erp/app/routes/x+/settings+/sales.tsxindex a1a138c493..3807b884a4 100644--- a/apps/erp/app/routes/x+/settings+/sales.tsx+++ b/apps/erp/app/routes/x+/settings+/sales.tsx@@ -2,7 +2,13 @@ import { error, useCarbon } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";// biome-ignore lint/suspicious/noShadowRestrictedNames: suppressed due to migration-import { Boolean, Submit, ValidatedForm, validator } from "@carbon/form";+import {+ Boolean,+ Number,+ Submit,+ ValidatedForm,+ validator+} from "@carbon/form";import type { JSONContent } from "@carbon/react";import {Badge,@@ -36,9 +42,11 @@ import {getCompanySettings,getTerms,includeThumbnailsOnSalesPdfsValidator,+ quoteLineCategoryMarkupsSettingsValidator,rfqReadyValidator,updateDefaultCustomerCc,updateDigitalQuoteSetting,+ updateQuoteLineCategoryMarkups,updateRfqReadySetting,updateSalesPdfThumbnails} from "~/modules/settings";@@ -139,6 +147,32 @@ export async function action({ request }: ActionFunctionArgs) {return { success: true, message: "RFQ setting updated" };+ case "categoryMarkups":+ const categoryMarkupsValidation = await validator(+ quoteLineCategoryMarkupsSettingsValidator+ ).validate(formData);++ if (categoryMarkupsValidation.error) {+ return { success: false, message: "Invalid form data" };+ }++ const categoryMarkupsResult = await updateQuoteLineCategoryMarkups(+ client,+ companyId,+ categoryMarkupsValidation.data+ );++ if (categoryMarkupsResult.error)+ return {+ success: false,+ message: categoryMarkupsResult.error.message+ };++ return {+ success: true,+ message: "Default category markups updated"+ };+case "emails":const defaultCustomerCcValidation = await validator(defaultCustomerCcValidator@@ -419,6 +453,10 @@ export default function SalesSettingsRoute() {</CardFooter></ValidatedForm></Card>+ <CategoryMarkupsCard+ companySettings={companySettings}+ fetcher={fetcher}+ /><Card><HStack className="justify-between items-start"><CardHeader>@@ -456,3 +494,95 @@ export default function SalesSettingsRoute() {</ScrollArea>);}++const costCategoryKeys = [+ "materialCost",+ "partCost",+ "toolCost",+ "consumableCost",+ "laborCost",+ "machineCost",+ "overheadCost",+ "outsideCost"+] as const;++const categoryLabels: Record<string, string> = {+ materialCost: "Material",+ partCost: "Part",+ toolCost: "Tool",+ consumableCost: "Consumable",+ laborCost: "Labor",+ machineCost: "Machine",+ overheadCost: "Overhead",+ outsideCost: "Outside"+};++function CategoryMarkupsCard({+ companySettings,+ fetcher+}: {+ companySettings: ReturnType<+ typeof useLoaderData<typeof loader>+ >["companySettings"];+ fetcher: ReturnType<typeof useFetcher<typeof action>>;+}) {+ const saved = (companySettings as Record<string, unknown>)+ .quoteLineCategoryMarkups as Record<string, number> | null;++ return (+ <Card>+ <ValidatedForm+ method="post"+ validator={quoteLineCategoryMarkupsSettingsValidator}+ defaultValues={{+ materialCost: saved?.materialCost ?? 0,+ partCost: saved?.partCost ?? 0,+ toolCost: saved?.toolCost ?? 0,+ consumableCost: saved?.consumableCost ?? 0,+ laborCost: saved?.laborCost ?? 0,+ machineCost: saved?.machineCost ?? 0,+ overheadCost: saved?.overheadCost ?? 0,+ outsideCost: saved?.outsideCost ?? 0+ }}+ fetcher={fetcher}+ >+ <input type="hidden" name="intent" value="categoryMarkups" />+ <CardHeader>+ <CardTitle>Quote Markups</CardTitle>+ <CardDescription>+ Set default markup percentages for each cost category on new quote+ lines+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">+ {costCategoryKeys.map((key) => (+ <Number+ key={key}+ name={key}+ label={categoryLabels[key]}+ formatOptions={{+ style: "percent",+ minimumFractionDigits: 0,+ maximumFractionDigits: 2+ }}+ minValue={0}+ />+ ))}+ </div>+ </CardContent>+ <CardFooter>+ <Submit+ isDisabled={fetcher.state !== "idle"}+ isLoading={+ fetcher.state !== "idle" &&+ fetcher.formData?.get("intent") === "categoryMarkups"+ }+ >+ Save+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>+ );+}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 553b8a8ef3..3c05d53a43 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -2510,6 +2510,7 @@ export type Database = {suggestionNotificationGroup: string[]taxId: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Insert: {@@ -2536,6 +2537,7 @@ export type Database = {suggestionNotificationGroup?: string[]taxId?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Update: {@@ -2562,6 +2564,7 @@ export type Database = {suggestionNotificationGroup?: string[]taxId?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Relationships: [@@ -2609,6 +2612,160 @@ export type Database = {},]}+ companyAccountsPayableBillingAddress: {+ Row: {+ addressLine1: string | null+ addressLine2: string | null+ city: string | null+ countryCode: string | null+ email: string | null+ fax: string | null+ id: string+ name: string | null+ phone: string | null+ postalCode: string | null+ state: string | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ addressLine1?: string | null+ addressLine2?: string | null+ city?: string | null+ countryCode?: string | null+ email?: string | null+ fax?: string | null+ id: string+ name?: string | null+ phone?: string | null+ postalCode?: string | null+ state?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ addressLine1?: string | null+ addressLine2?: string | null+ city?: string | null+ countryCode?: string | null+ email?: string | null+ fax?: string | null+ id?: string+ name?: string | null+ phone?: string | null+ postalCode?: string | null+ state?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "companyAccountsPayableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companyAccountsPayableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companyAccountsPayableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "companyAccountsPayableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ ]+ }+ companyAccountsReceivableBillingAddress: {+ Row: {+ addressLine1: string | null+ addressLine2: string | null+ city: string | null+ countryCode: string | null+ email: string | null+ fax: string | null+ id: string+ name: string | null+ phone: string | null+ postalCode: string | null+ state: string | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ addressLine1?: string | null+ addressLine2?: string | null+ city?: string | null+ countryCode?: string | null+ email?: string | null+ fax?: string | null+ id: string+ name?: string | null+ phone?: string | null+ postalCode?: string | null+ state?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ addressLine1?: string | null+ addressLine2?: string | null+ city?: string | null+ countryCode?: string | null+ email?: string | null+ fax?: string | null+ id?: string+ name?: string | null+ phone?: string | null+ postalCode?: string | null+ state?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "companyAccountsReceivableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companyAccountsReceivableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companyAccountsReceivableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "companyAccountsReceivableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ ]+ }companyIntegration: {Row: {active: boolean@@ -2762,6 +2919,10 @@ export type Database = {}companySettings: {Row: {+ accountsPayableAddress: boolean | null+ accountsPayableEmail: string | null+ accountsReceivableAddress: boolean | null+ accountsReceivableEmail: string | nulldefaultCustomerCc: string[] | nulldefaultSupplierCc: string[] | nulldigitalQuoteEnabled: boolean@@ -2783,6 +2944,7 @@ export type Database = {productLabelSize: string | nullpurchasePriceUpdateTiming: Database["public"]["Enums"]["purchasePriceUpdateTiming"]qualityDispatchNotificationGroup: string[] | null+ quoteLineCategoryMarkups: Json | nullrfqReadyNotificationGroup: string[]salesJobCompletedNotificationGroup: string[]shelfLabelSize: string | null@@ -2790,6 +2952,10 @@ export type Database = {useMetric: boolean}Insert: {+ accountsPayableAddress?: boolean | null+ accountsPayableEmail?: string | null+ accountsReceivableAddress?: boolean | null+ accountsReceivableEmail?: string | nulldefaultCustomerCc?: string[] | nulldefaultSupplierCc?: string[] | nulldigitalQuoteEnabled?: boolean@@ -2811,6 +2977,7 @@ export type Database = {productLabelSize?: string | nullpurchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]qualityDispatchNotificationGroup?: string[] | null+ quoteLineCategoryMarkups?: Json | nullrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]shelfLabelSize?: string | null@@ -2818,6 +2985,10 @@ export type Database = {useMetric?: boolean}Update: {+ accountsPayableAddress?: boolean | null+ accountsPayableEmail?: string | null+ accountsReceivableAddress?: boolean | null+ accountsReceivableEmail?: string | nulldefaultCustomerCc?: string[] | nulldefaultSupplierCc?: string[] | nulldigitalQuoteEnabled?: boolean@@ -2839,6 +3010,7 @@ export type Database = {productLabelSize?: string | nullpurchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]qualityDispatchNotificationGroup?: string[] | null+ quoteLineCategoryMarkups?: Json | nullrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]shelfLabelSize?: string | null@@ -4157,16 +4329,17 @@ export type Database = {embedding: unknownfax: string | nullid: string- invoicingContactId: string | nulllogo: string | nullname: stringphone: string | nullsalesContactId: string | null+ salesLocationId: string | nulltags: string[] | nulltaxId: string | nulltaxPercent: numberupdatedAt: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Insert: {@@ -4183,16 +4356,17 @@ export type Database = {embedding?: unknownfax?: string | nullid?: string- invoicingContactId?: string | nulllogo?: string | nullname: stringphone?: string | nullsalesContactId?: string | null+ salesLocationId?: string | nulltags?: string[] | nulltaxId?: string | nulltaxPercent?: numberupdatedAt?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Update: {@@ -4209,16 +4383,17 @@ export type Database = {embedding?: unknownfax?: string | nullid?: string- invoicingContactId?: string | nulllogo?: string | nullname?: stringphone?: string | nullsalesContactId?: string | null+ salesLocationId?: string | nulltags?: string[] | nulltaxId?: string | nulltaxPercent?: numberupdatedAt?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Relationships: [@@ -4377,17 +4552,17 @@ export type Database = {referencedColumns: ["id"]},{- foreignKeyName: "customer_invoicingContactId_fkey"- columns: ["invoicingContactId"]+ foreignKeyName: "customer_salesContactId_fkey"+ columns: ["salesContactId"]isOneToOne: falsereferencedRelation: "customerContact"referencedColumns: ["id"]},{- foreignKeyName: "customer_salesContactId_fkey"- columns: ["salesContactId"]+ foreignKeyName: "customer_salesLocationId_fkey"+ columns: ["salesLocationId"]isOneToOne: false- referencedRelation: "customerContact"+ referencedRelation: "customerLocation"referencedColumns: ["id"]},{@@ -25034,6 +25209,8 @@ export type Database = {quantityToInvoice: number | nullquantityToReceive: number | nullreceivedComplete: boolean+ receivedDate: string | null+ requestedDate: string | nullrequiresInspection: booleansetupPrice: number | nullshelfId: string | null@@ -25081,6 +25258,8 @@ export type Database = {quantityToInvoice?: number | nullquantityToReceive?: number | nullreceivedComplete?: boolean+ receivedDate?: string | null+ requestedDate?: string | nullrequiresInspection?: booleansetupPrice?: number | nullshelfId?: string | null@@ -25128,6 +25307,8 @@ export type Database = {quantityToInvoice?: number | nullquantityToReceive?: number | nullreceivedComplete?: boolean+ receivedDate?: string | null+ requestedDate?: string | nullrequiresInspection?: booleansetupPrice?: number | nullshelfId?: string | null@@ -27828,6 +28009,7 @@ export type Database = {}quoteLinePrice: {Row: {+ categoryMarkups: Json | nullconvertedNetExtendedPrice: number | nullconvertedNetUnitPrice: number | nullconvertedShippingCost: number | null@@ -27848,6 +28030,7 @@ export type Database = {updatedBy: string | null}Insert: {+ categoryMarkups?: Json | nullconvertedNetExtendedPrice?: number | nullconvertedNetUnitPrice?: number | nullconvertedShippingCost?: number | null@@ -27868,6 +28051,7 @@ export type Database = {updatedBy?: string | null}Update: {+ categoryMarkups?: Json | nullconvertedNetExtendedPrice?: number | nullconvertedNetUnitPrice?: number | nullconvertedShippingCost?: number | null@@ -33134,6 +33318,48 @@ export type Database = {},]}+ searchIndex_6c79NxG3ZDag1uLg7D2uMy: {+ Row: {+ createdAt: string+ description: string | null+ entityId: string+ entityType: string+ id: number+ link: string+ metadata: Json | null+ searchVector: unknown+ tags: string[] | null+ title: string+ updatedAt: string | null+ }+ Insert: {+ createdAt?: string+ description?: string | null+ entityId: string+ entityType: string+ id?: number+ link: string+ metadata?: Json | null+ searchVector?: unknown+ tags?: string[] | null+ title: string+ updatedAt?: string | null+ }+ Update: {+ createdAt?: string+ description?: string | null+ entityId?: string+ entityType?: string+ id?: number+ link?: string+ metadata?: Json | null+ searchVector?: unknown+ tags?: string[] | null+ title?: string+ updatedAt?: string | null+ }+ Relationships: []+ }searchIndexRegistry: {Row: {companyId: string@@ -35416,11 +35642,11 @@ export type Database = {embedding: unknownfax: string | nullid: string- invoicingContactId: string | nulllogo: string | nullname: stringphone: string | nullpurchasingContactId: string | null+ purchasingLocationId: string | nullsupplierStatusId: string | nullsupplierTypeId: string | nulltags: string[] | null@@ -35428,6 +35654,7 @@ export type Database = {taxPercent: numberupdatedAt: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Insert: {@@ -35442,11 +35669,11 @@ export type Database = {embedding?: unknownfax?: string | nullid?: string- invoicingContactId?: string | nulllogo?: string | nullname: stringphone?: string | nullpurchasingContactId?: string | null+ purchasingLocationId?: string | nullsupplierStatusId?: string | nullsupplierTypeId?: string | nulltags?: string[] | null@@ -35454,6 +35681,7 @@ export type Database = {taxPercent?: numberupdatedAt?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Update: {@@ -35468,11 +35696,11 @@ export type Database = {embedding?: unknownfax?: string | nullid?: string- invoicingContactId?: string | nulllogo?: string | nullname?: stringphone?: string | nullpurchasingContactId?: string | null+ purchasingLocationId?: string | nullsupplierStatusId?: string | nullsupplierTypeId?: string | nulltags?: string[] | null@@ -35480,6 +35708,7 @@ export type Database = {taxPercent?: numberupdatedAt?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Relationships: [@@ -35624,17 +35853,17 @@ export type Database = {referencedColumns: ["code"]},{- foreignKeyName: "supplier_invoicingContactId_fkey"- columns: ["invoicingContactId"]+ foreignKeyName: "supplier_purchasingContactId_fkey"+ columns: ["purchasingContactId"]isOneToOne: falsereferencedRelation: "supplierContact"referencedColumns: ["id"]},{- foreignKeyName: "supplier_purchasingContactId_fkey"- columns: ["purchasingContactId"]+ foreignKeyName: "supplier_purchasingLocationId_fkey"+ columns: ["purchasingLocationId"]isOneToOne: false- referencedRelation: "supplierContact"+ referencedRelation: "supplierLocation"referencedColumns: ["id"]},{@@ -43067,10 +43296,13 @@ export type Database = {Row: {addressLine1: string | nulladdressLine2: string | null+ auditLogEnabled: boolean | nullbaseCurrencyCode: string | nullcity: string | nullcompanyId: string | nullcountryCode: string | null+ countryName: string | null+ createdAt: string | nullemail: string | nullemployeeType: string | nullfax: string | null@@ -43086,9 +43318,11 @@ export type Database = {role: Database["public"]["Enums"]["role"] | nullslackChannel: string | nullstateProvince: string | null+ suggestionNotificationGroup: string[] | nulltaxId: string | nullupdatedBy: string | nulluserId: string | null+ vatNumber: string | nullwebsite: string | null}Relationships: [@@ -43563,18 +43797,20 @@ export type Database = {externalId: Json | nullfax: string | nullid: string | null- invoicingContactId: string | nulllogo: string | nullname: string | nullorderCount: number | nullphone: string | nullsalesContactId: string | null+ salesLocationId: string | nullstatus: string | null+ tags: string[] | nulltaxId: string | nulltaxPercent: number | nulltype: string | nullupdatedAt: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Relationships: [@@ -43733,17 +43969,17 @@ export type Database = {referencedColumns: ["id"]},{- foreignKeyName: "customer_invoicingContactId_fkey"- columns: ["invoicingContactId"]+ foreignKeyName: "customer_salesContactId_fkey"+ columns: ["salesContactId"]isOneToOne: falsereferencedRelation: "customerContact"referencedColumns: ["id"]},{- foreignKeyName: "customer_salesContactId_fkey"- columns: ["salesContactId"]+ foreignKeyName: "customer_salesLocationId_fkey"+ columns: ["salesLocationId"]isOneToOne: false- referencedRelation: "customerContact"+ referencedRelation: "customerLocation"referencedColumns: ["id"]},{@@ -47665,14 +47901,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -48777,6 +49013,8 @@ export type Database = {quantityToInvoice: number | nullquantityToReceive: number | nullreceivedComplete: boolean | null+ receivedDate: string | null+ requestedDate: string | nullrequiresInspection: boolean | nullsetupPrice: number | nullshelfId: string | null@@ -49052,11 +49290,15 @@ export type Database = {supplierAddressLine1: string | nullsupplierAddressLine2: string | nullsupplierCity: string | null+ supplierContactEmail: string | null+ supplierContactName: string | nullsupplierCountryCode: string | nullsupplierCountryName: string | nullsupplierName: string | nullsupplierPostalCode: string | nullsupplierStateProvince: string | null+ supplierTaxId: string | null+ supplierVatNumber: string | null}Relationships: [{@@ -49083,6 +49325,8 @@ export type Database = {companyId: string | nullcreatedAt: string | nullcreatedBy: string | null+ createdByEmail: string | null+ createdByFullName: string | nullcurrencyCode: string | nullcustomFields: Json | nulldeliveryDate: string | null@@ -52188,8 +52432,23 @@ export type Database = {invoiceCustomerName: string | nullinvoicePostalCode: string | nullinvoiceStateProvince: string | null+ shipmentAddressLine1: string | null+ shipmentAddressLine2: string | null+ shipmentCity: string | null+ shipmentCountryCode: string | null+ shipmentCountryName: string | null+ shipmentCustomerName: string | null+ shipmentPostalCode: string | null+ shipmentStateProvince: string | null}Relationships: [+ {+ foreignKeyName: "address_countryCode_fkey"+ columns: ["customerCountryCode"]+ isOneToOne: false+ referencedRelation: "country"+ referencedColumns: ["alpha2"]+ },{foreignKeyName: "address_countryCode_fkey"columns: ["invoiceCountryCode"]@@ -52199,7 +52458,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -52742,14 +53001,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -54948,13 +55207,13 @@ export type Database = {externalId: Json | nullfax: string | nullid: string | null- invoicingContactId: string | nulllogo: string | nullname: string | nullorderCount: number | nullpartCount: number | nullphone: string | nullpurchasingContactId: string | null+ purchasingLocationId: string | nullstatus: string | nullsupplierStatusId: string | nullsupplierTypeId: string | null@@ -54964,6 +55223,7 @@ export type Database = {type: string | nullupdatedAt: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Relationships: [@@ -55108,17 +55368,17 @@ export type Database = {referencedColumns: ["code"]},{- foreignKeyName: "supplier_invoicingContactId_fkey"- columns: ["invoicingContactId"]+ foreignKeyName: "supplier_purchasingContactId_fkey"+ columns: ["purchasingContactId"]isOneToOne: falsereferencedRelation: "supplierContact"referencedColumns: ["id"]},{- foreignKeyName: "supplier_purchasingContactId_fkey"- columns: ["purchasingContactId"]+ foreignKeyName: "supplier_purchasingLocationId_fkey"+ columns: ["purchasingLocationId"]isOneToOne: false- referencedRelation: "supplierContact"+ referencedRelation: "supplierLocation"referencedColumns: ["id"]},{@@ -55910,7 +56170,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: number@@ -55950,7 +56209,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: number@@ -55990,7 +56248,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: number@@ -56369,7 +56626,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: number@@ -57080,7 +57336,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: numberdiff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex 71f8de786f..f4db15ae42 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -19,6 +19,7 @@ import {} from "npm:@internationalized/date";import { corsHeaders } from "../lib/headers.ts";import {+ calculateQuoteLinePrices,getJobMethodTree,getQuoteMethodTree,getRatesFromSupplierProcesses,@@ -2147,6 +2148,8 @@ serve(async (req: Request) => {await traverseMethod(methodTree, quoteMakeMethod.data.id);});+ await calculateQuoteLinePrices(client, quoteId, quoteLineId, companyId, userId);+break;}case "itemToQuoteMakeMethod": {@@ -4743,6 +4746,8 @@ serve(async (req: Request) => {} // end if (parts.billOfProcess)});+ await calculateQuoteLinePrices(client, targetQuoteId, targetQuoteLineId, companyId, userId);+break;}diff --git a/packages/database/supabase/functions/lib/methods.ts b/packages/database/supabase/functions/lib/methods.tsindex 4efded587f..59202a0f8d 100644--- a/packages/database/supabase/functions/lib/methods.ts+++ b/packages/database/supabase/functions/lib/methods.ts@@ -290,3 +290,500 @@ export const getRatesFromSupplierProcesses =operationLeadTime: 0,};};++type SupplierPriceMap = Record<+ string,+ {+ priceBreaks: { quantity: number; unitPrice: number }[];+ fallbackUnitPrice: number | null;+ }+>;++type CostCategoryKey =+ | "materialCost"+ | "partCost"+ | "toolCost"+ | "consumableCost"+ | "serviceCost"+ | "laborCost"+ | "machineCost"+ | "overheadCost"+ | "outsideCost";++const costCategoryKeys: CostCategoryKey[] = [+ "materialCost",+ "partCost",+ "toolCost",+ "consumableCost",+ "serviceCost",+ "laborCost",+ "machineCost",+ "overheadCost",+ "outsideCost",+];++type CostEffects = Record<CostCategoryKey, ((qty: number) => number)[]>;++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 });++ const spToItem = new Map<string, string>();+ for (const sp of supplierParts.data) {+ spToItem.set(sp.id, sp.itemId);+ }++ const result: SupplierPriceMap = {};++ 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;+ }+ }++ 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;+}++function lookupPriceFromBreaks(+ priceBreaks: { quantity: number; unitPrice: number }[],+ 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;+}++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+ );+}++function normalizeTimeToHours(+ time: number,+ unit: string+): { fixedHours: number; hoursPerUnit: number } {+ let fixedHours = 0;+ let hoursPerUnit = 0;+ switch (unit) {+ case "Total Hours":+ fixedHours = time;+ break;+ case "Total Minutes":+ fixedHours = time / 60;+ break;+ case "Hours/Piece":+ hoursPerUnit = time;+ break;+ case "Hours/100 Pieces":+ hoursPerUnit = time / 100;+ break;+ case "Hours/1000 Pieces":+ hoursPerUnit = time / 1000;+ break;+ case "Minutes/Piece":+ hoursPerUnit = time / 60;+ break;+ case "Minutes/100 Pieces":+ hoursPerUnit = time / 100 / 60;+ break;+ case "Minutes/1000 Pieces":+ hoursPerUnit = time / 1000 / 60;+ break;+ case "Pieces/Hour":+ hoursPerUnit = 1 / time;+ break;+ case "Pieces/Minute":+ hoursPerUnit = 1 / (time / 60);+ break;+ case "Seconds/Piece":+ hoursPerUnit = time / 3600;+ break;+ }+ return { fixedHours, hoursPerUnit };+}++export async function calculateQuoteLinePrices(+ client: SupabaseClient<Database>,+ quoteId: string,+ quoteLineId: string,+ companyId: string,+ userId: string+) {+ // 1. Fetch data in parallel+ const [quoteLineResult, settingsResult, quoteResult, operationsResult] =+ await Promise.all([+ client+ .from("quoteLine")+ .select("quantity, methodType, unitPricePrecision")+ .eq("id", quoteLineId)+ .single(),+ client+ .from("companySettings")+ .select("quoteLineCategoryMarkups")+ .eq("id", companyId)+ .single(),+ client.from("quote").select("exchangeRate").eq("id", quoteId).single(),+ client+ .from("quoteOperation")+ .select("*")+ .eq("quoteLineId", quoteLineId),+ ]);++ if (quoteLineResult.error) throw new Error("Failed to get quote line");+ if (settingsResult.error) throw new Error("Failed to get company settings");+ if (quoteResult.error) throw new Error("Failed to get quote");++ const quoteLine = quoteLineResult.data;+ const quantities = quoteLine.quantity ?? [1];+ const exchangeRate = quoteResult.data.exchangeRate ?? 1;+ const precision = quoteLine.unitPricePrecision ?? 2;+ const operations = operationsResult.data ?? [];++ // Parse default markups from settings (stored as decimals, convert to whole numbers)+ const rawMarkups =+ (settingsResult.data.quoteLineCategoryMarkups as Record<string, number>) ??+ {};+ const defaultMarkups: Record<string, number> = {};+ for (const [key, value] of Object.entries(rawMarkups)) {+ defaultMarkups[key] = value * 100;+ }++ // 2. Fix Buy material costs with supplier price breaks+ const buyMaterials = await client+ .from("quoteMaterial")+ .select("id, itemId, unitCost")+ .eq("quoteLineId", quoteLineId)+ .eq("methodType", "Buy");++ const buyItemIds = [+ ...new Set((buyMaterials.data ?? []).map((m) => m.itemId)),+ ];+ const priceMap = await getSupplierPriceBreaksForItems(client, buyItemIds);++ for (const mat of buyMaterials.data ?? []) {+ const price = lookupBuyPriceFromMap(mat.itemId, 1, priceMap, mat.unitCost);+ if (price !== mat.unitCost) {+ await client+ .from("quoteMaterial")+ .update({ unitCost: price })+ .eq("id", mat.id);+ }+ }++ // 3. Build the quote method tree+ const rootMethod = await client+ .from("quoteMakeMethod")+ .select("id")+ .eq("quoteLineId", quoteLineId)+ .is("parentMaterialId", null)+ .single();++ if (rootMethod.error) throw new Error("Failed to get root make method");++ const tree = await getQuoteMethodTree(client, rootMethod.data.id);+ if (tree.error) throw new Error("Failed to get quote method tree");++ // 4. Enhance tree: multiply quantities through parent chain, attach operations+ type EnhancedNode = {+ itemId: string;+ itemType: string;+ methodType: string;+ quantity: number;+ unitCost: number;+ quoteMaterialMakeMethodId: string;+ operations: typeof operations;+ children: EnhancedNode[];+ };++ function buildEnhancedTree(+ node: QuoteMethodTreeItem,+ parentQuantity: number+ ): EnhancedNode {+ const qty = node.data.quantity * parentQuantity;+ const nodeOps = operations.filter(+ (o) => o.quoteMakeMethodId === node.data.quoteMaterialMakeMethodId+ );+ return {+ itemId: node.data.itemId,+ itemType: node.data.itemType,+ methodType: node.data.methodType,+ quantity: qty,+ unitCost: node.data.unitCost,+ quoteMaterialMakeMethodId: node.data.quoteMaterialMakeMethodId,+ operations: nodeOps,+ children: node.children.map((c) => buildEnhancedTree(c, qty)),+ };+ }++ // 5. Build cost effects+ const effects: CostEffects = {+ materialCost: [],+ partCost: [],+ toolCost: [],+ consumableCost: [],+ serviceCost: [],+ laborCost: [],+ machineCost: [],+ overheadCost: [],+ outsideCost: [],+ };++ function pushBuyCostEffect(+ itemId: string,+ itemType: string,+ quantity: number,+ unitCost: number+ ) {+ const costFn = (outerQty: number) => {+ const requestedQty = quantity * outerQty;+ const resolved = lookupBuyPriceFromMap(+ itemId,+ requestedQty,+ priceMap,+ 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;+ }+ }++ function walkTree(node: EnhancedNode) {+ if (node.methodType === "Buy") {+ pushBuyCostEffect(node.itemId, node.itemType, node.quantity, node.unitCost);+ } else if (node.methodType === "Pick") {+ const costFn = (quantity: number) =>+ node.unitCost * node.quantity * quantity;+ switch (node.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;+ }+ }++ for (const operation of node.operations) {+ if (operation.operationType === "Inside") {+ if (operation.setupTime) {+ const { fixedHours, hoursPerUnit } = normalizeTimeToHours(+ operation.setupTime,+ operation.setupUnit+ );+ effects.laborCost.push((quantity) => {+ return (+ hoursPerUnit * quantity * node.quantity * (operation.laborRate ?? 0) ++ fixedHours * (operation.laborRate ?? 0)+ );+ });+ effects.overheadCost.push((quantity) => {+ return (+ hoursPerUnit *+ quantity *+ node.quantity *+ (operation.overheadRate ?? 0) ++ fixedHours * (operation.overheadRate ?? 0)+ );+ });+ }++ let laborFixedHours = 0;+ let laborHoursPerUnit = 0;+ let machineFixedHours = 0;+ let machineHoursPerUnit = 0;++ if (operation.laborTime) {+ const normalized = normalizeTimeToHours(+ operation.laborTime,+ operation.laborUnit+ );+ laborFixedHours = normalized.fixedHours;+ laborHoursPerUnit = normalized.hoursPerUnit;++ effects.laborCost.push((quantity) => {+ return (+ laborHoursPerUnit *+ quantity *+ node.quantity *+ (operation.laborRate ?? 0) ++ laborFixedHours * (operation.laborRate ?? 0)+ );+ });+ }++ if (operation.machineTime) {+ const normalized = normalizeTimeToHours(+ operation.machineTime,+ operation.machineUnit+ );+ machineFixedHours = normalized.fixedHours;+ machineHoursPerUnit = normalized.hoursPerUnit;++ effects.machineCost.push((quantity) => {+ return (+ machineHoursPerUnit *+ quantity *+ node.quantity *+ (operation.machineRate ?? 0) ++ machineFixedHours * (operation.machineRate ?? 0)+ );+ });+ }++ const hoursPerUnit = Math.max(laborHoursPerUnit, machineHoursPerUnit);+ const fixedHours = Math.max(laborFixedHours, machineFixedHours);++ effects.overheadCost.push((quantity) => {+ if (hoursPerUnit * quantity * node.quantity > fixedHours) {+ return (+ hoursPerUnit *+ quantity *+ node.quantity *+ (operation.overheadRate ?? 0)+ );+ } else {+ return fixedHours * (operation.overheadRate ?? 0);+ }+ });+ } else if (operation.operationType === "Outside") {+ effects.outsideCost.push((quantity) => {+ const unitCost =+ operation.operationUnitCost * node.quantity * quantity;+ return Math.max(operation.operationMinimumCost, unitCost);+ });+ }+ }++ for (const child of node.children) {+ walkTree(child);+ }+ }++ // Build enhanced trees and walk them+ for (const root of tree.data) {+ const enhanced = buildEnhancedTree(root, 1);+ walkTree(enhanced);+ }++ // 6. Compute prices for each quantity+ const priceRows = quantities.map((qty) => {+ const categoryCosts: Record<CostCategoryKey, number> = {+ materialCost: 0,+ partCost: 0,+ toolCost: 0,+ consumableCost: 0,+ serviceCost: 0,+ laborCost: 0,+ machineCost: 0,+ overheadCost: 0,+ outsideCost: 0,+ };++ for (const key of costCategoryKeys) {+ categoryCosts[key] = effects[key].reduce(+ (acc, effect) => acc + effect(qty),+ 0+ );+ // Convert to per-unit cost+ if (qty > 0) {+ categoryCosts[key] = categoryCosts[key] / qty;+ }+ }++ // Apply markups+ const unitPrice = costCategoryKeys.reduce((sum, key) => {+ const cost = categoryCosts[key] ?? 0;+ const markup = defaultMarkups[key] ?? 0;+ return sum + cost * (1 + markup / 100);+ }, 0);++ const roundedUnitPrice = Number(unitPrice.toFixed(precision));++ return {+ quoteId,+ quoteLineId,+ quantity: qty,+ unitPrice: roundedUnitPrice,+ categoryMarkups: defaultMarkups,+ exchangeRate,+ createdBy: userId,+ leadTime: 0,+ discountPercent: 0,+ };+ });++ // 7. Insert quoteLinePrice rows+ const insertResult = await client.from("quoteLinePrice").insert(priceRows);+ if (insertResult.error) throw new Error("Failed to insert quote line prices");+}diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 553b8a8ef3..3c05d53a43 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -2510,6 +2510,7 @@ export type Database = {suggestionNotificationGroup: string[]taxId: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Insert: {@@ -2536,6 +2537,7 @@ export type Database = {suggestionNotificationGroup?: string[]taxId?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Update: {@@ -2562,6 +2564,7 @@ export type Database = {suggestionNotificationGroup?: string[]taxId?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Relationships: [@@ -2609,6 +2612,160 @@ export type Database = {},]}+ companyAccountsPayableBillingAddress: {+ Row: {+ addressLine1: string | null+ addressLine2: string | null+ city: string | null+ countryCode: string | null+ email: string | null+ fax: string | null+ id: string+ name: string | null+ phone: string | null+ postalCode: string | null+ state: string | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ addressLine1?: string | null+ addressLine2?: string | null+ city?: string | null+ countryCode?: string | null+ email?: string | null+ fax?: string | null+ id: string+ name?: string | null+ phone?: string | null+ postalCode?: string | null+ state?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ addressLine1?: string | null+ addressLine2?: string | null+ city?: string | null+ countryCode?: string | null+ email?: string | null+ fax?: string | null+ id?: string+ name?: string | null+ phone?: string | null+ postalCode?: string | null+ state?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "companyAccountsPayableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companyAccountsPayableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companyAccountsPayableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "companyAccountsPayableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ ]+ }+ companyAccountsReceivableBillingAddress: {+ Row: {+ addressLine1: string | null+ addressLine2: string | null+ city: string | null+ countryCode: string | null+ email: string | null+ fax: string | null+ id: string+ name: string | null+ phone: string | null+ postalCode: string | null+ state: string | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ addressLine1?: string | null+ addressLine2?: string | null+ city?: string | null+ countryCode?: string | null+ email?: string | null+ fax?: string | null+ id: string+ name?: string | null+ phone?: string | null+ postalCode?: string | null+ state?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ addressLine1?: string | null+ addressLine2?: string | null+ city?: string | null+ countryCode?: string | null+ email?: string | null+ fax?: string | null+ id?: string+ name?: string | null+ phone?: string | null+ postalCode?: string | null+ state?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "companyAccountsReceivableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companyAccountsReceivableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companyAccountsReceivableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "companyAccountsReceivableBillingAddress_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ ]+ }companyIntegration: {Row: {active: boolean@@ -2762,6 +2919,10 @@ export type Database = {}companySettings: {Row: {+ accountsPayableAddress: boolean | null+ accountsPayableEmail: string | null+ accountsReceivableAddress: boolean | null+ accountsReceivableEmail: string | nulldefaultCustomerCc: string[] | nulldefaultSupplierCc: string[] | nulldigitalQuoteEnabled: boolean@@ -2783,6 +2944,7 @@ export type Database = {productLabelSize: string | nullpurchasePriceUpdateTiming: Database["public"]["Enums"]["purchasePriceUpdateTiming"]qualityDispatchNotificationGroup: string[] | null+ quoteLineCategoryMarkups: Json | nullrfqReadyNotificationGroup: string[]salesJobCompletedNotificationGroup: string[]shelfLabelSize: string | null@@ -2790,6 +2952,10 @@ export type Database = {useMetric: boolean}Insert: {+ accountsPayableAddress?: boolean | null+ accountsPayableEmail?: string | null+ accountsReceivableAddress?: boolean | null+ accountsReceivableEmail?: string | nulldefaultCustomerCc?: string[] | nulldefaultSupplierCc?: string[] | nulldigitalQuoteEnabled?: boolean@@ -2811,6 +2977,7 @@ export type Database = {productLabelSize?: string | nullpurchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]qualityDispatchNotificationGroup?: string[] | null+ quoteLineCategoryMarkups?: Json | nullrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]shelfLabelSize?: string | null@@ -2818,6 +2985,10 @@ export type Database = {useMetric?: boolean}Update: {+ accountsPayableAddress?: boolean | null+ accountsPayableEmail?: string | null+ accountsReceivableAddress?: boolean | null+ accountsReceivableEmail?: string | nulldefaultCustomerCc?: string[] | nulldefaultSupplierCc?: string[] | nulldigitalQuoteEnabled?: boolean@@ -2839,6 +3010,7 @@ export type Database = {productLabelSize?: string | nullpurchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]qualityDispatchNotificationGroup?: string[] | null+ quoteLineCategoryMarkups?: Json | nullrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]shelfLabelSize?: string | null@@ -4157,16 +4329,17 @@ export type Database = {embedding: unknownfax: string | nullid: string- invoicingContactId: string | nulllogo: string | nullname: stringphone: string | nullsalesContactId: string | null+ salesLocationId: string | nulltags: string[] | nulltaxId: string | nulltaxPercent: numberupdatedAt: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Insert: {@@ -4183,16 +4356,17 @@ export type Database = {embedding?: unknownfax?: string | nullid?: string- invoicingContactId?: string | nulllogo?: string | nullname: stringphone?: string | nullsalesContactId?: string | null+ salesLocationId?: string | nulltags?: string[] | nulltaxId?: string | nulltaxPercent?: numberupdatedAt?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Update: {@@ -4209,16 +4383,17 @@ export type Database = {embedding?: unknownfax?: string | nullid?: string- invoicingContactId?: string | nulllogo?: string | nullname?: stringphone?: string | nullsalesContactId?: string | null+ salesLocationId?: string | nulltags?: string[] | nulltaxId?: string | nulltaxPercent?: numberupdatedAt?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Relationships: [@@ -4377,17 +4552,17 @@ export type Database = {referencedColumns: ["id"]},{- foreignKeyName: "customer_invoicingContactId_fkey"- columns: ["invoicingContactId"]+ foreignKeyName: "customer_salesContactId_fkey"+ columns: ["salesContactId"]isOneToOne: falsereferencedRelation: "customerContact"referencedColumns: ["id"]},{- foreignKeyName: "customer_salesContactId_fkey"- columns: ["salesContactId"]+ foreignKeyName: "customer_salesLocationId_fkey"+ columns: ["salesLocationId"]isOneToOne: false- referencedRelation: "customerContact"+ referencedRelation: "customerLocation"referencedColumns: ["id"]},{@@ -25034,6 +25209,8 @@ export type Database = {quantityToInvoice: number | nullquantityToReceive: number | nullreceivedComplete: boolean+ receivedDate: string | null+ requestedDate: string | nullrequiresInspection: booleansetupPrice: number | nullshelfId: string | null@@ -25081,6 +25258,8 @@ export type Database = {quantityToInvoice?: number | nullquantityToReceive?: number | nullreceivedComplete?: boolean+ receivedDate?: string | null+ requestedDate?: string | nullrequiresInspection?: booleansetupPrice?: number | nullshelfId?: string | null@@ -25128,6 +25307,8 @@ export type Database = {quantityToInvoice?: number | nullquantityToReceive?: number | nullreceivedComplete?: boolean+ receivedDate?: string | null+ requestedDate?: string | nullrequiresInspection?: booleansetupPrice?: number | nullshelfId?: string | null@@ -27828,6 +28009,7 @@ export type Database = {}quoteLinePrice: {Row: {+ categoryMarkups: Json | nullconvertedNetExtendedPrice: number | nullconvertedNetUnitPrice: number | nullconvertedShippingCost: number | null@@ -27848,6 +28030,7 @@ export type Database = {updatedBy: string | null}Insert: {+ categoryMarkups?: Json | nullconvertedNetExtendedPrice?: number | nullconvertedNetUnitPrice?: number | nullconvertedShippingCost?: number | null@@ -27868,6 +28051,7 @@ export type Database = {updatedBy?: string | null}Update: {+ categoryMarkups?: Json | nullconvertedNetExtendedPrice?: number | nullconvertedNetUnitPrice?: number | nullconvertedShippingCost?: number | null@@ -33134,6 +33318,48 @@ export type Database = {},]}+ searchIndex_6c79NxG3ZDag1uLg7D2uMy: {+ Row: {+ createdAt: string+ description: string | null+ entityId: string+ entityType: string+ id: number+ link: string+ metadata: Json | null+ searchVector: unknown+ tags: string[] | null+ title: string+ updatedAt: string | null+ }+ Insert: {+ createdAt?: string+ description?: string | null+ entityId: string+ entityType: string+ id?: number+ link: string+ metadata?: Json | null+ searchVector?: unknown+ tags?: string[] | null+ title: string+ updatedAt?: string | null+ }+ Update: {+ createdAt?: string+ description?: string | null+ entityId?: string+ entityType?: string+ id?: number+ link?: string+ metadata?: Json | null+ searchVector?: unknown+ tags?: string[] | null+ title?: string+ updatedAt?: string | null+ }+ Relationships: []+ }searchIndexRegistry: {Row: {companyId: string@@ -35416,11 +35642,11 @@ export type Database = {embedding: unknownfax: string | nullid: string- invoicingContactId: string | nulllogo: string | nullname: stringphone: string | nullpurchasingContactId: string | null+ purchasingLocationId: string | nullsupplierStatusId: string | nullsupplierTypeId: string | nulltags: string[] | null@@ -35428,6 +35654,7 @@ export type Database = {taxPercent: numberupdatedAt: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Insert: {@@ -35442,11 +35669,11 @@ export type Database = {embedding?: unknownfax?: string | nullid?: string- invoicingContactId?: string | nulllogo?: string | nullname: stringphone?: string | nullpurchasingContactId?: string | null+ purchasingLocationId?: string | nullsupplierStatusId?: string | nullsupplierTypeId?: string | nulltags?: string[] | null@@ -35454,6 +35681,7 @@ export type Database = {taxPercent?: numberupdatedAt?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Update: {@@ -35468,11 +35696,11 @@ export type Database = {embedding?: unknownfax?: string | nullid?: string- invoicingContactId?: string | nulllogo?: string | nullname?: stringphone?: string | nullpurchasingContactId?: string | null+ purchasingLocationId?: string | nullsupplierStatusId?: string | nullsupplierTypeId?: string | nulltags?: string[] | null@@ -35480,6 +35708,7 @@ export type Database = {taxPercent?: numberupdatedAt?: string | nullupdatedBy?: string | null+ vatNumber?: string | nullwebsite?: string | null}Relationships: [@@ -35624,17 +35853,17 @@ export type Database = {referencedColumns: ["code"]},{- foreignKeyName: "supplier_invoicingContactId_fkey"- columns: ["invoicingContactId"]+ foreignKeyName: "supplier_purchasingContactId_fkey"+ columns: ["purchasingContactId"]isOneToOne: falsereferencedRelation: "supplierContact"referencedColumns: ["id"]},{- foreignKeyName: "supplier_purchasingContactId_fkey"- columns: ["purchasingContactId"]+ foreignKeyName: "supplier_purchasingLocationId_fkey"+ columns: ["purchasingLocationId"]isOneToOne: false- referencedRelation: "supplierContact"+ referencedRelation: "supplierLocation"referencedColumns: ["id"]},{@@ -43067,10 +43296,13 @@ export type Database = {Row: {addressLine1: string | nulladdressLine2: string | null+ auditLogEnabled: boolean | nullbaseCurrencyCode: string | nullcity: string | nullcompanyId: string | nullcountryCode: string | null+ countryName: string | null+ createdAt: string | nullemail: string | nullemployeeType: string | nullfax: string | null@@ -43086,9 +43318,11 @@ export type Database = {role: Database["public"]["Enums"]["role"] | nullslackChannel: string | nullstateProvince: string | null+ suggestionNotificationGroup: string[] | nulltaxId: string | nullupdatedBy: string | nulluserId: string | null+ vatNumber: string | nullwebsite: string | null}Relationships: [@@ -43563,18 +43797,20 @@ export type Database = {externalId: Json | nullfax: string | nullid: string | null- invoicingContactId: string | nulllogo: string | nullname: string | nullorderCount: number | nullphone: string | nullsalesContactId: string | null+ salesLocationId: string | nullstatus: string | null+ tags: string[] | nulltaxId: string | nulltaxPercent: number | nulltype: string | nullupdatedAt: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Relationships: [@@ -43733,17 +43969,17 @@ export type Database = {referencedColumns: ["id"]},{- foreignKeyName: "customer_invoicingContactId_fkey"- columns: ["invoicingContactId"]+ foreignKeyName: "customer_salesContactId_fkey"+ columns: ["salesContactId"]isOneToOne: falsereferencedRelation: "customerContact"referencedColumns: ["id"]},{- foreignKeyName: "customer_salesContactId_fkey"- columns: ["salesContactId"]+ foreignKeyName: "customer_salesLocationId_fkey"+ columns: ["salesLocationId"]isOneToOne: false- referencedRelation: "customerContact"+ referencedRelation: "customerLocation"referencedColumns: ["id"]},{@@ -47665,14 +47901,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -48777,6 +49013,8 @@ export type Database = {quantityToInvoice: number | nullquantityToReceive: number | nullreceivedComplete: boolean | null+ receivedDate: string | null+ requestedDate: string | nullrequiresInspection: boolean | nullsetupPrice: number | nullshelfId: string | null@@ -49052,11 +49290,15 @@ export type Database = {supplierAddressLine1: string | nullsupplierAddressLine2: string | nullsupplierCity: string | null+ supplierContactEmail: string | null+ supplierContactName: string | nullsupplierCountryCode: string | nullsupplierCountryName: string | nullsupplierName: string | nullsupplierPostalCode: string | nullsupplierStateProvince: string | null+ supplierTaxId: string | null+ supplierVatNumber: string | null}Relationships: [{@@ -49083,6 +49325,8 @@ export type Database = {companyId: string | nullcreatedAt: string | nullcreatedBy: string | null+ createdByEmail: string | null+ createdByFullName: string | nullcurrencyCode: string | nullcustomFields: Json | nulldeliveryDate: string | null@@ -52188,8 +52432,23 @@ export type Database = {invoiceCustomerName: string | nullinvoicePostalCode: string | nullinvoiceStateProvince: string | null+ shipmentAddressLine1: string | null+ shipmentAddressLine2: string | null+ shipmentCity: string | null+ shipmentCountryCode: string | null+ shipmentCountryName: string | null+ shipmentCustomerName: string | null+ shipmentPostalCode: string | null+ shipmentStateProvince: string | null}Relationships: [+ {+ foreignKeyName: "address_countryCode_fkey"+ columns: ["customerCountryCode"]+ isOneToOne: false+ referencedRelation: "country"+ referencedColumns: ["alpha2"]+ },{foreignKeyName: "address_countryCode_fkey"columns: ["invoiceCountryCode"]@@ -52199,7 +52458,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -52742,14 +53001,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -54948,13 +55207,13 @@ export type Database = {externalId: Json | nullfax: string | nullid: string | null- invoicingContactId: string | nulllogo: string | nullname: string | nullorderCount: number | nullpartCount: number | nullphone: string | nullpurchasingContactId: string | null+ purchasingLocationId: string | nullstatus: string | nullsupplierStatusId: string | nullsupplierTypeId: string | null@@ -54964,6 +55223,7 @@ export type Database = {type: string | nullupdatedAt: string | nullupdatedBy: string | null+ vatNumber: string | nullwebsite: string | null}Relationships: [@@ -55108,17 +55368,17 @@ export type Database = {referencedColumns: ["code"]},{- foreignKeyName: "supplier_invoicingContactId_fkey"- columns: ["invoicingContactId"]+ foreignKeyName: "supplier_purchasingContactId_fkey"+ columns: ["purchasingContactId"]isOneToOne: falsereferencedRelation: "supplierContact"referencedColumns: ["id"]},{- foreignKeyName: "supplier_purchasingContactId_fkey"- columns: ["purchasingContactId"]+ foreignKeyName: "supplier_purchasingLocationId_fkey"+ columns: ["purchasingLocationId"]isOneToOne: false- referencedRelation: "supplierContact"+ referencedRelation: "supplierLocation"referencedColumns: ["id"]},{@@ -55910,7 +56170,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: number@@ -55950,7 +56209,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: number@@ -55990,7 +56248,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: number@@ -56369,7 +56626,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: number@@ -57080,7 +57336,6 @@ export type Database = {laborUnit: Database["public"]["Enums"]["factor"]machineTime: numbermachineUnit: Database["public"]["Enums"]["factor"]- operationDueDate: stringoperationOrder: numberoperationOrderType: Database["public"]["Enums"]["methodOperationOrder"]operationQuantity: numberdiff --git a/packages/database/supabase/migrations/20260307000000_quote-line-category-markups.sql b/packages/database/supabase/migrations/20260307000000_quote-line-category-markups.sqlnew file mode 100644index 0000000000..58c492bcdb--- /dev/null+++ b/packages/database/supabase/migrations/20260307000000_quote-line-category-markups.sql@@ -0,0 +1,2 @@+ALTER TABLE "quoteLinePrice" ADD COLUMN "categoryMarkups" JSONB DEFAULT '{}';+ALTER TABLE "companySettings" ADD COLUMN "quoteLineCategoryMarkups" JSONB DEFAULT '{}';\ No newline at end of file