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.
paths: - "packages/database/supabase/migrations/pricing-rules.sql" - "apps/erp/app/modules/sales/sales.service.ts" - "apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx" - "apps/erp/app/modules/sales/ui/Pricing/*.tsx"
Quote Discount & Pricing System
Discounts live on quote line prices (per quantity break), and there is also a standalone, company-scoped pricing rule engine (Discount/Markup) that drives the base unit price during cost rollup. The two are distinct — see "Two layers" below.
Schema: quoteLinePrice
PK is (quoteLineId, quantity) — there is no id column (the original id PK
was dropped in 20240802114117_quote-line-quantities.sql, which also dropped the
original unitCost/markupPercent/extendedPrice columns and added unitPrice).
Current columns (after later migrations):
quoteId,quoteLineId,quantityNUMERIC,unitPriceNUMERICdiscountPercentNUMERIC(10,5) DEFAULT 0 — stored as a fraction 0..1 (e.g. 0.10 = 10%), NOT a whole numberleadTimeNUMERIC,shippingCostNUMERIC (20241105002325_quote-taxes-and-shipping.sql)exchangeRateNUMERIC DEFAULT 1 (20241010193506_quote-order-presentation-currency.sql)categoryMarkupsJSONB DEFAULT'{}'(20260307000000_quote-line-category-markups.sql) — per-cost-category markup % keyed bycostCategoryKeys, stored as whole percent (e.g. 25 = 25%)- Generated (STORED) columns from
20241010193506:netUnitPrice=unitPrice * (1 - discountPercent)convertedUnitPrice=unitPrice * exchangeRateconvertedNetUnitPrice=unitPrice * exchangeRate * (1 - discountPercent)netExtendedPrice=unitPrice * (1 - discountPercent) * quantityconvertedNetExtendedPrice=unitPrice * exchangeRate * (1 - discountPercent) * quantityconvertedShippingCost=shippingCost * exchangeRate
A trigger on quote.exchangeRate cascades the new rate into every quoteLinePrice row.
quoteLine itself has no discountPercent; it has taxPercent, additionalCharges
(JSONB), quantity (array of breaks), plus pricingRuleId and priceTrace JSONB
(20260413120001_pricing-rules.sql). quote has no discount field.
Schema: pricingRule (20260413120001_pricing-rules.sql)
Standalone rules, id default id('pr'), scoped to a company. Columns: name,
ruleType (pricingRuleType enum = 'Discount' | 'Markup' | 'Configuration'), amountType
(pricingRuleAmountType enum = 'Percentage' | 'Fixed', default Percentage),
amount NUMERIC, priority INT, minQuantity/maxQuantity, customerIds[],
customerTypeIds[], itemIds[], itemPostingGroupId, validFrom/validTo,
active BOOLEAN. Same migration adds salesOrderLine.pricingRuleId + priceTrace.
Two layers, and how discount is applied
Quote-line discount (
quoteLinePrice.discountPercent): a per-quantity-break percentage editors enter inQuoteLinePricing.tsx. Net price =unitPrice * (1 - discount)(also materialized in the generatednetUnitPricecolumn). The UI computes the same net for display; persistence is the generated columns.Pricing-rule engine (
resolvePriceinsales.service.ts→applyPriceRulesinsales.utils.ts): resolves a base unit price during quote-line price recalculation (cost rollup withcategoryMarkups, thenresolvePrice). Precedence: customer override > customer-type override > all-customers override > base (itemUnitSalePrice). Overrides may setapplyRulesOnTop=falseto skip the discount and markup rules. ThenapplyPriceRules:- Discount rules: non-stacking — highest
prioritywins; ties broken by best effective amount. Percentage =price * amount; Fixed =amount. - Markup rules: stack in priority order, compounding on the running price.
- Configuration rules (
ruleType = 'Configuration', one configurable item, amount 0): theirconfigurationPricesare signed per-unit surcharges added to the starting price BEFORE the discount, stacking across every matched Configuration rule; they need the line'sconfiguration(quoteLine/salesOrderLine), passed toresolvePriceasinput.configuration. Trace steps carry the parameter'slabel, saved on each price entry by the rule form (no lookup at pricing time). An override withapplyRulesOnTop=falseskips discounts and markups but still applies the configuration prices (applyPriceRules(..., { configurationOnly: true })). - Final price clamped to ≥ 0.
Each step is recorded as a
PriceTraceStep({ step, source, amount, adjustment?, ruleId?, overrideId? }; an override step'soverrideIdis the override it applied, linked fromPriceTraceModal). The trace is a snapshot stored with the price — pricing rules are edited in place, so re-running today's rules cannot explain yesterday's price. quoteLinePrice.priceTrace(migration20261001125824), one per quantity break. Written by every system-pricing path: the threebuild*PriceRowsbuilders,recalculateQuoteLinePrices, the grid's Markup % (recalculate-priceroute,priceTracesByQuantity) and per-category markup edits, andrepriceQuoteLineFromRules. A typed price (priceSource = 'manual') writesnull.rewriteQuoteLinePricesdoes NOT carry an omitted trace over (it explains the unit price, which every caller restates) — except the precision rebuild, which passes the stored one. Kysely writesJSON.stringifyit (a JS array would go out as a Postgres array literal).get-methodquoteToQuotecopies it.withBasePriceSourcerenames the Base Price step's source (QUOTE_BASE_PRICE_SOURCES: "Cost + Markup", "Supplier Price"), sinceresolvePricenames every base the item's sale price.salesOrderLine.priceTrace, posted bySalesOrderLineForm(typing a price posts"null"), set bycreateReplacementSalesOrder, and copied byconvertfrom the converted break viaquoteToOrderPriceTrace(packages/database/src/price-trace.ts), which appends the quote line discount so the trace ends at the order line's net price.quoteLine.priceTraceis dead — one trace cannot describe several breaks. Nothing fills it;get-methodquoteToQuotecopies it (always null).getQuoteLinePriceTraces(x+/quote+/$quoteId.$lineId.price-trace.tsxloader,shouldRevalidatefalse — it is expensive, so the grid loads it only on modal open, after a reprice, and once on mount for a line with an untraced system price) returns each break's storedtraceplus acurrentTrace: today's pipeline re-run from the base the row's builder starts from (cost-plus rollup with the row's markups / configured sale price for Make to Order, supplier break for Purchase to Order, item sale price for Pull from Inventory); none for amanualrow. It callsbuildCostEffects(..., { refreshBuyCosts: false })so the read never writesquoteMaterial.unitCost. The route's action,repriceQuoteLineFromRules, stores eachcurrentTraceand its final price in oneupsertQuoteLinePricestransaction. It refuses a non-Draft quote itself (QuoteLockedError) because it is also an MCP tool.
- Discount rules: non-stacking — highest
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). Per-quantity carry-over
of the user-entered fields (discountPercent, leadTime, shippingCost,
categoryMarkups, priceSource) is explicit-wins, omit-preserves
(resolvePreservedQuoteLinePriceFields in sales.utils.ts): a value the caller
provides is written, a field the caller omits keeps the stored value for that
quantity, and a brand-new row with neither falls back to the column default —
priceSource defaulting to "manual" (a hand-set price with no declared source
is a manual override, not a system cost-plus price). This is why the recalc route
($quoteId.$lineId.recalculate-price.tsx) passes ONLY the recomputed unitPrice
(+ explicit priceSource: "system") and omits lead time / discount / shipping —
so the user's entries survive. When an explicit prices array is passed, the
rewrite also syncs quoteLine.quantity to the sorted distinct quantities of
the rows (the precision rebuild, which omits prices, leaves the breaks alone).
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 resolvePreservedQuoteLinePriceFields 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. 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 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. 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 & UI
QuotationPricetype = a row ofgetQuoteLinePrices(...)(sales.service.ts), derived inapps/erp/app/modules/sales/types.ts(not a hand-written list).PricingRuletype andPriceTraceStepalso intypes.ts.pricingRuleValidatorinsales.models.ts; Percentageamountmust be ≤ 1.- UI:
ui/Quotes/QuoteLinePricing.tsx(per-quantity discount/markup editing) and theui/Pricing/folder (PricingRuleForm,PricingRulesTable,PriceOverrideForm,PriceTraceModal).PriceTraceModal(calculator icon → modal; sales order line, price list) rendersPriceTraceTable; the quote grid's Unit Price row shows a calculatorIconButtononly whenhasPriceAdjustmentsfinds an override, rule or configuration step in some break's stored trace (from the grid's own price rows — no request) or fetched current trace, and opensQuoteLinePriceTraceModal: onePriceTraceTableper quantity from the stored trace (today's calculation for a row priced before traces were recorded), a "repricing gives X" note when today's final price differs at the line's precision (repricedUnitPrice,sales.utils.ts), and a Reprice with current rules button on a Draft quote. - Every path that turns a cost rollup into a quote line price runs it through
resolvePriceasexistingBasePricewith the line'sconfiguration: the server builders andrecalculateQuoteLinePrices, and the pricing grid's Markup % and per-category markup edits (resolveRollupPrice→api/sales/resolve-price). Computingcost × markupalone drops the pricing rules and the configuration prices.getMethod(production.service.ts, ported from theget-methodserver function) seeds rows at cost-plus only, so every ERP route that invokes it on a quote line (itemToQuoteLine,quoteLineToQuoteLine) follows withrecalculateQuoteLinePrices. A typed unit price or markup percent is a manual price and is never repriced. - A configured Make to Order line whose part has a unit sale price starts from
that sale price instead of the cost rollup — the base its sales order line uses —
so the configuration prices land on the same base on the quote and the order
(
configuredQuoteBasePriceinsales.utils.ts, used bybuildMakeToOrderPriceRowsandrecalculateQuoteLinePrices). Such rows storecategoryMarkups = {}. A row whose markups someone chose (Markup % or a category edit — anything other than empty or the company defaults it was seeded with) stays cost-plus. Unconfigured lines are always cost-plus.
Gotchas
discountPercentis a fraction (0..1), not 0..100.categoryMarkupsvalues are whole percent;companySettings.quoteLineCategoryMarkupsdefaults are stored as fractions and multiplied by 100 when used as fallback.- The doc's old claim that
markupPercent/extendedPriceexist onquoteLinePriceis wrong — they were dropped in 2024. Markup now lives incategoryMarkups(rollup) andpricingRule(engine). quoteLinePricehas noid— PK is(quoteLineId, quantity).- Sales orders/invoices:
salesOrderLinecarriespricingRuleId+priceTrace(the trace propagates from the quote throughconvert; nothing writespricingRuleId), but invoice lines do not. Quote→order conversion goes throughconvertDocument(shared.service.ts, ported from theconvertserver function) (convertQuoteToOrder).