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
fix(sales): make an empty price rewrite a no-op, not a wipe
sidgaikwad1795f7cc4cb0
diff --git a/.claude/rules/quote-discount-system.md b/.claude/rules/quote-discount-system.mdindex a0b311cdfe..9028352d7f 100644--- a/.claude/rules/quote-discount-system.md+++ b/.claude/rules/quote-discount-system.md@@ -77,12 +77,17 @@ route must authorize with `requirePermissions` first. Any user-entered column adto that carry-over list or the delete+reinsert silently resets it to its default.The rewrite throws if the quote or line is missing for that company, because theinsert's `companyId` is overwritten by a trigger from the parent quote — without-the check it would write into whichever company owns the quote.+the check it would write into whichever company owns the quote. An **empty**+`prices` array is a no-op, not a wipe: dropping a quantity break is+`reconcileQuantityBreaks`' job, so an empty rewrite leaves the rows alone.`updateQuoteLinePrecision(db, companyId, quoteId, lineId, precision)` shares thattransaction: it sets `quoteLine.unitPricePrecision` and re-rounds the existingprice rows together, so the line can never advertise a precision its prices were-never rounded to.+never rounded to. `precision` is not validated in app code — `quoteLine` carries+`CHECK ("unitPricePrecision" IN (2,3,4))`, and the update runs before any+rounding, so an out-of-range value aborts the transaction before `toFixed` sees+it.## Types & UIdiff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex ffea865a5a..ca0199c94e 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -3243,31 +3243,9 @@ export async function updateQuoteLinePrecision();}- const existingPrices = await trx- .selectFrom("quoteLinePrice")- .selectAll()- .where("quoteLineId", "=", lineId)- .where("companyId", "=", companyId)- .execute();-- if (existingPrices.length === 0) return;-- // node-postgres hands back NUMERIC as a string; rewriteQuoteLinePrices does- // arithmetic on these, so coerce before passing them back in.- await rewriteQuoteLinePrices(- trx,- companyId,- quoteId,- lineId,- existingPrices.map((price) => ({- quoteLineId: lineId,- quantity: Number(price.quantity),- unitPrice: Number(price.unitPrice),- leadTime: Number(price.leadTime),- discountPercent: Number(price.discountPercent),- createdBy: price.createdBy- }))- );+ // No replacement prices: rewrite the rows already on the line so they are+ // re-rounded to the precision just set.+ await rewriteQuoteLinePrices(trx, companyId, quoteId, lineId);});}@@ -3938,6 +3916,21 @@ export async function upsertQuoteLineAdditionalCharges(return client.from("quoteLine").update(update).eq("id", lineId);}+type QuoteLinePriceInput = {+ quoteLineId: string;+ unitPrice: number;+ leadTime: number;+ discountPercent: number;+ quantity: number;+ createdBy: string;+ categoryMarkups?: Record<string, number>;+ priceSource?: "system" | "manual";+};++// `quoteLinePrices` is spelled out rather than typed as QuoteLinePriceInput+// because scripts/generate-mcp.ts only inlines literal object types — a named+// alias collapses this tool's published schema to an untyped array. Comments+// inside the parameter list leak into that schema, so keep them out here.export async function upsertQuoteLinePrices(db: Kysely<KyselyDatabase>,companyId: string,@@ -3972,16 +3965,7 @@ async function rewriteQuoteLinePrices(companyId: string,quoteId: string,lineId: string,- quoteLinePrices: {- quoteLineId: string;- unitPrice: number;- leadTime: number;- discountPercent: number;- quantity: number;- createdBy: string;- categoryMarkups?: Record<string, number>;- priceSource?: "system" | "manual";- }[]+ quoteLinePrices?: QuoteLinePriceInput[]) {const existingPrices = await trx.selectFrom("quoteLinePrice")@@ -3990,13 +3974,24 @@ async function rewriteQuoteLinePrices(.where("companyId", "=", companyId).execute();- await trx- .deleteFrom("quoteLinePrice")- .where("quoteLineId", "=", lineId)- .where("companyId", "=", companyId)- .execute();-- if (quoteLinePrices.length === 0) return;+ // Omitted replacements means "rewrite what is already there" (a precision+ // change). node-postgres hands back NUMERIC as a string, so coerce the values+ // this function does arithmetic on.+ const replacements: QuoteLinePriceInput[] =+ quoteLinePrices ??+ existingPrices.map((price) => ({+ quoteLineId: lineId,+ quantity: Number(price.quantity),+ unitPrice: Number(price.unitPrice),+ leadTime: Number(price.leadTime),+ discountPercent: Number(price.discountPercent),+ createdBy: price.createdBy+ }));++ // Nothing to write. Leave the existing rows alone rather than clearing the+ // line's pricing — removing a quantity break is reconcileQuantityBreaks' job,+ // not a side effect of an empty rewrite.+ if (replacements.length === 0) return;const quote = await trx.selectFrom("quote")@@ -4016,13 +4011,20 @@ async function rewriteQuoteLinePrices(// derives its companyId from the parent quote via trigger, so inserting// against a quote in another company would silently write there. Missing// rows also mean the exchange rate and precision below would fall back to- // 1 and 2 and mis-price the line. Throwing rolls the delete back.+ // 1 and 2 and mis-price the line. Checked before the delete so a bad id+ // never reaches it.if (!quote || !quoteLine) {throw new Error(`Quote ${quoteId} / line ${lineId} was not found for company ${companyId}`);}+ await trx+ .deleteFrom("quoteLinePrice")+ .where("quoteLineId", "=", lineId)+ .where("companyId", "=", companyId)+ .execute();+// node-postgres returns NUMERIC as a string ("10.00000"), where PostgREST// returned it as a number — so the quantity has to be normalized on both// sides or every lookup misses and nothing gets preserved.@@ -4033,7 +4035,7 @@ async function rewriteQuoteLinePrices(await trx.insertInto("quoteLinePrice").values(- quoteLinePrices.map((p) => {+ replacements.map((p) => {const existing = existingByQuantity.get(Number(p.quantity));return {diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.update-precision.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.update-precision.tsxindex b3bf1eabc5..5227d130f6 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.update-precision.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.update-precision.tsx@@ -34,7 +34,11 @@ export async function action({ request, params }: ActionFunctionArgs) {precision);} catch (err) {- logger.error("Failed to update quote line precision", { error: err });+ logger.error("Failed to update quote line precision", {+ error: err,+ quoteId,+ lineId+ });return data({ data: null, error: "Failed to update quote line precision" },{ status: 400 }