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
Stop quoting a private contract price to every shopper
Damian Legawiec9a1f291f269e
diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsxindex 946a42591e..dd1012fbe9 100644--- a/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsx+++ b/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsx@@ -200,11 +200,7 @@ export function VariantTierDialog({}onChange={(id, field, next) =>setDraft((prev) =>- prev.map((rung) =>- rung.id === id- ? { ...rung, [field === 'minQuantity' ? 'minQuantity' : 'value']: next }- : rung,- ),+ prev.map((rung) => (rung.id === id ? { ...rung, [field]: next } : rung)),)}onAdd={() => {diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.tsindex ff764bfdb3..76ac59c1e2 100644--- a/packages/dashboard/src/schemas/catalog.ts+++ b/packages/dashboard/src/schemas/catalog.ts@@ -425,16 +425,16 @@ export function catalogPricingValues(// next Save would clear terms the merchant never saw// (docs/plans/6.0-volume-pricing.md).const bandsOnly = pricing_mode !== 'automatic' && bands.length > 0+ // The shallowest band decides the whole ladder's direction: the form offers+ // one increase/decrease control, and the magnitudes below are read through+ // it.+ const bandDirection = Number(bands[0]?.percentage) > 0 ? 'increase' : 'decrease'return {pricing_mode: bandsOnly ? 'automatic' : pricing_mode,// With no percentage of its own the direction comes from the bands, so// the magnitudes below read as the discounts they are.- adjustment_direction: bandsOnly- ? Number(bands[0]?.percentage) > 0- ? 'increase'- : 'decrease'- : adjustment_direction,+ adjustment_direction: bandsOnly ? bandDirection : adjustment_direction,adjustment_magnitude,adjust_compare_at: priceList.adjust_compare_at ?? false,minimum_quantity: minimumQuantityOf(priceList.price_rules),diff --git a/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rbindex 895829dacb..262d4aca65 100644--- a/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb@@ -70,7 +70,10 @@ module Spreeenddef collection_includes- [:catalog_products, :price_list, :order_minimums]+ # The serializer reads each catalog's pricing strategy, which asks+ # its list whether it carries bands — preloaded so an index does+ # not pay a query per row.+ [:catalog_products, :order_minimums, { price_list: :price_adjustment_tiers }]enddef create_workflowdiff --git a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rbindex af2446b43f..eae21e0cf7 100644--- a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb@@ -114,6 +114,13 @@ module Spreesuper.orderedend+ # The serializer always renders a list's bands — the pricing card+ # cannot show a percentage without them — so the index preloads them+ # rather than paying a query per row.+ def collection_includes+ [:price_adjustment_tiers]+ end+def permitted_paramsattrs = normalize_params(params.permit(diff --git a/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rbindex 4f85d16dc5..0534d668fb 100644--- a/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb@@ -55,13 +55,18 @@ module Spreeresult = Spree::Prices::BulkUpsert.call(rows: rows)# The cap lives in the service, since every write path reaches it# and none of them run model validations- # (docs/plans/6.0-volume-pricing.md).- unless result.success?+ # (docs/plans/6.0-volume-pricing.md). Guarded on the failure+ # actually carrying `over_cap`, so a failure mode the service grows+ # later is not reported under this one's name.+ if (over_cap = result.error&.value.try(:[], :over_cap))return render_error(code: 'too_many_breaks',- message: "A variant can carry at most #{Spree::Price::MAXIMUM_BREAKS_PER_VARIANT} quantity breaks on one price list.",+ message: Spree.t(+ 'activerecord.errors.models.spree/price.attributes.min_quantity.too_many_breaks',+ count: Spree::Price::MAXIMUM_BREAKS_PER_VARIANT+ ).upcase_first,status: :unprocessable_content,- details: { ladders: result.error.value[:over_cap] }+ details: { ladders: over_cap })enddiff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rbindex 77eb215040..db67a837a6 100644--- a/spree/core/app/models/concerns/spree/product_scopes.rb+++ b/spree/core/app/models/concerns/spree/product_scopes.rb@@ -221,9 +221,13 @@ module Spreefor_channel(channel).where(Spree::ProductPublication.table_name => { unpublished_at: [nil, Time.current.beginning_of_minute..] })end+ # Products the shop sells in this currency. Base prices only: a price+ # list's rows are what one audience pays under an agreement, so a product+ # priced only by a contract is not on sale here to everyone+ # (docs/plans/6.0-volume-pricing.md).def self.with_currency(currency)joins(variants: :prices).- where(Price.table_name => { currency: currency.upcase }).+ where(Price.table_name => { currency: currency.upcase, price_list_id: nil }).where.not(Price.table_name => { amount: nil }).distinctenddiff --git a/spree/core/app/models/concerns/spree/purchase/line_item_currencies.rb b/spree/core/app/models/concerns/spree/purchase/line_item_currencies.rbindex 7a9b754ac4..b13b5e8920 100644--- a/spree/core/app/models/concerns/spree/purchase/line_item_currencies.rb+++ b/spree/core/app/models/concerns/spree/purchase/line_item_currencies.rb@@ -15,8 +15,13 @@ module Spreeendend+ # The variant's own price in the new currency. Scoped to base prices: a+ # price list's rows belong to one audience and a ladder holds several+ # rows for one variant, so an unscoped `first` would re-price the line at+ # whichever row the database happened to return+ # (docs/plans/6.0-volume-pricing.md).def price_from_line_item(line_item)- line_item.variant.prices.where(currency: currency).first+ line_item.variant.prices.base_prices.where(currency: currency).firstenddef update_line_item_price!(line_item)diff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rbindex 86c4c99b7a..f62627ffa0 100644--- a/spree/core/app/models/spree/catalog.rb+++ b/spree/core/app/models/spree/catalog.rb@@ -168,7 +168,7 @@ module Spree# this the walk is one query per catalog again, plus one per list.if catalogs.any?ActiveRecord::Associations::Preloader.new(- records: catalogs, associations: { price_list: :price_rules }+ records: catalogs, associations: { price_list: [:price_rules, :price_adjustment_tiers] }).callendcatalogsdiff --git a/spree/core/app/models/spree/price.rb b/spree/core/app/models/spree/price.rbindex fa8d6959c3..a0fb070ebd 100644--- a/spree/core/app/models/spree/price.rb+++ b/spree/core/app/models/spree/price.rb@@ -61,9 +61,7 @@ module Spreescope :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) }+ # A variant's rungs above its ordinary price on a list.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|diff --git a/spree/core/app/models/spree/price_adjustment_tier.rb b/spree/core/app/models/spree/price_adjustment_tier.rbindex cc1d9db334..4105e8926d 100644--- a/spree/core/app/models/spree/price_adjustment_tier.rb+++ b/spree/core/app/models/spree/price_adjustment_tier.rb@@ -35,8 +35,6 @@ module Spreevalidate :tiers_within_capscope :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) }# No ransack allowlist: a band is reached only through the list that owns# it, exactly like a PriceRule, and there is no endpoint that filtersdiff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rbindex 38be66e82a..e21796c449 100644--- a/spree/core/app/models/spree/price_list.rb+++ b/spree/core/app/models/spree/price_list.rb@@ -142,6 +142,9 @@ module Spree.with_status(:active, :scheduled).current(timezone).by_position+ # Every matched list is asked whether it prices automatically, which+ # reads its bands — without this the walk pays a query per list.+ .preload(:price_adjustment_tiers)enddef self.match_policies@@ -249,7 +252,9 @@ module Spreedef derived_price_from(base, quantity = nil)return if base.nil? || base.amount.nil?- factor = adjustment_factor(quantity)+ band = band_for(quantity)+ percentage = band ? band.percentage : price_adjustment_percentage+ factor = percentage && 1 + (percentage / 100)# 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@@ -266,7 +271,7 @@ module Spreecurrency: 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,+ min_quantity: band&.min_quantity || 1,price_list_id: id)enddiff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rbindex 9b84d30bd6..7b469d2fd0 100644--- a/spree/core/app/models/spree/pricing_provider/internal.rb+++ b/spree/core/app/models/spree/pricing_provider/internal.rb@@ -124,72 +124,55 @@ module Spree# @param price_list [Spree::PriceList]# @return [Spree::Price, nil]def find_price_for_list(price_list)- explicit = explicit_price_for_list(price_list)+ rows = rows_for_list(price_list)++ explicit = rows.select { |row| row.min_quantity <= line_quantity }.max_by(&:min_quantity)return explicit if explicitreturn nil unless price_list.automatic_pricing?- return nil if variant_has_breaks_on?(price_list)+ return nil if rows.any?(&:quantity_break?)derived_price_for_list(price_list)end- # 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.+ # This variant's chargeable rows on one list in this currency — the+ # rungs of its ladder, which is a single row for a variant with no+ # breaks (docs/plans/6.0-volume-pricing.md).+ #+ # Read once per list and memoized, so the two questions asked of it —+ # which rung this line reaches, and whether a ladder exists at all —+ # cost one lookup rather than two and cannot answer inconsistently.+ #+ # 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. The skip is per row, so a placeholder at one+ # rung does not hide a real amount at a lower one.## @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+ # @return [Array<Spree::Price>]+ def rows_for_list(price_list)+ @rows_for_list ||= {}+ @rows_for_list[price_list.id] ||=+ if prices.loaded?+ prices.select do |row|+ row.currency == currency && row.price_list_id == price_list.id && !row.amount.nil?+ end+ else+ context.variant.prices.+ with_currency(currency).+ where(price_list_id: price_list.id).+ where.not(amount: nil).to_aend- else- context.variant.prices- .with_currency(currency)- .where(price_list_id: price_list.id)- .where.not(amount: nil)- .breaks- .exists?- endend- # An amount someone typed for this variant on this list, at the- # deepest quantity break the line reaches.+ # The context's currency, upcased like every lookup that compares+ # against it.#- # 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)- currency = context.currency&.upcase+ # @return [String, nil]+ def currency+ return @currency if defined?(@currency)- # 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. A placeholder at one rung does not- # hide a real amount at a lower one — the skip is per row.- if prices.loaded?- prices.select do |p|- p.currency == currency &&- p.price_list_id == price_list.id &&- !p.amount.nil? &&- p.min_quantity.to_i <= line_quantity- end.max_by { |p| p.min_quantity.to_i }- else- context.variant.prices- .with_currency(currency)- .where(price_list_id: price_list.id)- .where.not(amount: nil)- .for_quantity(line_quantity)- .first- end+ @currency = context.currency&.upcaseend# The size of the line being priced. A context that carries no@@ -231,8 +214,6 @@ module Spreedef base_pricereturn @base_price if defined?(@base_price)- currency = context.currency&.upcase-@base_price = if prices.loaded?prices.detect do |p|p.currency == currency &&diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex 5934ecdf55..5033ed916f 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -626,8 +626,13 @@ module Spreeendend+ # Whether the shop price differs between this product's variants. Reads+ # base prices only: a price list's rows are what one audience pays under an+ # agreement, and a ladder holds several rows for one variant, so counting+ # them would report a product as varying when it does not+ # (docs/plans/6.0-volume-pricing.md).def price_varies?(currency)- prices.find_all { |p| p.currency == currency && p.non_zero? }.map(&:amount).uniq.count > 1+ shop_prices(currency).map(&:amount).uniq.count > 1enddef any_variant_available?(currency)@@ -637,7 +642,22 @@ module Spree# returns the lowest price for the product in the given currency# prices are usually already loaded, so this should not trigger an extra querydef lowest_price(currency)- prices.find_all { |p| p.currency == currency && p.non_zero? }.min_by(&:amount)+ shop_prices(currency).min_by(&:amount)+ end++ # The prices this product is offered at publicly — one per variant. A price+ # list's rows are excluded: they are what one audience pays under an+ # agreement, so surfacing the cheapest of them as the product's "from"+ # price would quote every shopper a contract they are not party to.+ #+ # Filtered in memory rather than through a scope because callers have+ # already loaded the association, and a scope would re-query per product+ # in a listing.+ #+ # @param currency [String]+ # @return [Array<Spree::Price>]+ def shop_prices(currency)+ prices.find_all { |p| p.currency == currency && p.price_list_id.nil? && p.non_zero? }end# for adding products which are closely related to existing onesdiff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex dc7f813697..376d5c057f 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -187,9 +187,15 @@ module Spreescope :not_deleted, -> { where("#{Spree::Variant.quoted_table_name}.deleted_at IS NULL") }+ # Variants the shop sells in this currency. Base prices only: a price+ # list's rows are what one audience pays under an agreement, and a ladder+ # holds several rows for one variant, so a contract-only variant is not+ # available to everyone (docs/plans/6.0-volume-pricing.md).scope :for_currency_and_available_price_amount, lambda { |currency = nil|currency ||= Spree::Store.default.default_currency- joins(:prices).where("#{Spree::Price.table_name}.currency = ?", currency).where("#{Spree::Price.table_name}.amount IS NOT NULL").distinct+ joins(:prices).+ where(Spree::Price.table_name => { currency: currency, price_list_id: nil }).+ where("#{Spree::Price.table_name}.amount IS NOT NULL").distinct}scope :active, lambda { |currency = nil|diff --git a/spree/core/app/services/spree/catalogs/resolve_prices.rb b/spree/core/app/services/spree/catalogs/resolve_prices.rbindex 70073abc22..2d7bfbca8d 100644--- a/spree/core/app/services/spree/catalogs/resolve_prices.rb+++ b/spree/core/app/services/spree/catalogs/resolve_prices.rb@@ -129,9 +129,14 @@ module Spreeend# How many bands this list's percentage carries above quantity 1.+ # Memoized and loaded rather than counted: this is asked once per product+ # row, and `.size` on an unloaded association issues a COUNT every time+ # without ever populating it.# @return [Integer]def band_count- price_list ? price_list.price_adjustment_tiers.size : 0+ return @band_count if defined?(@band_count)++ @band_count = price_list ? price_list.price_adjustment_tiers.to_a.size : 0enddef build(price, source, break_count: 0)diff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rbindex f419e7bbc0..502abfec30 100644--- a/spree/core/app/services/spree/prices/bulk_upsert.rb+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb@@ -137,23 +137,30 @@ module Spree# @param rows [Array<Hash>] the rows carrying an amount# @return [Array<Hash>] `[{ variant_id:, currency:, price_list_id: }, ...]`def ladders_over_cap(rows)- touched = rows.each_with_object(Hash.new { |hash, key| hash[key] = Set.new }) do |row, ladders|- next if row[:price_list_id].blank?- next if quantity_of(row) == 1-- ladders[[row[:variant_id].to_s, row[:currency], row[:price_list_id].to_s]] << quantity_of(row)- end+ touched = rows.+ reject { |row| row[:price_list_id].blank? || quantity_of(row) == 1 }.+ group_by { |row| [row[:variant_id].to_s, row[:currency], row[:price_list_id].to_s] }.+ transform_values { |group| group.map { |row| quantity_of(row) }.to_set }return [] if touched.empty?- touched.filter_map do |(variant_id, currency, price_list_id), incoming|- stored = Spree::Price.- where(variant_id: variant_id, currency: currency, price_list_id: price_list_id).- breaks.- pluck(:min_quantity)-- next if (stored.to_set | incoming).size <= Spree::Price::MAXIMUM_BREAKS_PER_VARIANT-- { variant_id: variant_id, currency: currency, price_list_id: price_list_id }+ # One query for every ladder in the batch rather than one each: an+ # import writing a ladder across two hundred variants would otherwise+ # issue two hundred round trips inside the request. Cross-pairs the+ # `IN` clauses pull in are dropped by the lookup below, the same way+ # #sweep handles them.+ stored = Spree::Price.+ where(variant_id: touched.keys.map { |key| key[0] },+ currency: touched.keys.map { |key| key[1] },+ price_list_id: touched.keys.map { |key| key[2] }).+ breaks.+ pluck(:variant_id, :currency, :price_list_id, :min_quantity).+ group_by { |variant_id, currency, price_list_id, _| [variant_id.to_s, currency, price_list_id.to_s] }++ touched.filter_map do |key, incoming|+ rungs = stored.fetch(key, []).map(&:last).to_set | incoming+ next if rungs.size <= Spree::Price::MAXIMUM_BREAKS_PER_VARIANT++ { variant_id: key[0], currency: key[1], price_list_id: key[2] }endenddiff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rbindex 827bf945d0..8b868bcb82 100644--- a/spree/core/spec/models/spree/product_spec.rb+++ b/spree/core/spec/models/spree/product_spec.rb@@ -1598,6 +1598,22 @@ describe Spree::Product, type: :model doit { is_expected.to be(true) }end++ # A price list's rows are what one audience pays under an agreement, and a+ # ladder holds several rows for one variant — neither makes the shop price+ # vary (docs/plans/6.0-volume-pricing.md).+ context 'when a price list prices the variants differently' do+ let(:price_list) { create(:price_list, :active) }++ before do+ create(:price, variant: variant_1, currency: 'USD', amount: 10)+ create(:price, variant: variant_2, currency: 'USD', amount: 10)+ create(:price, variant: variant_1, currency: 'USD', amount: 7, price_list: price_list)+ create(:price, variant: variant_1, currency: 'USD', amount: 5, price_list: price_list, min_quantity: 24)+ end++ it { is_expected.to be(false) }+ endenddescribe '#any_variant_available?' do@@ -1673,6 +1689,16 @@ describe Spree::Product, type: :model doit 'returns the lowest price' doexpect(subject).to eq(price_3)end++ # Quoting a contract price as the product's "from" price would show every+ # shopper an agreement they are not party to.+ it 'ignores a price list\'s rows, including its quantity breaks' do+ list = create(:price_list, :active)+ create(:price, variant: variant_2, currency: 'USD', amount: 9, price_list: list)+ create(:price, variant: variant_2, currency: 'USD', amount: 3, price_list: list, min_quantity: 24)++ expect(subject).to eq(price_3)+ endenddescribe 'scopes' do