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
Greatly simplify sorting of products
Damian Legawiec637efc6a0a24
diff --git a/packages/sdk/src/params.ts b/packages/sdk/src/params.tsindex 4c94815fc5..42d0a54558 100644--- a/packages/sdk/src/params.ts+++ b/packages/sdk/src/params.ts@@ -1,41 +1,43 @@/*** Keys that are passed through to the API without wrapping in q[...].*/-const PASSTHROUGH_KEYS = new Set(['page', 'per_page', 'includes', 'include']);+const PASSTHROUGH_KEYS = new Set(['page', 'per_page', 'includes', 'include', 'sort']);++type ParamValue = string | number | boolean | (string | number)[] | undefined;/*** Transforms flat SDK params into Ransack-compatible query params.*- * - `page`, `per_page`, `includes`, `include` pass through unchanged- * - `sort` maps to `q[s]`+ * - `page`, `per_page`, `includes`, `include`, `sort` pass through unchanged* - Keys already in `q[...]` format pass through (backward compat)* - All other keys are wrapped: `name_cont` → `q[name_cont]`*/export function transformListParams(params: Record<string, unknown>-): Record<string, string | number | undefined> {- const result: Record<string, string | number | undefined> = {};+): Record<string, ParamValue> {+ const result: Record<string, ParamValue> = {};for (const [key, value] of Object.entries(params)) {if (value === undefined) continue;if (PASSTHROUGH_KEYS.has(key)) {- result[key] = value as string | number;- continue;- }-- if (key === 'sort') {- result['q[s]'] = value as string;+ result[key] = value as ParamValue;continue;}// Backward compat: already-wrapped q[...] keys pass throughif (key.startsWith('q[')) {- result[key] = value as string | number;+ result[key] = value as ParamValue;continue;}- result[`q[${key}]`] = value as string | number;+ // Handle array bracket keys: `foo[]` → `q[foo][]`+ if (key.endsWith('[]')) {+ const base = key.slice(0, -2);+ result[`q[${base}][]`] = value as ParamValue;+ } else {+ result[`q[${key}]`] = value as ParamValue;+ }}return result;diff --git a/packages/sdk/src/request.ts b/packages/sdk/src/request.tsindex 8e95f44064..e4f7c6373b 100644--- a/packages/sdk/src/request.ts+++ b/packages/sdk/src/request.ts@@ -30,7 +30,7 @@ export interface RequestOptions {export interface InternalRequestOptions extends RequestOptions {body?: unknown;- params?: Record<string, string | number | undefined>;+ params?: Record<string, string | number | boolean | (string | number)[] | undefined>;}export class SpreeError extends Error {diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.tsindex 851c31729e..3f44bf609d 100644--- a/packages/sdk/src/types/index.ts+++ b/packages/sdk/src/types/index.ts@@ -61,7 +61,7 @@ export interface ListParams {}export interface ProductListParams extends ListParams {- /** Sort order, e.g. 'price asc', 'created_at desc' */+ /** Sort: 'price-low-to-high', 'price-high-to-low', 'best-selling', or Ransack e.g. 'name asc' */sort?: string;/** Full-text search across name and SKU */multi_search?: string;@@ -71,10 +71,14 @@ export interface ProductListParams extends ListParams {price_gte?: number;/** Filter: price <= value */price_lte?: number;+ /** Filter: only in-stock products */+ in_stock_items?: boolean;+ /** Filter: only out-of-stock products */+ out_of_stock_items?: boolean;/** Filter: products in taxon */taxons_id_eq?: string;/** Any additional Ransack predicate */- [key: string]: string | number | boolean | undefined;+ [key: string]: string | number | boolean | (string | number)[] | undefined;}export interface TaxonListParams extends ListParams {@@ -86,7 +90,7 @@ export interface TaxonListParams extends ListParams {parent_id_eq?: string | number;depth_eq?: number;/** Any additional Ransack predicate */- [key: string]: string | number | boolean | undefined;+ [key: string]: string | number | boolean | (string | number)[] | undefined;}export interface OrderListParams extends ListParams {@@ -98,7 +102,7 @@ export interface OrderListParams extends ListParams {completed_at_gte?: string;completed_at_lte?: string;/** Any additional Ransack predicate */- [key: string]: string | number | boolean | undefined;+ [key: string]: string | number | boolean | (string | number)[] | undefined;}// Cart operations@@ -185,23 +189,25 @@ export interface CompletePaymentSetupSessionParams {// Product Filters typesexport interface FilterOption {id: string;- label: string;count: number;}export interface OptionFilterOption extends FilterOption {name: string;+ presentation: string;position: number;}-export interface TaxonFilterOption extends FilterOption {+export interface TaxonFilterOption {+ id: string;+ name: string;permalink: string;+ count: number;}export interface PriceRangeFilter {id: 'price';type: 'price_range';- label: string;min: number;max: number;currency: string;@@ -210,22 +216,20 @@ export interface PriceRangeFilter {export interface AvailabilityFilter {id: 'availability';type: 'availability';- label: string;options: FilterOption[];}export interface OptionFilter {id: string;type: 'option';- label: string;name: string;+ presentation: string;options: OptionFilterOption[];}export interface TaxonFilter {id: 'taxons';type: 'taxon';- label: string;options: TaxonFilterOption[];}@@ -233,7 +237,6 @@ export type ProductFilter = PriceRangeFilter | AvailabilityFilter | OptionFilterexport interface SortOption {id: string;- label: string;}export interface ProductFiltersResponse {diff --git a/packages/sdk/tests/params.test.ts b/packages/sdk/tests/params.test.tsindex 29f2f7efc5..2716d9b33a 100644--- a/packages/sdk/tests/params.test.ts+++ b/packages/sdk/tests/params.test.ts@@ -17,9 +17,14 @@ describe('transformListParams', () => {expect(result).toEqual({ include: 'variants' });});- it('transforms sort to q[s]', () => {+ it('passes through sort param unchanged', () => {const result = transformListParams({ sort: 'price asc' });- expect(result).toEqual({ 'q[s]': 'price asc' });+ expect(result).toEqual({ sort: 'price asc' });+ });++ it('passes through custom sort values like price-low-to-high', () => {+ const result = transformListParams({ sort: 'price-low-to-high' });+ expect(result).toEqual({ sort: 'price-low-to-high' });});it('wraps filter keys in q[...]', () => {@@ -50,6 +55,15 @@ describe('transformListParams', () => {expect(result).toEqual({ page: 1 });});+ it('wraps array bracket keys correctly: foo[] → q[foo][]', () => {+ const result = transformListParams({+ 'with_option_value_ids[]': ['optval_abc', 'optval_def'],+ });+ expect(result).toEqual({+ 'q[with_option_value_ids][]': ['optval_abc', 'optval_def'],+ });+ });+it('handles a full combined query', () => {const result = transformListParams({page: 1,@@ -64,7 +78,7 @@ describe('transformListParams', () => {page: 1,per_page: 12,includes: 'images,default_variant',- 'q[s]': 'created_at desc',+ sort: 'created_at desc','q[name_cont]': 'shirt','q[price_gte]': 20,'q[taxons_id_eq]': 'txn_abc123',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.rbindex 7d66be7022..a246ab62e6 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@@ -3,9 +3,11 @@ module Spreemodule V3module Storeclass ProductsController < ResourceController- SORT_OPTIONS = {- 'price-low-to-high' => :ascend_by_price,- 'price-high-to-low' => :descend_by_price+ # Sort values that require special scopes (not plain Ransack column sorts).+ CUSTOM_SORT_SCOPES = {+ 'price asc' => :ascend_by_price,+ 'price desc' => :descend_by_price,+ 'best_selling' => :by_best_selling}.freezeprotected@@ -48,24 +50,41 @@ module Spree!custom_sort_requested?end- # Apply custom sorting scopes for price/best-selling+ # Applies sorting from the unified `sort` param.+ # Custom values ('price asc', 'best_selling') use product-specific scopes.+ # Standard Ransack values ('name asc', 'created_at desc') are passed to q[s].def apply_collection_sort(collection)- sort_by = params.dig(:q, :sort_by) || params[:sort_by]- return collection unless sort_by.present?+ sort_value = sort_param+ return collection unless sort_value.present?- return collection.distinct(false).reorder(nil).by_best_selling if sort_by == 'best-selling'+ scope_method = CUSTOM_SORT_SCOPES[sort_value]+ return collection unless scope_method- scope_method = SORT_OPTIONS[sort_by]- return collection.reorder(nil).send(scope_method) if scope_method.present?+ sorted = collection.reorder(nil)+ sort_value == 'best_selling' ? sorted.distinct(false).send(scope_method) : sorted.send(scope_method)+ end++ # Inject sort into ransack params when it's a standard Ransack sort+ def ransack_params+ rp = super+ sort_value = sort_param++ if sort_value.present? && !CUSTOM_SORT_SCOPES.key?(sort_value)+ rp = rp.respond_to?(:to_unsafe_h) ? rp.to_unsafe_h : rp.dup+ rp['s'] = sort_value+ end- collection+ rpendprivate+ def sort_param+ params[:sort] || params.dig(:q, :s)+ end+def custom_sort_requested?- sort_by = params.dig(:q, :sort_by) || params[:sort_by]- SORT_OPTIONS.key?(sort_by)+ CUSTOM_SORT_SCOPES.key?(sort_param)endendenddiff --git a/spree/api/app/services/spree/api/v3/filters_aggregator.rb b/spree/api/app/services/spree/api/v3/filters_aggregator.rbindex b0ec4ccc20..b5d0ad08ef 100644--- a/spree/api/app/services/spree/api/v3/filters_aggregator.rb+++ b/spree/api/app/services/spree/api/v3/filters_aggregator.rb@@ -2,16 +2,7 @@ module Spreemodule Apimodule V3class FiltersAggregator- SORT_OPTION_IDS = %w[- manual- best-selling- price-low-to-high- price-high-to-low- newest-first- oldest-first- name-a-z- name-z-a- ].freeze+ SORT_OPTION_IDS = Spree::Taxon::SORT_ORDERS# @param scope [ActiveRecord::Relation] Base product scope (already filtered by store, availability, taxon, etc.)# @param currency [String] Currency for price range@@ -43,11 +34,10 @@ module Spreeenddef sort_options- SORT_OPTION_IDS.map do |id|- { id: id, label: Spree.t("products_sort_options.#{id.underscore}") }- end+ SORT_OPTION_IDS.map { |id| { id: id } }end+def price_filter# Remove ordering to avoid PostgreSQL DISTINCT + ORDER BY conflictsprices = Spree::Price.for_products(@scope.reorder(''), @currency)@@ -58,7 +48,6 @@ module Spree{id: 'price',type: 'price_range',- label: Spree.t(:price),min: min.to_f,max: max.to_f,currency: @currency@@ -74,10 +63,9 @@ module Spree{id: 'availability',type: 'availability',- label: Spree.t(:availability),options: [- { id: 'in_stock', label: Spree.t(:in_stock), count: in_stock_count },- { id: 'out_of_stock', label: Spree.t(:out_of_stock), count: out_of_stock_count }+ { id: 'in_stock', count: in_stock_count },+ { id: 'out_of_stock', count: out_of_stock_count }]}end@@ -90,8 +78,8 @@ module Spree{id: option_type.prefixed_id,type: 'option',- label: option_type.presentation,name: option_type.name,+ presentation: option_type.presentation,options: values.map { |ov| option_value_data(option_type, ov) }}end@@ -110,8 +98,8 @@ module Spree{id: option_value.prefixed_id,- label: option_value.presentation,name: option_value.name,+ presentation: option_value.presentation,position: option_value.position,count: count}@@ -135,7 +123,6 @@ module Spree{id: 'taxons',type: 'taxon',- label: Spree.t(:category),options: child_taxons.map { |t| taxon_option_data(t) }}end@@ -145,7 +132,7 @@ module Spree{id: taxon.prefixed_id,- label: taxon.name,+ name: taxon.name,permalink: taxon.permalink,count: count}diff --git a/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rbindex e7d6ca2296..9ca3724285 100644--- a/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb@@ -82,12 +82,12 @@ RSpec.describe Spree::Api::V3::Store::Products::FiltersController, type: :controsize_filter = json_response['filters'].find { |f| f['name'] == 'size' }expect(size_filter).to be_presentexpect(size_filter['type']).to eq('option')- expect(size_filter['label']).to eq('Size')+ expect(size_filter['presentation']).to eq('Size')size_options = size_filter['options']- expect(size_options.map { |o| o['label'] }).to include('S', 'M')+ expect(size_options.map { |o| o['presentation'] }).to include('S', 'M')- small_option = size_options.find { |o| o['label'] == 'S' }+ small_option = size_options.find { |o| o['presentation'] == 'S' }expect(small_option['count']).to eq(1)end@@ -96,8 +96,8 @@ RSpec.describe Spree::Api::V3::Store::Products::FiltersController, type: :controsort_ids = json_response['sort_options'].map { |s| s['id'] }expect(sort_ids).to include(- 'manual', 'best-selling', 'price-low-to-high', 'price-high-to-low',- 'newest-first', 'oldest-first', 'name-a-z', 'name-z-a'+ 'manual', 'best_selling', 'price asc', 'price desc',+ 'available_on desc', 'available_on asc', 'name asc', 'name desc')end@@ -121,15 +121,15 @@ RSpec.describe Spree::Api::V3::Store::Products::FiltersController, type: :controexpect(taxon_filter).to be_presenttaxon_options = taxon_filter['options']- expect(taxon_options.map { |t| t['label'] }).to include('Shirts', 'Pants')+ expect(taxon_options.map { |t| t['name'] }).to include('Shirts', 'Pants')endit 'returns default_sort from taxon' do- taxon.update!(sort_order: 'price-low-to-high')+ taxon.update!(sort_order: 'price asc')get :index, params: { taxon_id: taxon.prefixed_id }- expect(json_response['default_sort']).to eq('price-low-to-high')+ expect(json_response['default_sort']).to eq('price asc')endenddiff --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.rbindex f16366dd39..a06b5ced93 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@@ -162,7 +162,7 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller doendit 'sorts by price low to high' do- get :index, params: { q: { sort_by: 'price-low-to-high' } }+ get :index, params: { sort: 'price asc' }expect(response).to have_http_status(:ok)prices = json_response['data'].map { |p| p['price']['amount'].to_f }@@ -170,7 +170,7 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller doendit 'sorts by price high to low' do- get :index, params: { q: { sort_by: 'price-high-to-low' } }+ get :index, params: { sort: 'price desc' }expect(response).to have_http_status(:ok)prices = json_response['data'].map { |p| p['price']['amount'].to_f }@@ -181,7 +181,7 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller doSpree::StoreProduct.find_by(product: product, store: store).update!(units_sold_count: 10, revenue: 100)Spree::StoreProduct.find_by(product: product2, store: store).update!(units_sold_count: 50, revenue: 500)- get :index, params: { sort_by: 'best-selling' }+ get :index, params: { sort: 'best_selling' }expect(response).to have_http_status(:ok)ids = json_response['data'].map { |p| p['id'] }diff --git a/spree/api/spec/controllers/spree/api/v3/store/taxons/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/taxons/products_controller_spec.rbindex c5ed629135..291e187f96 100644--- a/spree/api/spec/controllers/spree/api/v3/store/taxons/products_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/taxons/products_controller_spec.rb@@ -157,7 +157,7 @@ RSpec.describe Spree::Api::V3::Store::Taxons::ProductsController, type: :controlendit 'sorts by price low to high' do- get :index, params: { taxon_id: taxon.permalink, q: { sort_by: 'price-low-to-high' } }+ get :index, params: { taxon_id: taxon.permalink, sort: 'price asc' }expect(response).to have_http_status(:ok)prices = json_response['data'].map { |p| p['price']['amount'].to_f }@@ -165,7 +165,7 @@ RSpec.describe Spree::Api::V3::Store::Taxons::ProductsController, type: :controlendit 'sorts by price high to low' do- get :index, params: { taxon_id: taxon.permalink, q: { sort_by: 'price-high-to-low' } }+ get :index, params: { taxon_id: taxon.permalink, sort: 'price desc' }expect(response).to have_http_status(:ok)prices = json_response['data'].map { |p| p['price']['amount'].to_f }diff --git a/spree/api/spec/integration/spree/api/v3/store/products_spec.rb b/spree/api/spec/integration/spree/api/v3/store/products_spec.rbindex 6aaee9c858..310422fb79 100644--- a/spree/api/spec/integration/spree/api/v3/store/products_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/store/products_spec.rb@@ -201,10 +201,9 @@ RSpec.describe 'Products API', type: :request, swagger_doc: 'api-reference/storeitems: {type: :object,properties: {- id: { type: :string },- label: { type: :string }+ id: { type: :string }},- required: %w[id label]+ required: %w[id]}},default_sort: {@@ -242,7 +241,7 @@ RSpec.describe 'Products API', type: :request, swagger_doc: 'api-reference/store# Check sort optionssort_ids = data['sort_options'].map { |s| s['id'] }- expect(sort_ids).to include('manual', 'price-low-to-high', 'newest-first')+ expect(sort_ids).to include('manual', 'price asc', 'available_on desc')endend@@ -265,7 +264,7 @@ RSpec.describe 'Products API', type: :request, swagger_doc: 'api-reference/store# Should include taxon filter with child taxonstaxon_filter = data['filters'].find { |f| f['type'] == 'taxon' }expect(taxon_filter).to be_present- expect(taxon_filter['options'].map { |t| t['label'] }).to include('Shirts')+ expect(taxon_filter['options'].map { |t| t['name'] }).to include('Shirts')endenddiff --git a/spree/api/spec/services/spree/api/v3/filters_aggregator_spec.rb b/spree/api/spec/services/spree/api/v3/filters_aggregator_spec.rbindex ab511c9eea..b2cc7ead34 100644--- a/spree/api/spec/services/spree/api/v3/filters_aggregator_spec.rb+++ b/spree/api/spec/services/spree/api/v3/filters_aggregator_spec.rb@@ -38,12 +38,12 @@ RSpec.describe Spree::Api::V3::FiltersAggregator doit 'returns sort_options array' doexpect(result[:sort_options]).to be_an(Array)- expect(result[:sort_options].first).to include(id: 'manual', label: Spree.t('products_sort_options.manual'))+ expect(result[:sort_options].first).to include(id: 'manual')endit 'returns default_sort from taxon' do- taxon.update!(sort_order: 'newest-first')- expect(result[:default_sort]).to eq('newest-first')+ taxon.update!(sort_order: 'available_on desc')+ expect(result[:default_sort]).to eq('available_on desc')endit 'returns manual as default_sort when no taxon' do@@ -81,16 +81,16 @@ RSpec.describe Spree::Api::V3::FiltersAggregator doexpect(size_filter).to be_presentexpect(size_filter[:type]).to eq('option')- expect(size_filter[:label]).to eq('Size')+ expect(size_filter[:presentation]).to eq('Size')endit 'includes option values with counts' dosize_filter = result[:filters].find { |f| f[:name] == 'size' }options = size_filter[:options]- expect(options.map { |o| o[:label] }).to contain_exactly('S', 'M')+ expect(options.map { |o| o[:presentation] }).to contain_exactly('S', 'M')- s_option = options.find { |o| o[:label] == 'S' }+ s_option = options.find { |o| o[:presentation] == 'S' }expect(s_option[:count]).to eq(1)end@@ -108,7 +108,7 @@ RSpec.describe Spree::Api::V3::FiltersAggregator dotaxon_filter = result[:filters].find { |f| f[:type] == 'taxon' }expect(taxon_filter).to be_present- expect(taxon_filter[:options].map { |t| t[:label] }).to include('Child')+ expect(taxon_filter[:options].map { |t| t[:name] }).to include('Child')endit 'does not include taxon filter when no taxon provided' do@@ -120,7 +120,7 @@ RSpec.describe Spree::Api::V3::FiltersAggregator doit 'includes product count per taxon' dotaxon_filter = result[:filters].find { |f| f[:type] == 'taxon' }- child_option = taxon_filter[:options].find { |t| t[:label] == 'Child' }+ child_option = taxon_filter[:options].find { |t| t[:name] == 'Child' }expect(child_option[:count]).to eq(2)enddiff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rbindex b6c6116db9..98d10fe994 100644--- a/spree/core/app/models/concerns/spree/product_scopes.rb+++ b/spree/core/app/models/concerns/spree/product_scopes.rb@@ -91,6 +91,14 @@ module Spreejoins(:variants_including_master).merge(Spree::Variant.in_stock_or_backorderable)endend++ add_search_scope :price_lte do |price|+ where(Price.table_name => { amount: ..price })+ end++ add_search_scope :price_gte do |price|+ where(Price.table_name => { amount: price.. })+ endsearch_scopes << :in_stockdef self.out_of_stock(out_of_stock = true)diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex 0a126b80b7..a60b011f91 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -220,7 +220,9 @@ module Spreeself.whitelisted_ransackable_associations = %w[taxons stores variants_including_master master variants tags labelsshipping_category classifications option_types]self.whitelisted_ransackable_scopes = %w[not_discontinued search_by_name in_taxon price_between+ price_lte price_gtemulti_search in_stock out_of_stock with_option_value_ids+ascend_by_price descend_by_price][diff --git a/spree/core/app/models/spree/taxon.rb b/spree/core/app/models/spree/taxon.rbindex e6923e0ca7..613956894f 100644--- a/spree/core/app/models/spree/taxon.rb+++ b/spree/core/app/models/spree/taxon.rb@@ -5,16 +5,16 @@ module Spreehas_prefix_id :txn # Spree-specific: taxonRULES_MATCH_POLICIES = %w[all any].freeze- SORT_ORDERS = %w[- manual- best-selling- name-a-z- name-z-a- price-high-to-low- price-low-to-high- newest-first- oldest-first- ]+ SORT_ORDERS = [+ 'manual',+ 'best_selling',+ 'price asc',+ 'price desc',+ 'available_on desc',+ 'available_on asc',+ 'name asc',+ 'name desc'+ ].freezeinclude Spree::TranslatableResourceinclude Spree::TranslatableResourceSlug