Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

18.5 KB
Raw Blame

Volume Pricing (Quantity Breaks + Banded Adjustments)

Status: Implemented — schema, resolver, banded adjustment, Admin API and both dashboard tier editors shipped 2026-09-07 (spree/spree#14589); the price-list CSV export/import, the fixed-tiers note and the tier-editor end-to-end coverage followed the same day (follow-up PR) Target: Spree 6.0 — fully (2026-09-07: first the schema/resolver phases were pulled into the major because min_quantity changes the row identity of the released spree_prices table; then the whole plan followed — shipping the feature in one release is faster than splitting the UI off by a release boundary) Depends on: Catalog Agreement Rework (6.0-catalog-agreement-rework.md — implemented; owned lists + contextual rules), Price List Automatic Pricing (6.0-price-list-automatic-pricing.md — implemented; the ±% machinery this extends), B2B Quantity Rules (6.0-b2b-quantity-rules.md — the separate ordering axis) Author: Damian + Claude Last updated: 2026-09-07

Summary

B2B unit prices change with quantity. Today Spree covers the single threshold elegantly (a price list with a VolumeRule — standalone or catalog-owned — optionally with the ±% adjustment) and stops exactly where a real ladder begins: a catalog owns one list, so 24/48/96/200 tiers cannot exist on it, and per-variant breaks cannot exist at all. This plan closes the gap with two symmetric extensions of the pricing machinery itself (2026-09-07 review — the earlier promotions-based percent design was superseded the same day): fixed contracted ladders become a dimension of the price row (min_quantity — the shape every platform with real volume pricing converged on; nobody models tiers as list-matching rules), and percentage ladders become quantity bands on the list's ±% adjustment — the implemented automatic-pricing machinery already treats a percentage as pricing (computed on read, clean unit price, never touching explicit rows), so bands are consistent extension with an already-answered "percent off what": the base price. Both halves live on the price list and edit on the catalog's Pricing card. Marketing- visible volume discounts (strikethrough, D2C "buy more save more") remain promotion territory and are deliberately deferred.

Key Decisions (do not deviate without discussion)

  • The tier doctrine, one sentence (2026-09-07): promotions = DTC consumers, price lists = B2B. Agreement pricing — fixed or percent — lives on price lists and renders as unit prices; consumer-facing marketing discounts live on promotions and render as discounts. Every volume-pricing question resolves by asking which side of that line it sits on.

  • Fixed breaks are price rows, never rules or discounts (2026-09-07, interactive review): spree_prices.min_quantity (integer, default 1, null: false — integer defaults are house-legal, so every existing row is a quantity-1 price with zero backfill); row identity becomes (variant, currency, price_list, min_quantity) with the unique indexes extended accordingly. The resolver picks, within the winning list, the row with the highest min_quantity ≤ the line quantity. Contracted unit prices must appear as unit prices on every B2B document — a $9.00 agreement rendered as "$10.00 minus discount" is unacceptable paperwork.

  • A break ladder beats the list's ±% adjustment for that variant (the market leader's exact precedence, stated in their docs as "volume pricing fixes the price"): our resolver already gives explicit-row-beats-adjustment; the dashboard marks such variants ("fixed tiers — the list's % adjustment doesn't apply here").

  • Breaks live on price lists only in v1 (min_quantity > 1 requires price_list_id): base-price tiers would make every D2C PDP quantity-dependent — a storefront surface no platform ships natively. Lifting it later is deleting one validation; the column is the same. ≤10 breaks per variant (the leader's cap — a UI sanity bound, model- validated).

  • Percentage ladders are quantity bands on the adjustment (2026-09-07, superseding the same-day promotions design): the list keeps price_adjustment_percentage as its quantity-1 value; a new spree_price_adjustment_tiers table (price_list_id, min_quantity, percentage, unique per (list, min_quantity)) holds the higher bands, and the resolver picks the band with the highest min_quantity ≤ the line quantity, falling back to the column. Computed on read off the base price exactly like the implemented adjustment — clean unit prices, no discount rows, no promotion machinery — and never applied to explicit rows (the implemented precedence): a buyer whose price is the adjusted base gets "percent off their current price" by construction; a buyer with negotiated explicit rows uses fixed breaks. A ladder shared across many agreements verbatim is repeated per list — accepted: terms differ per agreement, and the genuinely shared case is marketing.

  • Volume pricing stays separate from quantity rules (MOQ/multiples — 6.0-b2b-quantity-rules.md): ordering constraints and price tiers are sibling axes everywhere in the market and in the merchant's own framing ("how many they may buy" vs "what they pay"). No coupling, ever.

  • VolumeRule on price lists is kept for list-level eligibility (a wholesale list that only exists at 48+) — it swaps whole lists, breaks and bands price within one; different jobs, documented as such.

  • Marketing volume discounts stay promotions, later: a visible strikethrough "buy more save more" (D2C) would be a line-quantity promotion rule + a quantity-tiered percent calculator (sibling of the existing TieredPercent) — recorded as the deferred design, not built here. Contracted terms never render as discounts; marketing never hides as pricing.

  • Price-list CSV ships as a per-list export and a merge import (2026-09-07, follow-up review — supersedes the same-day deferral): the plan had assumed a price-list CSV that never existed, so it is built here on the shipped export/import pipelines rather than as a column on the product CSV. Four calls, each with the cheaper alternative rejected:

    • A row is keyed by SKU — the same key the product CSV uses, and the file carries nothing else the import would not read (2026-09-08: the read-only product/variant columns first shipped were dropped, since a column that changes nothing on the way back reads as if it would). A variant without a SKU, or a SKU two sellers share, is refused row by row with a message. A prefixed variant_id fallback column was rejected as one more rule to explain for a case the product CSV does not cover either.
    • An import merges — rows in the file are written or updated, a row with a blank price removes that rung, and rungs the file does not mention stay as they are. Exactly the bulk editor's write semantics (Prices::BulkUpsert), so the two surfaces can never disagree. A "replace the whole list" mode was rejected: it needs a destructive confirm, and a half-failed import would leave a half-replaced list.
    • The export writes priced rows only. A placeholder row (on the list, no amount) is not written as a blank price, because re-importing an unchanged export would then remove those products from the list.
    • Both homes, like the tier editors: the buttons sit next to "Edit prices" on the price-list page and on the catalog's pricing card.
    • A sample file ships (db/sample_data/price_list_prices.csv) and sample data loads it onto the Wholesale list, so the example download in the import sheet is a working ladder rather than a header row. The product CSV is untouched: breaks require a price list, so every base row is quantity 1 by construction.
  • The ≤10 cap is a model validation, scoped to (variant, currency, price_list) (2026-09-07): an eleventh break is refused with a message, and the bulk-upsert path refuses a batch that would cross the cap, so no writer can get past it. A dashboard-only cap would leave the API unbounded and let the resolver's per-line row scan grow without limit.

  • A ladder may never charge more for a bigger order (2026-09-16): every rung is refused if it costs more than the quantity below it buys — inside the ladder that is the rung beneath, and for a ladder with no quantity-1 row of its own it is the variant's base price, which is what the buyer actually pays up to the threshold. A bottom rung above base stays legal: an agreement is free to be dearer than the shop, and only a break promises a better price for a bigger order. Without this a break entered above the shop price multiplied the bill at the threshold, in separate columns where nothing looked wrong (V-3644). Four consequences worth stating, because each was a hole the first cut left open:

    • Enforced on both paths, like the break cap. Prices::BulkUpsert judges the whole ladder, since only the batch sees it whole; a model validation covers the single-row writers, which would otherwise create exactly the state the bulk path refuses.
    • A base price is part of the ladder's shape. Lowering the shop price under a break raises the bill at the threshold as surely as mispricing the break, so a batch carrying only base rows is checked too, and the floor is the base price as the batch leaves it.
    • Every save is judged on the state it would leave, not on what it changed. An earlier cut exempted a breach that predated the batch, so a ladder found rising stayed editable. That exemption was dropped: no write path can produce a rising ladder, so one found rising came from outside them — raw SQL, or data predating the rule — and comparing against it let a new breach above the old one through unreported. Repairing the offending rung is always allowed, which is the way out.
    • The floor is the base price, not the price the buyer would really pay. A different list may undercut base below the threshold and leave the buyer paying more at it; the write path cannot know which list wins for which buyer. Narrower than the silence it replaces, and the reason the resolver is not the place for this check.
  • The import is applied a row at a time, so a ladder passes through states it would refuse (2026-09-16): lowering every rung of a stored ladder fails on the first row unless the file lists the higher quantities first, because the intermediate ladder really does rise. The refusal names the rung and the floor and says so. Batching a variant's rungs into one write is the structural fix, and belongs with the row-processor contract rather than here.

  • Two rows addressing one rung are refused, not merged (2026-09-16): upsert_all cannot carry a key twice, and keeping the last occurrence answered success while discarding a price the merchant had typed. The batch now fails and names the repeated quantity.

  • A ladder needs no quantity-1 row (2026-09-07): a list may price a variant only from 24 up, and quantities below that fall through to the next list or the base price exactly as they do for a variant the list never priced. That is a real agreement ("wholesale from a case"), and requiring a base row would make bulk writes order-dependent. The tier editor still locks its first row to quantity 1 when one exists, as a convenience rather than a rule.

  • Quotes/draft orders: the volume price computes on quantity change through the existing repricing path (quantity is already in Pricing::Context); a price_source: 'manual' override still beats it — the negotiation ordering already recorded.

Design Details

  • Resolution: find_price_for_list becomes "rows for (variant, currency) on this list, min_quantity <= context.quantity (quantity nil → 1), pick max min_quantity"; nil-amount placeholder rows keep falling through per row. Cache keys gain the quantity bucket only where the resolution cache is quantity-sensitive (the line-item pricing path already carries quantity per call).
  • Dashboard: the price-list editor's variant×currency cell shows the quantity-1 price with a "+N tiers" badge; clicking opens the inline tier editor ([Min qty | Unit price] rows, add/delete, strictly-increasing validation) — one component, reused on the catalog page's products-with-prices view. The admin price endpoints + bulk upsert accept min_quantity. The price-list CSV is a per-list export and a merge import on the same pipelines as the product CSV (see Key Decisions).
  • Storefront: no ladder display in v1 (the merchant's own preference) — the line's unit price re-resolves as quantity crosses thresholds. A PDP "buy more, save more" widget is a later opt-in read of the same rows.
  • Banded adjustment: the catalog page's Pricing card gains "Add quantity tier" rows under the existing magnitude/direction controls — the catalog page only, since a percentage (and so a band) is refused on a standalone list (6.0-price-list-automatic-pricing.md) — same tier-editor component as the fixed breaks; the resolution cache keys gain the quantity band the same way the fixed-break path does.

Migration Path

  1. Schema — min_quantity on spree_prices (default 1) + the unique-index reshape; model validations (list-only, cap, increasing ladder via uniqueness). In the major so SDK types, CSV shapes, bulk upsert and integrations never harden against the old row identity.
  2. Resolver — quantity-aware row pick + specs (ladder pick, placeholder fallthrough, adjustment precedence, owned + standalone lists, quantity nil → identical behavior to today until tiers exist).
  3. Banded adjustment — spree_price_adjustment_tiers + resolver band pick + specs (band pick, column fallback, explicit-row precedence, owned + standalone).
  4. Admin API + dashboard — tier editor for breaks and bands (both homes), bulk upsert.

No data migration: the integer default makes every existing price a quantity-1 row.

Constraints on Current Work

  • Never model a contracted tier — fixed or percent — as a discount/promotion, and never build marketing volume discounts into pricing: agreement terms are price rows/bands, marketing is promotions.
  • Price-reading code must pass the line quantity through Pricing::Context — a caller that omits it silently gets quantity-1 prices.
  • No coupling between quantity rules (MOQ/multiple) and price tiers.
  • Exports/feeds reading list prices must account for tier rows (a quantity-1-only export silently drops the ladder). The price-list CSV carries min_quantity and writes every rung.

Open Questions

None for this scope; the four raised at implementation time (2026-09-07) are settled in Key Decisions above, as are the four the price-list CSV raised. Deferred, recorded: base-price (D2C) tiers = one validation to lift; PDP ladder widget; the marketing volume-discount promotion pair (LineQuantity rule + quantity-tiered percent calculator); per-tier kind: percent on price rows (rejected — bands on the adjustment cover it with the implemented semantics).

Notes from the build (2026-09-07)

  • Adding a dimension to a table changes what its existing readers mean. min_quantity gave spree_prices a second row per variant per list, and several readers were counting every row a variant had: Product#price_varies? and #lowest_price quoted the cheapest price-list row as the product's shop price, so a catalogue with any agreement attached advertised a private contract price to every shopper (reproduced on sample data: a toaster listing "from $23.99" against a $39.99 shop price). The leak predated this plan — any price-list row already caused it — but ladders deepen it, and the fix belongs here. Product#shop_prices, Variant.for_currency_and_available_price_amount, Products.with_currency and the line-item currency swap now all read base prices only. The general rule for the next such change: a column that changes row identity is not finished at the writers and the resolver — the readers that never asked the resolver are where it leaks.
  • One reader was missed, and it was in the dashboard (2026-09-22). expand=variants.prices serves every row a variant has, which is correct; the product form took the lot and posted it back as the variant's base prices, so saving a product on a price list overwrote its shop price with the list's amount and deleted the currencies the list only held placeholders for (V-3661). The fix filters in variantToFormValues, which both panels share. Narrowing the serializers was tried and rejected on review: a published read is not where a writer's constraint belongs. A form that posts a collection back owes that collection a filter.
  • The break cap lives in Prices::BulkUpsert rather than in a controller, because three write paths reach that service and none of them run model validations. Counted the same way in the model and the service: breaks above the ordinary price, placeholder rows not counted.
  • The CSV import is one more caller of Prices::BulkUpsert, which is what makes a blank price mean "remove this rung" in the file exactly as it does in the editor. The one thing the service does not check is the sign of an amount — it trusts its callers — so the row processor refuses a negative or unparsable figure itself before handing the row over.
  • The price-list page's products card reached parity with the catalog's on 2026-09-08 (follow-up PR): the same per-variant rows, source badge and ladder preview, read through the same resolver built from the list directly rather than through a catalog, so a draft list shows the rows being typed. One column set serves both pages; only the copy differs.
  • A band of exactly 0% is refused rather than stored: a factor of 1 makes the list decline to price the line at all, so a band meaning "no further discount here" would fall through to the next list. Removing the band is how a ladder stops.

References

  • Merchant feedback, 2026-09 (fixed + percentage tiers; catalog compatibility; storefront shows the applied price; MOQ separation; quotes override).
  • Platform research 2026-09-07 (break-on-the-price-record as the universal shape; fixed-only tiers; the leader's %-adjustment precedence; quantity rules as a sibling axis) — private, not in this repo.
  • spree/core/app/models/spree/price_rules/volume_rule.rb (kept, list-level), .../calculator/tiered_percent.rb (the sibling), .../adjusters/promotion.rb (winner-only).