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
Allow to sort products by sku in the Storefront/Platform API plus support sorting by multiple fields (#11270)
Szymon Iwacz94878b717a31
diff --git a/api/app/serializers/spree/v2/storefront/product_serializer.rb b/api/app/serializers/spree/v2/storefront/product_serializer.rbindex 5444820875..588e36e57a 100644--- a/api/app/serializers/spree/v2/storefront/product_serializer.rb+++ b/api/app/serializers/spree/v2/storefront/product_serializer.rb@@ -6,7 +6,7 @@ module Spreeset_type :product- attributes :name, :description, :available_on, :slug, :meta_description, :meta_keywords, :updated_at+ attributes :name, :description, :available_on, :slug, :meta_description, :meta_keywords, :updated_at, :skuattribute :purchasable do |product|product.purchasable?diff --git a/api/docs/v2/storefront/index.yaml b/api/docs/v2/storefront/index.yamlindex f28434bdf4..05f36aac5e 100644--- a/api/docs/v2/storefront/index.yaml+++ b/api/docs/v2/storefront/index.yaml@@ -1208,7 +1208,7 @@ paths:name: sortschema:type: string- example: '-updated_at,price,-name,created_at,-available_on'+ example: '-updated_at,price,-name,created_at,-available_on,sku'description: |-Sort products based on: <ul><li>name (ascending/descending)</li>@@ -1216,6 +1216,7 @@ paths:<li>available_on (ascending/descending)</li><li>created_at (ascending/descending)</li><li>updated_at (ascending/descending)</li>+ <li>sku (ascending/descending)</li></ul> Use <q>-</q> sign to set descending sort, eg. <q>-updated_at</q>- $ref: '#/components/parameters/PageParam'- $ref: '#/components/parameters/PerPageParam'diff --git a/api/spec/requests/spree/api/v2/storefront/products_spec.rb b/api/spec/requests/spree/api/v2/storefront/products_spec.rbindex 0c3a7766ad..cf1109de37 100644--- a/api/spec/requests/spree/api/v2/storefront/products_spec.rb+++ b/api/spec/requests/spree/api/v2/storefront/products_spec.rb@@ -451,6 +451,83 @@ describe 'API V2 Storefront Products Spec', type: :request doendendend++ context 'sorting by sku' do+ shared_examples 'returning products in ascending sku order' do+ before { get "/api/v2/storefront/products?sort=sku#{params}" }++ it_behaves_like 'returns 200 HTTP status'++ it 'returns products sorted by master variant sku' do+ expect(skus_array).to eq(skus_array.sort)+ expect(json_response['data'].count).to eq(store.products.available.count)+ expect(json_response['data'].map { |p| p['attributes']['sku'] }).to eq(available_products_with_master.map(&:sku).sort)+ end+ end++ shared_examples 'returning products in descending sku order' do+ before { get "/api/v2/storefront/products?sort=-sku#{params}" }++ it_behaves_like 'returns 200 HTTP status'++ it 'returns products sorted by master variant sku with descending order' do+ expect(skus_array).to eq(skus_array.sort.reverse)+ expect(json_response['data'].count).to eq(store.products.available.count)+ expect(json_response['data'].map { |p| p['attributes']['sku'] }).to eq(available_products_with_master.map(&:sku).sort.reverse)+ end+ end++ let(:skus_array) { json_response['data'].map { |p| p['attributes']['sku']} }+ let(:available_products_with_master) { products + [product_with_option, in_stock_product, not_backorderable_product, product_with_property] }+ let(:params) { '' }++ it_behaves_like 'returning products in ascending sku order'+ it_behaves_like 'returning products in descending sku order'++ context 'with variants' do+ let(:params) { '&include=variants' }++ it_behaves_like 'returning products in ascending sku order'+ it_behaves_like 'returning products in descending sku order'+ end++ context 'with updated_at sort' do+ let(:params) { ',updated_at' }+ let!(:time) { Time.current }++ context 'when updated_at date is same for each product' do+ before { store.products.each { |p| p.update(updated_at: time) } }++ it_behaves_like 'returning products in ascending sku order'+ it_behaves_like 'returning products in descending sku order'+ end++ context 'when updated_at date is different for each product' do+ shared_examples 'returns products in ascending updated_at order' do+ it 'returns products in ascending updated_at order' do+ expect(json_response['data'].count).to eq(store.products.available.count)+ expect(json_response['data'].map { |p| p['attributes']['sku'] }).to eq(available_products_with_master.sort { |a, b| a.updated_at <=> b.updated_at }.map(&:sku))+ end+ end++ before { available_products_with_master.each_with_index { |p, i| p.update(updated_at: time - i.day) } }++ context 'when sku sort order direction is ascending' do+ before { get "/api/v2/storefront/products?sort=sku#{params}" }++ it_behaves_like 'returns 200 HTTP status'+ it_behaves_like 'returns products in ascending updated_at order'+ end++ context 'when sku sort order direction is descending' do+ before { get "/api/v2/storefront/products?sort=-sku#{params}" }++ it_behaves_like 'returns 200 HTTP status'+ it_behaves_like 'returns products in ascending updated_at order'+ end+ end+ end+ endendcontext 'paginate products' do@@ -653,6 +730,7 @@ describe 'API V2 Storefront Products Spec', type: :request doexpect(json_response['data']).to have_attribute(:purchasable).with_value(product.purchasable?)expect(json_response['data']).to have_attribute(:in_stock).with_value(product.in_stock?)expect(json_response['data']).to have_attribute(:backorderable).with_value(product.backorderable?)+ expect(json_response['data']).to have_attribute(:sku).with_value(product.sku)expect(json_response['data']).to have_relationships(:variants, :option_types, :product_properties, :default_variantdiff --git a/core/app/sorters/spree/base_sorter.rb b/core/app/sorters/spree/base_sorter.rbindex c3f0bfca30..67aebdc9fb 100644--- a/core/app/sorters/spree/base_sorter.rb+++ b/core/app/sorters/spree/base_sorter.rb@@ -2,34 +2,46 @@ module Spreeclass BaseSorterdef initialize(scope, params = {}, allowed_sort_attributes = [])@scope = scope- @sort = params[:sort]@allowed_sort_attributes = allowed_sort_attributes+ @sort = sort_fields(params[:sort])enddef call- by_param_attribute(scope)+ by_param_attributes(scope)endprotectedattr_reader :scope, :collection, :sort, :allowed_sort_attributes- def by_param_attribute(scope)- return scope if sort_field.blank? || !allowed_sort_attributes.include?(sort_field.to_sym)+ def by_param_attributes(scope)+ return scope if sort.empty?- scope.order("#{sort_field}": order_direction)+ sort.each do |value, order|+ next if value.blank? || allowed_sort_attributes.exclude?(value.to_sym)++ scope = scope.order("#{value}": order)+ end++ scope+ end++ def sort_fields(sort)+ return [] if sort.nil?++ sort.split(',').map { |field| [sort_field(field), order_direction(field)] }end- def desc_order- @desc_order ||= String(sort)[0] == '-'+ def desc_order(field)+ String(field)[0] == '-'end- def sort_field- @sort_field ||= desc_order ? sort[1..-1] : sort+ def sort_field(field)+ desc_order(field) ? field[1..-1] : fieldend- def order_direction- desc_order ? :desc : :asc+ def order_direction(field)+ desc_order(field) ? :desc : :ascendendenddiff --git a/core/app/sorters/spree/products/sort.rb b/core/app/sorters/spree/products/sort.rbindex 590fb1d552..d480faa860 100644--- a/core/app/sorters/spree/products/sort.rb+++ b/core/app/sorters/spree/products/sort.rb@@ -7,8 +7,9 @@ module Spreeenddef call- products = by_param_attribute(scope)+ products = by_param_attributes(scope)products = by_price(products)+ products = by_sku(products)products.distinctend@@ -17,18 +18,27 @@ module Spreeattr_reader :sort, :scope, :currency, :allowed_sort_attributes- def price?- sort_field == 'price'- end-def by_price(scope)- return scope unless price?+ return scope unless (value = sort_by?('price'))scope.joins(master: :prices).select("#{Spree::Product.table_name}.*, #{Spree::Price.table_name}.amount").distinct.where(spree_prices: { currency: currency }).- order("#{Spree::Price.table_name}.amount #{order_direction}")+ order("#{Spree::Price.table_name}.amount #{value[1]}")+ end++ def by_sku(scope)+ return scope unless (value = sort_by?('sku'))++ scope.joins(:master).+ select("#{Spree::Product.table_name}.*, #{Spree::Variant.table_name}.sku").+ where(Spree::Variant.table_name.to_s => { is_master: true }).+ order("#{Spree::Variant.table_name}.sku #{value[1]}")+ end++ def sort_by?(field)+ sort.detect { |s| s[0] == field }endendend