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
Fixed V-3350 filtering by categories in API
Damian Legawiec3b8825dab1ca
diff --git a/docs/api-reference/store-api/querying.mdx b/docs/api-reference/store-api/querying.mdxindex 7755f76461..2ab058e0e2 100644--- a/docs/api-reference/store-api/querying.mdx+++ b/docs/api-reference/store-api/querying.mdx@@ -87,9 +87,14 @@ You can filter by associated model attributes using underscore notation:<CodeGroup>```typescript SDK-// Products in a specific category+// Products in a specific category (includes descendants)const products = await client.products.list({- categories_id_eq: 'ctg_abc123',+ in_category: 'ctg_abc123',+})++// Multiple categories (OR logic, checkbox filters)+const products = await client.products.list({+ in_categories: ['ctg_abc123', 'ctg_def456'],})// Categories at a specific depth@@ -99,10 +104,10 @@ const categories = await client.categories.list({``````bash cURL-# Products in a specific category+# Products in a specific category (includes descendants)curl -G 'http://localhost:3000/api/v3/store/products' \-H 'X-Spree-Api-Key: spree_pk_xxx' \- --data-urlencode 'q[categories_id_eq]=ctg_abc123'+ --data-urlencode 'q[in_category]=ctg_abc123'# Top-level categories onlycurl -G 'http://localhost:3000/api/v3/store/categories' \diff --git a/docs/api-reference/store.yaml b/docs/api-reference/store.yamlindex 5ff05b8f44..4f5ce804ce 100644--- a/docs/api-reference/store.yaml+++ b/docs/api-reference/store.yaml@@ -7943,12 +7943,20 @@ paths:description: Filter by name containing stringschema:type: string- - name: q[categories_id_eq]+ - name: q[in_category]in: queryrequired: false- description: Filter by category ID+ description: Filter by category prefixed ID (includes descendants)schema:type: string+ - name: q[in_categories][]+ in: query+ required: false+ description: Filter by multiple category prefixed IDs (OR logic, includes descendants)+ schema:+ type: array+ items:+ type: string- name: q[price_gte]in: queryrequired: falsediff --git a/docs/developer/core-concepts/search-filtering.mdx b/docs/developer/core-concepts/search-filtering.mdxindex 8422d0c0f5..8bd0fa7658 100644--- a/docs/developer/core-concepts/search-filtering.mdx+++ b/docs/developer/core-concepts/search-filtering.mdx@@ -80,9 +80,14 @@ const { data: products } = await client.categories.products.list('clothing/shirtlimit: 12,})-// Or filter by category ID+// Or filter by category ID (includes descendants)const { data: products } = await client.products.list({- categories_id_eq: 'ctg_xxx',+ in_category: 'ctg_xxx',+})++// Multiple categories (OR logic, checkbox filters)+const { data: products } = await client.products.list({+ in_categories: ['ctg_shirts', 'ctg_pants'],})```@@ -91,8 +96,12 @@ const { data: products } = await client.products.list({curl 'https://api.mystore.com/api/v3/store/categories/clothing/shirts/products?limit=12' \-H 'Authorization: Bearer spree_pk_xxx'-# Filter by category ID-curl 'https://api.mystore.com/api/v3/store/products?q[categories_id_eq]=ctg_xxx' \+# Filter by category ID (includes descendants)+curl 'https://api.mystore.com/api/v3/store/products?q[in_category]=ctg_xxx' \+ -H 'Authorization: Bearer spree_pk_xxx'++# Multiple categories (OR logic)+curl 'https://api.mystore.com/api/v3/store/products?q[in_categories][]=ctg_shirts&q[in_categories][]=ctg_pants' \-H 'Authorization: Bearer spree_pk_xxx'```diff --git a/docs/plans/5.4-search-provider.md b/docs/plans/5.4-search-provider.mdindex 285cca2b64..94910b2d79 100644--- a/docs/plans/5.4-search-provider.md+++ b/docs/plans/5.4-search-provider.md@@ -162,7 +162,7 @@ module Spree## @param scope [ActiveRecord::Relation] base scope (store-scoped, visibility-filtered, authorized)# @param query [String, nil] text search query- # @param filters [Hash] structured filters (price_gte, with_option_value_ids, categories_id_eq, etc.)+ # @param filters [Hash] structured filters (price_gte, with_option_value_ids, in_category, in_categories, etc.)# @param sort [String, nil] sort param (e.g. 'price', '-price', 'best_selling')# @param page [Integer] page number# @param limit [Integer] results per pagediff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.mdindex 6767012b9b..9e176c4328 100644--- a/packages/sdk/CHANGELOG.md+++ b/packages/sdk/CHANGELOG.md@@ -7,6 +7,12 @@- **Webhook signature verification** — new `@spree/sdk/webhooks` subpath export with `verifyWebhookSignature()` for HMAC-SHA256 signature verification with replay protection. Works with any framework (Express, Hono, Cloudflare Workers, Next.js, etc.)- **Webhook event types** — `WebhookEvent<T>` generic envelope type. Use existing SDK types (`Order`, `Payment`, `Fulfillment`, etc.) as the type parameter — webhook payloads use the same V3 serializers as the REST API+### Bug Fixes++- **Category filtering** — replaced `categories_id_eq` with `in_category` and `in_categories` scopes. Category filters now correctly include products in descendant categories, fixing empty results on multi-level taxonomy PLPs+ - `in_category` — single category prefixed ID, includes descendants+ - `in_categories` — array of category prefixed IDs, OR logic (checkbox filters), each includes descendants+## 0.16.0### Breaking Changesdiff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.tsindex 5bc5360b9c..39594895b6 100644--- a/packages/sdk/src/types/index.ts+++ b/packages/sdk/src/types/index.ts@@ -171,8 +171,10 @@ export interface ProductListParams extends ListParams {in_stock?: boolean;/** Filter: only out-of-stock products */out_of_stock?: boolean;- /** Filter: products in category */- categories_id_eq?: string;+ /** Filter: products in category (includes descendants) */+ in_category?: string;+ /** Filter: products in any of the given categories (includes descendants, OR logic) */+ in_categories?: string[];/** Any additional Ransack predicate */[key: string]: string | number | boolean | (string | number)[] | undefined;}diff --git a/packages/sdk/tests/params.test.ts b/packages/sdk/tests/params.test.tsindex b11ac0f8c3..29b0fa5783 100644--- a/packages/sdk/tests/params.test.ts+++ b/packages/sdk/tests/params.test.ts@@ -99,7 +99,7 @@ describe('transformListParams', () => {sort: '-created_at',name_cont: 'shirt',price_gte: 20,- categories_id_eq: 'ctg_abc123',+ in_category: 'ctg_abc123',});expect(result).toEqual({page: 1,@@ -108,7 +108,7 @@ describe('transformListParams', () => {sort: '-created_at','q[name_cont]': 'shirt','q[price_gte]': 20,- 'q[categories_id_eq]': 'ctg_abc123',+ 'q[in_category]': 'ctg_abc123',});});});diff --git a/spree/admin/config/locales/en.yml b/spree/admin/config/locales/en.ymlindex f0076f148a..3f77bad0ef 100644--- a/spree/admin/config/locales/en.yml+++ b/spree/admin/config/locales/en.yml@@ -426,7 +426,6 @@ en:health_label: Healthnew: New Webhook Endpointre_enable: Re-enable- re_enable: Re-enablesecret_key: Secret Keysecret_key_help: Use this key to verify webhook signatures. Keep it secure and do not share it publicly.send_test: Send Testdiff --git a/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rbindex eefeed469d..19a78a6c96 100644--- a/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb@@ -133,7 +133,7 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARCdescribe 'filtering by category' doit 'filters by category ID' do- get :index, params: { q: { categories_id_eq: clothing_category.prefixed_id } }+ get :index, params: { q: { in_category: clothing_category.prefixed_id } }expect(response).to have_http_status(:ok)names = json_response['data'].map { |p| p['name'] }@@ -173,7 +173,7 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARCendit 'searches text and filters by category' do- get :index, params: { q: { search: 'blue', categories_id_eq: shoes_category.prefixed_id } }+ get :index, params: { q: { search: 'blue', in_category: shoes_category.prefixed_id } }expect(response).to have_http_status(:ok)names = json_response['data'].map { |p| p['name'] }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 9ede774e89..b32693668d 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@@ -54,8 +54,10 @@ RSpec.describe 'Products API', type: :request, swagger_doc: 'api-reference/storedescription: 'Sort order. Prefix with - for descending. Values: price, -price, best_selling, name, -name, -available_on, available_on'parameter name: 'q[name_cont]', in: :query, type: :string, required: false,description: 'Filter by name containing string'- parameter name: 'q[categories_id_eq]', in: :query, type: :string, required: false,- description: 'Filter by category ID'+ parameter name: 'q[in_category]', in: :query, type: :string, required: false,+ description: 'Filter by category prefixed ID (includes descendants)'+ parameter name: 'q[in_categories][]', in: :query, type: :string, required: false,+ description: 'Filter by multiple category prefixed IDs (OR logic, includes descendants)'parameter name: 'q[price_gte]', in: :query, type: :number, required: false,description: 'Filter by minimum price'parameter name: 'q[price_lte]', in: :query, type: :number, required: false,diff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rbindex 8440bdb536..42935cb09d 100644--- a/spree/core/app/models/concerns/spree/product_scopes.rb+++ b/spree/core/app/models/concerns/spree/product_scopes.rb@@ -147,8 +147,32 @@ module Spreewhere("#{Classification.table_name}.taxon_id" => taxon.cached_self_and_descendants_ids).distinct}- # Alias for in_taxon — public API name- scope :in_category, ->(category) { in_taxon(category) }+ # Products in a category AND all its descendants.+ # Accepts a Category record or a prefixed ID string (e.g. 'ctg_xxx').+ def self.in_category(category_or_id)+ category = category_or_id.is_a?(String) ? Spree::Taxon.find_by_prefix_id(category_or_id) : category_or_id+ return none unless category++ in_taxon(category)+ end++ # Products in ANY of the given categories (OR logic), each including descendants.+ # Accepts an array of Category records, prefixed ID strings, or a mix.+ def self.in_categories(*categories_or_ids)+ categories_or_ids = categories_or_ids.flatten.compact+ return none if categories_or_ids.empty?++ ids, records = categories_or_ids.partition { |c| c.is_a?(String) }+ if ids.any?+ decoded = ids.filter_map { |id| Spree::Taxon.decode_prefixed_id(id) }+ records += Spree::Taxon.where(id: decoded).to_a if decoded.any?+ end+ return none if records.empty?++ taxon_ids = records.flat_map(&:cached_self_and_descendants_ids).uniq++ joins(:classifications).where(Classification.table_name => { taxon_id: taxon_ids }).distinct+ end# Deprecated — remove in 6.0. Use in_taxon instead.def self.in_taxons(*taxons)diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex 70c01dbbc1..f262b419cb 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -200,7 +200,7 @@ module Spreeself.whitelisted_ransackable_attributes = %w[description name slug discontinue_on status available_on created_at updated_at]self.whitelisted_ransackable_associations = %w[taxons categories 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+ self.whitelisted_ransackable_scopes = %w[not_discontinued search_by_name in_taxon in_category in_categories price_betweenprice_lte price_gtesearch multi_search in_stock out_of_stock with_option_value_idsdiff --git a/spree/core/app/models/spree/search_provider/base.rb b/spree/core/app/models/spree/search_provider/base.rbindex eaa42c7cc9..c8e6b9da3e 100644--- a/spree/core/app/models/spree/search_provider/base.rb+++ b/spree/core/app/models/spree/search_provider/base.rb@@ -17,7 +17,7 @@ module Spree## @param scope [ActiveRecord::Relation] base scope (store-scoped, visibility-filtered, authorized)# @param query [String, nil] text search query- # @param filters [Hash] structured filters (price_gte, with_option_value_ids, categories_id_eq, etc.)+ # @param filters [Hash] structured filters (price_gte, with_option_value_ids, in_category, in_categories, etc.)# @param sort [String, nil] sort param (e.g. 'price', '-price', 'best_selling')# @param page [Integer] page number# @param limit [Integer] results per pagediff --git a/spree/core/app/models/spree/search_provider/meilisearch.rb b/spree/core/app/models/spree/search_provider/meilisearch.rbindex 677e618e62..4b43a325cd 100644--- a/spree/core/app/models/spree/search_provider/meilisearch.rb+++ b/spree/core/app/models/spree/search_provider/meilisearch.rb@@ -198,8 +198,10 @@ module Spree'in_stock = true' if value.to_s != '0'when 'out_of_stock''in_stock = false' if value.to_s != '0'- when 'categories_id_eq'+ when 'in_category'"category_ids = '#{sanitize_prefixed_id(value)}'" if valid_prefixed_id?(value)+ when 'in_categories'+ Array(value).filter_map { |id| "category_ids = '#{sanitize_prefixed_id(id)}'" if valid_prefixed_id?(id) }when 'with_option_value_ids'Array(value).filter_map { |ov| "option_value_ids = '#{sanitize_prefixed_id(ov)}'" if valid_prefixed_id?(ov) }enddiff --git a/spree/core/spec/models/spree/search_provider/database_spec.rb b/spree/core/spec/models/spree/search_provider/database_spec.rbindex 4a4264ba04..aa247138d8 100644--- a/spree/core/spec/models/spree/search_provider/database_spec.rb+++ b/spree/core/spec/models/spree/search_provider/database_spec.rb@@ -118,6 +118,52 @@ module Spreeexpect(result.products).not_to include(product_2, product_3)endend++ context 'with in_category filter' do+ let(:taxonomy) { create(:taxonomy, store: store) }+ let(:parent_taxon) { create(:taxon, taxonomy: taxonomy, name: 'Clothing') }+ let(:child_taxon) { create(:taxon, taxonomy: taxonomy, parent: parent_taxon, name: 'Shirts') }++ before do+ product_1.taxons << child_taxon+ product_2.taxons << parent_taxon+ end++ it 'returns products directly in the category' do+ result = provider.search_and_filter(scope: scope, filters: { 'in_category' => child_taxon.prefixed_id })+ expect(result.products).to include(product_1)+ expect(result.products).not_to include(product_2, product_3)+ end++ it 'returns products in descendant categories when filtering by parent' do+ result = provider.search_and_filter(scope: scope, filters: { 'in_category' => parent_taxon.prefixed_id })+ expect(result.products).to include(product_1, product_2)+ expect(result.products).not_to include(product_3)+ end++ it 'returns no products for an invalid category ID' do+ result = provider.search_and_filter(scope: scope, filters: { 'in_category' => 'ctg_nonexistent' })+ expect(result.products).to be_empty+ expect(result.total_count).to eq(0)+ end+ end++ context 'with in_categories filter (multiple, OR logic)' do+ let(:taxonomy) { create(:taxonomy, store: store) }+ let(:shirts_taxon) { create(:taxon, taxonomy: taxonomy, name: 'Shirts') }+ let(:pants_taxon) { create(:taxon, taxonomy: taxonomy, name: 'Pants') }++ before do+ product_1.taxons << shirts_taxon+ product_2.taxons << pants_taxon+ end++ it 'returns products in any of the given categories' do+ result = provider.search_and_filter(scope: scope, filters: { 'in_categories' => [shirts_taxon.prefixed_id, pants_taxon.prefixed_id] })+ expect(result.products).to include(product_1, product_2)+ expect(result.products).not_to include(product_3)+ end+ endenddescribe '#index' do