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.

Fixed ability to chain `in_stock` product scope (#13753)

Damian Legawiec3f5815ffc809
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 0777d99a6a..62adafe7e1 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
@@ -58,7 +58,7 @@ module Spree
return collection unless scope_method
sorted = collection.reorder(nil)
- sort_value == 'best_selling' ? sorted.distinct(false).send(scope_method) : sorted.send(scope_method)
+ sorted.send(scope_method)
end
# Skip base Ransack sort injection for custom sort scopes
diff --git a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
index a7dd3c08a8..18242fc02a 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
@@ -219,6 +219,14 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
names = json_response['data'].map { |p| p['name'] }
expect(names).to eq(names.sort)
end
+
+ # Regression test: combining in_stock filter with price sorting caused
+ # PG::UndefinedTable due to table alias conflicts on spree_variants
+ it 'sorts by price while filtering in_stock' do
+ get :index, params: { sort: '-price', q: { in_stock: true } }
+
+ expect(response).to have_http_status(:ok)
+ end
end
context 'authentication' do
diff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rb
index 561733b2ed..0bab19aaae 100644
--- a/spree/core/app/models/concerns/spree/product_scopes.rb
+++ b/spree/core/app/models/concerns/spree/product_scopes.rb
@@ -87,6 +87,25 @@ module Spree
where(Price.table_name => { amount: price.. })
end
+ # Joins spree_variants and spree_stock_items directly (without association
+ # aliases) so that the table names stay as-is. This avoids alias conflicts
+ # when combined with other scopes (e.g., price sorting) that also join
+ # spree_variants through associations which generate aliases.
+ def self.join_variants_and_stock_items
+ joins("INNER JOIN #{Variant.table_name} ON #{Variant.table_name}.deleted_at IS NULL AND #{Variant.table_name}.product_id = #{Product.table_name}.id").
+ joins("LEFT OUTER JOIN #{StockItem.table_name} ON #{StockItem.table_name}.deleted_at IS NULL AND #{StockItem.table_name}.variant_id = #{Variant.table_name}.id")
+ end
+ private_class_method :join_variants_and_stock_items
+
+ # Mirrors Spree::Variant.in_stock_or_backorderable logic using raw table
+ # names (to pair with join_variants_and_stock_items).
+ scope :in_stock_or_backorderable_condition, -> {
+ where(
+ "#{Variant.table_name}.track_inventory = ? OR #{StockItem.table_name}.count_on_hand > ? OR #{StockItem.table_name}.backorderable = ?",
+ false, 0, true
+ )
+ }
+
# Can't use add_search_scope for this as it needs a default argument
# Ransack calls with '1' to activate, '0' or nil to skip
# In Ruby code: in_stock(true) for in-stock, in_stock(false) for out-of-stock
@@ -94,7 +113,7 @@ module Spree
if in_stock == '0' || !in_stock
all
else
- joins(:variants_including_master).merge(Spree::Variant.in_stock_or_backorderable)
+ join_variants_and_stock_items.in_stock_or_backorderable_condition
end
end
@@ -111,17 +130,17 @@ module Spree
if out_of_stock == '0' || !out_of_stock
all
else
- where.not(id: joins(:variants_including_master).merge(Spree::Variant.in_stock_or_backorderable))
+ where.not(id: join_variants_and_stock_items.in_stock_or_backorderable_condition)
end
end
search_scopes << :out_of_stock
add_search_scope :backorderable do
- joins(:variants_including_master).merge(Spree::Variant.backorderable)
+ join_variants_and_stock_items.where(StockItem.table_name => { backorderable: true })
end
add_search_scope :in_stock_or_backorderable do
- joins(:variants_including_master).merge(Spree::Variant.in_stock_or_backorderable)
+ join_variants_and_stock_items.in_stock_or_backorderable_condition
end
# This scope selects products in taxon AND all its descendants
@@ -329,25 +348,22 @@ module Spree
end
# Orders products by best selling based on units_sold_count and revenue
- # stored in spree_products_stores table.
- #
- # These metrics are updated asynchronously when orders are completed
- # via the ProductMetricsSubscriber.
+ # from spree_products_stores (already joined via store.products).
#
- # @param order_direction [Symbol] :desc (default) or :asc
- # @return [ActiveRecord::Relation]
+ # Uses Arel::Nodes::As so that ORDER BY expressions appear in SELECT
+ # and work with DISTINCT (same pattern as the price sorting scopes).
add_search_scope :by_best_selling do |order_direction = :desc|
- store_id = Spree::Current.store&.id
- sp_table = StoreProduct.arel_table
- products_table = Product.arel_table
-
- conditions = sp_table[:product_id].eq(products_table[:id]).and(sp_table[:store_id].eq(store_id))
-
- units_sold = Arel::Nodes::NamedFunction.new('COALESCE', [sp_table.project(sp_table[:units_sold_count]).where(conditions), 0])
- revenue = Arel::Nodes::NamedFunction.new('COALESCE', [sp_table.project(sp_table[:revenue]).where(conditions), 0])
+ sp_table = StoreProduct.table_name
+ units_expr = Arel.sql("COALESCE(#{sp_table}.units_sold_count, 0)")
+ revenue_expr = Arel.sql("COALESCE(#{sp_table}.revenue, 0)")
order_dir = order_direction == :desc ? :desc : :asc
- order(units_sold.send(order_dir)).order(revenue.send(order_dir))
+
+ select("#{Product.table_name}.*").
+ select(Arel::Nodes::As.new(units_expr, Arel.sql('best_selling_units'))).
+ select(Arel::Nodes::As.new(revenue_expr, Arel.sql('best_selling_revenue'))).
+ order(units_expr.send(order_dir)).
+ order(revenue_expr.send(order_dir))
end
# .search_by_name
diff --git a/spree/core/spec/models/spree/product/scopes_spec.rb b/spree/core/spec/models/spree/product/scopes_spec.rb
index fa397786c9..cc590bd12a 100644
--- a/spree/core/spec/models/spree/product/scopes_spec.rb
+++ b/spree/core/spec/models/spree/product/scopes_spec.rb
@@ -261,6 +261,13 @@ describe 'Product scopes', type: :model do
it 'can be chained with other scopes without error' do
expect { Spree::Product.in_stock.in_stock_or_backorderable.count }.not_to raise_error
end
+
+ # Regression test: in_stock combined with price sorting scopes should not
+ # raise table alias conflicts (variants_including_masters_spree_products)
+ it 'can be chained with price sorting scopes without error' do
+ expect { Spree::Product.in_stock.descend_by_price.to_a }.not_to raise_error
+ expect { Spree::Product.in_stock.ascend_by_price.to_a }.not_to raise_error
+ end
end
describe '#out_of_stock' do
@@ -308,12 +315,12 @@ describe 'Product scopes', type: :model do
end
it 'orders products by units_sold_count in descending order by default' do
- products = Spree::Product.where(id: test_product_ids).by_best_selling
+ products = store.products.where(id: test_product_ids).by_best_selling
expect(products.map(&:name)).to eq(['Product 2', 'Product 1', 'Product 3', 'Product 4'])
end
it 'orders products by units_sold_count in ascending order when specified' do
- products = Spree::Product.where(id: test_product_ids).by_best_selling(:asc)
+ products = store.products.where(id: test_product_ids).by_best_selling(:asc)
expect(products.map(&:name)).to eq(['Product 4', 'Product 3', 'Product 1', 'Product 2'])
end
end
@@ -331,7 +338,7 @@ describe 'Product scopes', type: :model do
end
it 'only counts units from completed orders' do
- products = Spree::Product.where(id: test_product_ids).by_best_selling
+ products = store.products.where(id: test_product_ids).by_best_selling
expect(products.first.name).to eq('Product 1')
product_1_store_product = product_1.store_products.find_by(store: store)
@@ -355,7 +362,7 @@ describe 'Product scopes', type: :model do
end
it 'uses revenue as secondary sort criteria' do
- products = Spree::Product.where(id: test_product_ids).by_best_selling
+ products = store.products.where(id: test_product_ids).by_best_selling
# Both have 2 units sold, but product_2 has higher revenue
expect(products.first.name).to eq('Product 2')
expect(products.second.name).to eq('Product 1')
@@ -384,7 +391,7 @@ describe 'Product scopes', type: :model do
end
it 'sums line item quantities for units_sold_count' do
- products = Spree::Product.where(id: test_product_ids).by_best_selling
+ products = store.products.where(id: test_product_ids).by_best_selling
product_1_store_product = product_1.store_products.find_by(store: store)
product_2_store_product = product_2.store_products.find_by(store: store)
@@ -419,7 +426,7 @@ describe 'Product scopes', type: :model do
end
it 'ranks by total units sold across all orders' do
- products = Spree::Product.where(id: test_product_ids).by_best_selling
+ products = store.products.where(id: test_product_ids).by_best_selling
product_1_store_product = product_1.store_products.find_by(store: store)
product_2_store_product = product_2.store_products.find_by(store: store)
@@ -441,7 +448,7 @@ describe 'Product scopes', type: :model do
end
it 'includes products with no orders at the end' do
- products = Spree::Product.where(id: test_product_ids).by_best_selling
+ products = store.products.where(id: test_product_ids).by_best_selling
expect(products.length).to eq(4)
# All products should be included, those without orders have units_sold_count = 0
[product_1, product_2, product_3, product_4].each do |p|
@@ -470,7 +477,7 @@ describe 'Product scopes', type: :model do
end
it 'includes products with only pending orders with units_sold_count = 0' do
- products = Spree::Product.where(id: test_product_ids).by_best_selling
+ products = store.products.where(id: test_product_ids).by_best_selling
# All products should be included
expect(products.length).to eq(4)
@@ -496,7 +503,7 @@ describe 'Product scopes', type: :model do
end
it 'orders products correctly with pending orders included' do
- products = Spree::Product.where(id: test_product_ids).by_best_selling
+ products = store.products.where(id: test_product_ids).by_best_selling
# Product 1: 2 units sold (first)
# Product 3: 1 unit sold (second)
# Product 2 & 4: 0 units sold (last, order between them is non-deterministic)