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): rewrite quote line prices in a transaction

sidgaikwadefd366dba003
diff --git a/.claude/rules/quote-discount-system.md b/.claude/rules/quote-discount-system.md
index 981060354e..75885e0205 100644
--- a/.claude/rules/quote-discount-system.md
+++ b/.claude/rules/quote-discount-system.md
@@ -67,9 +67,13 @@ Standalone rules, `id` default `id('pr')`, scoped to a company. Columns: `name`,
Each step is recorded as a `PriceTraceStep` (`{ step, source, amount, adjustment?, ruleId? }`)
into `priceTrace`. The winning rule's id lands on `quoteLine.pricingRuleId`.
-`upsertQuoteLinePrices` deletes and re-inserts rows, **preserving** the existing
-`discountPercent`, `leadTime`, `shippingCost`, and `categoryMarkups` per quantity
-when present. Any user-entered column added to `quoteLinePrice` has to be added
+`upsertQuoteLinePrices(db, companyId, quoteId, lineId, prices)` deletes and
+re-inserts rows **inside one Kysely transaction** (so a failed insert rolls the
+delete back instead of leaving the line with no pricing), **preserving** the
+existing `discountPercent`, `leadTime`, `shippingCost`, and `categoryMarkups` per
+quantity when present. It takes a `Kysely<KyselyDatabase>`, not a supabase client,
+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.
## Types & UI
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 799f9eecd7..39bd9de239 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -3869,7 +3869,8 @@ export async function upsertQuoteLineAdditionalCharges(
}
export async function upsertQuoteLinePrices(
- client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
quoteId: string,
lineId: string,
quoteLinePrices: {
@@ -3883,82 +3884,75 @@ export async function upsertQuoteLinePrices(
priceSource?: "system" | "manual";
}[]
) {
- const existingPrices = await client
- .from("quoteLinePrice")
- .select("*")
- .eq("quoteLineId", lineId);
- if (existingPrices.error) {
- return existingPrices;
- }
-
- const deletePrices = await client
- .from("quoteLinePrice")
- .delete()
- .eq("quoteLineId", lineId);
- if (deletePrices.error) {
- return deletePrices;
- }
-
- const quoteExchangeRate = await client
- .from("quote")
- .select("id, exchangeRate")
- .eq("id", quoteId)
- .single();
-
- const quoteLineUnitPricePrecision = await client
- .from("quoteLine")
- .select("unitPricePrecision")
- .eq("id", lineId)
- .single();
-
- const pricesByQuantity = existingPrices.data.reduce<
- Record<
- number,
- {
- discountPercent: number;
- leadTime: number;
- shippingCost: number;
- categoryMarkups: unknown;
- priceSource: string;
- }
- >
- >((acc, price) => {
- acc[price.quantity] = price;
- return acc;
- }, {});
-
- const pricesWithExistingDiscountsAndLeadTimes = quoteLinePrices.map((p) => {
- const existing = pricesByQuantity[p.quantity];
- const roundedUnitPrice = Number(
- p.unitPrice.toFixed(
- quoteLineUnitPricePrecision.data?.unitPricePrecision ?? 2
- )
+ // 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();
+
+ const existingByQuantity = new Map(
+ existingPrices.map((price) => [price.quantity, price])
);
- return {
- ...p,
- unitPrice: roundedUnitPrice,
- 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",
- quoteId: quoteId,
- exchangeRate: quoteExchangeRate.data?.exchangeRate ?? 1
- };
+ await trx
+ .insertInto("quoteLinePrice")
+ .values(
+ quoteLinePrices.map((p) => {
+ const existing = existingByQuantity.get(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();
});
-
- return (
- client
- .from("quoteLinePrice")
- // @ts-expect-error - categoryMarkups is a Json object
- .insert(pricesWithExistingDiscountsAndLeadTimes)
- );
}
async function buildCostEffects(
diff --git a/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts b/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts
index 136e37462c..f2ae5b5c50 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts
@@ -18,6 +18,7 @@ import * as salesFunctions from "~/modules/sales/sales.service";
import * as settingsFunctions from "~/modules/settings/settings.service";
import * as sharedFunctions from "~/modules/shared/shared.service";
import * as usersFunctions from "~/modules/users/users.service";
+import { getDatabaseClient } from "~/services/database.server";
import { isMcpBlockedTool } from "./mcp-blocked-tools";
import toolMetadata from "./tool-metadata.json";
import type { AuthField } from "./types";
@@ -149,6 +150,11 @@ export async function executeFunction(
for (const paramName of paramNames) {
if (paramName === "client") {
functionArgs.push(context.client);
+ } else if (paramName === "db") {
+ // Services that run in a transaction take a Kysely client instead of
+ // the supabase one. Without this they fall through to the positional
+ // arg branches and are handed a business argument as their client.
+ functionArgs.push(getDatabaseClient());
} else if (paramName === "userId") {
functionArgs.push(context.userId);
} else if (paramName === "companyId") {
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 b2b92bd6f1..e8a88ba9cb 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-10T02:45:42.644Z",
+ "generated": "2026-08-10T10:45:07.156Z",
"totalTools": 1431,
"modules": 15,
"tools": [
@@ -38142,7 +38142,8 @@
"description": "upsert quote line prices",
"paramCount": 3,
"serviceParams": [
- "client",
+ "db",
+ "companyId",
"quoteId",
"lineId",
"quoteLinePrices"
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 7b8ee04815..60fe063012 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
@@ -5,6 +5,7 @@ import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { z } from "zod";
import { upsertQuoteLinePrices } from "~/modules/sales";
+import { getDatabaseClient } from "~/services/database.server";
const logger = getLogger("erp", "quoteid-lineid-recalculate-price");
@@ -13,7 +14,7 @@ const numberArrayValidator = z.array(z.number());
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "sales"
});
@@ -83,16 +84,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
};
});
- const insertLinePrices = await upsertQuoteLinePrices(
- client,
- quoteId,
- lineId,
- inserts
- );
- if (insertLinePrices.error) {
- logger.error(insertLinePrices.error);
+ try {
+ await upsertQuoteLinePrices(
+ getDatabaseClient(),
+ companyId,
+ quoteId,
+ lineId,
+ inserts
+ );
+ } catch (err) {
+ logger.error("Failed to recalculate quote line prices", { error: err });
return data(
- { data: null, error: insertLinePrices.error.message },
+ { data: null, error: "Failed to recalculate quote line prices" },
{ status: 400 }
);
}
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 d46141abdf..cc30736fd2 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
@@ -6,11 +6,12 @@ import {
updateQuoteLinePrecision,
upsertQuoteLinePrices
} from "~/modules/sales";
+import { getDatabaseClient } from "~/services/database.server";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
update: "sales"
});
@@ -50,15 +51,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
createdBy: price.createdBy
}));
- const updatePrices = await upsertQuoteLinePrices(
- client,
- quoteId,
- lineId,
- roundedPrices
- );
- if (updatePrices.error) {
+ try {
+ await upsertQuoteLinePrices(
+ getDatabaseClient(),
+ companyId,
+ quoteId,
+ lineId,
+ roundedPrices
+ );
+ } catch {
return data(
- { data: null, error: updatePrices.error.message },
+ { data: null, error: "Failed to update quote line prices" },
{ status: 400 }
);
}