Skip to content

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.

refactor: harden code for markup by categories on quotes

Brad Barbin95b0adefee6d
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index d93fec5e1d..e709a64919 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -2603,10 +2603,13 @@ export async function calculatePricesForQuantities(
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(),
+ // 1. Fetch quote (with companyId) and line in parallel
+ const [quoteResult, lineResult] = await Promise.all([
+ client
+ .from("quote")
+ .select("companyId, exchangeRate")
+ .eq("id", quoteId)
+ .single(),
client
.from("quoteLine")
.select("unitPricePrecision")
@@ -2614,7 +2617,16 @@ export async function calculatePricesForQuantities(
.single()
]);
- if (settingsResult.error || quoteResult.error || lineResult.error) return;
+ if (quoteResult.error || lineResult.error) return;
+
+ // Fetch settings filtered by company (required for service-role access)
+ const settingsResult = await client
+ .from("companySettings")
+ .select("quoteLineCategoryMarkups")
+ .eq("id", quoteResult.data.companyId)
+ .single();
+
+ if (settingsResult.error) return;
const exchangeRate = quoteResult.data.exchangeRate ?? 1;
const precision = lineResult.data.unitPricePrecision ?? 2;
@@ -2681,15 +2693,37 @@ export async function recalculateQuoteLinePrices(
if (!existingPrices.data?.length) return;
- // 2. Fetch line precision
- const lineResult = await client
- .from("quoteLine")
- .select("unitPricePrecision")
- .eq("id", quoteLineId)
- .single();
+ // 2. Fetch line precision and company default markups
+ const [lineResult, quoteResult] = await Promise.all([
+ client
+ .from("quoteLine")
+ .select("unitPricePrecision")
+ .eq("id", quoteLineId)
+ .single(),
+ client.from("quote").select("companyId").eq("id", quoteId).single()
+ ]);
const precision = lineResult.data?.unitPricePrecision ?? 2;
+ // Fetch default markups to use as fallback for legacy rows without categoryMarkups
+ let defaultMarkups: Record<string, number> = {};
+ if (quoteResult.data?.companyId) {
+ const settingsResult = await client
+ .from("companySettings")
+ .select("quoteLineCategoryMarkups")
+ .eq("id", quoteResult.data.companyId)
+ .single();
+
+ const rawDefaults =
+ (settingsResult.data?.quoteLineCategoryMarkups as Record<
+ string,
+ number
+ >) ?? {};
+ for (const [key, value] of Object.entries(rawDefaults)) {
+ defaultMarkups[key] = value * 100;
+ }
+ }
+
// 3. Build cost effects
const result = await buildCostEffects(client, quoteLineId);
if (!result) return;
@@ -2699,7 +2733,9 @@ export async function recalculateQuoteLinePrices(
// 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 rowMarkups = (row.categoryMarkups as Record<string, number>) ?? {};
+ const markups =
+ Object.keys(rowMarkups).length > 0 ? rowMarkups : defaultMarkups;
const categoryCosts: Record<string, number> = {};
for (const key of costCategoryKeys) {
@@ -2728,9 +2764,20 @@ export async function recalculateQuoteLinePrices(
});
// 5. Delete existing and re-insert with updated prices
- await client.from("quoteLinePrice").delete().eq("quoteLineId", quoteLineId);
+ const deleteResult = await client
+ .from("quoteLinePrice")
+ .delete()
+ .eq("quoteLineId", quoteLineId);
+
+ if (deleteResult.error) {
+ throw new Error(`Failed to delete prices: ${deleteResult.error.message}`);
+ }
+
+ const insertResult = await client.from("quoteLinePrice").insert(updatedRows);
- await client.from("quoteLinePrice").insert(updatedRows);
+ if (insertResult.error) {
+ throw new Error(`Failed to insert prices: ${insertResult.error.message}`);
+ }
}
export async function upsertQuoteLineMethod(
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.tsx
index 43ed74e314..1188b9247a 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
@@ -28,9 +28,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
JSON.parse((formData.get("quantities") ?? "[]") as string)
);
- const categoryMarkupsByQuantity = JSON.parse(
- (formData.get("categoryMarkupsByQuantity") as string) ?? "{}"
- ) as Record<string, Record<string, number>>;
+ const categoryMarkupsByQuantityValidator = z.record(
+ z.record(z.number().min(0))
+ );
+ const categoryMarkupsByQuantity =
+ categoryMarkupsByQuantityValidator.safeParse(
+ JSON.parse((formData.get("categoryMarkupsByQuantity") as string) ?? "{}")
+ );
if (unitPricesByQuantity.success === false) {
return data(
@@ -46,6 +50,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ if (categoryMarkupsByQuantity.success === false) {
+ return data(
+ { data: null, errors: "Invalid category markups" },
+ { status: 400 }
+ );
+ }
+
+ if (unitPricesByQuantity.data.length !== quantities.data.length) {
+ return data(
+ { data: null, errors: "Prices and quantities must have the same length" },
+ { status: 400 }
+ );
+ }
+
const inserts = unitPricesByQuantity.data.map((unitPrice, index) => {
const quantity = quantities.data[index];
return {
@@ -55,7 +73,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
discountPercent: 0,
leadTime: 0,
createdBy: userId,
- categoryMarkups: categoryMarkupsByQuantity[quantity] ?? undefined
+ categoryMarkups: categoryMarkupsByQuantity.data[quantity] ?? undefined
};
});
diff --git a/packages/documents/src/pdf/QuotePDF.tsx b/packages/documents/src/pdf/QuotePDF.tsx
index ab950cfcaa..6d06a797d2 100644
--- a/packages/documents/src/pdf/QuotePDF.tsx
+++ b/packages/documents/src/pdf/QuotePDF.tsx
@@ -291,23 +291,15 @@ const QuotePDF = ({
const unitPriceFormatter = getCurrencyFormatter(
currencyCode,
locale,
- line.unitPricePrecision
+ line.unitPricePrecision ?? 2
);
const additionalCharges = line.additionalCharges ?? {};
return (
- <View
- key={line.id}
- wrap={false}
- style={
- line.quantity.length > 1
- ? tw("border-l-2 border-blue-300")
- : undefined
- }
- >
+ <View key={line.id} wrap={false}>
{line.status !== "No Quote" ? (
- line.quantity.map((quantity, index) => {
+ line.quantity?.map((quantity, index) => {
const prices = pricesByLine[line.id] ?? [];
const price = prices.find((p) => p.quantity === quantity);
const unitPrice = price?.convertedUnitPrice ?? 0;