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.

Introduce Store Product Metrics (#13467)

Damian Legawiecac5c7b1c2c10
diff --git a/core/app/jobs/spree/products/refresh_metrics_job.rb b/core/app/jobs/spree/products/refresh_metrics_job.rb
new file mode 100644
index 0000000000..1a941818b9
--- /dev/null
+++ b/core/app/jobs/spree/products/refresh_metrics_job.rb
@@ -0,0 +1,14 @@
+module Spree
+ module Products
+ class RefreshMetricsJob < Spree::BaseJob
+ queue_as Spree.queues.products
+
+ def perform(product_id, store_id)
+ store_product = Spree::StoreProduct.find_by(product_id: product_id, store_id: store_id)
+ return unless store_product
+
+ store_product.refresh_metrics!
+ end
+ end
+ end
+end
diff --git a/core/app/models/concerns/spree/product_scopes.rb b/core/app/models/concerns/spree/product_scopes.rb
index c513ac0bc8..5ff49dd05e 100644
--- a/core/app/models/concerns/spree/product_scopes.rb
+++ b/core/app/models/concerns/spree/product_scopes.rb
@@ -327,6 +327,27 @@ module Spree
group('spree_products.id').joins(:taxons).where(Taxon.arel_table[:name].eq(name))
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.
+ #
+ # @param order_direction [Symbol] :desc (default) or :asc
+ # @return [ActiveRecord::Relation]
+ add_search_scope :by_best_selling do |order_direction = :desc|
+ order_dir = order_direction == :desc ? 'DESC' : 'ASC'
+ store_id = Spree::Current.store&.id
+
+ joins(:store_products)
+ .where(StoreProduct.table_name => { store_id: store_id })
+ .select("#{Product.table_name}.*",
+ "#{StoreProduct.table_name}.units_sold_count",
+ "#{StoreProduct.table_name}.revenue")
+ .order(Arel.sql("#{StoreProduct.table_name}.units_sold_count #{order_dir}"))
+ .order(Arel.sql("#{StoreProduct.table_name}.revenue #{order_dir}"))
+ end
+
# .search_by_name
if defined?(PgSearch)
include PgSearch::Model
diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rb
index a5fae93be8..acd34f5f82 100644
--- a/core/app/models/spree/product.rb
+++ b/core/app/models/spree/product.rb
@@ -209,18 +209,6 @@ module Spree
joins(:stock_items).where("#{Spree::Variant.table_name}.track_inventory = ? OR #{Spree::StockItem.table_name}.count_on_hand <= ?", false, 0)
}
- scope :by_best_selling, lambda { |order_direction = :desc|
- order_dir = order_direction == :desc ? 'DESC' : 'ASC'
- completed_orders_count_sql = "COUNT(DISTINCT CASE WHEN #{Spree::Order.table_name}.completed_at IS NOT NULL THEN #{Spree::Order.table_name}.id END)"
- completed_orders_total_sql = "COALESCE(SUM(CASE WHEN #{Spree::Order.table_name}.completed_at IS NOT NULL THEN (#{Spree::LineItem.table_name}.price * #{Spree::LineItem.table_name}.quantity) END), 0)"
-
- left_joins(variants_including_master: { line_items: :order }).
- select("#{Spree::Product.table_name}.*", "#{completed_orders_count_sql} AS completed_orders_count", "#{completed_orders_total_sql} AS completed_orders_total").
- group("#{Spree::Product.table_name}.id").
- order(Arel.sql("#{completed_orders_count_sql} #{order_dir}")).
- order(Arel.sql("#{completed_orders_total_sql} #{order_dir}"))
- }
-
attr_accessor :option_values_hash
accepts_nested_attributes_for :product_properties, allow_destroy: true, reject_if: lambda { |pp|
diff --git a/core/app/models/spree/store_product.rb b/core/app/models/spree/store_product.rb
index 4657d2a828..cb3c7ed5b9 100644
--- a/core/app/models/spree/store_product.rb
+++ b/core/app/models/spree/store_product.rb
@@ -7,5 +7,19 @@ module Spree
validates :store, :product, presence: true
validates :store_id, uniqueness: { scope: :product_id }
+
+ def refresh_metrics!
+ completed_order_ids = product.completed_orders.where(store_id: store_id).select(:id)
+ variant_ids = product.variants_including_master.ids
+
+ line_items = Spree::LineItem.joins(:order)
+ .where(spree_orders: { id: completed_order_ids })
+ .where(variant_id: variant_ids)
+
+ update!(
+ units_sold_count: line_items.sum(:quantity),
+ revenue: line_items.sum(:pre_tax_amount)
+ )
+ end
end
end
diff --git a/core/app/subscribers/spree/product_metrics_subscriber.rb b/core/app/subscribers/spree/product_metrics_subscriber.rb
new file mode 100644
index 0000000000..2813cfcc90
--- /dev/null
+++ b/core/app/subscribers/spree/product_metrics_subscriber.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module Spree
+ # Handles order completion events to update product metrics.
+ #
+ # When an order is completed, this subscriber enqueues background jobs
+ # to refresh the metrics (units_sold_count, revenue) for each product
+ # in the order.
+ class ProductMetricsSubscriber < Spree::Subscriber
+ subscribes_to 'order.completed'
+
+ on 'order.completed', :refresh_product_metrics
+
+ def refresh_product_metrics(event)
+ order_id = event.payload['id']
+ store_id = event.payload['store_id']
+ return unless order_id && store_id
+
+ order = Spree::Order.find_by(id: order_id)
+ return unless order
+
+ product_ids = order.line_items.includes(:variant).map { |li| li.variant.product_id }.uniq
+ return if product_ids.empty?
+
+ jobs = product_ids.map { |product_id| Spree::Products::RefreshMetricsJob.new(product_id, store_id) }
+ ActiveJob.perform_all_later(jobs)
+ end
+ end
+end
diff --git a/core/db/migrate/20260118120000_add_statistics_to_store_products.rb b/core/db/migrate/20260118120000_add_statistics_to_store_products.rb
new file mode 100644
index 0000000000..03e8d80ac7
--- /dev/null
+++ b/core/db/migrate/20260118120000_add_statistics_to_store_products.rb
@@ -0,0 +1,11 @@
+class AddStatisticsToStoreProducts < ActiveRecord::Migration[7.0]
+ def change
+ add_column :spree_products_stores, :units_sold_count, :integer, default: 0, null: false
+ add_column :spree_products_stores, :revenue, :decimal, precision: 10, scale: 2, default: 0, null: false
+
+ add_index :spree_products_stores, [:store_id, :units_sold_count],
+ name: 'index_products_stores_on_store_and_units_sold'
+ add_index :spree_products_stores, [:store_id, :revenue],
+ name: 'index_products_stores_on_store_and_revenue'
+ end
+end
diff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rb
index 2fd8df141f..7eaea1c612 100644
--- a/core/lib/spree/core.rb
+++ b/core/lib/spree/core.rb
@@ -99,6 +99,7 @@ module Spree
exports: :default,
images: :default,
imports: :default,
+ products: :default,
reports: :default,
variants: :default,
taxons: :default,
diff --git a/core/lib/spree/core/engine.rb b/core/lib/spree/core/engine.rb
index df3fedfb43..a4abe2a7ee 100644
--- a/core/lib/spree/core/engine.rb
+++ b/core/lib/spree/core/engine.rb
@@ -301,7 +301,8 @@ module Spree
Spree.subscribers.concat [
Spree::ExportSubscriber,
Spree::ReportSubscriber,
- Spree::InvitationEmailSubscriber
+ Spree::InvitationEmailSubscriber,
+ Spree::ProductMetricsSubscriber
]
end
diff --git a/core/lib/spree/testing_support/factories/store_product_factory.rb b/core/lib/spree/testing_support/factories/store_product_factory.rb
new file mode 100644
index 0000000000..5fee39c335
--- /dev/null
+++ b/core/lib/spree/testing_support/factories/store_product_factory.rb
@@ -0,0 +1,6 @@
+FactoryBot.define do
+ factory :store_product, class: Spree::StoreProduct do
+ store
+ product
+ end
+end
diff --git a/core/lib/tasks/product_metrics.rake b/core/lib/tasks/product_metrics.rake
new file mode 100644
index 0000000000..e46ec41a14
--- /dev/null
+++ b/core/lib/tasks/product_metrics.rake
@@ -0,0 +1,23 @@
+namespace :spree do
+ namespace :product_metrics do
+ desc 'Enqueue background jobs to populate product metrics for all store products'
+ task populate: :environment do
+ total_count = 0
+
+ Spree::StoreProduct.in_batches(of: 100) do |batch|
+ jobs = batch.pluck(:product_id, :store_id).map do |product_id, store_id|
+ Spree::Products::RefreshMetricsJob.new(product_id, store_id)
+ end
+ ActiveJob.perform_all_later(jobs)
+ total_count += jobs.size
+ print '.'
+ end
+
+ if total_count.zero?
+ puts 'No store products found.'
+ else
+ puts "\nEnqueued #{total_count} jobs to refresh product metrics."
+ end
+ end
+ end
+end
diff --git a/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb b/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb
new file mode 100644
index 0000000000..5ff64b852d
--- /dev/null
+++ b/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb
@@ -0,0 +1,49 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Products::RefreshMetricsJob, type: :job do
+ describe '#perform' do
+ let(:store) { create(:store) }
+ let(:product) { create(:product, stores: [store]) }
+ let(:store_product) { product.store_products.find_by(store: store) }
+
+ subject { described_class.perform_now(product.id, store.id) }
+
+ context 'when store_product exists' do
+ it 'calls refresh_metrics! on the store_product' do
+ expect_any_instance_of(Spree::StoreProduct).to receive(:refresh_metrics!)
+
+ subject
+ end
+ end
+
+ context 'when store_product does not exist' do
+ subject { described_class.perform_now(product.id, create(:store).id) }
+
+ it 'does nothing' do
+ expect_any_instance_of(Spree::StoreProduct).not_to receive(:refresh_metrics!)
+
+ subject
+ end
+ end
+
+ context 'when product_id is invalid' do
+ subject { described_class.perform_now('non-existent-id', store.id) }
+
+ it 'does nothing' do
+ expect_any_instance_of(Spree::StoreProduct).not_to receive(:refresh_metrics!)
+
+ subject
+ end
+ end
+
+ context 'when store_id is invalid' do
+ subject { described_class.perform_now(product.id, 'non-existent-id') }
+
+ it 'does nothing' do
+ expect_any_instance_of(Spree::StoreProduct).not_to receive(:refresh_metrics!)
+
+ subject
+ end
+ end
+ end
+end
diff --git a/core/spec/models/spree/order_spec.rb b/core/spec/models/spree/order_spec.rb
index 6de1abd1bd..e3af0b6961 100644
--- a/core/spec/models/spree/order_spec.rb
+++ b/core/spec/models/spree/order_spec.rb
@@ -411,6 +411,17 @@ describe Spree::Order, type: :model do
allow(order).to receive(:publish_event).with(anything)
order.finalize!
end
+
+ it 'enqueues RefreshMetricsJob for each product in the order' do
+ # Clear any previously enqueued jobs
+ clear_enqueued_jobs
+
+ order.finalize!
+ perform_enqueued_jobs(only: Spree::Events::SubscriberJob)
+
+ product_count = order.line_items.map { |li| li.variant.product_id }.uniq.count
+ expect(Spree::Products::RefreshMetricsJob).to have_been_enqueued.exactly(product_count).times
+ end
end
end
diff --git a/core/spec/models/spree/product/scopes_spec.rb b/core/spec/models/spree/product/scopes_spec.rb
index 8eeff62a81..a6ea17230a 100644
--- a/core/spec/models/spree/product/scopes_spec.rb
+++ b/core/spec/models/spree/product/scopes_spec.rb
@@ -327,6 +327,233 @@ describe 'Product scopes', type: :model do
end
end
+ describe '.by_best_selling' do
+ let!(:product_1) { create(:product, name: 'Product 1', stores: [store]) }
+ let!(:product_2) { create(:product, name: 'Product 2', stores: [store]) }
+ let!(:product_3) { create(:product, name: 'Product 3', stores: [store]) }
+ let!(:product_4) { create(:product, name: 'Product 4', stores: [store]) }
+ let(:test_product_ids) { [product_1.id, product_2.id, product_3.id, product_4.id] }
+
+ def refresh_all_metrics!
+ [product_1, product_2, product_3, product_4].each do |p|
+ p.store_products.find_by(store: store)&.refresh_metrics!
+ end
+ end
+
+ context 'with completed orders' do
+ before do
+ # Product 2: 3 units sold (3 orders x 1 quantity each)
+ create_list(:completed_order_with_totals, 3, line_items_price: 100, store: store, variants: [product_2.master])
+
+ # Product 1: 2 units sold (2 orders x 1 quantity each)
+ create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
+
+ # Product 3: 1 unit sold (1 order x 1 quantity)
+ create(:completed_order_with_totals, line_items_price: 150, store: store, variants: [product_3.master])
+
+ # Product 4: no completed orders
+
+ refresh_all_metrics!
+ 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
+ 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)
+ expect(products.map(&:name)).to eq(['Product 4', 'Product 3', 'Product 1', 'Product 2'])
+ end
+ end
+
+ context 'with incomplete orders' do
+ before do
+ # Product 1: 2 units sold (2 completed orders)
+ create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
+
+ # Product 2: 1 unit sold (1 completed order) + 2 incomplete orders (should not be counted)
+ create(:completed_order_with_totals, line_items_price: 100, store: store, variants: [product_2.master])
+ create_list(:order_with_totals, 2, line_items_price: 100, store: store, variants: [product_2.master])
+
+ refresh_all_metrics!
+ end
+
+ it 'only counts units from completed orders' do
+ products = Spree::Product.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)
+ product_2_store_product = product_2.store_products.find_by(store: store)
+
+ expect(product_1_store_product.units_sold_count).to eq(2)
+ expect(product_2_store_product.units_sold_count).to eq(1)
+ end
+ end
+
+ context 'when products have same units_sold_count' do
+ before do
+ # Both products have 2 units sold, but different revenue
+ # Product 1: 2 units, lower revenue
+ create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
+
+ # Product 2: 2 units, higher revenue
+ create_list(:completed_order_with_totals, 2, line_items_price: 150, store: store, variants: [product_2.master])
+
+ refresh_all_metrics!
+ end
+
+ it 'uses revenue as secondary sort criteria' do
+ products = Spree::Product.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')
+
+ product_1_store_product = product_1.store_products.find_by(store: store)
+ product_2_store_product = product_2.store_products.find_by(store: store)
+
+ expect(product_2_store_product.revenue).to be > product_1_store_product.revenue
+ end
+ end
+
+ context 'with varying quantities' do
+ before do
+ # Product 1: 5 units sold (quantity 2 + quantity 3)
+ order1 = create(:order_with_line_items, line_items_count: 0, store: store)
+ create(:line_item, order: order1, variant: product_1.master, price: 50, quantity: 2)
+ create(:line_item, order: order1, variant: product_1.master, price: 50, quantity: 3)
+ order1.update!(completed_at: Time.current)
+
+ # Product 2: 2 units sold (quantity 2)
+ order2 = create(:order_with_line_items, line_items_count: 0, store: store)
+ create(:line_item, order: order2, variant: product_2.master, price: 100, quantity: 2)
+ order2.update!(completed_at: Time.current)
+
+ refresh_all_metrics!
+ end
+
+ it 'sums line item quantities for units_sold_count' do
+ products = Spree::Product.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)
+
+ # Product 1: 2 + 3 = 5 units
+ expect(product_1_store_product.units_sold_count).to eq(5)
+ # Product 2: 2 units
+ expect(product_2_store_product.units_sold_count).to eq(2)
+
+ # Product 1 should be ranked higher due to more units sold
+ expect(products.first.name).to eq('Product 1')
+ end
+ end
+
+ context 'with multiple orders containing multiple line items' do
+ before do
+ # Product 1: 5 units sold across 2 orders (quantity 3 + quantity 2)
+ order1 = create(:order_with_line_items, line_items_count: 0, store: store)
+ create(:line_item, order: order1, variant: product_1.master, price: 50, quantity: 3)
+ order1.update!(completed_at: Time.current)
+
+ order2 = create(:order_with_line_items, line_items_count: 0, store: store)
+ create(:line_item, order: order2, variant: product_1.master, price: 50, quantity: 2)
+ order2.update!(completed_at: Time.current)
+
+ # Product 2: 4 units sold in 1 order (quantity 4)
+ order3 = create(:order_with_line_items, line_items_count: 0, store: store)
+ create(:line_item, order: order3, variant: product_2.master, price: 100, quantity: 4)
+ order3.update!(completed_at: Time.current)
+
+ refresh_all_metrics!
+ end
+
+ it 'ranks by total units sold across all orders' do
+ products = Spree::Product.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)
+
+ # Product 1: 3 + 2 = 5 units sold
+ expect(product_1_store_product.units_sold_count).to eq(5)
+ # Product 2: 4 units sold
+ expect(product_2_store_product.units_sold_count).to eq(4)
+
+ # Product 1 should rank first because it has more units sold (5 vs 4)
+ expect(products.first.name).to eq('Product 1')
+ expect(products.second.name).to eq('Product 2')
+ end
+ end
+
+ context 'with products having no orders' do
+ before do
+ refresh_all_metrics!
+ end
+
+ it 'includes products with no orders at the end' do
+ products = Spree::Product.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|
+ store_product = p.store_products.find_by(store: store)
+ expect(store_product.units_sold_count).to eq(0)
+ expect(store_product.revenue).to eq(0)
+ end
+ end
+ end
+
+ context 'with products having only pending orders (no completed_at)' do
+ before do
+ # Product 1: 2 units sold (2 completed orders)
+ create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
+
+ # Product 2: 1 pending order (no completed_at) - should not be counted
+ create(:order_with_line_items, line_items_count: 1, store: store, variants: [product_2.master])
+
+ # Product 3: 2 pending orders (not counted) + 1 completed order (1 unit)
+ create_list(:order_with_line_items, 2, line_items_count: 1, store: store, variants: [product_3.master])
+ create(:completed_order_with_totals, line_items_price: 100, store: store, variants: [product_3.master])
+
+ # Product 4: no orders at all
+
+ refresh_all_metrics!
+ 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
+
+ # All products should be included
+ expect(products.length).to eq(4)
+
+ product_1_sp = product_1.store_products.find_by(store: store)
+ product_2_sp = product_2.store_products.find_by(store: store)
+ product_3_sp = product_3.store_products.find_by(store: store)
+ product_4_sp = product_4.store_products.find_by(store: store)
+
+ # Product 2 has pending orders but no completed orders - count should be 0
+ expect(product_2_sp.units_sold_count).to eq(0)
+ expect(product_2_sp.revenue).to eq(0)
+
+ # Product 1 has 2 units sold (2 completed orders with quantity 1 each)
+ expect(product_1_sp.units_sold_count).to eq(2)
+
+ # Product 3 has 1 unit sold (1 completed order, pending orders not counted)
+ expect(product_3_sp.units_sold_count).to eq(1)
+
+ # Product 4 has no orders at all - count should be 0
+ expect(product_4_sp.units_sold_count).to eq(0)
+ expect(product_4_sp.revenue).to eq(0)
+ end
+
+ it 'orders products correctly with pending orders included' do
+ products = Spree::Product.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, but Product 2 still included despite having pending orders)
+ expect(products.map(&:name)).to eq(['Product 1', 'Product 3', 'Product 2', 'Product 4'])
+ end
+ end
+ end
+
context 'options scopes' do
let(:option_type) { create(:option_type) }
let(:option_value) { create(:option_value, option_type: option_type) }
diff --git a/core/spec/models/spree/product_spec.rb b/core/spec/models/spree/product_spec.rb
index 0b604b2f89..ad41441c7f 100644
--- a/core/spec/models/spree/product_spec.rb
+++ b/core/spec/models/spree/product_spec.rb
@@ -1313,232 +1313,6 @@ describe Spree::Product, type: :model do
end
end
- describe '.by_best_selling' do
- let!(:product_1) { create(:product, name: 'Product 1', stores: [store]) }
- let!(:product_2) { create(:product, name: 'Product 2', stores: [store]) }
- let!(:product_3) { create(:product, name: 'Product 3', stores: [store]) }
- let!(:product_4) { create(:product, name: 'Product 4', stores: [store]) }
- let(:test_product_ids) { [product_1.id, product_2.id, product_3.id, product_4.id] }
-
- context 'with completed orders' do
- before do
- # Product 2: 3 completed orders, total: $300
- create_list(:completed_order_with_totals, 3, line_items_price: 100, store: store, variants: [product_2.master])
-
- # Product 1: 2 completed orders, total: $200
- create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
-
- # Product 3: 1 completed order, total: $150
- create(:completed_order_with_totals, line_items_price: 150, store: store, variants: [product_3.master])
-
- # Product 4: no completed orders
- end
-
- it 'orders products by completed orders count in descending order by default' do
- products = described_class.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 completed orders count in ascending order when specified' do
- products = described_class.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
-
- context 'with incomplete orders' do
- before do
- # Product 1: 2 completed orders
- create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
-
- # Product 2: 1 completed order + 2 incomplete orders (should not be counted)
- create(:completed_order_with_totals, line_items_price: 100, store: store, variants: [product_2.master])
-
- create_list(:order_with_totals, 2, line_items_price: 100, store: store, variants: [product_2.master])
- end
-
- it 'only counts completed orders' do
- products = described_class.where(id: test_product_ids).by_best_selling
- expect(products.first.name).to eq('Product 1')
-
- product_1_result = products.find { |p| p.id == product_1.id }
- product_2_result = products.find { |p| p.id == product_2.id }
-
- expect(product_1_result.completed_orders.count).to eq(2)
- expect(product_2_result.completed_orders.count).to eq(1)
- end
- end
-
- context 'when products have same order count' do
- before do
- # Both products have 2 completed orders, but different totals
- # Product 1: total $200
- create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
-
- # Product 2: total $300
- create_list(:completed_order_with_totals, 2, line_items_price: 150, store: store, variants: [product_2.master])
- end
-
- it 'uses completed_orders_total as secondary sort criteria' do
- products = described_class.where(id: test_product_ids).by_best_selling
- # Both have 2 orders, but product_2 has higher total
- expect(products.first.name).to eq('Product 2')
- expect(products.second.name).to eq('Product 1')
-
- product_1_result = products.find { |p| p.id == product_1.id }
- product_2_result = products.find { |p| p.id == product_2.id }
-
- expect(product_2_result.completed_orders.sum(:total)).to be > product_1_result.completed_orders.sum(:total)
- end
- end
-
- context 'with varying quantities' do
- before do
- # Product 1: 1 order with 2 line items (same product, different quantities)
- # Line item 1: price $50, quantity 2 = $100
- # Line item 2: price $50, quantity 3 = $150
- # Total: $250
- order1 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order1, variant: product_1.master, price: 50, quantity: 2)
- create(:line_item, order: order1, variant: product_1.master, price: 50, quantity: 3)
- order1.update!(completed_at: Time.current)
-
- # Product 2: 1 order with 1 line item
- # Line item: price $100, quantity 2 = $200
- # Total: $200
- order2 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order2, variant: product_2.master, price: 100, quantity: 2)
- order2.update!(completed_at: Time.current)
- end
-
- it 'calculates total correctly with price * quantity for each line item' do
- products = described_class.where(id: test_product_ids).by_best_selling
-
- product_1_result = products.find { |p| p.id == product_1.id }
- product_2_result = products.find { |p| p.id == product_2.id }
-
- # Both have 1 completed order
- expect(product_1_result.completed_orders.count).to eq(1)
- expect(product_2_result.completed_orders.count).to eq(1)
-
- # Product 1 should have line item total of $250 (50*2 + 50*3)
- # Product 2 should have line item total of $200 (100*2)
- product_1_line_item_total = product_1_result.line_items.joins(:order).merge(Spree::Order.complete).sum('spree_line_items.price * spree_line_items.quantity')
- product_2_line_item_total = product_2_result.line_items.joins(:order).merge(Spree::Order.complete).sum('spree_line_items.price * spree_line_items.quantity')
- expect(product_1_line_item_total).to eq(250)
- expect(product_2_line_item_total).to eq(200)
-
- # Product 1 should be ranked higher due to higher total
- expect(products.first.name).to eq('Product 1')
- end
- end
-
- context 'with multiple orders containing multiple line items' do
- before do
- # Product 1: 2 completed orders with varying quantities
- # Order 1: price $50, quantity 3 = $150
- # Order 2: price $50, quantity 2 = $100
- # Total: $250, Orders: 2
- order1 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order1, variant: product_1.master, price: 50, quantity: 3)
- order1.update!(completed_at: Time.current)
-
- order2 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order2, variant: product_1.master, price: 50, quantity: 2)
- order2.update!(completed_at: Time.current)
-
- # Product 2: 1 completed order with higher total
- # Order 1: price $100, quantity 4 = $400
- # Total: $400, Orders: 1
- order3 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order3, variant: product_2.master, price: 100, quantity: 4)
- order3.update!(completed_at: Time.current)
- end
-
- it 'prioritizes order count over total when ranking' do
- products = described_class.where(id: test_product_ids).by_best_selling
-
- product_1_result = products.find { |p| p.id == product_1.id }
- product_2_result = products.find { |p| p.id == product_2.id }
-
- # Verify counts
- expect(product_1_result.completed_orders.count).to eq(2)
- expect(product_2_result.completed_orders.count).to eq(1)
-
- # Verify line item totals
- product_1_line_item_total = product_1_result.line_items.joins(:order).merge(Spree::Order.complete).sum('spree_line_items.price * spree_line_items.quantity')
- product_2_line_item_total = product_2_result.line_items.joins(:order).merge(Spree::Order.complete).sum('spree_line_items.price * spree_line_items.quantity')
- expect(product_1_line_item_total).to eq(250)
- expect(product_2_line_item_total).to eq(400)
-
- # Product 1 should rank first because it has more orders (2 vs 1)
- # even though Product 2 has a higher total ($400 vs $250)
- expect(products.first.name).to eq('Product 1')
- expect(products.second.name).to eq('Product 2')
- end
- end
-
- context 'with products having no orders' do
- it 'includes products with no orders at the end' do
- products = described_class.where(id: test_product_ids).by_best_selling
- expect(products.length).to eq(4)
- # All products should be included, those without orders have count = 0
- products.select { |p| p.completed_orders.none? }.each do |product|
- expect(test_product_ids).to include(product.id)
- end
- end
- end
-
- context 'with products having only pending orders (no completed_at)' do
- before do
- # Product 1: 2 completed orders
- create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
-
- # Product 2: 1 pending order (no completed_at)
- create(:order_with_line_items, line_items_count: 1, store: store, variants: [product_2.master])
-
- # Product 3: 2 pending orders (no completed_at) + 1 completed order
- create_list(:order_with_line_items, 2, line_items_count: 1, store: store, variants: [product_3.master])
- create(:completed_order_with_totals, line_items_price: 100, store: store, variants: [product_3.master])
-
- # Product 4: no orders at all
- end
-
- it 'includes products with only pending orders with count = 0' do
- products = described_class.where(id: test_product_ids).by_best_selling
-
- # All products should be included
- expect(products.length).to eq(4)
-
- product_1_result = products.find { |p| p.id == product_1.id }
- product_2_result = products.find { |p| p.id == product_2.id }
- product_3_result = products.find { |p| p.id == product_3.id }
- product_4_result = products.find { |p| p.id == product_4.id }
-
- # Product 2 has pending orders but no completed orders - count should be 0
- expect(product_2_result.completed_orders.count).to eq(0)
- expect(product_2_result.completed_orders.sum(:total)).to eq(0)
-
- # Product 1 has 2 completed orders
- expect(product_1_result.completed_orders.count).to eq(2)
-
- # Product 3 has 1 completed order (pending orders not counted)
- expect(product_3_result.completed_orders.count).to eq(1)
-
- # Product 4 has no orders at all - count should be 0
- expect(product_4_result.completed_orders.count).to eq(0)
- expect(product_4_result.completed_orders.sum(:total)).to eq(0)
- end
-
- it 'orders products correctly with pending orders included' do
- products = described_class.where(id: test_product_ids).by_best_selling
- # Product 1: 2 completed orders (first)
- # Product 3: 1 completed order (second)
- # Product 2 & 4: 0 completed orders (last, but Product 2 still included despite having pending orders)
- expect(products.map(&:name)).to eq(['Product 1', 'Product 3', 'Product 2', 'Product 4'])
- end
- end
- end
-
describe '.available' do
let!(:discontinued_product) { create(:product, discontinue_on: 1.day.ago, stores: [store]) }
let!(:future_product) { create(:product, available_on: 1.day.from_now, status: 'active', stores: [store]) }
diff --git a/core/spec/models/spree/store_product_spec.rb b/core/spec/models/spree/store_product_spec.rb
new file mode 100644
index 0000000000..8ed1f55c26
--- /dev/null
+++ b/core/spec/models/spree/store_product_spec.rb
@@ -0,0 +1,138 @@
+require 'spec_helper'
+
+RSpec.describe Spree::StoreProduct, type: :model do
+ describe 'associations' do
+ it { is_expected.to belong_to(:store).class_name('Spree::Store').without_validating_presence }
+ it { is_expected.to belong_to(:product).class_name('Spree::Product').without_validating_presence }
+ end
+
+ describe 'validations' do
+ subject { build(:store_product) }
+
+ it { is_expected.to validate_presence_of(:store) }
+ it { is_expected.to validate_presence_of(:product) }
+ it { is_expected.to validate_uniqueness_of(:store_id).scoped_to(:product_id) }
+ end
+
+ describe '#refresh_metrics!' do
+ let(:store) { create(:store) }
+ let(:product) { create(:product, stores: [store]) }
+ let(:store_product) { product.store_products.find_by(store: store) }
+
+ context 'when there are no completed orders' do
+ it 'sets statistics to zero' do
+ store_product.refresh_metrics!
+
+ expect(store_product.units_sold_count).to eq(0)
+ expect(store_product.revenue).to eq(0)
+ end
+ end
+
+ context 'when there are completed orders' do
+ let!(:completed_order_1) do
+ create(:completed_order_with_totals, store: store, variants: [product.master], line_items_price: 20)
+ end
+
+ let!(:completed_order_2) do
+ create(:completed_order_with_totals, store: store, variants: [product.master], line_items_price: 30)
+ end
+
+ it 'calculates units_sold_count from line item quantities' do
+ store_product.refresh_metrics!
+
+ # Each order has 1 line item with quantity 1
+ expect(store_product.units_sold_count).to eq(2)
+ end
+
+ it 'calculates revenue from line item pre_tax_amount' do
+ store_product.refresh_metrics!
+
+ # pre_tax_amount is set by the order creation process
+ expected_revenue = completed_order_1.line_items.sum(:pre_tax_amount) +
+ completed_order_2.line_items.sum(:pre_tax_amount)
+ expect(store_product.revenue).to eq(expected_revenue)
+ end
+ end
+
+ context 'when orders are from different stores' do
+ let(:other_store) { create(:store) }
+
+ let!(:order_in_store) do
+ create(:completed_order_with_totals, store: store, variants: [product.master], line_items_price: 25)
+ end
+
+ let!(:order_in_other_store) do
+ create(:completed_order_with_totals, store: other_store, variants: [product.master], line_items_price: 100)
+ end
+
+ it 'only counts statistics from the specific store' do
+ store_product.refresh_metrics!
+
+ expect(store_product.units_sold_count).to eq(1)
+ expect(store_product.revenue).to eq(order_in_store.line_items.sum(:pre_tax_amount))
+ end
+ end
+
+ context 'when orders have multiple line items with different quantities' do
+ let!(:completed_order) do
+ create(:completed_order_with_totals, store: store, variants: [product.master], line_items_price: 10).tap do |order|
+ order.line_items.first.update!(quantity: 3)
+ end
+ end
+
+ it 'sums quantities for units_sold_count' do
+ store_product.refresh_metrics!
+
+ expect(store_product.units_sold_count).to eq(3)
+ end
+
+ it 'uses pre_tax_amount for revenue' do
+ store_product.refresh_metrics!
+
+ expect(store_product.revenue).to eq(completed_order.line_items.sum(:pre_tax_amount))
+ end
+ end
+
+ context 'when product has variants' do
+ let(:variant) { create(:variant, product: product) }
+
+ let!(:order_with_variant) do
+ create(:completed_order_with_totals, store: store, variants: [variant], line_items_price: 15)
+ end
+
+ it 'includes orders with product variants in statistics' do
+ store_product.refresh_metrics!
+
+ expect(store_product.units_sold_count).to eq(1)
+ expect(store_product.revenue).to eq(order_with_variant.line_items.sum(:pre_tax_amount))
+ end
+ end
+
+ context 'when there are multiple line items across orders' do
+ let!(:order_1) do
+ create(:completed_order_with_totals, store: store, variants: [product.master], line_items_price: 10).tap do |order|
+ order.line_items.first.update!(quantity: 2)
+ end
+ end
+
+ let!(:order_2) do
+ create(:completed_order_with_totals, store: store, variants: [product.master], line_items_price: 15).tap do |order|
+ order.line_items.first.update!(quantity: 5)
+ end
+ end
+
+ it 'sums all quantities across orders' do
+ store_product.refresh_metrics!
+
+ expect(store_product.units_sold_count).to eq(7) # 2 + 5
+ end
+
+ it 'sums all pre_tax_amounts across orders' do
+ store_product.refresh_metrics!
+
+ expected_revenue = order_1.line_items.sum(:pre_tax_amount) + order_2.line_items.sum(:pre_tax_amount)
+ expect(store_product.revenue).to eq(expected_revenue)
+ end
+ end
+ end
+end
diff --git a/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb b/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb
new file mode 100644
index 0000000000..e540a17c10
--- /dev/null
+++ b/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb
@@ -0,0 +1,137 @@
+# frozen_string_literal: true
+
+require 'spec_helper'
+
+RSpec.describe Spree::ProductMetricsSubscriber do
+ include ActiveJob::TestHelper
+
+ describe '.subscription_patterns' do
+ it 'subscribes to order.completed event' do
+ expect(described_class.subscription_patterns).to include('order.completed')
+ end
+ end
+
+ describe '.event_handlers' do
+ it 'routes order.completed to refresh_product_metrics' do
+ expect(described_class.event_handlers['order.completed']).to eq(:refresh_product_metrics)
+ end
+ end
+
+ describe '#refresh_product_metrics' do
+ let(:store) { create(:store) }
+ let(:product_1) { create(:product, stores: [store]) }
+ let(:product_2) { create(:product, stores: [store]) }
+ let(:subscriber) { described_class.new }
+
+ let(:order) do
+ create(:completed_order_with_totals, store: store).tap do |o|
+ o.line_items.first.update!(product: product_1, variant: product_1.master)
+ create(:line_item, order: o, product: product_2, variant: product_2.master)
+ end
+ end
+
+ let(:event) do
+ Spree::Event.new(
+ name: 'order.completed',
+ payload: { 'id' => order.id, 'store_id' => store.id }
+ )
+ end
+
+ it 'enqueues refresh jobs for all products in the order' do
+ expect {
+ subscriber.refresh_product_metrics(event)
+ }.to have_enqueued_job(Spree::Products::RefreshMetricsJob).exactly(2).times
+ end
+
+ it 'enqueues jobs with correct arguments' do
+ subscriber.refresh_product_metrics(event)
+
+ expect(Spree::Products::RefreshMetricsJob).to have_been_enqueued.with(product_1.id, store.id)
+ expect(Spree::Products::RefreshMetricsJob).to have_been_enqueued.with(product_2.id, store.id)
+ end
+
+ context 'when order_id is missing' do
+ let(:event) do
+ Spree::Event.new(
+ name: 'order.completed',
+ payload: { 'store_id' => store.id }
+ )
+ end
+
+ it 'does not enqueue any jobs' do
+ expect {
+ subscriber.refresh_product_metrics(event)
+ }.not_to have_enqueued_job(Spree::Products::RefreshMetricsJob)
+ end
+ end
+
+ context 'when store_id is missing' do
+ let(:event) do
+ Spree::Event.new(
+ name: 'order.completed',
+ payload: { 'id' => order.id }
+ )
+ end
+
+ it 'does not enqueue any jobs' do
+ expect {
+ subscriber.refresh_product_metrics(event)
+ }.not_to have_enqueued_job(Spree::Products::RefreshMetricsJob)
+ end
+ end
+
+ context 'when order does not exist' do
+ let(:event) do
+ Spree::Event.new(
+ name: 'order.completed',
+ payload: { 'id' => 'non-existent-id', 'store_id' => store.id }
+ )
+ end
+
+ it 'does not enqueue any jobs' do
+ expect {
+ subscriber.refresh_product_metrics(event)
+ }.not_to have_enqueued_job(Spree::Products::RefreshMetricsJob)
+ end
+ end
+
+ context 'when order has no line items' do
+ let(:order_without_items) { create(:order, store: store, completed_at: Time.current) }
+
+ let(:event) do
+ Spree::Event.new(
+ name: 'order.completed',
+ payload: { 'id' => order_without_items.id, 'store_id' => store.id }
+ )
+ end
+
+ it 'does not enqueue any jobs' do
+ expect {
+ subscriber.refresh_product_metrics(event)
+ }.not_to have_enqueued_job(Spree::Products::RefreshMetricsJob)
+ end
+ end
+
+ context 'when order has duplicate products' do
+ let(:order_with_duplicates) do
+ create(:completed_order_with_totals, store: store).tap do |o|
+ o.line_items.first.update!(product: product_1, variant: product_1.master)
+ create(:line_item, order: o, product: product_1, variant: product_1.master)
+ end
+ end
+
+ let(:event) do
+ Spree::Event.new(
+ name: 'order.completed',
+ payload: { 'id' => order_with_duplicates.id, 'store_id' => store.id }
+ )
+ end
+
+ it 'only enqueues one job per unique product' do
+ expect {
+ subscriber.refresh_product_metrics(event)
+ }.to have_enqueued_job(Spree::Products::RefreshMetricsJob).exactly(1).times
+ end
+ end
+ end
+end
diff --git a/storefront/spec/features/product_list_spec.rb b/storefront/spec/features/product_list_spec.rb
index 749945385e..67dbdfb187 100644
--- a/storefront/spec/features/product_list_spec.rb
+++ b/storefront/spec/features/product_list_spec.rb
@@ -185,6 +185,11 @@ RSpec.describe 'Product list', type: :feature, js: true, job: true do
let!(:completed_order_6) { create(:completed_order_with_totals, variants: [product6.master]) }
before do
+ # Refresh product metrics for best selling sort to work
+ [product1, product2, product3, product4, product6].each do |product|
+ product.store_products.find_by(store: store)&.refresh_metrics!
+ end
+
visit spree.products_path
end