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
Merge branch 'main' into 6-0-dev
Łukasz Adamczykdf09f85340dc
diff --cc CLAUDE.mdindex 9e869ca967,f41c82a331..143fb8b41e--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -24,11 -24,13 +24,13 @@@ Active plans (6.0 target, work pending)- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider)- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)- - `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator, drop Zone model (TaxRate gets direct country/state FKs)- - `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider, replaces Estimator + Calculator, DeliveryZone with postal code support+ - `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`)+ - `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod, enriched DeliveryRate (carrier/service/date/metadata)+ - `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window)- `6.0-rich-text-descriptions.md` — Drop ActionText storage, store HTML in text columns, sanitize on write, serve `description` + `description_html` in API (description_html serializer field shipped in 5.4)- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (renamed from Vendor — `Spree::Vendor` is the marketplace seller, see decisions.md 2026-07-14) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.-- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). `Spree::Category < Spree::Taxon` alias + Category API surface shipped in 5.5; table rename + Collection pending.+- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.+ - `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.Multi-version plans (some phases shipped, some pending):- `5.4-store-api-naming-standardization.md` — Standardize API naming against industry (address fields, discounts, customer_note, label, brand/last4, etc.). 5.4 model/API aliases shipped; 6.0 column/table renames pending.diff --cc spree/api/app/services/spree/api/v3/filters_aggregator.rbindex d0cf4fc2f4,54cc3d4e51..cd4b33987b--- a/spree/api/app/services/spree/api/v3/filters_aggregator.rb+++ b/spree/api/app/services/spree/api/v3/filters_aggregator.rb@@@ -38,7 -36,7 +38,7 @@@ module Spreenddef sort_options- Spree::Collection::SORT_ORDERS.map { |id| { id: to_api_sort(id) } }- Spree::Taxon::SORT_ORDERS.map { |id| { id: to_api_sort(id), label: nil } }++ Spree::Collection::SORT_ORDERS.map { |id| { id: to_api_sort(id), label: nil } }end# Converts internal sort format ('price asc') to API format ('price', '-price')diff --cc spree/core/app/models/spree/search_provider/database.rbindex 817207a10a,d72626ff7c..94657dc42c--- a/spree/core/app/models/spree/search_provider/database.rb+++ b/spree/core/app/models/spree/search_provider/database.rb@@@ -51,7 -45,8 +51,8 @@@ module Sprescope_before_optionsend- filter_facets = build_facets(scope_with_options, category: category, option_value_ids: option_value_ids, scope_before_options: scope_before_options)+ filter_facets = build_facets(scope_with_options, category: category, sort_order: collection&.sort_order, option_value_ids: option_value_ids, scope_before_options: scope_before_options)+ filter_facets[:sort_options] = filter_facets[:sort_options] + metafield_sort_optionsFiltersResult.new(filters: filter_facets[:filters],@@@ -79,8 -77,8 +83,8 @@@Pagy::Offset.new(count: count, page: page, limit: limit)end- def build_facets(scope, category: nil, option_value_ids: [], scope_before_options: nil)+ def build_facets(scope, category: nil, sort_order: nil, option_value_ids: [], scope_before_options: nil)- return { filters: [], sort_options: available_sort_options, default_sort: 'manual', total_count: scope.distinct.count } unless defined?(Spree::Api::V3::FiltersAggregator)+ return { filters: [], sort_options: built_in_sort_options, default_sort: 'manual', total_count: scope.distinct.count } unless defined?(Spree::Api::V3::FiltersAggregator)Spree::Api::V3::FiltersAggregator.new(scope: scope,@@@ -125,46 -118,48 +131,86 @@@endend+ # 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 } }+ # Project the ORDER BY expression into the SELECT list so PostgreSQL+ # accepts it when DISTINCT is applied. Null-rank keeps products without+ # the metafield last for both ASC and DESC.+ def apply_metafield_sort(scope, parsed)+ definition = metafield_schema.entry_for(parsed[:attribute])+ return scope unless definition++ products = Spree::Product.arel_table+ # Aliased so this join can't collide with the `filter_cf` correlated+ # subquery when a cf_* filter and a cf_* sort are combined.+ metafields = Spree::Metafield.arel_table.alias('sort_cf')++ sort_expr = Spree::Product.metafield_value_expression(metafields[:value], definition.field_type)+ # NULL-rank so products missing the metafield sort last (Meilisearch parity).+ # Projected as cf_sort_missing because PostgreSQL rejects (alias IS NULL) in ORDER BY.+ null_rank = sort_expr.eq(nil)++ direction = parsed[:direction] == 'desc' ? :desc : :asc++ join = products.+ outer_join(metafields).+ on(+ metafields[:resource_type].eq('Spree::Product').+ and(metafields[:resource_id].eq(products[:id])).+ and(metafields[:metafield_definition_id].eq(definition.id))+ ).+ join_sources++ scope.+ joins(join).+ select(products[Arel.star]).+ select(Arel::Nodes::As.new(sort_expr, Arel.sql('cf_sort_value'))).+ select(Arel::Nodes::As.new(null_rank, Arel.sql('cf_sort_missing'))).+ reorder(Arel.sql('cf_sort_missing').asc, sort_expr.public_send(direction))+ end++ def built_in_sort_options+ %w[price -price best_selling name -name -available_on available_on].map { |id| { id: id, label: nil } }+ end++ def metafield_sort_options+ metafield_schema.sort_optionsendendenddiff --cc spree/core/app/models/spree/search_provider/meilisearch.rbindex fc60029eab,e9b7b8525f..6e6407a864--- a/spree/core/app/models/spree/search_provider/meilisearch.rb+++ b/spree/core/app/models/spree/search_provider/meilisearch.rb@@@ -5,6 -5,8 +5,8 @@@ module Spreclass Meilisearch < BasePREFIXED_ID_PATTERN = /\A[a-z]+_[A-Za-z0-9]+\z/ALLOWED_STATUSES = %w[active draft archived paused].freeze- BUILT_IN_FILTERABLE_ATTRIBUTES = %w[product_id status in_stock preorder store_ids channel_ids locale currency available_on discontinue_on price category_ids tags option_value_ids].freeze++ BUILT_IN_FILTERABLE_ATTRIBUTES = %w[product_id status in_stock preorder store_ids channel_ids locale currency available_on discontinue_on price category_ids collection_ids grouping_id tags option_value_ids].freeze+ METAFIELD_RANGE_OPERATORS = { 'gt' => '>', 'gteq' => '>=', 'lt' => '<', 'lteq' => '<=' }.freezedef self.indexing_required?true@@@ -57,17 -53,17 +59,17 @@@unless ms_resultreturn FiltersResult.new(filters: [],- sort_options: available_sort_options.map { |id| { id: id } },+ sort_options: built_in_and_metafield_sort_options,- default_sort: 'manual',+ default_sort: default_sort,total_count: 0)endFiltersResult.new(filters: build_facet_response(facet_distribution),- sort_options: available_sort_options.map { |id| { id: id } },+ sort_options: built_in_and_metafield_sort_options,- default_sort: 'manual',- total_count: ms_result['estimatedTotalHits'] || 0+ default_sort: default_sort,+ total_count: ms_result['totalHits'] || 0)end@@@ -99,14 -92,10 +101,15 @@@enddef reindex(scope = nil)+ full_reindex = scope.nil?scope ||= store.products+ @metafield_schema = MetafieldSchema.newensure_index_settings!+ # On a full reindex, clear first so stale docs (e.g. membership docs for+ # removed groupings) don't linger; a scoped reindex keeps upsert semantics.+ client.index(index_name).delete_all_documents if full_reindex+indexed = 0scope.reorder(id: :asc).preload_associations_lazily@@@ -293,34 -251,24 +296,41 @@@enddef sortable_attributes- %w[name price created_at available_on units_sold_count position]- %w[name price created_at available_on units_sold_count] + metafield_schema.sortable_attribute_keys++ %w[name price created_at available_on units_sold_count position] + metafield_schema.sortable_attribute_keysend+ # Facets stay built-in only — cf_* distributions aren't consumed by+ # +build_facet_response+, so requesting them would be wasted work.def facet_attributes- filterable_attributes+ BUILT_IN_FILTERABLE_ATTRIBUTESend+ # Collapses the per-grouping membership docs to one row per product on+ # non-grouping queries (shop-all, search, non-manual sorts). Facet counts+ # and totals honor distinct on Meilisearch >= 1.40.+ def distinct_attribute+ 'product_id'+ end++ # Sourced from Spree::Collection::SORT_ORDERS (matching FiltersAggregator) so+ # both providers advertise identical options — including 'manual'.def available_sort_options- Spree::Collection::SORT_ORDERS.map { |sort_order| to_api_sort(sort_order) }- %w[price -price name -name -available_on available_on best_selling] + metafield_schema.sort_ids++ Spree::Collection::SORT_ORDERS.map { |sort_order| to_api_sort(sort_order) } + metafield_schema.sort_ids+ end++ # Converts internal sort format ('price asc') to API format ('price', '-price').+ def to_api_sort(sort_value)+ return sort_value unless sort_value.to_s.include?(' ')++ field, direction = sort_value.split(' ', 2)+ direction == 'desc' ? "-#{field}" : fieldend+ def built_in_and_metafield_sort_options- %w[price -price name -name -available_on available_on best_selling].map { |id| { id: id, label: nil } } +++ Spree::Collection::SORT_ORDERS.map { |sort_order| { id: to_api_sort(sort_order), label: nil } } ++ metafield_schema.sort_options+ end+# Build Meilisearch filter conditions from API params.# Combines system scoping (always applied) with user-facing filters.def build_filters(filters)diff --cc spree/core/spec/models/spree/search_provider/database_spec.rbindex dec5c2ad6c,58cf235299..d6235613e3--- a/spree/core/spec/models/spree/search_provider/database_spec.rb+++ b/spree/core/spec/models/spree/search_provider/database_spec.rb@@@ -195,75 -195,184 +195,254 @@@ module Spreendend+ 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 searchable metafields' do+ let!(:definition) do+ create(:metafield_definition, :short_text_field, :searchable,+ namespace: 'custom', key: 'label')+ end++ before do+ product_2.set_metafield(definition, 'wool-blend')+ end++ it 'finds products by searchable metafield value' do+ result = provider.search_and_filter(scope: scope, query: 'wool')+ expect(result.products).to include(product_2)+ expect(result.products).not_to include(product_1, product_3)+ end+ end++ context 'with sortable metafields' do+ let!(:definition) do+ create(:metafield_definition, :short_text_field, :sortable,+ namespace: 'custom', key: 'label')+ end++ before do+ product_1.set_metafield(definition, 'charlie')+ product_2.set_metafield(definition, 'alpha')+ product_3.set_metafield(definition, 'bravo')+ end++ it 'sorts ascending by cf_* attribute' do+ result = provider.search_and_filter(scope: scope, sort: 'cf_custom_label')+ expect(result.products.map(&:id)).to eq([product_2.id, product_3.id, product_1.id])+ end++ it 'sorts descending by -cf_* attribute' do+ result = provider.search_and_filter(scope: scope, sort: '-cf_custom_label')+ expect(result.products.map(&:id)).to eq([product_1.id, product_3.id, product_2.id])+ end++ it 'sorts with Ransack filters present (SELECT DISTINCT compatible)' do+ result = provider.search_and_filter(+ scope: scope,+ filters: { 'name_cont' => 'Blue' },+ sort: 'cf_custom_label'+ )+ expect(result.products.map(&:id)).to eq([product_3.id, product_1.id])+ end++ context 'with missing metafield values' do+ before do+ product_2.metafields.destroy_all+ end++ it 'keeps missing values last when sorting ascending' do+ result = provider.search_and_filter(scope: scope, sort: 'cf_custom_label')+ expect(result.products.map(&:id)).to eq([product_3.id, product_1.id, product_2.id])+ end++ it 'keeps missing values last when sorting descending' do+ result = provider.search_and_filter(scope: scope, sort: '-cf_custom_label')+ expect(result.products.map(&:id)).to eq([product_1.id, product_3.id, product_2.id])+ end+ end+ end++ context 'with metafield filters' do+ let!(:material) do+ create(:metafield_definition, :short_text_field, :searchable,+ namespace: 'custom', key: 'material')+ end+ let!(:weight) do+ create(:metafield_definition, :number_field, :sortable,+ namespace: 'custom', key: 'weight')+ end++ before do+ product_1.set_metafield(material, 'wool-blend')+ product_2.set_metafield(material, 'cotton')+ product_1.set_metafield(weight, '10')+ product_2.set_metafield(weight, '2')+ product_3.set_metafield(weight, '3.5')+ end++ it 'filters text values with cont' do+ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_material_cont' => 'wool' })+ expect(result.products).to contain_exactly(product_1)+ expect(result.total_count).to eq(1)+ end++ it 'filters text values case-insensitively with i_cont' do+ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_material_i_cont' => 'WOOL' })+ expect(result.products).to contain_exactly(product_1)+ end++ it 'filters text values with eq' do+ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_material_eq' => 'cotton' })+ expect(result.products).to contain_exactly(product_2)+ end++ it 'filters text values with not_eq (value set and different)' do+ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_material_not_eq' => 'cotton' })+ expect(result.products).to contain_exactly(product_1)+ end++ it 'filters text values with start and end' do+ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_material_start' => 'wool' })+ expect(result.products).to contain_exactly(product_1)++ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_material_end' => 'blend' })+ expect(result.products).to contain_exactly(product_1)+ end++ it 'filters numerically rather than lexicographically' do+ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_weight_gteq' => '3' })+ expect(result.products).to contain_exactly(product_1, product_3)++ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_weight_lt' => '3' })+ expect(result.products).to contain_exactly(product_2)+ end++ it 'filters with present and blank' do+ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_material_present' => '1' })+ expect(result.products).to contain_exactly(product_1, product_2)++ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_material_blank' => '1' })+ expect(result.products).to contain_exactly(product_3)+ end++ it 'combines metafield and ransack filters' do+ result = provider.search_and_filter(+ scope: scope,+ filters: { 'name_cont' => 'Blue', 'cf_custom_weight_gteq' => '5' }+ )+ expect(result.products).to contain_exactly(product_1)+ end++ it 'combines metafield filters with metafield sort' do+ result = provider.search_and_filter(+ scope: scope,+ filters: { 'cf_custom_weight_gteq' => '3' },+ sort: '-cf_custom_weight'+ )+ expect(result.products.map(&:id)).to eq([product_1.id, product_3.id])+ end++ it 'ignores non-numeric values on number predicates' do+ result = provider.search_and_filter(scope: scope, filters: { 'cf_custom_weight_gteq' => 'abc' })+ expect(result.total_count).to eq(3)+ end++ it 'ignores cf_ keys that match no definition' do+ result = provider.search_and_filter(scope: scope, filters: { 'cf_bogus_field_eq' => 'x' })+ 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)+ endend++ context 'with sortable number metafields' do+ let!(:definition) do+ create(:metafield_definition, :number_field, :sortable,+ namespace: 'custom', key: 'weight')+ end++ before do+ product_1.set_metafield(definition, '10')+ product_2.set_metafield(definition, '2')+ product_3.set_metafield(definition, '3')+ end++ it 'sorts ascending numerically rather than lexicographically' do+ result = provider.search_and_filter(scope: scope, sort: 'cf_custom_weight')+ expect(result.products.map(&:id)).to eq([product_2.id, product_3.id, product_1.id])+ end++ it 'sorts descending numerically' do+ result = provider.search_and_filter(scope: scope, sort: '-cf_custom_weight')+ expect(result.products.map(&:id)).to eq([product_1.id, product_3.id, product_2.id])+ end+ endenddescribe '#filters' dodiff --cc spree/core/spec/models/spree/search_provider/meilisearch_spec.rbindex 5ec7be4f2b,539506cfa3..a16f6baa83--- a/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb+++ b/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb@@@ -458,29 -356,79 +481,102 @@@ module Spreexpect(mock_index).to receive(:add_documents).at_least(:once)provider.reindex(store.products)end++ it 'clears the index before a full (unscoped) reindex' do+ expect(mock_index).to receive(:delete_all_documents)+ allow(mock_index).to receive(:add_documents)+ provider.reindex+ end++ it 'does not clear the index for a scoped reindex' do+ expect(mock_index).not_to receive(:delete_all_documents)+ allow(mock_index).to receive(:add_documents)+ provider.reindex(store.products)+ end+ end++ describe '#ensure_index_settings!' do+ it 'declares grouping_id filterable, position sortable, and product_id distinct' do+ expect(mock_index).to receive(:update_filterable_attributes).with(include('grouping_id'))+ expect(mock_index).to receive(:update_sortable_attributes).with(include('position'))+ expect(mock_index).to receive(:update_distinct_attribute).with('product_id')+ allow(mock_index).to receive(:update_searchable_attributes)++ provider.ensure_index_settings!+ endend++ describe 'metafield searchable / sortable settings' do+ let!(:definition) do+ create(:metafield_definition, :short_text_field, :searchable, :sortable,+ namespace: 'custom', key: 'label')+ end++ it 'includes cf_* in searchable and sortable attributes' do+ expect(provider.send(:searchable_attributes)).to include('cf_custom_label')+ expect(provider.send(:sortable_attributes)).to include('cf_custom_label')+ end++ it 'includes cf_* in filterable attributes but not in requested facets' do+ expect(provider.send(:filterable_attributes)).to include('cf_custom_label')+ expect(provider.send(:facet_attributes)).not_to include('cf_custom_label')+ end++ it 'maps cf_* sort params without namespace resolution' do+ expect(provider.send(:sort_mapping, 'cf_custom_label')).to eq(['cf_custom_label:asc'])+ expect(provider.send(:sort_mapping, '-cf_custom_label')).to eq(['cf_custom_label:desc'])+ end+ end++ describe 'metafield filter conditions' do+ let!(:label) do+ create(:metafield_definition, :short_text_field, :searchable,+ namespace: 'custom', key: 'label')+ end+ let!(:weight) do+ create(:metafield_definition, :number_field, :sortable,+ namespace: 'custom', key: 'weight')+ end++ it 'builds equality conditions for text metafields' do+ expect(provider.send(:build_filter_condition, 'cf_custom_label_eq', 'wool')).to eq("cf_custom_label = 'wool'")+ expect(provider.send(:build_filter_condition, 'cf_custom_label_not_eq', 'wool')).to eq("cf_custom_label != 'wool'")+ end++ it 'escapes quotes and backslashes in text values' do+ expect(provider.send(:build_filter_condition, 'cf_custom_label_eq', "o'brien\\x")).to eq("cf_custom_label = 'o\\'brien\\\\x'")+ end++ it 'builds range conditions for number metafields' do+ expect(provider.send(:build_filter_condition, 'cf_custom_weight_gteq', '3.5')).to eq('cf_custom_weight >= 3.5')+ expect(provider.send(:build_filter_condition, 'cf_custom_weight_lt', '10')).to eq('cf_custom_weight < 10.0')+ end++ it 'builds EXISTS conditions for present and blank' do+ expect(provider.send(:build_filter_condition, 'cf_custom_label_present', '1')).to eq('cf_custom_label EXISTS')+ expect(provider.send(:build_filter_condition, 'cf_custom_label_blank', '1')).to eq('cf_custom_label NOT EXISTS')+ end++ it 'ignores substring predicates Meilisearch cannot filter on' do+ expect(provider.send(:build_filter_condition, 'cf_custom_label_cont', 'wool')).to be_nil+ end++ it 'ignores non-numeric values on number predicates' do+ expect(provider.send(:build_filter_condition, 'cf_custom_weight_gteq', 'abc')).to be_nil+ end++ it 'ignores unknown cf_ keys' do+ expect(provider.send(:build_filter_condition, 'cf_bogus_field_eq', 'x')).to be_nil+ end++ it 'passes metafield conditions through to the Meilisearch query' do+ ms_response = { 'hits' => [], 'estimatedTotalHits' => 0, 'facetDistribution' => {} }+ expect(mock_index).to receive(:search).with(anything, hash_including(+ filter: include('cf_custom_weight >= 3.5')+ )).and_return(ms_response)++ provider.search_and_filter(scope: store.products, filters: { 'cf_custom_weight_gteq' => '3.5' })+ end+ endendend