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.

Add PLP filtering/sorting in API

Damian Legawieca077ec2e4b01
diff --git a/api/app/controllers/spree/api/v3/resource_controller.rb b/api/app/controllers/spree/api/v3/resource_controller.rb
index 0b0ace89f7..507867c7c5 100644
--- a/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -96,11 +96,22 @@ module Spree
@search = scope.includes(collection_includes).
preload_associations_lazily.
ransack(ransack_params)
- result = @search.result(distinct: true)
+ result = @search.result(distinct: collection_distinct?)
+ result = apply_collection_sort(result)
@pagy, @collection = pagy(result, limit: limit, page: page)
@collection
end
+ # Override in subclass to disable distinct (e.g., for custom sorting with computed columns)
+ def collection_distinct?
+ true
+ end
+
+ # Override in subclass to apply custom sorting
+ def apply_collection_sort(collection)
+ collection
+ end
+
def collection_includes
[]
end
diff --git a/api/app/controllers/spree/api/v3/store/products/filters_controller.rb b/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
new file mode 100644
index 0000000000..163f599489
--- /dev/null
+++ b/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
@@ -0,0 +1,34 @@
+module Spree
+ module Api
+ module V3
+ module Store
+ module Products
+ class FiltersController < Store::BaseController
+ def index
+ aggregator = Spree::Api::V3::FiltersAggregator.new(
+ scope: filters_scope,
+ currency: current_currency,
+ taxon: taxon
+ )
+ render json: aggregator.call
+ end
+
+ private
+
+ # Build scope from taxon and/or ransack params
+ def filters_scope
+ scope = current_store.products.available(Time.current, current_currency)
+ scope = scope.in_taxon(taxon) if taxon.present?
+ scope = scope.ransack(params[:q]).result if params[:q].present?
+ scope.accessible_by(current_ability, :show)
+ end
+
+ def taxon
+ @taxon ||= params[:taxon_id].present? ? current_store.taxons.find_by_param(params[:taxon_id]) : nil
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/api/app/controllers/spree/api/v3/store/products_controller.rb b/api/app/controllers/spree/api/v3/store/products_controller.rb
index 8912139d18..935f01822b 100644
--- a/api/app/controllers/spree/api/v3/store/products_controller.rb
+++ b/api/app/controllers/spree/api/v3/store/products_controller.rb
@@ -3,6 +3,12 @@ module Spree
module V3
module Store
class ProductsController < ResourceController
+ SORT_OPTIONS = {
+ 'price-low-to-high' => :ascend_by_price,
+ 'price-high-to-low' => :descend_by_price,
+ 'best-selling' => :by_best_selling
+ }.freeze
+
protected
def model_class
@@ -32,10 +38,33 @@ module Spree
def scope_includes
[
thumbnail: [attachment_attachment: :blob],
- master: [:prices, { stock_items: :stock_location }],
- variants: [:prices, { stock_items: :stock_location }]
+ master: [:prices],
+ variants: [:prices]
]
end
+
+ # Disable distinct when using custom sort scopes that add computed columns
+ def collection_distinct?
+ !custom_sort_requested?
+ end
+
+ # Apply custom sorting scopes for price/best-selling
+ def apply_collection_sort(collection)
+ sort_by = params.dig(:q, :sort_by) || params[:sort_by]
+ return collection unless sort_by.present?
+
+ scope_method = SORT_OPTIONS[sort_by]
+ return collection.reorder(nil).send(scope_method) if scope_method.present?
+
+ collection
+ end
+
+ private
+
+ def custom_sort_requested?
+ sort_by = params.dig(:q, :sort_by) || params[:sort_by]
+ SORT_OPTIONS.key?(sort_by)
+ end
end
end
end
diff --git a/api/app/services/spree/api/v3/filters_aggregator.rb b/api/app/services/spree/api/v3/filters_aggregator.rb
new file mode 100644
index 0000000000..0bdb9335fa
--- /dev/null
+++ b/api/app/services/spree/api/v3/filters_aggregator.rb
@@ -0,0 +1,138 @@
+module Spree
+ module Api
+ module V3
+ class FiltersAggregator
+ SORT_OPTIONS = [
+ { id: 'manual', label: 'Default' },
+ { id: 'best-selling', label: 'Best Selling' },
+ { id: 'price-low-to-high', label: 'Price: Low to High' },
+ { id: 'price-high-to-low', label: 'Price: High to Low' },
+ { id: 'newest-first', label: 'Newest First' },
+ { id: 'oldest-first', label: 'Oldest First' },
+ { id: 'name-a-z', label: 'Name: A-Z' },
+ { id: 'name-z-a', label: 'Name: Z-A' }
+ ].freeze
+
+ # @param scope [ActiveRecord::Relation] Base product scope (already filtered by store, availability, taxon, etc.)
+ # @param currency [String] Currency for price range
+ # @param taxon [Spree::Taxon, nil] Optional taxon for default_sort and taxon filtering context
+ def initialize(scope:, currency:, taxon: nil)
+ @scope = scope
+ @currency = currency
+ @taxon = taxon
+ end
+
+ def call
+ {
+ filters: build_filters,
+ sort_options: SORT_OPTIONS,
+ default_sort: @taxon&.sort_order || 'manual',
+ total_count: @scope.distinct.count
+ }
+ end
+
+ private
+
+ def build_filters
+ [
+ price_filter,
+ availability_filter,
+ *option_type_filters,
+ taxon_filter
+ ].compact
+ end
+
+ def price_filter
+ prices = Spree::Price.for_products(@scope, @currency)
+ min = prices.minimum(:amount)
+ max = prices.maximum(:amount)
+ return nil if min.nil? || max.nil?
+
+ {
+ id: 'price',
+ type: 'price_range',
+ label: 'Price',
+ min: min.to_f,
+ max: max.to_f,
+ currency: @currency
+ }
+ end
+
+ def availability_filter
+ in_stock_count = @scope.in_stock.distinct.count
+ out_of_stock_count = @scope.out_of_stock.distinct.count
+
+ return nil if in_stock_count.zero? && out_of_stock_count.zero?
+
+ {
+ id: 'availability',
+ type: 'availability',
+ label: 'Availability',
+ options: [
+ { id: 'in_stock', label: 'In Stock', count: in_stock_count },
+ { id: 'out_of_stock', label: 'Out of Stock', count: out_of_stock_count }
+ ]
+ }
+ end
+
+ def option_type_filters
+ Spree::OptionType.filterable.includes(:option_values).order(:position).filter_map do |option_type|
+ values = option_type.option_values.for_products(@scope).distinct.order(:position)
+ next if values.empty?
+
+ {
+ id: option_type.prefix_id,
+ type: 'option',
+ label: option_type.presentation,
+ name: option_type.name,
+ options: values.map { |ov| option_value_data(option_type, ov) }
+ }
+ end
+ end
+
+ def option_value_data(option_type, option_value)
+ # with_option_value uses group, so we need to count the keys or use a different approach
+ count = @scope.with_option_value(option_type.name, option_value.name).length
+
+ {
+ id: option_value.prefix_id,
+ label: option_value.presentation,
+ name: option_value.name,
+ position: option_value.position,
+ count: count
+ }
+ end
+
+ def taxon_filter
+ return nil if @taxon.nil?
+
+ # Get child taxons at the next depth level
+ child_taxons = @taxon.children.order(:lft).select do |child|
+ # Only include taxons that have products in the current scope
+ @scope.in_taxon(child).exists?
+ end
+
+ return nil if child_taxons.empty?
+
+ {
+ id: 'taxons',
+ type: 'taxon',
+ label: 'Category',
+ options: child_taxons.map { |t| taxon_option_data(t) }
+ }
+ end
+
+ def taxon_option_data(taxon)
+ count = @scope.in_taxon(taxon).distinct.count
+
+ {
+ id: taxon.prefix_id,
+ label: taxon.name,
+ permalink: taxon.permalink,
+ count: count
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/api/config/routes.rb b/api/config/routes.rb
index 88c60a24e6..eab4a2e72a 100644
--- a/api/config/routes.rb
+++ b/api/config/routes.rb
@@ -15,7 +15,11 @@ Spree::Core::Engine.add_routes do
resources :countries, only: [:index, :show]
# Catalog
- resources :products, only: [:index, :show]
+ resources :products, only: [:index, :show] do
+ collection do
+ get :filters, to: 'products/filters#index'
+ end
+ end
resources :taxonomies, only: [:index, :show]
resources :taxons, only: [:index, :show], id: /.+/ do
resources :products, only: [:index], controller: 'taxons/products'
diff --git a/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb b/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb
new file mode 100644
index 0000000000..86cd2ee4c9
--- /dev/null
+++ b/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb
@@ -0,0 +1,158 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Store::Products::FiltersController, type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ let(:taxonomy) { create(:taxonomy, store: store) }
+ let!(:taxon) { create(:taxon, taxonomy: taxonomy) }
+ let!(:child_taxon1) { create(:taxon, taxonomy: taxonomy, parent: taxon, name: 'Shirts') }
+ let!(:child_taxon2) { create(:taxon, taxonomy: taxonomy, parent: taxon, name: 'Pants') }
+
+ let(:option_type_size) { create(:option_type, name: 'size', presentation: 'Size', filterable: true, position: 1) }
+ let(:option_type_color) { create(:option_type, name: 'color', presentation: 'Color', filterable: true, position: 2) }
+ let(:option_value_small) { create(:option_value, option_type: option_type_size, name: 'small', presentation: 'S', position: 1) }
+ let(:option_value_medium) { create(:option_value, option_type: option_type_size, name: 'medium', presentation: 'M', position: 2) }
+ let(:option_value_red) { create(:option_value, option_type: option_type_color, name: 'red', presentation: 'Red', position: 1) }
+ let(:option_value_blue) { create(:option_value, option_type: option_type_color, name: 'blue', presentation: 'Blue', position: 2) }
+
+ let!(:product1) do
+ create(:product, stores: [store], status: 'active', taxons: [child_taxon1]).tap do |p|
+ p.option_types << option_type_size
+ p.option_types << option_type_color
+ variant = p.master
+ variant.option_values << option_value_small
+ variant.option_values << option_value_red
+ end
+ end
+
+ let!(:product2) do
+ create(:product, stores: [store], status: 'active', taxons: [child_taxon1]).tap do |p|
+ p.option_types << option_type_size
+ variant = p.master
+ variant.option_values << option_value_medium
+ end
+ end
+
+ let!(:product3) do
+ create(:product, stores: [store], status: 'active', taxons: [child_taxon2]).tap do |p|
+ p.option_types << option_type_color
+ variant = p.master
+ variant.option_values << option_value_blue
+ end
+ end
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ end
+
+ describe 'GET #index' do
+ it 'returns filter metadata' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response).to have_key('filters')
+ expect(json_response).to have_key('sort_options')
+ expect(json_response).to have_key('default_sort')
+ expect(json_response).to have_key('total_count')
+ end
+
+ it 'returns price filter' do
+ get :index
+
+ price_filter = json_response['filters'].find { |f| f['type'] == 'price_range' }
+ expect(price_filter).to be_present
+ expect(price_filter['id']).to eq('price')
+ expect(price_filter).to have_key('min')
+ expect(price_filter).to have_key('max')
+ expect(price_filter).to have_key('currency')
+ end
+
+ it 'returns availability filter' do
+ get :index
+
+ availability_filter = json_response['filters'].find { |f| f['type'] == 'availability' }
+ expect(availability_filter).to be_present
+ expect(availability_filter['options']).to include(
+ hash_including('id' => 'in_stock'),
+ hash_including('id' => 'out_of_stock')
+ )
+ end
+
+ it 'returns option type filters with counts' do
+ get :index
+
+ size_filter = json_response['filters'].find { |f| f['name'] == 'size' }
+ expect(size_filter).to be_present
+ expect(size_filter['type']).to eq('option')
+ expect(size_filter['label']).to eq('Size')
+
+ size_options = size_filter['options']
+ expect(size_options.map { |o| o['label'] }).to include('S', 'M')
+
+ small_option = size_options.find { |o| o['label'] == 'S' }
+ expect(small_option['count']).to eq(1)
+ end
+
+ it 'returns all sort options' do
+ get :index
+
+ sort_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'
+ )
+ end
+
+ it 'returns total product count' do
+ get :index
+
+ expect(json_response['total_count']).to eq(3)
+ end
+
+ context 'with taxon_id parameter' do
+ it 'scopes filters to taxon' do
+ get :index, params: { taxon_id: child_taxon1.prefix_id }
+
+ expect(json_response['total_count']).to eq(2) # Only products in child_taxon1
+ end
+
+ it 'returns child taxons as filter options' do
+ get :index, params: { taxon_id: taxon.prefix_id }
+
+ taxon_filter = json_response['filters'].find { |f| f['type'] == 'taxon' }
+ expect(taxon_filter).to be_present
+
+ taxon_options = taxon_filter['options']
+ expect(taxon_options.map { |t| t['label'] }).to include('Shirts', 'Pants')
+ end
+
+ it 'returns default_sort from taxon' do
+ taxon.update!(sort_order: 'price-low-to-high')
+
+ get :index, params: { taxon_id: taxon.prefix_id }
+
+ expect(json_response['default_sort']).to eq('price-low-to-high')
+ end
+ end
+
+ context 'with ransack query params' do
+ it 'applies ransack filters to scope' do
+ get :index, params: { q: { name_cont: product1.name } }
+
+ expect(json_response['total_count']).to eq(1)
+ end
+ end
+
+ context 'without API key' do
+ before { request.headers['X-Spree-Api-Key'] = nil }
+
+ it 'returns unauthorized' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+ end
+end
diff --git a/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb b/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
index 1b158a82a9..05de1992c8 100644
--- a/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
+++ b/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
@@ -114,6 +114,44 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
end
end
+ context 'sorting' do
+ let!(:cheap_product) do
+ create(:product, stores: [store], status: 'active', name: 'Cheap').tap do |p|
+ p.master.prices.first.update!(amount: 10.0)
+ end
+ end
+
+ let!(:expensive_product) do
+ create(:product, stores: [store], status: 'active', name: 'Expensive').tap do |p|
+ p.master.prices.first.update!(amount: 100.0)
+ end
+ end
+
+ it 'sorts by price low to high' do
+ get :index, params: { q: { sort_by: 'price-low-to-high' } }
+
+ expect(response).to have_http_status(:ok)
+ prices = json_response['data'].map { |p| p['price']['amount'].to_f }
+ expect(prices).to eq(prices.sort)
+ end
+
+ it 'sorts by price high to low' do
+ get :index, params: { q: { sort_by: 'price-high-to-low' } }
+
+ expect(response).to have_http_status(:ok)
+ prices = json_response['data'].map { |p| p['price']['amount'].to_f }
+ expect(prices).to eq(prices.sort.reverse)
+ end
+
+ it 'sorts by name a-z with ransack' do
+ get :index, params: { q: { s: 'name asc' } }
+
+ expect(response).to have_http_status(:ok)
+ names = json_response['data'].map { |p| p['name'] }
+ expect(names).to eq(names.sort)
+ end
+ end
+
context 'authentication' do
context 'without API key' do
before { request.headers['X-Spree-Api-Key'] = nil }
diff --git a/api/spec/controllers/spree/api/v3/store/taxons/products_controller_spec.rb b/api/spec/controllers/spree/api/v3/store/taxons/products_controller_spec.rb
index 62abcbe401..f5ba0ae148 100644
--- a/api/spec/controllers/spree/api/v3/store/taxons/products_controller_spec.rb
+++ b/api/spec/controllers/spree/api/v3/store/taxons/products_controller_spec.rb
@@ -97,5 +97,43 @@ RSpec.describe Spree::Api::V3::Store::Taxons::ProductsController, type: :control
expect(response).to have_http_status(:unauthorized)
end
end
+
+ context 'sorting' do
+ let!(:cheap_product) do
+ create(:product, stores: [store], taxons: [taxon], status: 'active', name: 'Cheap').tap do |p|
+ p.master.prices.first.update!(amount: 10.0)
+ end
+ end
+
+ let!(:expensive_product) do
+ create(:product, stores: [store], taxons: [taxon], status: 'active', name: 'Expensive').tap do |p|
+ p.master.prices.first.update!(amount: 100.0)
+ end
+ end
+
+ it 'sorts by price low to high' do
+ get :index, params: { taxon_id: taxon.permalink, q: { sort_by: 'price-low-to-high' } }
+
+ expect(response).to have_http_status(:ok)
+ prices = json_response['data'].map { |p| p['price']['amount'].to_f }
+ expect(prices).to eq(prices.sort)
+ end
+
+ it 'sorts by price high to low' do
+ get :index, params: { taxon_id: taxon.permalink, q: { sort_by: 'price-high-to-low' } }
+
+ expect(response).to have_http_status(:ok)
+ prices = json_response['data'].map { |p| p['price']['amount'].to_f }
+ expect(prices).to eq(prices.sort.reverse)
+ end
+
+ it 'sorts by name a-z with ransack' do
+ get :index, params: { taxon_id: taxon.permalink, q: { s: 'name asc' } }
+
+ expect(response).to have_http_status(:ok)
+ names = json_response['data'].map { |p| p['name'] }
+ expect(names).to eq(names.sort)
+ end
+ end
end
end
diff --git a/api/spec/services/spree/api/v3/filters_aggregator_spec.rb b/api/spec/services/spree/api/v3/filters_aggregator_spec.rb
new file mode 100644
index 0000000000..363e69f527
--- /dev/null
+++ b/api/spec/services/spree/api/v3/filters_aggregator_spec.rb
@@ -0,0 +1,129 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::FiltersAggregator do
+ let(:store) { @default_store }
+ let(:currency) { 'USD' }
+ let(:taxonomy) { create(:taxonomy, store: store) }
+ let(:taxon) { create(:taxon, taxonomy: taxonomy) }
+ let(:child_taxon) { create(:taxon, taxonomy: taxonomy, parent: taxon, name: 'Child') }
+
+ let(:option_type) { create(:option_type, name: 'size', presentation: 'Size', filterable: true) }
+ let(:option_value_s) { create(:option_value, option_type: option_type, name: 'small', presentation: 'S') }
+ let(:option_value_m) { create(:option_value, option_type: option_type, name: 'medium', presentation: 'M') }
+
+ let!(:product1) do
+ create(:product, stores: [store], status: 'active', taxons: [child_taxon]).tap do |p|
+ p.option_types << option_type
+ p.master.option_values << option_value_s
+ end
+ end
+
+ let!(:product2) do
+ create(:product, stores: [store], status: 'active', taxons: [child_taxon]).tap do |p|
+ p.option_types << option_type
+ p.master.option_values << option_value_m
+ end
+ end
+
+ let(:scope) { store.products.available(Time.current, currency) }
+
+ subject { described_class.new(scope: scope, currency: currency, taxon: taxon) }
+
+ describe '#call' do
+ let(:result) { subject.call }
+
+ it 'returns filters array' do
+ expect(result[:filters]).to be_an(Array)
+ end
+
+ it 'returns sort_options array' do
+ expect(result[:sort_options]).to be_an(Array)
+ expect(result[:sort_options].first).to include(id: 'manual', label: 'Default')
+ end
+
+ it 'returns default_sort from taxon' do
+ taxon.update!(sort_order: 'newest-first')
+ expect(result[:default_sort]).to eq('newest-first')
+ end
+
+ it 'returns manual as default_sort when no taxon' do
+ aggregator = described_class.new(scope: scope, currency: currency, taxon: nil)
+ expect(aggregator.call[:default_sort]).to eq('manual')
+ end
+
+ it 'returns total_count' do
+ expect(result[:total_count]).to eq(2)
+ end
+
+ describe 'price filter' do
+ it 'includes price range' do
+ price_filter = result[:filters].find { |f| f[:type] == 'price_range' }
+
+ expect(price_filter).to be_present
+ expect(price_filter[:min]).to be_a(Numeric)
+ expect(price_filter[:max]).to be_a(Numeric)
+ expect(price_filter[:currency]).to eq(currency)
+ end
+ end
+
+ describe 'availability filter' do
+ it 'includes in_stock and out_of_stock options' do
+ availability_filter = result[:filters].find { |f| f[:type] == 'availability' }
+
+ expect(availability_filter).to be_present
+ expect(availability_filter[:options].map { |o| o[:id] }).to contain_exactly('in_stock', 'out_of_stock')
+ end
+ end
+
+ describe 'option type filters' do
+ it 'includes filterable option types with values' do
+ size_filter = result[:filters].find { |f| f[:name] == 'size' }
+
+ expect(size_filter).to be_present
+ expect(size_filter[:type]).to eq('option')
+ expect(size_filter[:label]).to eq('Size')
+ end
+
+ it 'includes option values with counts' do
+ size_filter = result[:filters].find { |f| f[:name] == 'size' }
+ options = size_filter[:options]
+
+ expect(options.map { |o| o[:label] }).to contain_exactly('S', 'M')
+
+ s_option = options.find { |o| o[:label] == 'S' }
+ expect(s_option[:count]).to eq(1)
+ end
+
+ it 'excludes option types with no values in scope' do
+ empty_option_type = create(:option_type, name: 'material', presentation: 'Material', filterable: true)
+ create(:option_value, option_type: empty_option_type, name: 'cotton')
+
+ material_filter = result[:filters].find { |f| f[:name] == 'material' }
+ expect(material_filter).to be_nil
+ end
+ end
+
+ describe 'taxon filter' do
+ it 'includes child taxons when taxon is provided' do
+ taxon_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')
+ end
+
+ it 'does not include taxon filter when no taxon provided' do
+ aggregator = described_class.new(scope: scope, currency: currency, taxon: nil)
+ taxon_filter = aggregator.call[:filters].find { |f| f[:type] == 'taxon' }
+
+ expect(taxon_filter).to be_nil
+ end
+
+ it 'includes product count per taxon' do
+ taxon_filter = result[:filters].find { |f| f[:type] == 'taxon' }
+ child_option = taxon_filter[:options].find { |t| t[:label] == 'Child' }
+
+ expect(child_option[:count]).to eq(2)
+ 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 3622a8f26a..73f452a173 100644
--- a/core/app/models/concerns/spree/product_scopes.rb
+++ b/core/app/models/concerns/spree/product_scopes.rb
@@ -209,6 +209,24 @@ module Spree
where(Spree::OptionValue.table_name => { name: value, option_type_id: option_type_id })
end
+ # Filters products by option value IDs (prefix IDs like 'optval_xxx')
+ # Accepts an array of option value IDs
+ add_search_scope :with_option_value_ids do |*ids|
+ ids = ids.flatten.compact
+ return none if ids.empty?
+
+ # Handle prefix IDs (optval_xxx) by extracting the actual IDs
+ actual_ids = ids.map do |id|
+ id.to_s.start_with?('optval_') ? OptionValue.find_by(prefix_id: id)&.id : id
+ end.compact
+
+ return none if actual_ids.empty?
+
+ group("#{Spree::Product.table_name}.id").
+ joins(variants_including_master: :option_values).
+ where(Spree::OptionValue.table_name => { id: actual_ids })
+ end
+
# Finds all products which have either:
# 1) have an option value with the name matching the one given
# 2) have a product property with a value matching the one given
diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rb
index 7e8be938e5..14b4f93035 100644
--- a/core/app/models/spree/product.rb
+++ b/core/app/models/spree/product.rb
@@ -234,11 +234,12 @@ module Spree
alias options product_option_types
- self.whitelisted_ransackable_attributes = %w[description name slug discontinue_on status]
+ self.whitelisted_ransackable_attributes = %w[description name slug discontinue_on status available_on created_at updated_at]
self.whitelisted_ransackable_associations = %w[taxons stores variants_including_master master variants tags labels
shipping_category classifications option_types properties]
self.whitelisted_ransackable_scopes = %w[not_discontinued search_by_name in_taxon price_between
- multi_search in_stock_items out_of_stock_items]
+ multi_search in_stock_items out_of_stock_items with_option_value_ids
+ ascend_by_price descend_by_price]
[
:sku, :barcode, :weight, :height, :width, :depth, :is_master, :dimensions_unit, :weight_unit
diff --git a/sdk/src/client.ts b/sdk/src/client.ts
index c17cf2a000..f5cc2a93b4 100644
--- a/sdk/src/client.ts
+++ b/sdk/src/client.ts
@@ -6,6 +6,8 @@ import type {
PaginatedResponse,
ListParams,
ProductListParams,
+ ProductFiltersParams,
+ ProductFiltersResponse,
TaxonListParams,
OrderListParams,
AddLineItemParams,
@@ -89,7 +91,12 @@ export class SpreeClient {
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined) {
- url.searchParams.set(key, String(value));
+ // Handle arrays by appending each value with the same key (Rails-style)
+ if (Array.isArray(value)) {
+ value.forEach((v) => url.searchParams.append(key, String(v)));
+ } else {
+ url.searchParams.set(key, String(value));
+ }
}
});
}
@@ -202,6 +209,19 @@ export class SpreeClient {
...options,
params,
}),
+
+ /**
+ * Get available filters for products
+ * Returns filter options (price range, availability, option types, taxons) with counts
+ */
+ filters: (
+ params?: ProductFiltersParams,
+ options?: RequestOptions
+ ): Promise<ProductFiltersResponse> =>
+ this.request<ProductFiltersResponse>('GET', '/products/filters', {
+ ...options,
+ params: params as Record<string, string | number | undefined>,
+ }),
};
// ============================================
diff --git a/sdk/src/types/index.ts b/sdk/src/types/index.ts
index 271c588de3..87bf0865bb 100644
--- a/sdk/src/types/index.ts
+++ b/sdk/src/types/index.ts
@@ -104,3 +104,69 @@ export interface UpdateOrderParams {
bill_address_attributes?: AddressParams;
ship_address_attributes?: AddressParams;
}
+
+// Product Filters types
+export interface FilterOption {
+ id: string;
+ label: string;
+ count: number;
+}
+
+export interface OptionFilterOption extends FilterOption {
+ name: string;
+ position: number;
+}
+
+export interface TaxonFilterOption extends FilterOption {
+ permalink: string;
+}
+
+export interface PriceRangeFilter {
+ id: 'price';
+ type: 'price_range';
+ label: string;
+ min: number;
+ max: number;
+ currency: string;
+}
+
+export interface AvailabilityFilter {
+ id: 'availability';
+ type: 'availability';
+ label: string;
+ options: FilterOption[];
+}
+
+export interface OptionFilter {
+ id: string;
+ type: 'option';
+ label: string;
+ name: string;
+ options: OptionFilterOption[];
+}
+
+export interface TaxonFilter {
+ id: 'taxons';
+ type: 'taxon';
+ label: string;
+ options: TaxonFilterOption[];
+}
+
+export type ProductFilter = PriceRangeFilter | AvailabilityFilter | OptionFilter | TaxonFilter;
+
+export interface SortOption {
+ id: string;
+ label: string;
+}
+
+export interface ProductFiltersResponse {
+ filters: ProductFilter[];
+ sort_options: SortOption[];
+ default_sort: string;
+ total_count: number;
+}
+
+export interface ProductFiltersParams {
+ taxon_id?: string;
+ q?: Record<string, unknown>;
+}