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.

Simplify: fix N+1s, extract shared code, remove duplication

Damian Legawiec1fdf8c4ce6a7
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/store/search_provider_support.rb b/spree/api/app/controllers/concerns/spree/api/v3/store/search_provider_support.rb
new file mode 100644
index 0000000000..645ee8b648
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/store/search_provider_support.rb
@@ -0,0 +1,27 @@
+module Spree
+ module Api
+ module V3
+ module Store
+ module SearchProviderSupport
+ extend ActiveSupport::Concern
+
+ private
+
+ def search_query
+ params.dig(:q, :search)
+ end
+
+ def search_filters
+ q = params[:q]&.to_unsafe_h || params[:q] || {}
+ q = q.to_h if q.respond_to?(:to_h) && !q.is_a?(Hash)
+ q.except('search').presence
+ end
+
+ def search_provider
+ @search_provider ||= Spree.search_provider.constantize.new(current_store)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
index 6db1190cf0..01517bb684 100644
--- a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
@@ -4,11 +4,13 @@ module Spree
module Store
module Products
class FiltersController < Store::BaseController
+ include Spree::Api::V3::Store::SearchProviderSupport
+
def index
result = search_provider.search_and_filter(
scope: filters_scope,
- query: params.dig(:q, :search),
- filters: search_filters.merge('_category' => category),
+ query: search_query,
+ filters: (search_filters || {}).merge('_category' => category),
page: 1,
limit: 0
)
@@ -29,19 +31,10 @@ module Spree
scope.accessible_by(current_ability, :show)
end
- def search_filters
- q = params[:q]&.to_unsafe_h || {}
- q.except('search')
- end
-
def category
category_id = params[:category_id]
@category ||= category_id.present? ? current_store.categories.find_by_param(category_id) : nil
end
-
- def search_provider
- @search_provider ||= Spree.search_provider.constantize.new(current_store)
- end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/products_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products_controller.rb
index 9345f8225c..6bca910bf5 100644
--- a/spree/api/app/controllers/spree/api/v3/store/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/products_controller.rb
@@ -4,6 +4,7 @@ module Spree
module Store
class ProductsController < ResourceController
include Spree::Api::V3::HttpCaching
+ include Spree::Api::V3::Store::SearchProviderSupport
protected
@@ -58,22 +59,6 @@ module Spree
@pagy = result.pagy
@collection = result.products
end
-
- private
-
- def search_query
- params.dig(:q, :search)
- end
-
- def search_filters
- q = params[:q]&.to_unsafe_h || params[:q] || {}
- q = q.to_h if q.respond_to?(:to_h) && !q.is_a?(Hash)
- q.except('search').presence
- end
-
- def search_provider
- @search_provider ||= Spree.search_provider.constantize.new(current_store)
- end
end
end
end
diff --git a/spree/core/app/models/spree/search_provider/base.rb b/spree/core/app/models/spree/search_provider/base.rb
index d6daf25a3e..eaa42c7cc9 100644
--- a/spree/core/app/models/spree/search_provider/base.rb
+++ b/spree/core/app/models/spree/search_provider/base.rb
@@ -66,6 +66,16 @@ module Spree
def reindex(scope = nil)
# no-op by default
end
+
+ private
+
+ def locale
+ Spree::Current.locale || store.default_market&.default_locale || I18n.locale.to_s
+ end
+
+ def currency
+ Spree::Current.currency || store.default_market&.currency
+ end
end
end
end
diff --git a/spree/core/app/models/spree/search_provider/database.rb b/spree/core/app/models/spree/search_provider/database.rb
index 0d5c364e33..139390a67c 100644
--- a/spree/core/app/models/spree/search_provider/database.rb
+++ b/spree/core/app/models/spree/search_provider/database.rb
@@ -24,10 +24,10 @@ module Spree
# 4. Facets (before sorting to avoid computed column conflicts with count)
filter_facets = build_facets(scope, category: category)
- # 4. Total count (before sorting to avoid computed column conflicts with count)
+ # 5. Total count (before sorting to avoid computed column conflicts with count)
total = scope.distinct.count
- # 5. Sorting + pagination
+ # 6. Sorting + pagination
scope = apply_sort(scope, sort)
page = [page.to_i, 1].max
limit = limit.to_i.clamp(1, 100)
@@ -55,7 +55,7 @@ module Spree
Spree::Api::V3::FiltersAggregator.new(
scope: scope,
- currency: Spree::Current.currency || store.default_market&.currency,
+ currency: currency,
category: category
).call
end
diff --git a/spree/core/app/models/spree/search_provider/meilisearch.rb b/spree/core/app/models/spree/search_provider/meilisearch.rb
index ce52130dfd..25d6e0d670 100644
--- a/spree/core/app/models/spree/search_provider/meilisearch.rb
+++ b/spree/core/app/models/spree/search_provider/meilisearch.rb
@@ -65,11 +65,7 @@ module Spree
end
def remove(product)
- # Delete all locale/currency variants of this product
- filter = "product_id = '#{sanitize_prefixed_id(product.prefixed_id)}'"
- client.index(index_name).delete_documents(filter: filter)
- rescue ::Meilisearch::ApiError => e
- raise unless e.http_code == 404
+ remove_by_id(product.prefixed_id)
end
def index_batch(documents)
@@ -89,8 +85,7 @@ module Spree
ensure_index_settings!
scope.reorder(id: :asc)
- .preload(:taxons, :option_types, :primary_media,
- variants_including_master: [:prices, :option_values])
+ .preload(*ProductPresenter::REQUIRED_PRELOADS)
.find_in_batches(batch_size: 500) do |batch|
documents = batch.flat_map { |product| ProductPresenter.new(product, store).call }
index_batch(documents)
@@ -176,8 +171,6 @@ module Spree
Array(value).each do |ov|
conditions << "option_value_ids = '#{sanitize_prefixed_id(ov)}'" if valid_prefixed_id?(ov)
end
- when 'status_eq'
- conditions << "status = '#{value}'" if ALLOWED_STATUSES.include?(value.to_s)
end
end
@@ -297,14 +290,6 @@ module Spree
Pagy::MeilisearchPaginator.paginate(fake_result, {})
end
- def locale
- Spree::Current.locale || store.default_market&.default_locale || I18n.locale.to_s
- end
-
- def currency
- Spree::Current.currency || store.default_market&.currency
- end
-
def valid_prefixed_id?(value)
value.to_s.match?(PREFIXED_ID_PATTERN)
end
diff --git a/spree/core/app/presenters/spree/search_provider/product_presenter.rb b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
index eb841a1124..3c3c145d46 100644
--- a/spree/core/app/presenters/spree/search_provider/product_presenter.rb
+++ b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
@@ -1,6 +1,12 @@
module Spree
module SearchProvider
class ProductPresenter
+ # Associations needed by this presenter — used by reindex and rake task for preloading
+ REQUIRED_PRELOADS = [
+ :taxons, :option_types, :primary_media, :store_products,
+ { variants_including_master: [:prices, :option_values] }
+ ].freeze
+
attr_reader :product, :store
def initialize(product, store)
@@ -36,8 +42,6 @@ module Spree
private
def build_document(locale, currency, fallback_locale)
- price = lowest_price(currency)
-
{
# Composite ID: product + locale + currency
prefixed_id: "#{product.prefixed_id}_#{locale}_#{currency}",
@@ -49,13 +53,13 @@ module Spree
description: translated(product, :description, fallback_locale),
slug: translated(product, :slug, fallback_locale),
# Price in this currency
- price: price&.to_f,
+ price: lowest_price(currency)&.to_f,
compare_at_price: compare_at_price(currency)&.to_f,
# Non-locale/currency fields
status: product.status,
sku: product.sku,
in_stock: product.in_stock?,
- store_ids: product.store_ids.map(&:to_s),
+ store_ids: cached_store_ids,
discontinue_on: product.discontinue_on&.to_i || 0,
category_ids: product.taxons.map(&:prefixed_id),
category_names: product.taxons.map { |t| translated(t, :name, fallback_locale) },
@@ -65,7 +69,7 @@ module Spree
option_values: variant_option_values_data.map { |ov| translated(ov, :presentation, fallback_locale) }.uniq,
tags: product.tag_list || [],
thumbnail_url: product.primary_media&.url(:large),
- units_sold_count: product.store_products.find_by(store: store)&.units_sold_count || 0,
+ units_sold_count: cached_units_sold_count,
available_on: product.available_on&.iso8601,
created_at: product.created_at&.iso8601,
updated_at: product.updated_at&.iso8601
@@ -84,31 +88,43 @@ module Spree
end
# Read a translated attribute with fallback to default locale.
- # Uses Mobility's locale: option which works across all backends.
def translated(record, attribute, fallback_locale)
value = record.send(attribute)
return value if value.present?
record.send(attribute, locale: fallback_locale.to_sym)
rescue ArgumentError
- # Attribute doesn't support locale: kwarg (not a Mobility attribute)
value
end
def lowest_price(currency)
- product.price_in(currency)&.amount
+ @prices_cache ||= {}
+ @prices_cache[currency] = product.price_in(currency)&.amount unless @prices_cache.key?(currency)
+ @prices_cache[currency]
end
def compare_at_price(currency)
- product.compare_at_amount_in(currency)
+ @compare_at_cache ||= {}
+ @compare_at_cache[currency] = product.compare_at_amount_in(currency) unless @compare_at_cache.key?(currency)
+ @compare_at_cache[currency]
+ end
+
+ # Memoized — avoids N+1 when called per document
+ def cached_store_ids
+ @cached_store_ids ||= product.store_ids.map(&:to_s)
+ end
+
+ def cached_units_sold_count
+ @cached_units_sold_count ||= product.store_products.detect { |sp| sp.store_id == store.id }&.units_sold_count || 0
end
def variant_option_value_ids
variant_option_values_data.map(&:prefixed_id).uniq
end
+ # Use variants_including_master (matches reindex preload) instead of variants.includes
def variant_option_values_data
- @variant_option_values_data ||= product.variants.includes(:option_values).flat_map(&:option_values)
+ @variant_option_values_data ||= product.variants_including_master.flat_map(&:option_values).uniq
end
end
end
diff --git a/spree/core/lib/tasks/search.rake b/spree/core/lib/tasks/search.rake
index 42ae5e6995..e666e91223 100644
--- a/spree/core/lib/tasks/search.rake
+++ b/spree/core/lib/tasks/search.rake
@@ -7,22 +7,8 @@ namespace :spree do
total = store.products.count
puts "Reindexing #{store.name} (#{total} products)..."
-
- # Configure index settings (filterable, sortable, searchable attributes)
- provider.ensure_index_settings! if provider.respond_to?(:ensure_index_settings!)
-
- indexed = 0
- store.products.reorder(id: :asc)
- .preload(:taxons, :option_types, :primary_media,
- variants_including_master: [:prices, :option_values])
- .find_in_batches(batch_size: 500) do |batch|
- documents = batch.flat_map { |product| Spree::SearchProvider::ProductPresenter.new(product, store).call }
- provider.index_batch(documents) if provider.respond_to?(:index_batch)
- indexed += batch.size
- print "\r #{indexed}/#{total} products indexed"
- end
-
- puts "\nDone."
+ provider.reindex(store.products)
+ puts "Done."
end
end
end