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
feat(core): manual (position) sort in the DB search provider
Łukasz Adamczyk1a388a533c6f
diff --git a/spree/core/app/models/spree/search_provider/database.rb b/spree/core/app/models/spree/search_provider/database.rbindex 49deeb7dd8..817207a10a 100644--- a/spree/core/app/models/spree/search_provider/database.rb+++ b/spree/core/app/models/spree/search_provider/database.rb@@ -10,6 +10,11 @@ module Spreedef search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)filters = filters.is_a?(Hash) ? filters.dup : {}option_value_ids = filters.delete('with_option_value_ids') || filters.delete(:with_option_value_ids)+ # Which grouping a 'manual' (position) sort orders within. The in_category /+ # in_collection filter (applied just below) already JOINs and scopes that+ # grouping's position table, so we only need to know *which* grouping is+ # active+ grouping = manual_sort_grouping(filters)scope = apply_search_and_filters(scope, query: query, filters: filters)scope = scope.with_option_value_ids(Array(option_value_ids)) if option_value_ids.present?@@ -18,7 +23,7 @@ module Spreetotal = scope.distinct.count# Sorting + pagination- scope = apply_sort(scope, sort)+ scope = apply_sort(scope, sort, grouping: grouping)page = [page.to_i, 1].maxlimit = limit.to_i.clamp(1, 100)products = scope.offset((page - 1) * limit).limit(limit)@@ -94,9 +99,15 @@ module Spreefilters.except('search', :search, '_category', :_category, '_collection', :_collection, 'with_option_value_ids', :with_option_value_ids)end- def apply_sort(scope, sort)+ def apply_sort(scope, sort, grouping: nil)+ # A category/collection page defaults to the merchant's manual (position)+ # order when `sort` is omitted — matching the `default_sort: 'manual'` the+ # filters endpoint advertises.+ sort = 'manual' if sort.blank? && grouping.present?return scope if sort.blank?+ return manual_sort(scope, grouping) if sort == 'manual'+scope_method = CUSTOM_SORT_SCOPES[sort]if scope_methodscope.reorder(nil).send(scope_method)@@ -114,6 +125,44 @@ module Spreeendend+ # Which grouping a 'manual' sort orders within, inferred from the filter that+ # was applied (and therefore joined its position table). Only single-grouping+ # PLPs sort manually — in_categories (plural) has no single position axis.+ def manual_sort_grouping(filters)+ return :collection if filters.key?('in_collection') || filters.key?(:in_collection)+ return :category if filters.key?('in_category') || filters.key?(:in_category)++ nil+ end++ # 'manual' sort = the merchant's hand-set position within the grouping. The+ # in_category / in_collection filter already joined and scoped the position+ # table, so we just order by it — no re-resolution, no extra query. With no+ # grouping, 'manual' falls back to the unsorted scope (nothing to order by).+ def manual_sort(scope, grouping)+ case grouping+ when :collection+ # Flat: one product_collections row per product, so order by its position.+ # The filtered scope is DISTINCT and PostgreSQL requires ORDER BY columns+ # in the SELECT list, so select the position too.+ position = "#{Spree::ProductCollection.table_name}.position"+ scope.reorder(nil).+ select("#{Spree::Product.table_name}.*", position).+ order(Arel.sql("#{position} ASC"))+ when :category+ # Hierarchical: a product under a category AND its descendants has several+ # product_categories rows (in_category joins the whole subtree), so collapse+ # to MIN(position) grouped by product.+ position = "MIN(#{Spree::ProductCategory.table_name}.position)"+ scope.reorder(nil).+ select("#{Spree::Product.table_name}.*", "#{position} AS manual_position").+ group("#{Spree::Product.table_name}.id").+ order(Arel.sql("#{position} ASC"))+ else+ scope+ end+ end+def available_sort_options%w[price -price best_selling name -name -available_on available_on].map { |id| { id: id } }enddiff --git a/spree/core/spec/models/spree/search_provider/database_spec.rb b/spree/core/spec/models/spree/search_provider/database_spec.rbindex 9e759ecf77..dec5c2ad6c 100644--- a/spree/core/spec/models/spree/search_provider/database_spec.rb+++ b/spree/core/spec/models/spree/search_provider/database_spec.rb@@ -194,6 +194,76 @@ module Spreeexpect(result.products).not_to include(product_3)endend++ context "with 'manual' sort by category" do+ let(:taxonomy) { create(:taxonomy, store: store) }+ let(:parent_category) { create(:taxon, taxonomy: taxonomy, name: 'Clothing') }+ let(:child_category) { create(:taxon, taxonomy: taxonomy, parent: parent_category, name: 'Shirts') }++ before do+ # Positions deliberately differ from id/creation order so the assertion+ # proves position ordering (not incidental default order). Positions span+ # the parent AND its descendant — manual sort collapses the subtree by MIN.+ Spree::ProductCategory.create!(category: parent_category, product: product_2).update_column(:position, 1)+ Spree::ProductCategory.create!(category: child_category, product: product_1).update_column(:position, 2)+ Spree::ProductCategory.create!(category: parent_category, product: product_3).update_column(:position, 3)+ end++ it 'orders products by their manual position within the category and its descendants' do+ result = provider.search_and_filter(scope: scope, filters: { 'in_category' => parent_category.prefixed_id }, sort: 'manual')+ expect(result.products.to_a).to eq([product_2, product_1, product_3])+ end+ end++ context "with 'manual' sort by collection" do+ let(:collection) { create(:collection, store: store) }++ before do+ Spree::ProductCollection.create!(collection: collection, product: product_3).update_column(:position, 1)+ Spree::ProductCollection.create!(collection: collection, product: product_1).update_column(:position, 2)+ Spree::ProductCollection.create!(collection: collection, product: product_2).update_column(:position, 3)+ end++ it 'orders products by their manual position within the collection' do+ result = provider.search_and_filter(scope: scope, filters: { 'in_collection' => collection.prefixed_id }, sort: 'manual')+ expect(result.products.to_a).to eq([product_3, product_1, product_2])+ end+ end++ context 'with no sort param on a category page' do+ let(:taxonomy) { create(:taxonomy, store: store) }+ let(:category) { create(:taxon, taxonomy: taxonomy, name: 'Clothing') }++ before do+ Spree::ProductCategory.create!(category: category, product: product_2).update_column(:position, 1)+ Spree::ProductCategory.create!(category: category, product: product_1).update_column(:position, 2)+ end++ it 'defaults to the merchant manual (position) order' do+ result = provider.search_and_filter(scope: scope, filters: { 'in_category' => category.prefixed_id })+ expect(result.products.to_a).to eq([product_2, product_1])+ end+ end++ context "with 'manual' sort and no category/collection filter" do+ subject(:result) { provider.search_and_filter(scope: scope, sort: 'manual') }++ it 'falls back to the default order without raising' do+ expect { result.products.to_a }.not_to raise_error+ expect(result.products).to include(product_1, product_2, product_3)+ expect(result.total_count).to eq(3)+ end+ end++ context "with 'manual' sort and a non-grouping filter" do+ subject(:result) { provider.search_and_filter(scope: scope, sort: 'manual', filters: { 'name_cont' => 'Blue' }) }++ it 'applies the filter and falls back to the default order' do+ expect(result.products).to include(product_1, product_3)+ expect(result.products).not_to include(product_2)+ expect(result.total_count).to eq(2)+ end+ endenddescribe '#filters' do