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.

Resolve applicable catalogs once per request instead of per variant (#14520)

Damian Legawiec75243e49f5c2
diff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rb
index 5737f21a9f..90f90f9fdd 100644
--- a/spree/core/app/models/spree/catalog.rb
+++ b/spree/core/app/models/spree/catalog.rb
@@ -33,6 +33,13 @@ module Spree
validates :name, presence: true
validate :price_list_in_same_store
+ # Request-scoped catalog memoization must not keep a set that a write
+ # in the same request has already superseded.
+ after_commit -> {
+ Spree::Current.applicable_catalogs = nil
+ Spree::Current.catalog_bound_price_list_ids = nil
+ }
+
scope :active, -> { where(active: true) }
scope :by_position, -> { order(position: :asc) }
@@ -86,6 +93,46 @@ module Spree
map(&:catalog).select(&:active?).sort_by { |catalog| catalog.position.to_i }.uniq
end
+ # Catalogs that apply to a buyer: the company subtree first, then the
+ # customer's groups, then the channel's default catalog — the one
+ # resolution chain both visibility ({Spree::Products::ForContext}) and
+ # pricing use. Pricing asks it once per request buyer via
+ # {Spree::Current#catalogs_for}.
+ #
+ # @param store [Spree::Store, nil]
+ # @param company [Spree::Company, nil]
+ # @param user [Object, nil]
+ # @param channel [Spree::Channel, nil]
+ # @return [Array<Spree::Catalog>]
+ def self.for_context(store:, company: nil, user: nil, channel: nil)
+ return [] if store.nil?
+
+ catalogs = store.catalogs.for_company(company)
+ if catalogs.empty? && user
+ groups = user.try(:customer_groups)&.where(store_id: store.id) || []
+ catalogs = store.catalogs.for_customer_groups(groups)
+ end
+ catalogs = [channel&.default_catalog].compact.select(&:active?) if catalogs.empty?
+ # Pricing reads each catalog's price list; without this the walk is one
+ # query per catalog again.
+ ActiveRecord::Associations::Preloader.new(records: catalogs, associations: :price_list).call if catalogs.any?
+ catalogs
+ end
+
+ # Price-list ids claimed by an active catalog of the store. Only ACTIVE
+ # catalogs claim their list: an inactive catalog is off, and blacklisting
+ # its list would silently kill a rule-based list that was working before
+ # the catalog draft existed.
+ #
+ # @param store [Spree::Store, nil]
+ # @return [Set<Integer>]
+ def self.bound_price_list_ids(store)
+ return Set.new if store.nil?
+
+ active.where(store_id: store.id).where.not(price_list_id: nil).
+ distinct.pluck(:price_list_id).to_set
+ end
+
# Adds products to the assortment, appending to the manual order and
# skipping ones already present. Written in one statement, so importing a
# whole price list is a single insert rather than a row per product.
diff --git a/spree/core/app/models/spree/catalog_assignment.rb b/spree/core/app/models/spree/catalog_assignment.rb
index 8c8224bfd7..a80613a690 100644
--- a/spree/core/app/models/spree/catalog_assignment.rb
+++ b/spree/core/app/models/spree/catalog_assignment.rb
@@ -22,6 +22,8 @@ module Spree
validates :catalog_id, uniqueness: { scope: [:assignable_type, :assignable_id, *spree_base_uniqueness_scope] }
validate :assignable_in_same_store
+ after_commit -> { Spree::Current.applicable_catalogs = nil }
+
delegate :store, :store_id, to: :catalog
private
diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rb
index 1748eed68c..cbf67376fb 100644
--- a/spree/core/app/models/spree/current.rb
+++ b/spree/core/app/models/spree/current.rb
@@ -4,7 +4,7 @@ module Spree
# All attributes are automatically reset between requests by Rails.
# Fallback chains ensure sensible defaults when attributes are not explicitly set.
class Current < ::ActiveSupport::CurrentAttributes
- attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :global_pricing_context, :provider_cache, :integrations
+ attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :applicable_catalogs, :catalog_bound_price_list_ids, :global_pricing_context, :provider_cache, :integrations
# Scratch space for provider strategies to memoize a call across the
# request — part of the delivery rate provider contract (nothing in core
@@ -90,6 +90,36 @@ module Spree
end
end
+ # Catalogs that apply to a buyer in this request, keyed by that buyer.
+ # A store can have many catalogs; only the company / customer-group /
+ # channel-default set is kept. Product listings price every variant
+ # through a new resolver, so the first call loads the set and the rest
+ # reuse it.
+ #
+ # @param company [Spree::Company, nil]
+ # @param user [Object, nil]
+ # @param channel [Spree::Channel, nil]
+ # @return [Array<Spree::Catalog>]
+ def catalogs_for(company: nil, user: nil, channel: nil)
+ channel ||= self.channel
+ key = [store&.id, company&.id, user&.id, channel&.id]
+ applicable_catalogs[key] ||= Spree::Catalog.for_context(
+ store: store, company: company, user: user, channel: channel
+ )
+ end
+
+ # Price-list ids claimed by any active catalog in the current store.
+ # One pluck per request — the listing path asked this for every variant.
+ # @return [Set<Integer>]
+ def catalog_bound_price_list_ids
+ super || (self.catalog_bound_price_list_ids = Spree::Catalog.bound_price_list_ids(store))
+ end
+
+ # @return [Hash]
+ def applicable_catalogs
+ super || (self.applicable_catalogs = {})
+ end
+
# Returns the current global pricing context, built from store, currency, country, and market.
# @return [Spree::Pricing::Context]
def global_pricing_context
diff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rb
index a34403ea8a..05377dc1f3 100644
--- a/spree/core/app/models/spree/pricing_provider/internal.rb
+++ b/spree/core/app/models/spree/pricing_provider/internal.rb
@@ -61,21 +61,7 @@ module Spree
# status and dates.
# @return [Array<Spree::PriceList>]
def catalog_price_lists
- @catalog_price_lists ||= begin
- # Every lookup starts from the context's store, so a catalog is
- # only ever reached through the tenant being priced for.
- store = context.store
- catalogs = store ? store.catalogs.for_company(context.company) : []
- if catalogs.empty? && context.user && store
- groups = context.user.try(:customer_groups)&.where(store_id: store.id) || []
- catalogs = store.catalogs.for_customer_groups(groups)
- end
- if catalogs.empty?
- catalogs = [context.channel&.default_catalog].compact.select(&:active?)
- end
-
- catalogs.filter_map(&:price_list).uniq.select(&:currently_active?)
- end
+ @catalog_price_lists ||= catalogs_for_context.filter_map(&:price_list).uniq.select(&:currently_active?)
end
# Returns the price lists that are applicable to the context.
@@ -94,14 +80,27 @@ module Spree
# that was working before the catalog draft existed.
def catalog_bound_price_list_ids
@catalog_bound_price_list_ids ||=
- if context.store
- Spree::Catalog.active.where(store_id: context.store.id).where.not(price_list_id: nil).
- distinct.pluck(:price_list_id).to_set
+ if context.store == Spree::Current.store
+ Spree::Current.catalog_bound_price_list_ids
else
- Set.new
+ Spree::Catalog.bound_price_list_ids(context.store)
end
end
+ # Catalogs that apply to this buyer. Reused from {Spree::Current}
+ # when the context is the current store, so a product listing does
+ # not re-resolve the same company / group / channel set per variant.
+ # @return [Array<Spree::Catalog>]
+ def catalogs_for_context
+ if context.store == Spree::Current.store
+ Spree::Current.catalogs_for(company: context.company, user: context.user, channel: context.channel)
+ else
+ Spree::Catalog.for_context(
+ store: context.store, company: context.company, user: context.user, channel: context.channel
+ )
+ end
+ end
+
# Returns the price lists for the context's store
# Uses Spree::Current.price_lists if the context matches, otherwise fetches directly
# @return [ActiveRecord::Relation<Spree::PriceList>]
diff --git a/spree/core/app/services/spree/products/for_context.rb b/spree/core/app/services/spree/products/for_context.rb
index 3eefa62d7a..a95f66a6b6 100644
--- a/spree/core/app/services/spree/products/for_context.rb
+++ b/spree/core/app/services/spree/products/for_context.rb
@@ -27,9 +27,15 @@ module Spree
base ||= store.products.for_channel(channel)
company ||= sole_standing_company(store, customer)
- catalogs = store.catalogs.for_company(company)
- catalogs = customer_group_catalogs(store, customer) if catalogs.empty?
- catalogs = [channel&.default_catalog].compact.select(&:active?) if catalogs.empty?
+ # Reuses the request-scoped set when resolving for the current store,
+ # so a listing that prices its variants right after does not resolve
+ # the same buyer's catalogs twice in one request.
+ catalogs =
+ if store == Spree::Current.store
+ Spree::Current.catalogs_for(company: company, user: customer, channel: channel)
+ else
+ Spree::Catalog.for_context(store: store, company: company, user: customer, channel: channel)
+ end
return success(base) if catalogs.empty?
@@ -69,13 +75,6 @@ module Spree
companies.one? ? companies.first : nil
end
-
- def customer_group_catalogs(store, customer)
- return [] if customer.nil?
-
- groups = customer.customer_groups.where(store_id: store.id)
- store.catalogs.for_customer_groups(groups)
- end
end
end
end
diff --git a/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb b/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb
index 772254e910..be15038213 100644
--- a/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb
+++ b/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb
@@ -91,4 +91,44 @@ describe 'catalog-aware pricing' do
expect(resolve(company: company).amount).to eq(80)
expect(resolve.amount).to eq(80)
end
+
+ # Product listings build one Pricing::Context per variant. The bound
+ # price-list ids and the catalogs that apply to this buyer are request
+ # scoped, so later rows must not query catalogs again.
+ it 'loads applicable catalogs once across many variant resolutions' do
+ catalog = create(:catalog, store: store, price_list: price_list_with_price(80))
+ create(:catalog_assignment, catalog: catalog, assignable: company)
+ variants = create_list(:variant, 3)
+
+ catalog_query_count = lambda do |&block|
+ queries = 0
+ counter = lambda do |*, payload|
+ next if payload[:name].to_s.match?(/SCHEMA|TRANSACTION/)
+
+ queries += 1 if payload[:sql].include?('spree_catalogs')
+ end
+ ActiveSupport::Notifications.subscribed(counter, 'sql.active_record', &block)
+ queries
+ end
+
+ price_variants = lambda do |records|
+ records.each do |priced_variant|
+ Spree::Pricing::PriceResolution.call(
+ Spree::Pricing::Context.new(
+ variant: priced_variant, currency: 'USD', store: store, company: company
+ )
+ )
+ end
+ end
+
+ Spree::Current.store = store
+ single = catalog_query_count.call { price_variants.call(variants.take(1)) }
+
+ Spree::Current.reset
+ Spree::Current.store = store
+ batched = catalog_query_count.call { price_variants.call(variants) }
+
+ expect(batched).to eq(single)
+ expect(single).to be > 0
+ end
end
diff --git a/spree/core/spec/models/spree/catalog_spec.rb b/spree/core/spec/models/spree/catalog_spec.rb
index b916d21803..d1c24eb825 100644
--- a/spree/core/spec/models/spree/catalog_spec.rb
+++ b/spree/core/spec/models/spree/catalog_spec.rb
@@ -89,6 +89,26 @@ describe Spree::Catalog, type: :model do
end
end
+ describe '.for_context' do
+ let(:company) { create(:company, store: store) }
+
+ it 'returns company catalogs and ignores ones that do not apply' do
+ assigned = create(:catalog, store: store)
+ create(:catalog, store: store)
+ create(:catalog_assignment, catalog: assigned, assignable: company)
+
+ expect(described_class.for_context(store: store, company: company)).to eq([assigned])
+ end
+
+ it 'falls back to the channel default catalog when nothing narrower applies' do
+ catalog = create(:catalog, store: store)
+ channel = store.default_channel
+ channel.update!(default_catalog: catalog)
+
+ expect(described_class.for_context(store: store, channel: channel)).to eq([catalog])
+ end
+ end
+
describe 'assignments' do
let(:catalog) { create(:catalog, store: store) }
diff --git a/spree/core/spec/models/spree/current_spec.rb b/spree/core/spec/models/spree/current_spec.rb
index a3ac256b9f..4fa32a83e5 100644
--- a/spree/core/spec/models/spree/current_spec.rb
+++ b/spree/core/spec/models/spree/current_spec.rb
@@ -243,6 +243,66 @@ RSpec.describe Spree::Current do
end
end
+ describe '#catalogs_for' do
+ let(:store) { @default_store }
+ let!(:company) { create(:company, store: store) }
+ let!(:assigned_catalog) { create(:catalog, store: store) }
+ let!(:other_catalog) { create(:catalog, store: store) }
+
+ before do
+ create(:catalog_assignment, catalog: assigned_catalog, assignable: company)
+ described_class.store = store
+ end
+
+ it 'returns only catalogs that apply to the buyer, not every catalog in the store' do
+ expect(described_class.catalogs_for(company: company)).to eq([assigned_catalog])
+ expect(described_class.catalogs_for(company: company)).not_to include(other_catalog)
+ end
+
+ it 'memoizes the applicable set for the same buyer' do
+ first = described_class.catalogs_for(company: company)
+ second = described_class.catalogs_for(company: company)
+ expect(first).to be(second)
+ end
+
+ it 'does not reuse one buyer set for another' do
+ other_company = create(:company, store: store)
+ other_assigned = create(:catalog, store: store)
+ create(:catalog_assignment, catalog: other_assigned, assignable: other_company)
+
+ expect(described_class.catalogs_for(company: company)).to eq([assigned_catalog])
+ expect(described_class.catalogs_for(company: other_company)).to eq([other_assigned])
+ end
+
+ it 'drops the memoized set when a catalog is written' do
+ expect(described_class.catalogs_for(company: company)).to eq([assigned_catalog])
+
+ created = create(:catalog, store: store)
+ create(:catalog_assignment, catalog: created, assignable: company)
+
+ expect(described_class.catalogs_for(company: company)).to contain_exactly(assigned_catalog, created)
+ end
+ end
+
+ describe '#catalog_bound_price_list_ids' do
+ let(:store) { @default_store }
+ let!(:price_list) { create(:price_list, :active, store: store) }
+
+ before { described_class.store = store }
+
+ it 'includes price lists claimed by an active catalog' do
+ create(:catalog, store: store, price_list: price_list)
+
+ expect(described_class.catalog_bound_price_list_ids).to include(price_list.id)
+ end
+
+ it 'memoizes the id set' do
+ first = described_class.catalog_bound_price_list_ids
+ second = described_class.catalog_bound_price_list_ids
+ expect(first).to be(second)
+ end
+ end
+
describe '.reset' do
let(:store) { create(:store) }
let(:country) { create(:country) }
@@ -277,6 +337,22 @@ RSpec.describe Spree::Current do
expect(described_class.instance_variable_get(:@price_lists)).to be_nil
end
+ it 'clears memoized applicable catalogs' do
+ described_class.catalogs_for
+
+ described_class.reset
+
+ expect(described_class.instance_variable_get(:@applicable_catalogs)).to be_nil
+ end
+
+ it 'clears memoized catalog_bound_price_list_ids' do
+ described_class.catalog_bound_price_list_ids
+
+ described_class.reset
+
+ expect(described_class.instance_variable_get(:@catalog_bound_price_list_ids)).to be_nil
+ end
+
it 'clears memoized global_pricing_context' do
# Access global_pricing_context to memoize
described_class.global_pricing_context