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): key inserted price rows to the validated line
sidgaikwad9a2bcb0a235b
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 0e56b4650d..f518163e2c 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -920,6 +920,6 @@ canvas hosting Radix popovers/selects.**Problem:** The function keys the snapshot of existing rows by quantity and looks each one up while building the reinsert. Through PostgREST a `NUMERIC` column arrives as a JS `number`, so `pricesByQuantity[10]` matched. Through node-postgres — which Kysely uses — the same column arrives as the string `"10.00000"`, because pg does not parse `NUMERIC` (oid 1700) to float and this repo sets no `setTypeParser` anywhere. Every `Map.get(10)` therefore missed, `existing` was always `undefined`, and each preserved field fell back to the caller's value: shipping to the column default `0`, discount and lead time to the zeros the recalculate route passes. The generated types say `number` on both paths, so `tsgo` cannot see it — the mismatch exists only at runtime.-**Rule:** When porting a query from supabase-js to Kysely, treat every `NUMERIC`/`DECIMAL`/`BIGINT` read as a **string** regardless of what the generated type claims. Normalize with `Number(...)` before using such a value as an object key, `Map` key, or in `===`/arithmetic. Writing them back is safe — pg accepts numeric strings for numeric params, and passing the string through preserves precision. More generally: a client swap can change runtime value types without changing a single TypeScript type, so a typecheck is not evidence that a port behaves identically — exercise it against a real database.+**Rule:** When porting a query from supabase-js to Kysely, treat every `NUMERIC`/`DECIMAL`/`BIGINT` read as a **string** regardless of what the generated type claims. Normalize with `Number(...)` only where the value has to be a number — an object/`Map` key, a `===` comparison, arithmetic — and only for bounded fields like a quantity or a precision. Do **not** normalize a whole row for tidiness: `Number()` on a `BIGINT` or a wide `NUMERIC` silently loses precision past `Number.MAX_SAFE_INTEGER`, and money is exactly where that matters. Writing values back untouched is both safe and preferable — pg accepts the canonical string for a numeric param, and passing it straight through preserves the stored value exactly. More generally: a client swap can change runtime value types without changing a single TypeScript type, so a typecheck is not evidence that a port behaves identically — exercise it against a real database.**Applies to:** `apps/erp/app/modules/sales/sales.service.ts` (`upsertQuoteLinePrices`), any `Kysely<KyselyDatabase>` service in `apps/erp/app/modules/**` or `packages/database/supabase/functions/**`, and the `getPostgresClient` pool in `packages/database/supabase/functions/lib/postgres/index.ts`.diff --git a/.claude/rules/quote-discount-system.md b/.claude/rules/quote-discount-system.mdindex 9028352d7f..d10849608b 100644--- a/.claude/rules/quote-discount-system.md+++ b/.claude/rules/quote-discount-system.md@@ -70,8 +70,9 @@ Standalone rules, `id` default `id('pr')`, scoped to a company. Columns: `name`,`upsertQuoteLinePrices(db, companyId, quoteId, lineId, prices)` deletes andre-inserts rows **inside one Kysely transaction** (so a failed insert rolls thedelete 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,+existing `discountPercent`, `leadTime`, `shippingCost`, `categoryMarkups`, and+`priceSource` per quantity when present (an explicit caller `categoryMarkups` or+`priceSource` wins over the stored value; the rest always keep the stored one). It takes a `Kysely<KyselyDatabase>`, not a supabase client,so it bypasses RLS — every statement is scoped by `companyId` explicitly and theroute must authorize with `requirePermissions` first. Any user-entered column added to `quoteLinePrice` has to be addedto that carry-over list or the delete+reinsert silently resets it to its default.diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex ca0199c94e..df008ece4b 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -4040,6 +4040,10 @@ async function rewriteQuoteLinePrices(return {...p,+ // The delete, the existing-price lookup and the quoteLine check are+ // all keyed on lineId. Honouring a payload's own quoteLineId would+ // write rows onto a line none of that covered.+ quoteLineId: lineId,companyId,quoteId,unitPrice: Number(p.unitPrice.toFixed(quoteLine.unitPricePrecision)),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 5227d130f6..64a49c5cd4 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@@ -8,6 +8,8 @@ import { getDatabaseClient } from "~/services/database.server";const logger = getLogger("erp", "quoteid-lineid-update-precision");+const SUPPORTED_PRECISIONS = [2, 3, 4];+export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -23,6 +25,16 @@ export async function action({ request, params }: ActionFunctionArgs) {const precision = Number(formData.get("precision") ?? 2);+ // `quoteLine.unitPricePrecision` is CHECK-constrained to these three, so an+ // out-of-range value would abort the transaction anyway — reject it here to+ // return the reason instead of a generic failure.+ if (!SUPPORTED_PRECISIONS.includes(precision)) {+ return data(+ { data: null, error: `Precision must be one of ${SUPPORTED_PRECISIONS}` },+ { status: 400 }+ );+ }+// Rounds the line's existing prices to the new precision in the same// transaction that sets it.try {