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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Price a line by how many of it someone is buying
Damian Legawieccd782389d080
diff --git a/docs/plans/6.0-volume-pricing.md b/docs/plans/6.0-volume-pricing.mdindex 46ef47cb58..23c4b49b4d 100644--- a/docs/plans/6.0-volume-pricing.md+++ b/docs/plans/6.0-volume-pricing.md@@ -1,6 +1,6 @@# Volume Pricing (Quantity Breaks + Banded Adjustments)-**Status:** Draft — design finalized 2026-09-07, nothing built+**Status:** In progress — design finalized 2026-09-07; implementation started 2026-09-07**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@@ -82,6 +82,29 @@ promotion territory and are deliberately deferred.existing `TieredPercent`) — recorded as the deferred design, not builthere. Contracted terms never render as discounts; marketing never hidesas pricing.+- **Price-list CSV is deferred, not shipped here** (2026-09-07,+ implementation review): the plan assumed a price-list CSV import/export+ that has never been built — the only price columns in any CSV today are+ the product export's base `price`/`compare_at_price`. Adding+ `min_quantity` to a surface that does not exist is not a column+ addition, it is a whole import/export pipeline. When a price-list CSV is+ built it carries `min_quantity` from its first version; the product CSV+ is untouched, since breaks require a price list and 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 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 changethrough the existing repricing path (`quantity` is already in`Pricing::Context`); a `price_source: 'manual'` override still beats it@@ -97,11 +120,10 @@ promotion territory and are deliberately deferred.already carries quantity per call).- Dashboard: the price-list editor's variant×currency cell shows thequantity-1 price with a "+N tiers" badge; clicking opens the inline tier- editor (`[Min qty | Unit price]` rows, first row locked to 1, add/delete,- strictly-increasing validation) — one component, reused on the catalog- page's products-with-prices view. CSV import/export of a list gains a- `min_quantity` column (one line per tier); the admin price endpoints +- bulk upsert accept it.+ 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`. Price-list CSV is deferred (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. APDP "buy more, save more" widget is a later opt-in read of the same@@ -125,7 +147,7 @@ promotion territory and are deliberately deferred.pick + specs (band pick, column fallback, explicit-row precedence,owned + standalone).4. **Admin API + dashboard** — tier editor for breaks and bands (both- homes), CSV, bulk upsert.+ homes), bulk upsert.No data migration: the integer default makes every existing price aquantity-1 row.@@ -144,11 +166,13 @@ quantity-1 row.## Open Questions-None for this scope. 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).+None for this scope; the four raised at implementation time (2026-09-07)+are settled in Key Decisions above. Deferred, recorded: price-list CSV+import/export (carrying `min_quantity` when built); 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).## Referencesdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex d0af3e154b..d1cf688d06 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -4854,6 +4854,41 @@ core use a symbol and parameters, never a preformatted string; nothing in thedashboard prints an API `label`/`name`/`description` directly; shared admin copygoes in `dashboard-core` locales, never in `packages/seller-dashboard`.+## 2026-09-07 — Volume pricing implementation: CSV deferred, the cap is a validation, and a ladder needs no quantity-1 rung++Settled before building `6.0-volume-pricing.md`. Three of the four are+narrow, one removes scope.++**Price-list CSV is deferred rather than shipped.** The plan called for+"CSV import/export of a list gains a `min_quantity` column", but no+price-list CSV surface has ever existed — the only price columns in any+export are the product CSV's base `price` / `compare_at_price`. Adding a+column to a pipeline that is not there is a whole export model, presenter,+import parser, endpoints and dashboard affordance: a feature of its own,+not a phase of this one. Recorded so the next person building a+price-list CSV carries `min_quantity` in its first version. The product+CSV stays untouched — breaks require a price list in v1, so every base row+is quantity 1 by construction and the column could never vary.++**The ≤10 break cap is a model validation scoped to+`(variant, currency, price_list)`**, and the bulk-upsert path refuses a+batch that would cross it. A dashboard-only cap leaves the API unbounded,+and the resolver scans a variant's rows per priced line, so an unbounded+ladder is a cost paid on every cart recalculation.++**A ladder needs no quantity-1 rung.** A list may price a variant only+from 24 up; quantities below fall through to the next list or the base+price exactly as they do for a variant the list never priced. That is the+"wholesale from a case" agreement, and requiring a base rung would make+bulk writes order-dependent (a batch inserting `24` before `1` would have+to be sorted to pass). The tier editor locks its first row to 1 when one+exists, which is a convenience and not a rule.++**Both tier editors ship together** — the price-list bulk editor and the+catalog's products-with-prices view — because they are one component with+two homes, and shipping one leaves the other showing a "+3 tiers" badge+nothing can open.+## 2026-09-07 — Three merchant asks resolved: market availability, the lot tier split, and the volume-pricing doctrineThe next feedback batch (market exclusions, lot detail + tier question,diff --git a/spree/core/app/models/spree/catalog_price.rb b/spree/core/app/models/spree/catalog_price.rbindex c40ac8cda6..29476b2061 100644--- a/spree/core/app/models/spree/catalog_price.rb+++ b/spree/core/app/models/spree/catalog_price.rb@@ -21,6 +21,10 @@ module Spreeattribute :amount, :decimalattribute :currency, :stringattribute :source, :string+ # How many quantity tiers sit above this amount — breaks on the list's own+ # rows, or bands on its percentage. Zero for a variant priced at one+ # figure whatever the order size (docs/plans/6.0-volume-pricing.md).+ attribute :break_count, :integer, default: 0validates :source, inclusion: { in: SOURCES }@@ -31,6 +35,12 @@ module Spreesource != 'base'end+ # Whether the amount is the bottom of a ladder rather than the only price.+ # @return [Boolean]+ def tiered?+ break_count.to_i.positive?+ end+# @return [Spree::Money]def moneySpree::Money.new(amount, currency: currency)diff --git a/spree/core/app/models/spree/price.rb b/spree/core/app/models/spree/price.rbindex 67f50d905e..479fe6c42c 100644--- a/spree/core/app/models/spree/price.rb+++ b/spree/core/app/models/spree/price.rb@@ -18,6 +18,12 @@ module SpreeMAXIMUM_AMOUNT = BigDecimal('99_999_999.99')+ # How many breaks one variant may carry on one list in one currency. A UI+ # sanity bound rather than a technical one — but enforced here so no+ # writer can get past it, since the resolver scans a variant's rows for+ # every priced line (docs/plans/6.0-volume-pricing.md).+ MAXIMUM_BREAKS_PER_VARIANT = 10+belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant', inverse_of: :prices, touch: truebelongs_to :price_list, class_name: 'Spree::PriceList', optional: true@@ -46,10 +52,19 @@ module Spreevalidates :currency, presence: true+ validates :min_quantity, presence: true,+ numericality: { only_integer: true, greater_than: 0 }+ validate :break_requires_price_list+ validate :breaks_within_cap+scope :with_currency, ->(currency) { where(currency: currency) }scope :non_zero, -> { where.not(amount: [nil, 0]) }scope :discounted, -> { where('compare_at_amount > amount') }scope :base_prices, -> { where(price_list_id: nil) }+ # Rows a line of this size may be charged at, deepest break first — the+ # resolver takes the first.+ scope :for_quantity, ->(quantity) { where(min_quantity: ..(quantity.to_i.positive? ? quantity.to_i : 1)).order(min_quantity: :desc) }+ scope :breaks, -> { where.not(min_quantity: 1) }scope :for_price_list, ->(price_list) { where(price_list_id: price_list) }scope :for_products, lambda { |products, currency = nil|currency ||= Spree::Store.default.default_currency@@ -63,7 +78,7 @@ module Spreemoney_methods :amount, :price, :compare_at_amountalias display_compare_at_price display_compare_at_amount- self.whitelisted_ransackable_attributes = %w[amount compare_at_amount currency price_list_id variant_id]+ self.whitelisted_ransackable_attributes = %w[amount compare_at_amount currency min_quantity price_list_id variant_id]self.whitelisted_ransackable_associations = %w[variant price_list]self.whitelisted_ransackable_scopes = %i[search]@@ -216,8 +231,40 @@ module Spreevariant&.product&.storeend+ # Whether this row is a quantity break rather than the list's ordinary+ # price for the variant.+ # @return [Boolean]+ def quantity_break?+ min_quantity.to_i > 1+ end+private+ # Base prices are what a shopper is quoted on a product page, and a+ # quantity-dependent shop price would make every PDP quantity-dependent —+ # a storefront surface v1 deliberately does not open+ # (docs/plans/6.0-volume-pricing.md). Lifting this later is deleting this+ # method; the column is already the right one.+ def break_requires_price_list+ return unless quantity_break?+ return if price_list_id.present?++ errors.add(:min_quantity, :requires_price_list)+ end++ # Counted over the siblings this row would join, so the message names the+ # ladder that is full rather than the row that arrived last.+ def breaks_within_cap+ return if price_list_id.blank? || variant_id.blank? || currency.blank?+ return unless will_save_change_to_attribute?(:min_quantity) || new_record?++ siblings = self.class.where(variant_id: variant_id, currency: currency, price_list_id: price_list_id)+ siblings = siblings.where.not(id: id) if persisted?+ return if siblings.count < MAXIMUM_BREAKS_PER_VARIANT++ errors.add(:min_quantity, :too_many_breaks, count: MAXIMUM_BREAKS_PER_VARIANT)+ end+def should_record_price_history?price_list_id.nil? &&amount.present? &&diff --git a/spree/core/app/models/spree/price_adjustment_tier.rb b/spree/core/app/models/spree/price_adjustment_tier.rbnew file mode 100644index 0000000000..e019998105--- /dev/null+++ b/spree/core/app/models/spree/price_adjustment_tier.rb@@ -0,0 +1,52 @@+module Spree+ # One band of a price list's percentage adjustment: from this quantity up,+ # the list adjusts base prices by this percentage instead of the one on its+ # own `price_adjustment_percentage` column.+ #+ # The column stays the list's quantity-1 value, so a list carrying no tiers+ # prices exactly as it did before bands existed. A band adjusts the *base*+ # price, like the column does — never a previous band's result — so a+ # merchant reading "-20% from fifty" gets twenty percent off the shop price+ # and not twenty percent off an already-discounted number+ # (docs/plans/6.0-volume-pricing.md).+ class PriceAdjustmentTier < Spree.base_class+ has_prefix_id :pat++ # How many bands one list may carry, matching the break cap so a merchant+ # meets one number rather than two.+ MAXIMUM_TIERS_PER_LIST = Spree::Price::MAXIMUM_BREAKS_PER_VARIANT++ belongs_to :price_list, class_name: 'Spree::PriceList', inverse_of: :price_adjustment_tiers, touch: true++ validates :min_quantity, presence: true,+ numericality: { only_integer: true, greater_than: 1 },+ uniqueness: { scope: :price_list_id }+ # The same bounds the list's own column carries: at -100 every derived+ # price is zero, below it the arithmetic goes negative, and above 1000 the+ # decimal(6,3) column cannot hold the value.+ validates :percentage, presence: true,+ numericality: { greater_than: -100, less_than: 1000 }+ validate :tiers_within_cap++ scope :by_quantity, -> { order(min_quantity: :asc) }+ # Bands a line of this size qualifies for, deepest first.+ scope :for_quantity, ->(quantity) { where(min_quantity: ..quantity.to_i).order(min_quantity: :desc) }++ self.whitelisted_ransackable_attributes = %w[min_quantity percentage price_list_id]++ private++ # Quantity 1 is the list's own column, so a band at 1 would be a second+ # answer to a question already answered — refused by the numericality+ # bound above rather than silently shadowing the column.+ def tiers_within_cap+ return if price_list_id.blank?++ siblings = self.class.where(price_list_id: price_list_id)+ siblings = siblings.where.not(id: id) if persisted?+ return if siblings.count < MAXIMUM_TIERS_PER_LIST++ errors.add(:base, :too_many_tiers, count: MAXIMUM_TIERS_PER_LIST)+ end+ end+enddiff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rbindex 39c5056552..5cbf7422ce 100644--- a/spree/core/app/models/spree/price_list.rb+++ b/spree/core/app/models/spree/price_list.rb@@ -21,6 +21,10 @@ module Spreehas_many :price_rules, class_name: 'Spree::PriceRule', autosave: true, dependent: :destroyalias rules price_ruleshas_many :prices, class_name: 'Spree::Price', dependent: :destroy_async+ # The higher bands of this list's percentage adjustment; the column is its+ # quantity-1 value (docs/plans/6.0-volume-pricing.md).+ has_many :price_adjustment_tiers, -> { by_quantity }, class_name: 'Spree::PriceAdjustmentTier',+ inverse_of: :price_list, autosave: true, dependent: :destroyhas_many :variants, -> { distinct }, through: :prices, source: :varianthas_many :products, -> { distinct }, through: :variants, source: :productalias price_list_products products@@ -169,16 +173,37 @@ module Spree# Zero is no adjustment at all: deriving base × 1.0 would stamp every# price with this list's id while changing nothing, and the dashboard# has no "0%" to show. It reads as a fixed list.- price_adjustment_percentage.present? && !price_adjustment_percentage.zero?+ #+ # A list whose column is blank but which carries bands still prices+ # automatically — it just prices nothing until a line reaches the first+ # band, which is the "no discount under a case" agreement.+ percentage_present?(price_adjustment_percentage) || price_adjustment_tiers.any?end- # What a base price is multiplied by to derive this list's price:- # -15% gives 0.85, +10% gives 1.1.+ # This list's percentage for a line of the given size: the deepest band it+ # reaches, or the list's own column below the first band. Quantity-1 (or+ # unknown) means the column, which is what a list carrying no bands always+ # answers (docs/plans/6.0-volume-pricing.md).+ #+ # @param quantity [Integer, nil]+ # @return [BigDecimal, nil]+ def adjustment_percentage_for(quantity = nil)+ band = band_for(quantity)+ return band.percentage if band++ price_adjustment_percentage+ end++ # What a base price is multiplied by to derive this list's price at the+ # given quantity: -15% gives 0.85, +10% gives 1.1.+ #+ # @param quantity [Integer, nil]# @return [BigDecimal, nil]- def adjustment_factor- return if price_adjustment_percentage.nil?+ def adjustment_factor(quantity = nil)+ percentage = adjustment_percentage_for(quantity)+ return if percentage.nil?- 1 + (price_adjustment_percentage / 100)+ 1 + (percentage / 100)end# This list's price for a base price, derived rather than stored: the base@@ -192,20 +217,30 @@ module Spree# reading an agreement and a shopper being charged cannot disagree.## @param base [Spree::Price] the variant's base price- # @return [Spree::Price, nil] nil when the base carries no amount- def derived_price_from(base)+ # @param quantity [Integer, nil] the line's size, which picks the band+ # @return [Spree::Price, nil] nil when the base carries no amount, or when+ # no band applies at this quantity and the list has no column of its own+ def derived_price_from(base, quantity = nil)return if base.nil? || base.amount.nil?+ factor = adjustment_factor(quantity)+ # A bands-only list below its first band adjusts nothing, so it prices+ # this line no more than a list holding no row for the variant does —+ # the walk moves on rather than stamping the base price with this+ # list's id.+ return if factor.nil? || factor == 1+compare_at =if adjust_compare_at && base.compare_at_amount.present?- Spree::Money::Rounding.to_currency(base.compare_at_amount * adjustment_factor, base.currency)+ Spree::Money::Rounding.to_currency(base.compare_at_amount * factor, base.currency)endSpree::Price.new(variant_id: base.variant_id,currency: base.currency,- amount: Spree::Money::Rounding.to_currency(base.amount * adjustment_factor, base.currency),+ amount: Spree::Money::Rounding.to_currency(base.amount * factor, base.currency),compare_at_amount: compare_at,+ min_quantity: band_for(quantity)&.min_quantity || 1,price_list_id: id)end@@ -234,7 +269,10 @@ module Spreevariant_ids = Spree::Variant.eligible.where(product_id: product_ids).distinct.pluck(:id)return if variant_ids.empty?- existing = prices.where(variant_id: variant_ids)+ # Only the bottom rung counts as "already here": a variant priced solely+ # from a case up still needs its quantity-1 placeholder, or the editor+ # has no row to show the ladder under.+ existing = prices.where(variant_id: variant_ids, min_quantity: 1).pluck(:variant_id, :currency).to_set@@ -248,6 +286,7 @@ module Spreevariant_id: variant_id,currency: currency,amount: nil,+ min_quantity: 1,price_list_id: id,created_at: now,updated_at: now@@ -266,7 +305,9 @@ module Spree# Removes products from the list. Hard-deletes their prices so the# unique index doesn't block re-adding the same products later# (acts_as_paranoid would leave soft-deleted rows blocking the- # `(variant_id, currency, price_list_id)` slot).+ # `(variant_id, currency, price_list_id, min_quantity)` slot). Every rung+ # of a variant's ladder goes with it — removing a product from a list+ # removes what the list charged for it, at every quantity.## @param product_ids [Array<String>] raw product PKs# @return [void]@@ -294,7 +335,7 @@ module Spree# Get current values for comparisonprice_ids = prices_attributes.map { |a| a[:id] || a['id'] }.compact.map(&:to_i)- current_values = prices.where(id: price_ids).pluck(:id, :amount, :compare_at_amount).to_h { |id, amount, compare_at| [id, { amount: amount, compare_at_amount: compare_at }] }+ current_values = prices.where(id: price_ids).pluck(:id, :amount, :compare_at_amount, :min_quantity).to_h { |id, amount, compare_at, min_quantity| [id, { amount: amount, compare_at_amount: compare_at, min_quantity: min_quantity }] }prices_attributes.each do |attrs|attrs = (attrs.respond_to?(:to_unsafe_h) ? attrs.to_unsafe_h : attrs.to_h).with_indifferent_access@@ -324,6 +365,10 @@ module Spreecurrency: attrs[:currency],amount: amount,compare_at_amount: compare_at_amount,+ # Carried from the stored row rather than the payload: this path+ # edits amounts on rungs that already exist, and a row's quantity is+ # not something an amount edit may move.+ min_quantity: current[:min_quantity],price_list_id: id}@@ -343,6 +388,23 @@ module Spreeprivate+ # The deepest band this quantity reaches, or nil when it reaches none.+ # Read off the loaded association so pricing a page of variants against+ # one list does not re-query per row.+ # @param quantity [Integer, nil]+ # @return [Spree::PriceAdjustmentTier, nil]+ def band_for(quantity)+ line_quantity = quantity.to_i+ return if line_quantity < 2++ price_adjustment_tiers.select { |tier| tier.min_quantity <= line_quantity }.max_by(&:min_quantity)+ end++ # Zero is not an adjustment — see #automatic_pricing?.+ def percentage_present?(percentage)+ percentage.present? && !percentage.zero?+ end+def apply_pending_rulesflush_pending_typed_association(:price_rules)end@@ -369,9 +431,12 @@ module Spree# whole store on sale while its product list changed nothing. So the# feature exists only inside an agreement.def percentage_requires_catalog- return if price_adjustment_percentage.nil? || catalog_id.present?+ return if catalog_id.present?- errors.add(:price_adjustment_percentage, :requires_catalog)+ # Bands are the same percentage asked at a quantity, so they are refused+ # on a standalone list for the same reason the column is.+ errors.add(:price_adjustment_percentage, :requires_catalog) if price_adjustment_percentage.present?+ errors.add(:price_adjustment_tiers, :requires_catalog) if price_adjustment_tiers.any?enddef starts_at_before_ends_atdiff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rbindex 1c25224ad4..9b84d30bd6 100644--- a/spree/core/app/models/spree/pricing_provider/internal.rb+++ b/spree/core/app/models/spree/pricing_provider/internal.rb@@ -113,14 +113,58 @@ module Spree# Returns the price for a given price list. An explicit row wins; a# list carrying a percentage adjustment otherwise derives one from the# base price.+ #+ # A variant carrying a break ladder on this list is priced by the+ # ladder alone — its rungs are the negotiated terms, and a percentage+ # meant for everything else must not undercut or overprice a figure+ # someone signed. So a line below the ladder's first rung falls to the+ # next list rather than to this one's percentage+ # (docs/plans/6.0-volume-pricing.md).+ ## @param price_list [Spree::PriceList]# @return [Spree::Price, nil]def find_price_for_list(price_list)- explicit_price_for_list(price_list) ||- (price_list.automatic_pricing? ? derived_price_for_list(price_list) : nil)+ explicit = explicit_price_for_list(price_list)+ return explicit if explicit+ return nil unless price_list.automatic_pricing?+ return nil if variant_has_breaks_on?(price_list)++ derived_price_for_list(price_list)end- # An amount someone typed for this variant on this list.+ # Whether this variant's rows on this list form a ladder. Asked only+ # when no rung matched, so it costs a query on a list that prices the+ # variant by percentage — which is the common case and answers false+ # from the loaded association whenever the caller preloaded prices.+ #+ # @param price_list [Spree::PriceList]+ # @return [Boolean]+ def variant_has_breaks_on?(price_list)+ currency = context.currency&.upcase++ if prices.loaded?+ prices.any? do |p|+ p.currency == currency && p.price_list_id == price_list.id && !p.amount.nil? && p.min_quantity.to_i > 1+ end+ else+ context.variant.prices+ .with_currency(currency)+ .where(price_list_id: price_list.id)+ .where.not(amount: nil)+ .breaks+ .exists?+ end+ end++ # An amount someone typed for this variant on this list, at the+ # deepest quantity break the line reaches.+ #+ # A list may hold several rows for one variant and currency — a+ # ladder — so this picks the highest `min_quantity` at or below the+ # line's size. With no breaks the ladder is one quantity-1 row and+ # this answers exactly what it always did+ # (docs/plans/6.0-volume-pricing.md).+ ## @param price_list [Spree::PriceList]# @return [Spree::Price, nil]def explicit_price_for_list(price_list)@@ -129,24 +173,38 @@ module Spree# Zero is a valid override (free for this list); only nil placeholder# rows (materialized by PriceList#add_products) are skipped, so a# placeholder on an adjustment list falls through to the derived- # amount rather than blocking it.+ # amount rather than blocking it. A placeholder at one rung does not+ # hide a real amount at a lower one — the skip is per row.if prices.loaded?- prices.detect do |p|+ prices.select do |p|p.currency == currency &&p.price_list_id == price_list.id &&- !p.amount.nil?- end+ !p.amount.nil? &&+ p.min_quantity.to_i <= line_quantity+ end.max_by { |p| p.min_quantity.to_i }elsecontext.variant.prices.with_currency(currency).where(price_list_id: price_list.id).where.not(amount: nil)+ .for_quantity(line_quantity).firstendend- # The base price times the list's factor, rounded to the currency's- # minor unit. Built unsaved and never written: deriving on read is+ # The size of the line being priced. A context that carries no+ # quantity is asking what one unit costs — a catalogue listing, an+ # export, a report — so it reads the ladder's bottom rung and behaves+ # exactly as it did before breaks existed.+ #+ # @return [Integer]+ def line_quantity+ quantity = context.quantity.to_i+ quantity.positive? ? quantity : 1+ end++ # The base price times the list's factor for this line's size, rounded+ # to the currency's minor unit. Built unsaved and never written: deriving on read is# what keeps an adjustment list from drifting when base prices move# (docs/plans/6.0-price-list-automatic-pricing.md).#@@ -157,7 +215,7 @@ module Spree# @param price_list [Spree::PriceList]# @return [Spree::Price, nil]def derived_price_for_list(price_list)- price_list.derived_price_from(base_price)+ price_list.derived_price_from(base_price, line_quantity)end# Returns the base price for the variant in the current currencydiff --git a/spree/core/app/services/spree/catalogs/resolve_prices.rb b/spree/core/app/services/spree/catalogs/resolve_prices.rbindex 25b4092163..674aa6ac02 100644--- a/spree/core/app/services/spree/catalogs/resolve_prices.rb+++ b/spree/core/app/services/spree/catalogs/resolve_prices.rb@@ -64,12 +64,24 @@ module Spreebase = rows.detect { |row| row.price_list_id.nil? }if price_list- explicit = rows.detect { |row| row.price_list_id == price_list.id }- return build(explicit, 'explicit') if explicit+ list_rows = rows.select { |row| row.price_list_id == price_list.id }+ # The bottom rung, because this reading makes no purchase — the+ # deeper rungs are reported as a count so the view can say "and+ # three more from a case up" without pretending to know the size of+ # an order nobody has placed.+ explicit = list_rows.min_by { |row| row.min_quantity.to_i }+ return build(explicit, 'explicit', break_count: list_rows.count { |row| row.min_quantity.to_i > 1 }) if explicit+# Derived by the list itself, so the amount a merchant reads here is# the one the pricing resolver charges — one formula, not two.- derived = price_list.automatic_pricing? ? price_list.derived_price_from(base) : nil- return build(derived, 'automatic') if derived+ derived = price_list.automatic_pricing? ? price_list.derived_price_from(base, 1) : nil+ return build(derived, 'automatic', break_count: band_count) if derived++ # A list whose percentage only starts at a quantity charges the base+ # price for a single unit, and says so — with the bands counted, so+ # the reading is "base now, and less from a case up" rather than a+ # bare base price that hides the agreement.+ return build(base, 'base', break_count: band_count) if base && band_count.positive?endbase && build(base, 'base')@@ -111,8 +123,16 @@ module Spreegroup_by(&:variant_id)end- def build(price, source)- Spree::CatalogPrice.new(amount: price.amount, currency: price.currency, source: source)+ # How many bands this list's percentage carries above quantity 1.+ # @return [Integer]+ def band_count+ price_list ? price_list.price_adjustment_tiers.size : 0+ end++ def build(price, source, break_count: 0)+ Spree::CatalogPrice.new(+ amount: price.amount, currency: price.currency, source: source, break_count: break_count+ )endendenddiff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rbindex 3a5e3d0b60..781a15bd48 100644--- a/spree/core/app/services/spree/prices/bulk_upsert.rb+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb@@ -6,7 +6,8 @@ module Spree# `spree_prices` is guarded by two partial unique indexes on PG/SQLite# (collapsed to one composite index on MySQL):# - base prices (price_list_id IS NULL): unique on (variant_id, currency)- # - overrides (price_list_id IS NOT NULL): unique on (variant_id, currency, price_list_id)+ # - overrides (price_list_id IS NOT NULL): unique on+ # (variant_id, currency, price_list_id, min_quantity)# A single `upsert_all` can only target one index, so rows ship in two# batches — base vs override — each routed to the correct ON CONFLICT.#@@ -19,19 +20,23 @@ module Spree# Two partial unique indexes guard `spree_prices` on PG/SQLite:# - base prices (price_list_id IS NULL): unique on (variant_id, currency)- # - overrides (price_list_id IS NOT NULL): unique on (variant_id, currency, price_list_id)+ # - overrides (price_list_id IS NOT NULL): unique on+ # (variant_id, currency, price_list_id, min_quantity)# A single `upsert_all` can only target one index, so base-price rows# and override rows ship in separate batches.BASE_UNIQUE_BY = %i[variant_id currency].freeze- OVERRIDE_UNIQUE_BY = %i[variant_id currency price_list_id].freeze+ OVERRIDE_UNIQUE_BY = %i[variant_id currency price_list_id min_quantity].freeze# @param rows [Array<Hash>] each row must carry- # `variant_id`, `currency`, and `amount`; `price_list_id` and- # `compare_at_amount` are optional. A blank `amount` is treated- # as "clear this price."+ # `variant_id`, `currency`, and `amount`; `price_list_id`,+ # `min_quantity` and `compare_at_amount` are optional. A blank+ # `amount` is treated as "clear this price", and a blank+ # `min_quantity` means the ladder's bottom rung.# @return [Spree::ServiceModule::Result] success carries# `{ price_count: N }` — the number of rows passed to- # `upsert_all`.+ # `upsert_all`. The break cap is enforced by the caller that can+ # report which rows crossed it — see the admin prices controller —+ # since this path writes in SQL and runs no model validations.def call(rows:)rows = Array(rows).map { |r| r.with_indifferent_access }keyed = rows.select { |r| r[:variant_id].present? && r[:currency].present? }@@ -39,11 +44,11 @@ module Spree# triple in one statement ("ON CONFLICT DO UPDATE command cannot# affect row a second time"). Last-write-wins: keep the last# occurrence of each triple.- deduped = keyed.reverse.uniq { |r| [r[:variant_id], r[:currency], r[:price_list_id]] }.reverse+ deduped = keyed.reverse.uniq { |r| row_key(r) }.reverseupsert_rows, clear_rows = deduped.partition { |r| r[:amount].present? }payload = build_payload(upsert_rows)- affected_keys = deduped.map { |r| [r[:variant_id], r[:currency], r[:price_list_id]] }+ affected_keys = deduped.map { |r| row_key(r) }return success(price_count: 0) if affected_keys.empty?@@ -65,7 +70,7 @@ module Spree# `Price -> Variant -> Product` `touch:` chain never fires —# downstream caches (`cache_key_with_version`) would stay stale.# Re-trigger the chain with one `.touch` per affected variant.- touch_variants(affected_keys.map(&:first).uniq)+ touch_variants(affected_keys.map { |k| k[0] }.uniq)endsuccess(price_count: payload.length)@@ -95,6 +100,7 @@ module Spreevariant_id: row[:variant_id],currency: row[:currency],price_list_id: row[:price_list_id],+ min_quantity: quantity_of(row),amount: parse_amount(row[:amount]),compare_at_amount: parse_amount(row[:compare_at_amount]),created_at: now,@@ -103,6 +109,18 @@ module Spreeendend+ # A row identifies one rung of one ladder. Rows arriving without a+ # quantity address the bottom rung, which is every row written before+ # breaks existed (docs/plans/6.0-volume-pricing.md).+ def row_key(row)+ [row[:variant_id], row[:currency], row[:price_list_id], quantity_of(row)]+ end++ def quantity_of(row)+ quantity = row[:min_quantity].to_i+ quantity.positive? ? quantity : 1+ end+# Parses locale-aware decimal input ("1.234,56" in DE, "1,234.56"# in en-US). Numeric values pass through; blank values become nil.def parse_amount(value)@@ -113,19 +131,20 @@ module Spreeenddef sweep(affected_keys, clear_rows)- cleared_keys = clear_rows.map { |r| [r[:variant_id], r[:currency], r[:price_list_id]] }.to_set+ cleared_keys = clear_rows.map { |r| row_key(r) }.to_setaffected_set = affected_keys.to_setcandidates = Spree::Price.where(- variant_id: affected_keys.map(&:first).uniq,+ variant_id: affected_keys.map { |k| k[0] }.uniq,currency: affected_keys.map { |k| k[1] }.uniq,- price_list_id: affected_keys.map(&:last).uniq+ price_list_id: affected_keys.map { |k| k[2] }.uniq,+ min_quantity: affected_keys.map { |k| k[3] }.uniq)- .pluck(:id, :variant_id, :currency, :price_list_id, :amount)+ .pluck(:id, :variant_id, :currency, :price_list_id, :min_quantity, :amount)- doomed_ids = candidates.filter_map do |id, variant_id, currency, price_list_id, amount|- key = [variant_id, currency, price_list_id]+ doomed_ids = candidates.filter_map do |id, variant_id, currency, price_list_id, min_quantity, amount|+ key = [variant_id, currency, price_list_id, min_quantity]next unless affected_set.include?(key)next id if amount.nil?next id if cleared_keys.include?(key)diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 58ab7a1acf..bba981ef5f 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -363,6 +363,15 @@ en:attributes:amount:greater_than_max_amount: is greater than the allowed maximum amount of %{max_amount}+ spree/price:+ attributes:+ min_quantity:+ requires_price_list: quantity breaks can only be set on a price list+ too_many_breaks: a variant can carry at most %{count} quantity breaks on one price list+ spree/price_adjustment_tier:+ attributes:+ base:+ too_many_tiers: a price list can carry at most %{count} quantity tiersspree/price_list:attributes:base:@@ -371,6 +380,8 @@ en:must_be_after_starts_at: must be after starts atprice_adjustment_percentage:requires_catalog: can only be set on a price list a catalog owns+ price_adjustment_tiers:+ requires_catalog: can only be set on a price list a catalog ownsspree/product:attributes:base:diff --git a/spree/core/db/migrate/20260907000001_add_min_quantity_to_spree_prices.rb b/spree/core/db/migrate/20260907000001_add_min_quantity_to_spree_prices.rbnew file mode 100644index 0000000000..f46259d09f--- /dev/null+++ b/spree/core/db/migrate/20260907000001_add_min_quantity_to_spree_prices.rb@@ -0,0 +1,28 @@+class AddMinQuantityToSpreePrices < ActiveRecord::Migration[8.1]+ def change+ # The quantity a line must reach for this row to be its price. Defaulting+ # to 1 makes every existing row a quantity-1 price, so a ladder is purely+ # additive and there is nothing to backfill+ # (docs/plans/6.0-volume-pricing.md).+ add_column :spree_prices, :min_quantity, :integer, null: false, default: 1++ # Row identity gains the column: a variant now holds one price per+ # (currency, list, break) rather than one per (currency, list).+ remove_index :spree_prices, name: 'index_spree_prices_on_variant_currency_price_list', if_exists: true++ if ActiveRecord::Base.connection.adapter_name == 'Mysql2'+ add_index :spree_prices, [:variant_id, :currency, :price_list_id, :min_quantity],+ name: 'index_spree_prices_on_variant_currency_list_quantity',+ unique: true+ else+ add_index :spree_prices, [:variant_id, :currency, :price_list_id, :min_quantity],+ name: 'index_spree_prices_on_variant_currency_list_quantity',+ unique: true,+ where: 'price_list_id IS NOT NULL AND deleted_at IS NULL AND amount IS NOT NULL'+ end++ # Reading a ladder means "this variant's rows on this list, ordered by+ # break" — the unique index above leads with variant_id, so it serves+ # that read too, and no second index is warranted.+ end+enddiff --git a/spree/core/db/migrate/20260907000002_create_spree_price_adjustment_tiers.rb b/spree/core/db/migrate/20260907000002_create_spree_price_adjustment_tiers.rbnew file mode 100644index 0000000000..bca2fa3d97--- /dev/null+++ b/spree/core/db/migrate/20260907000002_create_spree_price_adjustment_tiers.rb@@ -0,0 +1,19 @@+class CreateSpreePriceAdjustmentTiers < ActiveRecord::Migration[8.1]+ def change+ # The higher bands of a list's percentage adjustment. The list's own+ # `price_adjustment_percentage` column stays its quantity-1 value, so a+ # list with no tiers behaves exactly as it does today+ # (docs/plans/6.0-volume-pricing.md).+ create_table :spree_price_adjustment_tiers do |t|+ t.references :price_list, null: false, index: false+ t.integer :min_quantity, null: false, default: 1+ t.decimal :percentage, precision: 6, scale: 3, null: false, default: 0++ t.timestamps+ end++ add_index :spree_price_adjustment_tiers, [:price_list_id, :min_quantity],+ name: 'index_spree_price_adjustment_tiers_on_list_and_quantity',+ unique: true+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/price_adjustment_tier_factory.rb b/spree/core/lib/spree/testing_support/factories/price_adjustment_tier_factory.rbnew file mode 100644index 0000000000..3e8e90a372--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/price_adjustment_tier_factory.rb@@ -0,0 +1,7 @@+FactoryBot.define do+ factory :price_adjustment_tier, class: Spree::PriceAdjustmentTier do+ price_list+ min_quantity { 10 }+ percentage { -10 }+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/price_factory.rb b/spree/core/lib/spree/testing_support/factories/price_factory.rbindex 24fc5439d1..38a9f2ee6a 100644--- a/spree/core/lib/spree/testing_support/factories/price_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/price_factory.rb@@ -7,5 +7,11 @@ FactoryBot.define dofactory :price_eur docurrency { 'EUR' }end++ # A rung above the bottom of a list's ladder. Breaks need a list, so the+ # caller supplies one (docs/plans/6.0-volume-pricing.md).+ trait :quantity_break do+ min_quantity { 10 }+ endendenddiff --git a/spree/core/spec/models/spree/price_adjustment_tier_spec.rb b/spree/core/spec/models/spree/price_adjustment_tier_spec.rbnew file mode 100644index 0000000000..0113ef82c9--- /dev/null+++ b/spree/core/spec/models/spree/price_adjustment_tier_spec.rb@@ -0,0 +1,62 @@+require 'spec_helper'++describe Spree::PriceAdjustmentTier, type: :model do+ let(:catalog) { create(:catalog, store: @default_store) }+ let(:price_list) do+ create(:price_list, store: @default_store, catalog: catalog, price_adjustment_percentage: -5)+ end++ describe 'validations' do+ # Quantity 1 is the list's own column; a band there would be a second+ # answer to a question already answered.+ it 'refuses a band at or below one unit' do+ expect(build(:price_adjustment_tier, price_list: price_list, min_quantity: 1)).not_to be_valid+ expect(build(:price_adjustment_tier, price_list: price_list, min_quantity: 0)).not_to be_valid+ expect(build(:price_adjustment_tier, price_list: price_list, min_quantity: 2)).to be_valid+ end++ it 'refuses a second band at the same quantity' do+ create(:price_adjustment_tier, price_list: price_list, min_quantity: 10)++ expect(build(:price_adjustment_tier, price_list: price_list, min_quantity: 10)).not_to be_valid+ end++ it 'allows the same quantity on another list' do+ create(:price_adjustment_tier, price_list: price_list, min_quantity: 10)+ other = create(:price_list, store: @default_store, catalog: create(:catalog, store: @default_store))++ expect(build(:price_adjustment_tier, price_list: other, min_quantity: 10)).to be_valid+ end++ # The same bounds the list's own column carries: at -100 every derived+ # price is zero, and the decimal(6,3) column stops at 1000.+ it 'refuses a percentage the arithmetic or the column cannot hold' do+ band = ->(pct) { build(:price_adjustment_tier, price_list: price_list, min_quantity: 10, percentage: pct) }++ expect(band.call(-100)).not_to be_valid+ expect(band.call(1000)).not_to be_valid+ expect(band.call(-99.999)).to be_valid+ expect(band.call(999.999)).to be_valid+ end++ it 'refuses a ladder past the cap' do+ (2..(described_class::MAXIMUM_TIERS_PER_LIST + 1)).each do |quantity|+ create(:price_adjustment_tier, price_list: price_list, min_quantity: quantity)+ end++ extra = build(:price_adjustment_tier, price_list: price_list, min_quantity: 500)++ expect(extra).not_to be_valid+ expect(extra.errors.messages[:base].first).to include('at most 10')+ end+ end++ describe 'ordering' do+ it 'reads the list\'s bands from the shallowest up' do+ create(:price_adjustment_tier, price_list: price_list, min_quantity: 50)+ create(:price_adjustment_tier, price_list: price_list, min_quantity: 10)++ expect(price_list.reload.price_adjustment_tiers.map(&:min_quantity)).to eq([10, 50])+ end+ end+enddiff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rbindex c3937eb85a..2e3fa2e7cc 100644--- a/spree/core/spec/models/spree/price_list_spec.rb+++ b/spree/core/spec/models/spree/price_list_spec.rb@@ -65,6 +65,65 @@ describe Spree::PriceList, type: :model doendend+ # Percentage ladders: the column is the quantity-1 value, the tiers are the+ # bands above it (docs/plans/6.0-volume-pricing.md).+ describe 'quantity bands' do+ let(:catalog) { create(:catalog, store: @default_store) }+ let(:price_list) do+ create(:price_list, store: @default_store, catalog: catalog, price_adjustment_percentage: -5)+ end++ before do+ create(:price_adjustment_tier, price_list: price_list, min_quantity: 10, percentage: -10)+ create(:price_adjustment_tier, price_list: price_list, min_quantity: 50, percentage: -20)+ price_list.reload+ end++ it 'answers the deepest band a quantity reaches' do+ expect(price_list.adjustment_percentage_for(1)).to eq(-5)+ expect(price_list.adjustment_percentage_for(9)).to eq(-5)+ expect(price_list.adjustment_percentage_for(10)).to eq(-10)+ expect(price_list.adjustment_percentage_for(49)).to eq(-10)+ expect(price_list.adjustment_percentage_for(50)).to eq(-20)+ end++ it 'reads the column when asked without a quantity' do+ expect(price_list.adjustment_percentage_for).to eq(-5)+ expect(price_list.adjustment_factor).to eq(0.95)+ end++ it 'turns the band into the factor a base price is multiplied by' do+ expect(price_list.adjustment_factor(50)).to eq(0.80)+ end++ # A list may discount only from a quantity up, with no quantity-1+ # percentage at all.+ context 'with bands but no percentage of its own' do+ before { price_list.update!(price_adjustment_percentage: nil) }++ it 'still prices automatically' do+ expect(price_list).to be_automatic_pricing+ end++ it 'adjusts nothing below the first band' do+ base = build(:price, amount: 100, currency: 'USD')++ expect(price_list.derived_price_from(base, 5)).to be_nil+ expect(price_list.derived_price_from(base, 10).amount).to eq(90)+ end+ end++ # Bands are the same percentage asked at a quantity, so a standalone list+ # is refused them for the same reason it is refused the column.+ it 'is only valid on a list a catalog owns' do+ standalone = create(:price_list, store: @default_store)+ standalone.price_adjustment_tiers.build(min_quantity: 10, percentage: -10)++ expect(standalone).not_to be_valid+ expect(standalone.errors.messages[:price_adjustment_tiers]).to be_present+ end+ end+# An owned list is selected by its catalog, which already answered the# audience question — so only rules about the purchase itself still have# anything to say (docs/plans/6.0-price-list-automatic-pricing.md).diff --git a/spree/core/spec/models/spree/price_spec.rb b/spree/core/spec/models/spree/price_spec.rbindex 012099da00..7240f8d763 100644--- a/spree/core/spec/models/spree/price_spec.rb+++ b/spree/core/spec/models/spree/price_spec.rb@@ -198,6 +198,68 @@ describe Spree::Price, type: :model doit { is_expected.to be_valid }end++ # Quantity breaks (docs/plans/6.0-volume-pricing.md).+ describe 'min_quantity' do+ let(:amount) { 10 }+ let(:price_list) { create(:price_list) }++ it 'defaults to the ladder\'s bottom rung' do+ expect(described_class.new.min_quantity).to eq(1)+ end++ it 'refuses a quantity below one' do+ subject.min_quantity = 0++ expect(subject).not_to be_valid+ expect(subject.errors.messages[:min_quantity]).to be_present+ end++ # A quantity-dependent shop price would make every product page+ # quantity-dependent, which v1 deliberately does not open.+ it 'refuses a break with no price list' do+ subject.min_quantity = 24++ expect(subject).not_to be_valid+ expect(subject.errors.messages[:min_quantity]).to include('quantity breaks can only be set on a price list')+ end++ it 'accepts a break on a price list' do+ subject.assign_attributes(min_quantity: 24, price_list: price_list)++ expect(subject).to be_valid+ end++ it 'refuses a ladder past the cap' do+ (1..Spree::Price::MAXIMUM_BREAKS_PER_VARIANT).each do |rung|+ create(:price, variant: variant, currency: 'USD', amount: 10, price_list: price_list, min_quantity: rung)+ end++ eleventh = build(:price, variant: variant, currency: 'USD', amount: 9, price_list: price_list, min_quantity: 99)++ expect(eleventh).not_to be_valid+ expect(eleventh.errors.messages[:min_quantity].first).to include('at most 10')+ end++ # The cap counts a variant's rungs on one list in one currency, so a+ # second currency is a ladder of its own.+ it 'counts the cap per currency' do+ (1..Spree::Price::MAXIMUM_BREAKS_PER_VARIANT).each do |rung|+ create(:price, variant: variant, currency: 'USD', amount: 10, price_list: price_list, min_quantity: rung)+ end++ expect(build(:price, variant: variant, currency: 'EUR', amount: 9, price_list: price_list, min_quantity: 24)).to be_valid+ end+ end++ describe '#quantity_break?' do+ let(:amount) { 10 }++ it 'is false for the bottom rung and true above it' do+ expect(build(:price, min_quantity: 1)).not_to be_quantity_break+ expect(build(:price, min_quantity: 24)).to be_quantity_break+ end+ endenddescribe '#price_including_vat_for' dodiff --git a/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb b/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rbindex 3cbbbacaa0..798902957a 100644--- a/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb+++ b/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb@@ -361,6 +361,214 @@ describe Spree::PricingProvider::Internal::Resolution doendend+ # Fixed contracted ladders: a variant's rows on one list, each carrying+ # the quantity from which it applies (docs/plans/6.0-volume-pricing.md).+ context 'with a quantity break ladder on a price list' do+ let!(:price_list) { create(:price_list, :active, store: store) }++ before do+ variant.prices.base_prices.with_currency(currency).update_all(amount: 20.00)+ create(:price, variant: variant, currency: currency, amount: 10.00, price_list: price_list, min_quantity: 1)+ create(:price, variant: variant, currency: currency, amount: 9.00, price_list: price_list, min_quantity: 24)+ create(:price, variant: variant, currency: currency, amount: 8.00, price_list: price_list, min_quantity: 96)+ end++ def price_at(quantity)+ described_class.new(+ Spree::Pricing::Context.new(variant: variant, currency: currency, store: store, quantity: quantity)+ ).resolve+ end++ it 'charges the deepest break the line reaches' do+ expect(price_at(1).amount).to eq(10.00)+ expect(price_at(23).amount).to eq(10.00)+ expect(price_at(24).amount).to eq(9.00)+ expect(price_at(95).amount).to eq(9.00)+ expect(price_at(96).amount).to eq(8.00)+ expect(price_at(1_000).amount).to eq(8.00)+ end++ # A listing, an export or a report asks what one unit costs and must+ # read the bottom rung rather than the deepest.+ it 'reads the bottom rung when the context carries no quantity' do+ expect(price_at(nil).amount).to eq(10.00)+ end++ it 'stamps the list on the rung it charged' do+ price = price_at(96)++ expect(price.price_list_id).to eq(price_list.id)+ expect(price.min_quantity).to eq(96)+ end++ # The walk runs off the association when a caller preloaded it, so both+ # branches have to pick the same rung.+ it 'picks the same rung from a preloaded association' do+ variant.prices.load++ expect(described_class.new(+ Spree::Pricing::Context.new(variant: variant, currency: currency, store: store, quantity: 96)+ ).resolve.amount).to eq(8.00)+ end++ # A ladder that starts above one unit prices nothing below its first+ # rung; the walk moves on exactly as it would for a variant the list+ # never priced.+ context 'when the ladder starts above one unit' do+ before { variant.prices.where(price_list: price_list, min_quantity: 1).delete_all }++ it 'falls through to the base price below the first rung' do+ price = price_at(5)++ expect(price.amount).to eq(20.00)+ expect(price.price_list_id).to be_nil+ end++ it 'still charges the ladder from its first rung up' do+ expect(price_at(24).amount).to eq(9.00)+ end+ end++ # A placeholder is skipped per row, so it cannot hide a real amount+ # standing at a lower rung.+ context 'with a placeholder at the deepest rung' do+ before { variant.prices.where(price_list: price_list, min_quantity: 96).update_all(amount: nil) }++ it 'falls back to the rung below rather than to the base price' do+ expect(price_at(120).amount).to eq(9.00)+ end+ end+ end++ # A negotiated ladder is the agreement for that variant; the list's+ # percentage, written for everything else, must not undercut it+ # (docs/plans/6.0-volume-pricing.md).+ context 'with a break ladder on an automatic price list' do+ let(:company) { create(:company, store: store) }+ let(:catalog) do+ create(:catalog, store: store).tap do |owner|+ create(:catalog_assignment, catalog: owner, assignable: company)+ end+ end+ let!(:price_list) do+ create(:price_list, :active, store: store, catalog: catalog, price_adjustment_percentage: -10)+ end++ before do+ variant.prices.base_prices.with_currency(currency).update_all(amount: 20.00)+ create(:price, variant: variant, currency: currency, amount: 9.00, price_list: price_list, min_quantity: 24)+ end++ def price_at(quantity)+ described_class.new(+ Spree::Pricing::Context.new(+ variant: variant, currency: currency, store: store, company: company, quantity: quantity+ )+ ).resolve+ end++ it 'charges the ladder rather than the percentage once a rung is reached' do+ expect(price_at(24).amount).to eq(9.00)+ end++ it 'refuses the percentage below the ladder and falls through to base' do+ price = price_at(5)++ expect(price.amount).to eq(20.00)+ expect(price.price_list_id).to be_nil+ end++ # Only the laddered variant is exempt: everything else on the list is+ # still priced by the percentage.+ it 'still applies the percentage to a variant with no ladder' do+ other = create(:variant)+ other.prices.base_prices.with_currency(currency).update_all(amount: 50.00)++ price = described_class.new(+ Spree::Pricing::Context.new(+ variant: other, currency: currency, store: store, company: company, quantity: 1+ )+ ).resolve++ expect(price.amount).to eq(45.00)+ end+ end++ # Percentage ladders: bands on the list's own adjustment+ # (docs/plans/6.0-volume-pricing.md).+ context 'with quantity bands on an automatic price list' do+ let(:company) { create(:company, store: store) }+ let(:catalog) do+ create(:catalog, store: store).tap do |owner|+ create(:catalog_assignment, catalog: owner, assignable: company)+ end+ end+ let!(:price_list) do+ create(:price_list, :active, store: store, catalog: catalog, price_adjustment_percentage: -5)+ end++ before do+ variant.prices.base_prices.with_currency(currency).update_all(amount: 100.00)+ create(:price_adjustment_tier, price_list: price_list, min_quantity: 10, percentage: -10)+ create(:price_adjustment_tier, price_list: price_list, min_quantity: 50, percentage: -20)+ end++ def price_at(quantity)+ described_class.new(+ Spree::Pricing::Context.new(+ variant: variant, currency: currency, store: store, company: company, quantity: quantity+ )+ ).resolve+ end++ it 'applies the deepest band the line reaches' do+ expect(price_at(1).amount).to eq(95.00)+ expect(price_at(9).amount).to eq(95.00)+ expect(price_at(10).amount).to eq(90.00)+ expect(price_at(49).amount).to eq(90.00)+ expect(price_at(50).amount).to eq(80.00)+ end++ # Every band is a percentage off the base price, never off the band+ # below it — otherwise "20% from fifty" would quietly mean 24%.+ it 'takes each band off the base price rather than compounding' do+ expect(price_at(50).amount).to eq(80.00)+ end++ it 'falls back to the column when the line reaches no band' do+ expect(price_at(1).amount).to eq(95.00)+ end++ it 'reads the column when the context carries no quantity' do+ expect(price_at(nil).amount).to eq(95.00)+ end++ # A signed row is what someone agreed to; a band is what the list does+ # to everything else.+ it 'still prefers an explicit row over every band' do+ create(:price, variant: variant, currency: currency, amount: 42.00, price_list: price_list)++ expect(price_at(50).amount).to eq(42.00)+ end++ # A list whose discount only starts at a quantity has no quantity-1+ # percentage at all.+ context 'when the list carries bands but no percentage of its own' do+ before { price_list.update!(price_adjustment_percentage: nil) }++ it 'charges the base price below the first band' do+ price = price_at(5)++ expect(price.amount).to eq(100.00)+ expect(price.price_list_id).to be_nil+ end++ it 'applies the band once the line reaches it' do+ expect(price_at(10).amount).to eq(90.00)+ end+ end+ end+context 'with price list from different store' dolet(:other_store) { create(:store) }let!(:other_store_list) { create(:price_list, :active, store: other_store) }