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.

fix(sales): fail closed on a missing quote and share the precision transaction

sidgaikwad3ace7953cb81
diff --git a/.claude/rules/quote-discount-system.md b/.claude/rules/quote-discount-system.md
index 75885e0205..a0b311cdfe 100644
--- a/.claude/rules/quote-discount-system.md
+++ b/.claude/rules/quote-discount-system.md
@@ -75,6 +75,14 @@ quantity when present. It takes a `Kysely<KyselyDatabase>`, not a supabase clien
so it bypasses RLS — every statement is scoped by `companyId` explicitly and the
route must authorize with `requirePermissions` first. Any user-entered column added to `quoteLinePrice` has to be added
to 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 the
+insert's `companyId` is overwritten by a trigger from the parent quote — without
+the check it would write into whichever company owns the quote.
+
+`updateQuoteLinePrecision(db, companyId, quoteId, lineId, precision)` shares that
+transaction: it sets `quoteLine.unitPricePrecision` and re-rounds the existing
+price rows together, so the line can never advertise a precision its prices were
+never rounded to.
## Types & UI
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 535efd2c22..3ed4cbbbce 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -1,6 +1,6 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";
-import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
import { getLogger } from "@carbon/logger";
import type { PickPartial } from "@carbon/utils";
import { datetime } from "@carbon/utils";
@@ -3189,16 +3189,56 @@ export async function updateQuoteExchangeRate(
}
export async function updateQuoteLinePrecision(
- client: SupabaseClient<Database>,
- quoteLineId: string,
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ quoteId: string,
+ lineId: string,
precision: number
) {
- return client
- .from("quoteLine")
- .update({ unitPricePrecision: precision })
- .eq("id", quoteLineId)
- .select("id")
- .single();
+ // The stored prices are rounded to the line's precision, so changing the
+ // precision and rewriting the rows have to commit together — otherwise the
+ // line advertises a precision its prices were never rounded to.
+ return db.transaction().execute(async (trx) => {
+ const line = await trx
+ .updateTable("quoteLine")
+ .set({ unitPricePrecision: precision })
+ .where("id", "=", lineId)
+ .where("companyId", "=", companyId)
+ .returning("id")
+ .executeTakeFirst();
+
+ if (!line) {
+ throw new Error(
+ `Quote line ${lineId} was not found for company ${companyId}`
+ );
+ }
+
+ 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
+ }))
+ );
+ });
}
export async function updateSalesOrderExchangeRate(
@@ -3887,75 +3927,106 @@ export async function upsertQuoteLinePrices(
// Rewriting a line's prices is a delete + reinsert, so it has to be atomic:
// if the insert failed after the delete had already committed, the line would
// be left with no pricing at all and the previous values unrecoverable.
- // Kysely bypasses RLS, so every statement is scoped by companyId explicitly.
- return db.transaction().execute(async (trx) => {
- const existingPrices = await trx
- .selectFrom("quoteLinePrice")
- .selectAll()
- .where("quoteLineId", "=", lineId)
- .where("companyId", "=", companyId)
- .execute();
-
- await trx
- .deleteFrom("quoteLinePrice")
- .where("quoteLineId", "=", lineId)
- .where("companyId", "=", companyId)
- .execute();
-
- if (quoteLinePrices.length === 0) return;
-
- const quote = await trx
- .selectFrom("quote")
- .select("exchangeRate")
- .where("id", "=", quoteId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
-
- const quoteLine = await trx
- .selectFrom("quoteLine")
- .select("unitPricePrecision")
- .where("id", "=", lineId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
+ return db
+ .transaction()
+ .execute((trx) =>
+ rewriteQuoteLinePrices(trx, companyId, quoteId, lineId, quoteLinePrices)
+ );
+}
- // 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.
- const existingByQuantity = new Map(
- existingPrices.map((price) => [Number(price.quantity), price])
+// Must run inside a caller-owned transaction so the delete below rolls back with
+// everything else. Kysely bypasses RLS, so every statement is scoped by
+// companyId explicitly.
+async function rewriteQuoteLinePrices(
+ trx: KyselyTx,
+ 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";
+ }[]
+) {
+ const existingPrices = await trx
+ .selectFrom("quoteLinePrice")
+ .selectAll()
+ .where("quoteLineId", "=", lineId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ await trx
+ .deleteFrom("quoteLinePrice")
+ .where("quoteLineId", "=", lineId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ if (quoteLinePrices.length === 0) return;
+
+ const quote = await trx
+ .selectFrom("quote")
+ .select("exchangeRate")
+ .where("id", "=", quoteId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+
+ const quoteLine = await trx
+ .selectFrom("quoteLine")
+ .select("unitPricePrecision")
+ .where("id", "=", lineId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+
+ // Neither lookup is scoped by anything the insert repeats: quoteLinePrice
+ // 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.
+ if (!quote || !quoteLine) {
+ throw new Error(
+ `Quote ${quoteId} / line ${lineId} was not found for company ${companyId}`
);
+ }
- await trx
- .insertInto("quoteLinePrice")
- .values(
- quoteLinePrices.map((p) => {
- const existing = existingByQuantity.get(Number(p.quantity));
-
- return {
- ...p,
- companyId,
- quoteId,
- unitPrice: Number(
- p.unitPrice.toFixed(quoteLine?.unitPricePrecision ?? 2)
- ),
- discountPercent: existing?.discountPercent ?? p.discountPercent,
- leadTime: existing?.leadTime ?? p.leadTime,
- // Shipping is entered per quantity break and is independent of the
- // price being rewritten — without this the delete+reinsert resets
- // it to the column default of 0.
- shippingCost: existing?.shippingCost ?? 0,
- categoryMarkups:
- p.categoryMarkups ?? existing?.categoryMarkups ?? {},
- // Explicit caller intent wins; otherwise keep the row's provenance
- // so a delete+reinsert can never turn a manual price back into a
- // system one.
- priceSource: p.priceSource ?? existing?.priceSource ?? "system",
- exchangeRate: quote?.exchangeRate ?? 1
- };
- })
- )
- .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.
+ const existingByQuantity = new Map(
+ existingPrices.map((price) => [Number(price.quantity), price])
+ );
+
+ await trx
+ .insertInto("quoteLinePrice")
+ .values(
+ quoteLinePrices.map((p) => {
+ const existing = existingByQuantity.get(Number(p.quantity));
+
+ return {
+ ...p,
+ companyId,
+ quoteId,
+ unitPrice: Number(p.unitPrice.toFixed(quoteLine.unitPricePrecision)),
+ discountPercent: existing?.discountPercent ?? p.discountPercent,
+ leadTime: existing?.leadTime ?? p.leadTime,
+ // Shipping is entered per quantity break and is independent of the
+ // price being rewritten — without this the delete+reinsert resets
+ // it to the column default of 0.
+ shippingCost: existing?.shippingCost ?? 0,
+ categoryMarkups: p.categoryMarkups ?? existing?.categoryMarkups ?? {},
+ // Explicit caller intent wins; otherwise keep the row's provenance
+ // so a delete+reinsert can never turn a manual price back into a
+ // system one.
+ priceSource: p.priceSource ?? existing?.priceSource ?? "system",
+ exchangeRate: quote.exchangeRate ?? 1
+ };
+ })
+ )
+ .execute();
}
async function buildCostEffects(
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index e8a88ba9cb..cbda1f1a2b 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-08-10T10:45:07.156Z",
+ "generated": "2026-08-10T11:57:46.692Z",
"totalTools": 1431,
"modules": 15,
"tools": [
@@ -37423,10 +37423,12 @@
"module": "sales",
"classification": "WRITE",
"description": "update quote line precision",
- "paramCount": 2,
+ "paramCount": 3,
"serviceParams": [
- "client",
- "quoteLineId",
+ "db",
+ "companyId",
+ "quoteId",
+ "lineId",
"precision"
],
"injectAuth": [
@@ -37436,7 +37438,10 @@
"schema": {
"type": "object",
"properties": {
- "quoteLineId": {
+ "quoteId": {
+ "type": "string"
+ },
+ "lineId": {
"type": "string"
},
"precision": {
@@ -37444,7 +37449,8 @@
}
},
"required": [
- "quoteLineId",
+ "quoteId",
+ "lineId",
"precision"
]
}
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.tsx
index cc30736fd2..b3bf1eabc5 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
@@ -1,17 +1,17 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
-import {
- updateQuoteLinePrecision,
- upsertQuoteLinePrices
-} from "~/modules/sales";
+import { updateQuoteLinePrecision } from "~/modules/sales";
import { getDatabaseClient } from "~/services/database.server";
+const logger = getLogger("erp", "quoteid-lineid-update-precision");
+
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId } = await requirePermissions(request, {
+ const { companyId } = await requirePermissions(request, {
update: "sales"
});
@@ -23,49 +23,23 @@ export async function action({ request, params }: ActionFunctionArgs) {
const precision = Number(formData.get("precision") ?? 2);
- const updatePrecision = await updateQuoteLinePrecision(
- client,
- lineId,
- precision
- );
- if (updatePrecision.error) {
+ // Rounds the line's existing prices to the new precision in the same
+ // transaction that sets it.
+ try {
+ await updateQuoteLinePrecision(
+ getDatabaseClient(),
+ companyId,
+ quoteId,
+ lineId,
+ precision
+ );
+ } catch (err) {
+ logger.error("Failed to update quote line precision", { error: err });
return data(
- { data: null, error: updatePrecision.error.message },
+ { data: null, error: "Failed to update quote line precision" },
{ status: 400 }
);
}
- // Update all the prices for the quote line to reflect the new precision
- const prices = await client
- .from("quoteLinePrice")
- .select("*")
- .eq("quoteLineId", lineId);
-
- if (prices.data) {
- const roundedPrices = prices.data?.map((price) => ({
- quoteLineId: price.quoteLineId,
- unitPrice: Number(price.unitPrice.toFixed(precision)),
- leadTime: price.leadTime,
- discountPercent: price.discountPercent,
- quantity: price.quantity,
- createdBy: price.createdBy
- }));
-
- try {
- await upsertQuoteLinePrices(
- getDatabaseClient(),
- companyId,
- quoteId,
- lineId,
- roundedPrices
- );
- } catch {
- return data(
- { data: null, error: "Failed to update quote line prices" },
- { status: 400 }
- );
- }
- }
-
return { data: null, error: null };
}