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.

Wire search provider into Store API controllers, add documentation

Damian Legawiecf4ad1e2391e8
diff --git a/CLAUDE.md b/CLAUDE.md
index 314c127a9a..1e746a11a9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -24,6 +24,8 @@ Current plans:
- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain
- `6.0-channels-catalogs-b2b.md` — Channel, Catalog, ProductListing (replaces StoreProduct), Company/CompanyLocation/CompanyContact for B2B
- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename
+- `6.0-search-provider.md` — Pluggable SearchProvider interface (Database default, Meilisearch/Elasticsearch/Algolia adapters), MetafieldDefinition faceting, autocomplete endpoint
+- `6.0-tax-provider.md` — Pluggable TaxProvider interface (Internal default, Avalara/TaxJar/Vertex adapters), estimate/commit/void lifecycle, tax exemption certificates
- `5.x-store-api-bridges.md` — Bridge 6.0 naming into 5.5 Store API (fulfillments, delivery, status, remove master_variant)
- `spree-starter-and-create-spree-app.md` — Replace monorepo server/ with spree-starter template repo, always include backend/ in create-spree-app, add spree eject
diff --git a/docs/developer/customization/search-providers.mdx b/docs/developer/customization/search-providers.mdx
new file mode 100644
index 0000000000..f0548a0a90
--- /dev/null
+++ b/docs/developer/customization/search-providers.mdx
@@ -0,0 +1,179 @@
+---
+title: Search Providers
+description: "Replace the default database search with Meilisearch, Elasticsearch, or a custom search engine"
+---
+
+## Overview
+
+Spree uses a pluggable search provider architecture. The search provider handles product search, filtering, sorting, and faceted navigation. By default, Spree uses SQL-based search (ILIKE queries via Ransack). You can replace it with an external search engine like [Meilisearch](/integrations/search/meilisearch) for typo tolerance, relevance ranking, and faster faceted search.
+
+## Architecture
+
+```
+Store API Request
+ │
+ ├─ AR Scope (security + visibility)
+ │ store.products.active(currency).accessible_by(ability)
+ │
+ └─ Search Provider (search + filter + facets)
+ ├─ Database (default): ILIKE + Ransack + FiltersAggregator
+ └─ Meilisearch: one API call for search + filter + facets
+```
+
+The controller builds a base ActiveRecord scope for **security and visibility** (store scoping, active products, authorization), then delegates **everything else** to the search provider — text search, structured filtering, sorting, pagination, and facet aggregation.
+
+## Configuration
+
+Set the search provider in `config/initializers/spree.rb`:
+
+```ruby
+# Default — SQL-based search (no external dependencies)
+Spree.search_provider = 'Spree::SearchProvider::Database'
+
+# Meilisearch — recommended for production
+Spree.search_provider = 'Spree::SearchProvider::Meilisearch'
+```
+
+## Built-in Providers
+
+### Database (default)
+
+`Spree::SearchProvider::Database` wraps the existing Ransack + ILIKE search. No external dependencies. Suitable for development and small catalogs (< 10,000 products).
+
+- Text search: ILIKE on product name + variant SKU
+- Filtering: Ransack query params (price, options, categories, stock)
+- Facets: `FiltersAggregator` with per-option-value counts
+- Sorting: Ransack + custom scopes (price, best_selling)
+
+### Meilisearch
+
+`Spree::SearchProvider::Meilisearch` uses [Meilisearch](https://www.meilisearch.com/) for search, filtering, and faceting in a single API call. Recommended for production. See the [Meilisearch integration guide](/integrations/search/meilisearch) for setup instructions.
+
+## Building a Custom Search Provider
+
+Create a class that inherits from `Spree::SearchProvider::Base` and implements `search_and_filter`:
+
+```ruby
+# app/models/my_app/search_provider/typesense.rb
+module MyApp
+ module SearchProvider
+ class Typesense < Spree::SearchProvider::Base
+ def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)
+ # 1. Query your search engine
+ results = typesense_client.collections['products'].documents.search({
+ q: query || '*',
+ query_by: 'name,description,sku',
+ filter_by: build_filters(filters),
+ sort_by: build_sort(sort),
+ page: page,
+ per_page: limit,
+ facet_by: 'category_ids,in_stock,price'
+ })
+
+ # 2. Get product IDs from search results
+ ids = results['hits'].map { |h| h['document']['id'] }
+
+ # 3. Intersect with AR scope for security/visibility
+ products = ids.any? ? scope.where(id: ids).in_order_of(:id, ids) : scope.none
+
+ # 4. Return a SearchResult
+ Spree::SearchProvider::SearchResult.new(
+ products: products,
+ filters: build_facet_response(results['facet_counts']),
+ sort_options: %w[price -price name -name -available_on],
+ total_count: results['found']
+ )
+ end
+
+ # Index a product (called via background job on product save)
+ def index(product)
+ document = Spree::SearchProvider::ProductPresenter.new(product, store).call
+ typesense_client.collections['products'].documents.upsert(document)
+ end
+
+ def remove(product)
+ remove_by_id(product.id)
+ end
+
+ def remove_by_id(product_id)
+ typesense_client.collections['products'].documents[product_id].delete
+ end
+
+ def reindex(scope = nil)
+ scope ||= store.products
+ scope.find_in_batches(batch_size: 500) do |batch|
+ documents = batch.map { |p| Spree::SearchProvider::ProductPresenter.new(p, store).call }
+ typesense_client.collections['products'].documents.import(documents, action: 'upsert')
+ end
+ end
+ end
+ end
+end
+```
+
+Then register it:
+
+```ruby
+# config/initializers/spree.rb
+Spree.search_provider = 'MyApp::SearchProvider::Typesense'
+```
+
+### Provider Contract
+
+| Method | Required | Description |
+|--------|----------|-------------|
+| `search_and_filter(scope:, query:, filters:, sort:, page:, limit:)` | Yes | Search, filter, sort, paginate, and return facets. Must return a `SearchResult`. |
+| `index(product)` | No | Index a single product. Called via background job on create/update. No-op for database provider. |
+| `remove(product)` | No | Remove a product from the index. Called via background job on destroy. |
+| `remove_by_id(product_id)` | No | Remove by ID (product may already be deleted). |
+| `reindex(scope)` | No | Bulk reindex. Called via `rake spree:search:reindex`. |
+
+### SearchResult
+
+`search_and_filter` must return a `Spree::SearchProvider::SearchResult`:
+
+```ruby
+Spree::SearchProvider::SearchResult.new(
+ products: ar_relation, # ActiveRecord::Relation — paginated products
+ filters: [...], # Array of filter hashes (facets)
+ sort_options: [...], # Array of sort option strings
+ total_count: 150 # Integer — total matching products (before pagination)
+)
+```
+
+### ProductPresenter
+
+Use `Spree::SearchProvider::ProductPresenter` to serialize products for indexing. It handles multi-currency prices, translations, option values, categories (with prefixed IDs), and stock status:
+
+```ruby
+presenter = Spree::SearchProvider::ProductPresenter.new(product, store)
+document = presenter.call
+# => {
+# id: 42, prefixed_id: "prod_abc", name: "Blue Shirt", slug: "blue-shirt",
+# status: "active", sku: "SHIRT-001", in_stock: true,
+# category_ids: ["ctg_abc", "ctg_def"], category_names: ["Clothing", "Shirts"],
+# option_values: ["Small", "Medium", "Large", "Blue", "Red"],
+# price_USD: 29.99, price_EUR: 27.50, compare_at_price_USD: 39.99,
+# name_en: "Blue Shirt", name_fr: "Chemise Bleue", ...
+# }
+```
+
+### Indexing Lifecycle
+
+Products include the `Spree::SearchIndexable` concern which provides:
+
+- **Automatic indexing** — background jobs enqueue on `after_commit` (create/update/destroy). Jobs are skipped for the Database provider.
+- **Manual indexing** — `product.add_to_search_index` (synchronous, inline)
+- **Manual removal** — `product.remove_from_search_index` (synchronous, inline)
+- **Preview** — `product.search_presentation` returns the hash that would be indexed
+- **Bulk reindex** — `rake spree:search:reindex`
+
+### Important: Prefixed IDs
+
+Always use prefixed IDs (e.g., `ctg_abc`, `prod_xyz`) when indexing association references. Never use raw database IDs — Spree supports UUID primary keys.
+
+## Related Documentation
+
+- [Search & Filtering](/developer/core-concepts/search-filtering) — Store API search and filtering reference
+- [Meilisearch Integration](/integrations/search/meilisearch) — Setup guide for Meilisearch
+- [Dependencies](/developer/customization/dependencies) — How to swap Spree services
diff --git a/docs/developer/deployment/environment_variables.mdx b/docs/developer/deployment/environment_variables.mdx
index e55f43c5cd..9ded5abb19 100644
--- a/docs/developer/deployment/environment_variables.mdx
+++ b/docs/developer/deployment/environment_variables.mdx
@@ -65,6 +65,26 @@ By default, uploaded files (product images, assets) are stored on the local file
| `CLOUDFLARE_SECRET_ACCESS_KEY` | — | R2 secret key |
| `CLOUDFLARE_BUCKET` | `spree-production` | R2 bucket name |
+## Search (Meilisearch)
+
+Optional. When configured, Spree uses [Meilisearch](/integrations/search/meilisearch) for product search, filtering, and faceted navigation instead of SQL.
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `MEILISEARCH_URL` | `http://localhost:7700` | Meilisearch server URL |
+| `MEILISEARCH_API_KEY` | — | Meilisearch master key. Not needed for local development — only required when Meilisearch is started with `MEILI_MASTER_KEY`. |
+
+After setting these, enable the provider and reindex:
+
+```ruby
+# config/initializers/spree.rb
+Spree.search_provider = 'Spree::SearchProvider::Meilisearch'
+```
+
+```bash
+rake spree:search:reindex
+```
+
## Error Tracking (Sentry)
| Variable | Default | Description |
diff --git a/docs/integrations/search/meilisearch.mdx b/docs/integrations/search/meilisearch.mdx
new file mode 100644
index 0000000000..d013ce54db
--- /dev/null
+++ b/docs/integrations/search/meilisearch.mdx
@@ -0,0 +1,217 @@
+---
+title: Meilisearch
+description: "Set up Meilisearch for fast, typo-tolerant product search with faceted filtering"
+---
+
+## Overview
+
+[Meilisearch](https://www.meilisearch.com/) is a fast, open-source search engine that provides typo tolerance, relevance ranking, faceted filtering, and sub-50ms search responses. Spree includes a built-in Meilisearch search provider that replaces the default SQL-based search.
+
+**When to use Meilisearch:**
+- Catalogs with 1,000+ products
+- Need typo tolerance and relevance ranking
+- Want faceted filtering with adjusted counts
+- Require sub-second search responses
+
+**When the default Database provider is sufficient:**
+- Development environments
+- Small catalogs (< 1,000 products)
+- Simple search requirements
+
+## Setup
+
+### 1. Install Meilisearch
+
+<CodeGroup>
+
+```bash macOS (Homebrew)
+brew install meilisearch
+meilisearch
+# Running at http://localhost:7700 — no API key needed for development
+```
+
+```bash Docker
+docker run -d --name meilisearch \
+ -p 7700:7700 \
+ -v $(pwd)/meili_data:/meili_data \
+ getmeili/meilisearch:latest
+```
+
+```bash Meilisearch Cloud
+# Sign up at https://www.meilisearch.com/cloud
+# Get your URL and API key from the dashboard
+```
+
+</CodeGroup>
+
+<Info>
+For local development, Meilisearch runs without authentication by default — no API key is needed. For production, set a master key (minimum 16 bytes) via `MEILI_MASTER_KEY` when starting Meilisearch. Use this master key as your `MEILISEARCH_API_KEY`.
+</Info>
+
+### 2. Add the gem to your Gemfile
+
+```ruby
+gem 'meilisearch', '>= 0.28'
+```
+
+```bash
+bundle install
+```
+
+### 3. Configure environment variables
+
+```bash
+# .env
+
+# Local development — no API key needed
+MEILISEARCH_URL=http://localhost:7700
+
+# Production — use the master key you set when starting Meilisearch
+# MEILISEARCH_API_KEY=your-master-key-min-16-bytes
+```
+
+### 4. Set the search provider
+
+```ruby
+# config/initializers/spree.rb
+Spree.search_provider = 'Spree::SearchProvider::Meilisearch'
+```
+
+### 5. Index your products
+
+```bash
+rake spree:search:reindex
+```
+
+That's it. Your Store API now uses Meilisearch for all product search, filtering, and faceted navigation.
+
+## How It Works
+
+### Indexing
+
+Products are automatically indexed in background jobs when they are created, updated, or destroyed. Each product is serialized by `Spree::SearchProvider::ProductPresenter` which includes:
+
+- Product name, description, slug, SKU, status
+- Prices in **all currencies** (e.g., `price_USD: 29.99`, `price_EUR: 27.50`)
+- Translations in **all locales** (e.g., `name_en: "Shirt"`, `name_fr: "Chemise"`)
+- Category IDs (prefixed, e.g., `ctg_abc`)
+- Option values (e.g., `["Small", "Medium", "Blue", "Red"]`)
+- Stock status, tags, timestamps
+
+Preview what gets indexed:
+
+```ruby
+# Rails console
+product = Spree::Product.first
+product.search_presentation
+# => { id: 1, prefixed_id: "prod_abc", name: "Blue Shirt", price_USD: 29.99, ... }
+```
+
+### Search Flow
+
+```curl
+GET /api/v3/store/products?q[search]=shirt&q[price_gte]=20&sort=price
+```
+
+1. Controller builds AR scope: store.products.active('USD').accessible_by(ability)
+2. Provider sends one Meilisearch API call: search + filters + facets + sort + pagination
+3. Provider intersects Meilisearch IDs with AR scope (enforces visibility/authorization)
+4. Returns products + facets + total count
+
+The AR scope ensures that draft products, products from other stores, and unauthorized products are never returned — even if they exist in the Meilisearch index.
+
+### Index Name
+
+Each store gets its own Meilisearch index: `{store_code}_products`. For a store with code `"my-store"`, the index name is `my_store_products`.
+
+## Manual Operations
+
+### Reindex all products
+
+```bash
+rake spree:search:reindex
+```
+
+### Index a single product
+
+```ruby
+product.add_to_search_index
+```
+
+### Remove a product from the index
+
+```ruby
+product.remove_from_search_index
+```
+
+### Preview indexed data
+
+```ruby
+product.search_presentation
+```
+
+## Configuration
+
+| Environment Variable | Default | Description |
+|---|---|---|
+| `MEILISEARCH_URL` | `http://localhost:7700` | Meilisearch server URL |
+| `MEILISEARCH_API_KEY` | `nil` | Master or admin API key |
+
+The index is automatically configured with the correct filterable, sortable, and searchable attributes when you run `rake spree:search:reindex`.
+
+## Filterable Attributes
+
+The Meilisearch provider automatically configures these filterable attributes:
+
+- `status` — product status (active, draft, archived)
+- `in_stock` — boolean stock availability
+- `category_ids` — prefixed category IDs
+- `tags` — product tags
+- `option_values` — option value presentations (Size, Color, etc.)
+- `price_{CURRENCY}` — price per currency (e.g., `price_USD`, `price_EUR`)
+
+## Sortable Attributes
+
+- `price_{CURRENCY}` — sort by price in any currency
+- `created_at` — sort by creation date
+- `available_on` — sort by availability date
+
+## Store API Compatibility
+
+The Meilisearch provider is fully compatible with the existing Store API. No client-side changes are needed:
+
+```typescript
+// Same SDK calls work with both Database and Meilisearch providers
+const products = await client.products.list({
+ search: 'blue shirt',
+ price_gte: 20,
+ price_lte: 100,
+ in_stock: true,
+ sort: 'price',
+ limit: 12,
+})
+```
+
+## Production Recommendations
+
+### Separate search and admin keys
+
+Meilisearch supports [tenant tokens](https://www.meilisearch.com/docs/learn/security/tenant_tokens) for fine-grained access control. Use an admin key for indexing and a search key for queries.
+
+### Monitor index size
+
+Check your index stats:
+
+```ruby
+provider = Spree::SearchProvider::Meilisearch.new(Spree::Store.default)
+# Access the underlying client if needed for monitoring
+```
+
+### Meilisearch Cloud
+
+For production deployments, consider [Meilisearch Cloud](https://www.meilisearch.com/cloud) for managed hosting, automatic scaling, and monitoring.
+
+## Related Documentation
+
+- [Search & Filtering](/developer/core-concepts/search-filtering) — Store API search reference
+- [Search Providers](/developer/customization/search-providers) — Architecture and custom providers
diff --git a/docs/plans/spree-starter-and-create-spree-app.md b/docs/plans/5.4-spree-starter-and-create-spree-app.md
similarity index 99%
rename from docs/plans/spree-starter-and-create-spree-app.md
rename to docs/plans/5.4-spree-starter-and-create-spree-app.md
index be9c6b1f68..7911f062e0 100644
--- a/docs/plans/spree-starter-and-create-spree-app.md
+++ b/docs/plans/5.4-spree-starter-and-create-spree-app.md
@@ -1,6 +1,6 @@
# Spree Starter & create-spree-app Overhaul
-**Status:** Draft
+**Status:** Done
**Target:** Spree 5.4 (immediate, pre-6.0)
**Depends on:** None
**Author:** Damian + Claude
diff --git a/docs/plans/6.0-search-provider.md b/docs/plans/6.0-search-provider.md
new file mode 100644
index 0000000000..236fd3e3b6
--- /dev/null
+++ b/docs/plans/6.0-search-provider.md
@@ -0,0 +1,692 @@
+# Search Provider Interface
+
+**Status:** Draft
+**Target:** Spree 5.4 (provider + DB provider + PgSearch removal + add_search_scope removal), 6.0 (metafield faceting, Meilisearch gem)
+**Depends on:** None for 5.4. ProductType (6.0-product-types.md) for metafield faceting in 6.0.
+**Author:** Damian + Claude
+**Last updated:** 2026-03-18
+
+## Summary
+
+Add a pluggable search provider interface (`Spree::SearchProvider::Base`) that abstracts product search, filtering, sorting, and facet aggregation behind a clean contract. The default implementation (`Spree::SearchProvider::Database`) uses standard SQL/ILIKE scopes. Meilisearch is the recommended external provider, using `meilisearch-ruby` (raw client, no model overrides).
+
+This plan also:
+- Removes the `pg_search` dependency (legacy, replaced by the provider interface)
+- Removes the `add_search_scope` macro (legacy, replaced by standard Rails scopes)
+- Extends faceted filtering to include MetafieldDefinition-based facets
+
+## Problem
+
+1. **No search abstraction.** Search logic is spread across four layers — model scopes (`ProductScopes`), Ransack integration (`ResourceController`), a finder service (`Products::Find`), and a filter aggregator (`FiltersAggregator`). Replacing any one part means understanding and patching all four.
+
+2. **SQL search is inadequate for enterprise.** The `search` scope uses ILIKE (or PgSearch trigram when installed). No typo tolerance, synonyms, stemming, or relevance tuning. Every serious deployment replaces this, but there's no clean seam to do so.
+
+3. **PgSearch is a legacy dependency.** The `if defined?(PgSearch)` conditional in `Product` creates two code paths for search — one with PgSearch, one without. PgSearch only works with PostgreSQL, adds complexity for marginal benefit over plain ILIKE, and doesn't solve the real problems (relevance, typo tolerance, faceting). A proper search engine (Meilisearch) solves all of these. PgSearch should be removed entirely, not maintained alongside a provider interface.
+
+4. **`add_search_scope` is a non-standard macro.** `ProductScopes` defines ~25 scopes using `add_search_scope` which uses `singleton_class.send(:define_method, ...)` instead of standard Rails `scope`. This is legacy cruft — there's no benefit over standard scopes, and it creates confusion about which scopes are "search scopes" vs regular scopes. All should be converted to standard `scope` definitions.
+
+5. **Faceted filtering is OptionType-only.** `FiltersAggregator` builds facets from `OptionType.filterable` + `OptionValue` counts. Metafield-based attributes (material, brand, weight class) can't participate in faceted navigation, despite MetafieldDefinitions being the structured attribute system.
+
+6. **No autocomplete/typeahead endpoint.** Search-as-you-type is expected by enterprise buyers. No endpoint exists.
+
+7. **Filter counts are naive.** `FiltersAggregator` counts products per option value against the full scope, not adjusted for already-applied filters. This means selecting "Size: M" doesn't update the count on "Color: Red" to reflect only products that are both M and Red.
+
+## Current State
+
+| What exists | Where | What it does |
+|---|---|---|
+| `search` scope | `Product` model | ILIKE on name/SKU (or PgSearch trigram when gem installed — being removed) |
+| `search_by_name` scope | `Product` model (via PgSearch) | Trigram + word_similarity — being removed |
+| `add_search_scope` macro | `ProductScopes` concern | Legacy macro for defining scopes via `singleton_class.define_method` — being removed |
+| `pg_search` gem | Optional dependency | PostgreSQL-only trigram search — being removed |
+| `Products::Find` | `core/app/finders/` | Orchestrates complex filter chains (IDs, SKUs, price, taxons, options, tags, stock) |
+| `Products::Sort` | `core/app/finders/` | Sort by name, price, newest, best-selling |
+| `FiltersAggregator` | `api/app/services/` | Builds filter metadata: price range, availability, option facets, category facets |
+| `/products/filters` | Store API endpoint | Returns available filters + counts for a product scope |
+| `ProductScopes` | `core/app/models/concerns/` | ~30 scopes for filtering, sorting, stock, price, options, categories |
+| `ResourceController` | API base controller | Ransack param transformation, pagination, HTTP caching |
+| `Spree::Dependencies.products_finder` | Dependencies | Swappable finder service (already exists) |
+| `Spree::Dependencies.products_sorter` | Dependencies | Swappable sorter service (already exists) |
+
+## Key Decisions (do not deviate without discussion)
+
+### Provider owns search + filtering + facets; AR owns security + visibility
+
+The provider handles everything that a search engine does better than SQL:
+
+1. **Search** — text query → ranked results
+2. **Filter** — structured params (price, options, metafields, availability, categories)
+3. **Aggregate** — facets with adjusted counts
+
+AR scopes handle what must be enforced at the database level:
+
+1. **Store scoping** — `current_store.products`
+2. **Visibility** — `.active(currency)` for Store API (not applied for Admin)
+3. **Authorization** — `.accessible_by(current_ability, :show)`
+
+The controller builds a base AR scope for security/visibility, then hands everything else to the provider:
+
+```ruby
+# Store API controller
+base_scope = current_store.products.active(currency).accessible_by(current_ability, :show)
+
+result = search_provider.search_and_filter(
+ scope: base_scope,
+ query: params.dig(:q, :search),
+ filters: params[:q], # price_gte, with_option_value_ids, etc.
+ sort: params[:sort],
+ page: params[:page],
+ limit: params[:limit]
+)
+
+result.products # → AR relation (filtered, sorted, paginated)
+result.filters # → facets with counts
+result.total_count # → total matches
+```
+
+The Database provider implements this by chaining Ransack scopes + `FiltersAggregator` (same as today). The Meilisearch provider does search + filter + facets in **one Meilisearch API call**, then intersects with the base AR scope for security.
+
+```
+Store API Controller
+ │
+ ├─ base_scope = store.products.active.accessible_by(ability) ← AR (security)
+ │
+ └─ search_provider.search_and_filter(scope: base_scope, ...) ← Provider (search + filter + facets)
+ │
+ ├─ Database: scope.search(query).ransack(filters) + FiltersAggregator
+ │
+ └─ Meilisearch: meilisearch_client.search(query, filters, facets)
+ → Product.where(id: result_ids).merge(base_scope) ← intersect for security
+```
+
+### `Product.search` stays as a plain ILIKE scope
+
+- **`Product.search(query)` is a simple SQL scope.** ILIKE on name + SKU. It knows nothing about providers.
+- **Admin controllers, rake tasks, and console can call it directly** — no dependency on Meilisearch or the provider.
+- **The Database provider delegates to it internally.** The Meilisearch provider ignores it entirely and uses the `meilisearch-ruby` client.
+- **No model-level magic.** We use `meilisearch-ruby` (raw HTTP client), not `meilisearch-rails` (ActiveRecord override). The model stays clean.
+
+### Provider is registered via Spree::Dependencies
+
+```ruby
+Spree.search_provider = 'Spree::SearchProvider::Database' # default
+Spree.search_provider = 'SpreeMeilisearch::SearchProvider' # with meilisearch
+```
+
+Consistent with existing `products_finder`, `products_sorter` pattern.
+
+### MetafieldDefinition gains `filterable` flag
+
+- Add `filterable` boolean to `MetafieldDefinition` (default: `false`).
+- Both providers include filterable metafield definitions as facets.
+- Only choice-type metafields are facet-ready in v1: `single_line_text` and `number` types where values repeat across products. Rich text and JSON types are not filterable.
+- Metafield facets use the same filter response shape as option type facets, with `type: 'metafield'`.
+
+### Remove PgSearch dependency
+
+- **Drop `pg_search` entirely.** No conditional `if defined?(PgSearch)` branches. The `search` scope on Product uses plain ILIKE (the current fallback path).
+- **Remove PgSearch scopes from Product** — `search_by_name` (trigram) removed. ILIKE on name is sufficient for the Database provider.
+- **Remove PgSearch scopes from Variant** — `search_by_sku`, `search_by_sku_or_options` replaced by ILIKE equivalents.
+- **Remove `pg_search` from gemspec.** Currently an optional dependency. No migration needed — it's a gem removal.
+- **Meilisearch is the recommended upgrade path.** For merchants who want typo tolerance, stemming, and relevance tuning, install `spree_search_meilisearch`. This gives them far more than PgSearch ever did.
+
+### Remove `add_search_scope` macro
+
+- **Convert all `add_search_scope` calls to standard `scope` definitions.** There are ~25 scopes in `ProductScopes` using this macro. All become standard Rails scopes.
+- **Remove the `add_search_scope` method**, `search_scopes` class variable, and related infrastructure from `ProductScopes`.
+- **No behavior change.** The scopes do the same thing — only the definition mechanism changes.
+- **Ransack `whitelisted_ransackable_scopes` stays as-is.** Standard scopes work with Ransack identically.
+
+### Meilisearch is the recommended external provider
+
+- **Ship `spree_search_meilisearch` as an official Spree gem.** Uses `meilisearch-ruby` (raw client), NOT `meilisearch-rails` (no model-level overrides).
+- **Index all products** (all statuses). Store API applies `.active` scope to the base AR scope before passing to the provider. Admin passes all products. The provider searches the full index, AR scope intersects for visibility.
+- **Meilisearch handles search + filtering + faceting in one call** — replaces both Ransack filtering and `FiltersAggregator` with Meilisearch's native capabilities. Adjusted facet counts come for free.
+- **Docs recommend Meilisearch** as the production search solution. The Database provider is for development and small catalogs.
+
+## Design Details
+
+### Provider Base Class
+
+```ruby
+module Spree
+ module SearchProvider
+ class Base
+ attr_reader :store
+
+ def initialize(store)
+ @store = store
+ end
+
+ # Search, filter, and return facets in one call.
+ #
+ # @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 sort [String, nil] sort param (e.g. 'price', '-price', 'best_selling')
+ # @param page [Integer] page number
+ # @param limit [Integer] results per page
+ # @return [SearchResult] { products: AR::Relation, filters: Array, total_count: Integer }
+ def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)
+ raise NotImplementedError
+ end
+
+ # Index a product — called after product save. No-op for database provider.
+ #
+ # @param product [Spree::Product] the product to index
+ def index(product)
+ # no-op by default
+ end
+
+ # Remove a product from the index.
+ #
+ # @param product [Spree::Product] the product to remove
+ def remove(product)
+ # no-op by default
+ end
+
+ # Bulk reindex — full catalog sync. Called manually or via rake task.
+ #
+ # @param scope [ActiveRecord::Relation] products to reindex (default: all in store)
+ def reindex(scope = nil)
+ # no-op by default
+ end
+ end
+
+ # Returned by search_and_filter
+ SearchResult = Struct.new(:products, :filters, :sort_options, :total_count, keyword_init: true)
+ end
+end
+```
+
+### Database Provider (default)
+
+Wraps existing Ransack + SQL scopes + `FiltersAggregator`. Behavior identical to today.
+
+```ruby
+module Spree
+ module SearchProvider
+ class Database < Base
+ def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)
+ # 1. Text search via ILIKE scope
+ scope = scope.search(query) if query.present?
+
+ # 2. Structured filtering via Ransack
+ scope = scope.ransack(sanitize_filters(filters)).result(distinct: true) if filters.present?
+
+ # 3. Sorting
+ scope = apply_sort(scope, sort) if sort.present?
+
+ # 4. Facets via FiltersAggregator + metafield facets
+ filter_facets = build_facets(scope)
+
+ # 5. Pagination
+ total = scope.count
+ products = scope.offset((page - 1) * limit).limit(limit)
+
+ SearchResult.new(
+ products: products,
+ filters: filter_facets,
+ sort_options: available_sort_options,
+ total_count: total
+ )
+ end
+
+ private
+
+ def build_facets(scope)
+ aggregator = Spree::Api::V3::FiltersAggregator.new(
+ scope: scope,
+ store: store,
+ currency: Spree::Current.currency
+ )
+
+ result = aggregator.call
+ result[:filters].concat(build_metafield_facets(scope))
+ result[:filters]
+ end
+
+ def build_metafield_facets(scope)
+ definitions = Spree::MetafieldDefinition
+ .where(resource_type: 'Spree::Product', filterable: true)
+ .order(:sort_order)
+
+ product_ids = scope.select(:id)
+
+ definitions.filter_map do |definition|
+ values_with_counts = Spree::Metafield
+ .where(resource_type: 'Spree::Product', resource_id: product_ids)
+ .where(namespace: definition.namespace, key: definition.key)
+ .group(:value)
+ .count
+
+ next if values_with_counts.empty?
+
+ {
+ id: definition.prefixed_id,
+ type: 'metafield',
+ name: definition.key,
+ namespace: definition.namespace,
+ presentation: definition.name,
+ options: values_with_counts.map do |value, count|
+ { value: value, count: count }
+ end.sort_by { |o| -o[:count] }
+ }
+ end
+ end
+
+ def sanitize_filters(filters)
+ # Strip text search param — already handled by scope.search
+ filters.except(:search)
+ end
+
+ def apply_sort(scope, sort)
+ # Delegate to existing sort logic (Ransack s param or custom scopes)
+ scope
+ end
+
+ def available_sort_options
+ %w[price -price best_selling name -name -available_on available_on]
+ end
+ end
+ end
+end
+```
+
+### Meilisearch Provider (`spree_search_meilisearch` gem)
+
+Uses `meilisearch-ruby` (raw HTTP client). No model-level overrides.
+
+```ruby
+module SpreeMeilisearch
+ class SearchProvider < Spree::SearchProvider::Base
+ def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)
+ # One Meilisearch call: search + filter + facets
+ ms_result = client.index(index_name).search(query || '', {
+ filter: build_meilisearch_filters(filters),
+ facets: facet_attributes,
+ sort: build_meilisearch_sort(sort),
+ offset: (page - 1) * limit,
+ limit: limit
+ })
+
+ ids = ms_result['hits'].map { |h| h['id'] }
+
+ # Intersect with AR scope for security/visibility
+ products = scope.where(id: ids).in_order_of(:id, ids)
+
+ SearchResult.new(
+ products: products,
+ filters: build_filters_from_facet_distribution(ms_result['facetDistribution']),
+ sort_options: available_sort_options,
+ total_count: ms_result['estimatedTotalHits']
+ )
+ end
+
+ def index(product)
+ client.index(index_name).add_documents([serialize(product)])
+ end
+
+ def remove(product)
+ client.index(index_name).delete_document(product.id)
+ end
+
+ def reindex(scope = nil)
+ scope ||= store.products
+ scope.find_in_batches(batch_size: 500) do |batch|
+ client.index(index_name).add_documents(batch.map { |p| serialize(p) })
+ end
+ end
+
+ private
+
+ def client
+ @client ||= MeiliSearch::Client.new(
+ ENV['MEILISEARCH_URL'] || 'http://localhost:7700',
+ ENV['MEILISEARCH_API_KEY']
+ )
+ end
+
+ def index_name
+ "#{store.code}_products"
+ end
+
+ def serialize(product)
+ {
+ id: product.id,
+ prefixed_id: product.prefixed_id,
+ name: product.name,
+ description: product.description,
+ slug: product.slug,
+ status: product.status,
+ price: product.price_in(store.default_currency)&.amount&.to_f,
+ currency: store.default_currency,
+ category_ids: product.taxon_ids,
+ option_values: product.variants.flat_map { |v| v.option_values.map(&:presentation) },
+ sku: product.sku,
+ in_stock: product.in_stock?,
+ primary_media_url: product.primary_media&.url(:large),
+ created_at: product.created_at.to_i,
+ available_on: product.available_on&.to_i,
+ # Filterable metafields
+ **filterable_metafields(product)
+ }
+ end
+
+ def filterable_metafields(product)
+ Spree::MetafieldDefinition.where(resource_type: 'Spree::Product', filterable: true).each_with_object({}) do |defn, hash|
+ metafield = product.metafields.detect { |m| m.namespace == defn.namespace && m.key == defn.key }
+ hash["mf_#{defn.namespace}_#{defn.key}"] = metafield&.value
+ end
+ end
+
+ def facet_attributes
+ # Option types + filterable metafields + price + stock
+ ['price', 'in_stock', 'category_ids'] +
+ Spree::OptionType.filterable.pluck(:name).map { |n| "option_#{n}" } +
+ Spree::MetafieldDefinition.where(resource_type: 'Spree::Product', filterable: true)
+ .pluck(:namespace, :key).map { |ns, k| "mf_#{ns}_#{k}" }
+ end
+ end
+end
+```
+
+### Integration Points
+
+#### 1. Products Controller
+
+The Store API products controller delegates to the provider for all search + filtering:
+
+```ruby
+module Spree::Api::V3::Store
+ class ProductsController < ResourceController
+ private
+
+ def collection
+ base_scope = scope.accessible_by(current_ability, :show)
+
+ result = search_provider.search_and_filter(
+ scope: base_scope,
+ query: params.dig(:q, :search),
+ filters: params[:q]&.except(:search),
+ sort: params[:sort],
+ page: params[:page],
+ limit: params[:limit]
+ )
+
+ # Store filters for the response (if requested via expand=filters)
+ @filters = result.filters
+ @total_count = result.total_count
+
+ result.products
+ end
+
+ def search_provider
+ @search_provider ||= Spree.search_provider.constantize.new(current_store)
+ end
+ end
+end
+```
+
+#### 2. Filters Controller
+
+```ruby
+module Spree::Api::V3::Store
+ class Products::FiltersController < BaseController
+ def index
+ base_scope = current_store.products
+ .active(current_currency)
+ .accessible_by(current_ability, :show)
+
+ result = search_provider.search_and_filter(
+ scope: base_scope,
+ query: params.dig(:q, :search),
+ filters: params[:q]&.except(:search),
+ page: 1,
+ limit: 0 # no products needed, just facets
+ )
+
+ render json: {
+ filters: result.filters,
+ sort_options: result.sort_options,
+ total_count: result.total_count
+ }
+ end
+
+ private
+
+ def search_provider
+ @search_provider ||= Spree.search_provider.constantize.new(current_store)
+ end
+ end
+end
+```
+
+#### 3. Product Indexing Hooks
+
+```ruby
+module Spree
+ module SearchIndexable
+ extend ActiveSupport::Concern
+
+ included do
+ after_commit :index_in_search, on: [:create, :update]
+ after_commit :remove_from_search, on: :destroy
+ end
+
+ private
+
+ def index_in_search
+ return unless stores.any?
+
+ stores.each do |store|
+ provider = Spree.search_provider.constantize.new(store)
+ provider.index(self)
+ end
+ end
+
+ def remove_from_search
+ stores.each do |store|
+ provider = Spree.search_provider.constantize.new(store)
+ provider.remove(self)
+ end
+ end
+ end
+end
+
+# In Spree::Product
+class Spree::Product < Spree.base_class
+ include Spree::SearchIndexable
+end
+```
+
+For the Database provider, `index` and `remove` are no-ops. For external providers, these trigger async indexing (via a job wrapper if needed).
+
+#### 4. Rake Task
+
+```ruby
+# rake spree:search:reindex
+namespace :spree do
+ namespace :search do
+ task reindex: :environment do
+ Spree::Store.all.find_each do |store|
+ provider = Spree.search_provider.constantize.new(store)
+ puts "Reindexing #{store.name} (#{store.products.count} products)..."
+ provider.reindex(store.products)
+ puts "Done."
+ end
+ end
+ end
+end
+```
+
+### MetafieldDefinition Changes
+
+```ruby
+class Spree::MetafieldDefinition < Spree.base_class
+ # New column
+ attribute :filterable, :boolean, default: false
+
+ scope :filterable, -> { where(filterable: true) }
+end
+```
+
+### Store API Filter Response (extended)
+
+The filter response shape stays the same, with a new `type: 'metafield'` filter type:
+
+```json
+{
+ "filters": [
+ { "id": "price", "type": "price_range", "min": 10, "max": 100, "currency": "USD" },
+ { "id": "availability", "type": "availability", "options": [...] },
+ { "id": "opt_abc", "type": "option", "name": "size", "presentation": "Size", "options": [...] },
+ {
+ "id": "mfdef_xyz",
+ "type": "metafield",
+ "name": "material",
+ "namespace": "product",
+ "presentation": "Material",
+ "options": [
+ { "value": "Cotton", "count": 42 },
+ { "value": "Polyester", "count": 18 }
+ ]
+ }
+ ],
+ "sort_options": [...],
+ "total_count": 60
+}
+```
+
+### Product Filtering by Metafield
+
+New Ransack scope on Product:
+
+```ruby
+# In Product model
+scope :with_metafield, ->(namespace, key, value) {
+ joins(:metafields)
+ .where(spree_metafields: { namespace: namespace, key: key, value: value })
+}
+```
+
+API usage: `q[with_metafield][]=product|material|Cotton`
+
+### SDK Types (generated)
+
+```typescript
+interface MetafieldFilter {
+ id: string // prefixed MetafieldDefinition ID
+ type: 'metafield'
+ name: string // key
+ namespace: string
+ presentation: string // MetafieldDefinition.name
+ options: Array<{
+ value: string
+ count: number
+ }>
+}
+
+// ProductFilter union gains MetafieldFilter
+type ProductFilter = PriceRangeFilter | AvailabilityFilter | OptionFilter | CategoryFilter | MetafieldFilter
+
+```
+
+## Migration Path
+
+### Phase 1: Remove `add_search_scope` macro
+
+- Convert all ~25 `add_search_scope` calls in `ProductScopes` to standard `scope` definitions
+- Remove `add_search_scope` method, `search_scopes` class variable, and `self.search_scopes` accessor
+- Update `whitelisted_ransackable_scopes` if needed (should be identical)
+- Run full test suite to verify no behavior change
+
+### Phase 2: Remove PgSearch
+
+- Remove all `if defined?(PgSearch)` conditionals in Product and Variant
+- Keep only the ILIKE/SQL branches (the current fallback paths)
+- Remove `pg_search_scope` declarations: `search_by_name`, `search_by_sku`, `search_by_sku_or_options`
+- Replace with simple ILIKE scopes where needed (Product name search, Variant SKU search)
+- Remove `pg_search` from `spree_core.gemspec` optional dependencies
+- Remove any PgSearch-related translation model scopes (`Translation.search_by_name`)
+- Run full test suite — no test should depend on PgSearch
+
+### Phase 3: Provider interface + Database provider
+
+- Create `Spree::SearchProvider::Base` and `Spree::SearchProvider::Database`
+- Register `search_provider` in `Spree::Dependencies`
+- Database provider wraps existing `search` scope, `FiltersAggregator`, and ILIKE autocomplete
+- **Zero behavior change** — existing code paths are wrapped, not replaced
+
+### Phase 4: Controller integration
+
+- Wire `search_provider.search()` into `ProductsController` for `q[search]` param
+- Wire `search_provider.aggregate()` into `FiltersController`
+- Add `SearchIndexable` concern to Product (no-op for database provider)
+- Add `rake spree:search:reindex` task
+
+### Phase 5: Meilisearch provider (official gem)
+
+- Create `spree_search_meilisearch` gem (official, maintained by Spree team)
+- Uses `meilisearch-ruby` gem (raw client, no model-level overrides)
+- Indexes all products (all statuses) — storefront scopes handle visibility
+- Implements: search + filter + faceted aggregation with adjusted counts in one call
+- `SearchIndexable` concern on Product triggers async indexing
+- `rake spree:search:reindex` delegates to Meilisearch bulk indexing
+- Documented as the recommended production search solution
+
+### Phase 6: MetafieldDefinition.filterable (6.0)
+
+```ruby
+class AddFilterableToMetafieldDefinitions < ActiveRecord::Migration[7.2]
+ def change
+ add_column :spree_metafield_definitions, :filterable, :boolean, null: false, default: false
+ add_index :spree_metafield_definitions, :filterable
+ end
+end
+```
+
+- Add `filterable` column and scope
+- Extend both providers to include metafield facets
+- Add `with_metafield` Ransack scope to Product (for Database provider)
+- Meilisearch provider indexes filterable metafields as document attributes
+
+## Constraints on Current Work
+
+- **Don't add new `add_search_scope` calls.** Use standard `scope` definitions. The macro is being removed.
+- **Don't add new PgSearch scopes.** PgSearch is being removed. Use ILIKE for new search logic.
+- **Don't add new search logic to ProductScopes.** New search/filter behavior should be designed for the provider interface.
+- **Don't hardcode FiltersAggregator usage in controllers.** It will be wrapped by the provider.
+- **New filterable attributes should use MetafieldDefinition.** Don't add one-off `filterable` columns on other models.
+
+## Resolved Questions
+
+1. **Admin search.** Same provider powers both Store API and Admin API. Meilisearch indexes all products (all statuses). Store API applies `.active` scope to filter results. Admin has no such scope — gets full search across drafts, archived, paused. No separate admin provider needed.
+
+2. **PgSearch vs Meilisearch.** Drop PgSearch entirely. It's PostgreSQL-only, adds conditional code paths, and provides marginal benefit over ILIKE. Meilisearch is the recommended upgrade for serious search needs — typo tolerance, stemming, synonyms, faceting, and relevance tuning. The Database provider uses plain ILIKE as the baseline. We use `meilisearch-ruby` (raw client), not `meilisearch-rails`, to avoid model-level method overrides and own the integration fully.
+
+3. **`add_search_scope` removal.** Convert to standard Rails scopes. The macro adds no value — it was created before Rails scopes were as capable as they are today. Standard scopes work identically with Ransack.
+
+## Open Questions
+
+1. **Per-store providers.** Should different stores in the same Spree instance use different search providers? (e.g., small store uses Database, large store uses Meilisearch). If yes, provider config moves to Store model instead of global Dependencies. Leaning toward global for 6.0, per-store for 6.1.
+
+2. **Cross-model search.** Enterprise buyers want unified search across products, categories, pages, and blog posts. Should the provider interface support multiple resource types, or is product search the only contract? Leaning toward product-only for 6.0.
+
+3. **Filter count adjustment.** Should the Database provider attempt cross-filter count adjustment (selecting "Size: M" updates "Color: Red" count)? This requires N+1 subqueries in SQL. Meilisearch handles this natively via `facetDistribution`. Leaning toward naive counts for Database provider, adjusted counts for Meilisearch.
+
+## References
+
+- Current search scopes: `spree/core/app/models/concerns/spree/product_scopes.rb` (has `add_search_scope` macro — being removed)
+- Current finder: `spree/core/app/finders/spree/products/find.rb`
+- Current filter aggregator: `spree/api/app/services/spree/api/v3/filters_aggregator.rb`
+- Current filters endpoint: `spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb`
+- Current products controller: `spree/api/app/controllers/spree/api/v3/store/products_controller.rb`
+- Dependencies: `spree/core/lib/spree/core/dependencies.rb`
+- Product search scope: `spree/core/app/models/spree/product.rb` (has PgSearch conditional — being removed)
+- Variant search scopes: `spree/core/app/models/spree/variant.rb` (has PgSearch scopes — being removed)
+- MetafieldDefinition: `spree/core/app/models/spree/metafield_definition.rb`
+- meilisearch-ruby client: https://github.com/meilisearch/meilisearch-ruby
+- Rename: `multi_search` → `search` shipped in 5.4 (backward compat alias kept until 6.0)
+- Related plan: `6.0-product-types.md` (MetafieldDefinition schema enforcement)
+- Related plan: `6.0-channels-catalogs-b2b.md` (Catalog-scoped product visibility)
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.md
new file mode 100644
index 0000000000..2fad2d25e3
--- /dev/null
+++ b/docs/plans/6.0-tax-provider.md
@@ -0,0 +1,546 @@
+# Tax Provider Interface
+
+**Status:** Draft
+**Target:** Spree 6.0
+**Depends on:** Split Adjustments (6.0-split-adjustments.md) for TaxLine model, Channels/Catalogs/B2B (6.0-channels-catalogs-b2b.md) for Company.tax_exempt
+**Author:** Damian + Claude
+**Last updated:** 2026-03-18
+
+## Summary
+
+Add a pluggable tax provider interface (`Spree::TaxProvider::Base`) that abstracts tax calculation behind a clean contract. The default implementation (`Spree::TaxProvider::Internal`) preserves today's TaxRate + Zone + Calculator behavior. External providers (Avalara, TaxJar, Vertex) implement the same interface, enabling drop-in tax services without changing the checkout flow, adjustment system, or order updater.
+
+The interface sits between the adjuster layer ("calculate tax for these items") and the calculation engine ("here's how much tax is owed"). Everything upstream (checkout flow, OrderUpdater, TaxLine creation) and downstream (totals, serializers, reporting) is unchanged.
+
+## Problem
+
+1. **No tax provider seam.** `TaxRate.adjust(order, items)` is hardcoded to match rates from the database, compute amounts via `Calculator::DefaultTax`, and create adjustments. There's no point where an external service can intercept. Integrations like Avalara have to monkey-patch `TaxRate` or wrap the entire adjuster.
+
+2. **Internal rates don't scale across jurisdictions.** US merchants with nexus in 30+ states need thousands of rate entries with zip-code-level granularity. The admin UI isn't designed for this, and rates change constantly. External services handle this via API calls with real-time rate lookups.
+
+3. **No tax exemption flow.** `Company.tax_exempt` exists (from the B2B plan) but there's no exemption certificate management — no storage, validation, or automatic zero-rating based on certificate status. Enterprise B2B requires this.
+
+4. **No tax estimation vs commitment distinction.** External providers distinguish between "estimate" (during checkout, reversible) and "commit" (on order completion, creates a tax filing record). Spree treats all tax calculations identically.
+
+5. **VAT reverse charge is manual.** EU B2B transactions where the buyer is VAT-registered in another member state should reverse-charge (zero VAT from seller, buyer self-assesses). This requires VAT registration validation and is too complex for static rate tables.
+
+## Current State
+
+| What exists | Where | What it does |
+|---|---|---|
+| `TaxRate` model | `core/app/models/spree/tax_rate.rb` | Stores rate %, zone, tax category. `adjust()` is the entry point. |
+| `TaxRate.match(zone)` | TaxRate class method | Finds rates whose zone includes the order's tax zone |
+| `Calculator::DefaultTax` | `core/app/models/spree/calculator/` | Computes tax amount for line items, shipments, shipping rates |
+| `VatPriceCalculation` | `core/app/models/concerns/` | Handles included-in-price tax math |
+| `TaxRate.store_pre_tax_amount` | TaxRate class method | Computes and stores pre-tax amounts for VAT calculations |
+| `Adjuster::Tax` | `core/app/models/spree/adjustable/adjuster/` | Orchestrates tax adjustment updates during recalculation |
+| `TaxCategory` | `core/app/models/spree/tax_category.rb` | Groups products/variants by tax type |
+| `Zone.match(address)` | Zone class method | Finds geographic zone for an address |
+| `Order#tax_zone` | Order model | Resolves order's zone from ship/bill address + default zone fallback |
+| `Spree::Config[:tax_using_ship_address]` | Config | Controls whether ship or bill address determines tax zone |
+| `Spree.adjusters` | Engine config | Registry of adjuster classes (includes Tax adjuster) |
+
+### Key flow today
+
+```
+OrderUpdater#update
+ → recalculate_adjustments (each line item + shipment)
+ → Adjuster::Tax#update
+ → adjustment.update! (for each existing tax adjustment)
+ → TaxRate#compute_amount(item)
+ → Calculator::DefaultTax#compute_shipment_or_line_item(item)
+
+Order#create_tax_charge!
+ → TaxRate.adjust(order, line_items)
+ → TaxRate.match(order.tax_zone) → find matching rates
+ → TaxRate.store_pre_tax_amount(item, rates) → pre-tax for VAT
+ → rate.adjust(order, item) → create_adjustment (via AdjustmentSource)
+ → TaxRate.adjust(order, shipments)
+```
+
+## Key Decisions (do not deviate without discussion)
+
+### Provider replaces TaxRate.adjust, not TaxRate
+
+- **TaxRate stays as-is.** Rates, zones, categories, calculators — all unchanged. The internal provider uses them.
+- **The provider replaces `TaxRate.adjust(order, items)` as the entry point.** Instead of calling `TaxRate.adjust` directly, the adjuster calls the provider.
+- **TaxRate.adjust becomes an internal implementation detail** of `TaxProvider::Internal`, not a public API that integrations need to understand.
+
+### Provider contract: estimate and commit
+
+```ruby
+# Two-phase: estimate during checkout, commit on completion
+provider.estimate(order, items) # → writes TaxLine records (or Adjustments in 5.x)
+provider.commit(order) # → finalizes with external service, no-op for internal
+provider.void(order) # → cancels committed tax document, no-op for internal
+```
+
+- **Estimate** is called during checkout recalculation. It's idempotent — repeated calls update amounts.
+- **Commit** is called on order completion. For external providers, this creates a transaction in the tax service (for filing/reporting). For the internal provider, it's a no-op.
+- **Void** is called on order cancellation. Reverses the committed tax document.
+
+### Provider writes TaxLine records directly
+
+With the split-adjustments plan (6.0), tax results are written as `Spree::TaxLine` records with concrete FKs. The provider creates/updates these records — the same data model regardless of whether tax was computed internally or by Avalara.
+
+Before split-adjustments ships, the provider writes `Spree::Adjustment` records (backward compatible).
+
+### Provider is per-store
+
+Different stores may use different tax services (US store uses Avalara, EU store uses internal VAT rates). Configuration is on the Store model:
+
+```ruby
+store.preferred_tax_provider = 'Spree::TaxProvider::Internal' # default
+```
+
+This is a preference (Spree::Preferences), not a global Dependency, because it varies per store.
+
+### Tax exemption is part of the provider contract
+
+```ruby
+provider.exempt?(order) # → true if order should be tax-exempt
+```
+
+The provider checks Company.tax_exempt, exemption certificates, and any external validation. If exempt, `estimate` returns zero amounts. This keeps exemption logic in one place instead of scattered across models.
+
+### Internal provider preserves all existing behavior
+
+`TaxProvider::Internal` delegates to `TaxRate.match`, `TaxRate.store_pre_tax_amount`, and `Calculator::DefaultTax`. The behavior is identical to today — same rates, same zones, same VAT math. No regressions.
+
+## Design Details
+
+### Provider Base Class
+
+```ruby
+module Spree
+ module TaxProvider
+ class Base
+ attr_reader :store
+
+ def initialize(store)
+ @store = store
+ end
+
+ # Estimate tax for items in an order. Called during checkout recalculation.
+ # Must be idempotent — repeated calls update existing tax records.
+ #
+ # Creates/updates TaxLine records (6.0) or Adjustment records (5.x).
+ #
+ # @param order [Spree::Order]
+ # @param items [Array<Spree::LineItem, Spree::Shipment>] items to tax
+ # @return [void]
+ def estimate(order, items)
+ raise NotImplementedError
+ end
+
+ # Commit tax for a completed order. Creates a tax document in external
+ # services for filing/reporting. No-op for internal provider.
+ #
+ # @param order [Spree::Order]
+ # @return [void]
+ def commit(order)
+ # no-op by default
+ end
+
+ # Void a committed tax document. Called on order cancellation.
+ #
+ # @param order [Spree::Order]
+ # @return [void]
+ def void(order)
+ # no-op by default
+ end
+
+ # Refund tax for returned items. Creates an adjustment document in
+ # external services. Internal provider recalculates from remaining items.
+ #
+ # @param order [Spree::Order]
+ # @param return_items [Array<Spree::ReturnItem>]
+ # @return [void]
+ def refund(order, return_items)
+ # no-op by default — internal provider handles via recalculation
+ end
+
+ # Check if an order is tax-exempt.
+ #
+ # @param order [Spree::Order]
+ # @return [Boolean]
+ def exempt?(order)
+ return true if order.company&.tax_exempt?
+ return true if order.company_location&.tax_exempt?
+
+ false
+ end
+ end
+ end
+end
+```
+
+### Internal Provider (default)
+
+```ruby
+module Spree
+ module TaxProvider
+ class Internal < Base
+ # Wraps existing TaxRate.adjust logic
+ def estimate(order, items)
+ return clear_tax(order, items) if exempt?(order)
+
+ line_items = items.select { |i| i.is_a?(Spree::LineItem) }
+ shipments = items.select { |i| i.is_a?(Spree::Shipment) }
+
+ Spree::TaxRate.adjust(order, line_items) if line_items.any?
+ Spree::TaxRate.adjust(order, shipments) if shipments.any?
+ end
+
+ # Internal rates need no commit — no external service to notify
+ def commit(order)
+ # no-op
+ end
+
+ def void(order)
+ # no-op
+ end
+
+ def refund(order, return_items)
+ # Recalculation handles this — when items are returned,
+ # the next estimate() call recomputes with reduced amounts
+ end
+
+ private
+
+ def clear_tax(order, items)
+ items.each do |item|
+ item.adjustments.tax.destroy_all
+ item.update_columns(
+ included_tax_total: 0,
+ additional_tax_total: 0
+ )
+ end
+ end
+ end
+ end
+end
+```
+
+### External Provider Example (Avalara)
+
+Shows the contract — actual implementation in `spree_tax_avalara` gem:
+
+```ruby
+module SpreeTaxAvalara
+ class TaxProvider < Spree::TaxProvider::Base
+ def estimate(order, items)
+ return clear_tax(order, items) if exempt?(order)
+
+ # Build Avalara transaction request
+ request = build_transaction(order, items, type: :estimate)
+
+ # Call Avalara API
+ response = client.create_transaction(request)
+
+ # Write TaxLine records from response
+ response.lines.each do |avalara_line|
+ item = find_item(items, avalara_line.line_number)
+ next unless item
+
+ upsert_tax_line(
+ order: order,
+ item: item,
+ amount: avalara_line.tax,
+ included: avalara_line.tax_included,
+ label: avalara_line.tax_name,
+ tax_rate: find_or_create_rate(avalara_line)
+ )
+ end
+
+ # Store Avalara transaction ID for commit
+ order.update_column(:metadata,
+ order.metadata.merge('avalara_transaction_id' => response.id))
+ end
+
+ def commit(order)
+ transaction_id = order.metadata&.dig('avalara_transaction_id')
+ return unless transaction_id
+
+ client.commit_transaction(transaction_id)
+ end
+
+ def void(order)
+ transaction_id = order.metadata&.dig('avalara_transaction_id')
+ return unless transaction_id
+
+ client.void_transaction(transaction_id)
+ end
+
+ def refund(order, return_items)
+ request = build_return_transaction(order, return_items)
+ client.create_transaction(request)
+ end
+
+ def exempt?(order)
+ return true if super # company/location-level exemption
+
+ # Avalara-specific: check exemption certificate
+ if order.company&.metadata&.dig('avalara_exemption_id')
+ validate_exemption(order.company.metadata['avalara_exemption_id'])
+ else
+ false
+ end
+ end
+ end
+end
+```
+
+### Integration Point: Tax Adjuster
+
+The Tax adjuster (which coordinates tax recalculation) delegates to the provider instead of calling TaxRate directly:
+
+```ruby
+module Spree
+ module Adjustable
+ module Adjuster
+ class Tax < Base
+ def update
+ provider = tax_provider
+
+ # Delegate to provider
+ provider.estimate(order, [adjustable])
+
+ # Read back results for totals
+ tax = adjustable.adjustments.tax
+ included = tax.select(&:included?).sum(&:amount)
+ additional = tax.reject(&:included?).sum(&:amount)
+
+ @totals[:included_tax_total] = included
+ @totals[:additional_tax_total] = additional
+ end
+
+ private
+
+ def tax_provider
+ store = order.store
+ provider_class = store.preferred_tax_provider || 'Spree::TaxProvider::Internal'
+ provider_class.constantize.new(store)
+ end
+
+ def order
+ adjustable.respond_to?(:order) ? adjustable.order : adjustable
+ end
+ end
+ end
+ end
+end
+```
+
+After split-adjustments (6.0), this becomes:
+
+```ruby
+# Post-split-adjustments version
+module Spree
+ module Adjustable
+ module Adjuster
+ class Tax < Base
+ def update
+ provider = tax_provider
+ provider.estimate(order, [adjustable])
+
+ # Read from typed TaxLine records
+ included = adjustable.tax_lines.included_in_price.sum(:amount)
+ additional = adjustable.tax_lines.additional.sum(:amount)
+
+ @totals[:included_tax_total] = included
+ @totals[:additional_tax_total] = additional
+ end
+ end
+ end
+ end
+end
+```
+
+### Integration Point: Order Completion
+
+```ruby
+# In Spree::Checkout::Complete (or order completion flow)
+class Spree::Checkout::Complete
+ def call(order:)
+ # ... existing completion logic ...
+
+ # Commit tax document with provider
+ tax_provider = order.store.preferred_tax_provider&.constantize || Spree::TaxProvider::Internal
+ tax_provider.new(order.store).commit(order)
+
+ # ... rest of completion ...
+ end
+end
+```
+
+### Integration Point: Order Cancellation
+
+```ruby
+# In Spree::Orders::Cancel
+class Spree::Orders::Cancel
+ def call(order:)
+ # ... existing cancellation logic ...
+
+ # Void tax document
+ tax_provider = order.store.preferred_tax_provider&.constantize || Spree::TaxProvider::Internal
+ tax_provider.new(order.store).void(order)
+ end
+end
+```
+
+### Store Configuration
+
+```ruby
+class Spree::Store < Spree.base_class
+ preference :tax_provider, :string, default: 'Spree::TaxProvider::Internal'
+end
+```
+
+Admin API allows setting per store:
+
+```json
+PATCH /api/v3/admin/stores/:id
+{
+ "tax_provider": "SpreeTaxAvalara::TaxProvider"
+}
+```
+
+### Tax Exemption Certificates (B2B extension)
+
+Building on the Company model from `6.0-channels-catalogs-b2b.md`:
+
+```ruby
+class Spree::TaxExemptionCertificate < Spree.base_class
+ has_prefix_id :cert
+
+ belongs_to :company, class_name: 'Spree::Company'
+ belongs_to :zone, class_name: 'Spree::Zone', optional: true # jurisdiction
+
+ validates :certificate_number, presence: true
+ validates :status, presence: true # pending, verified, expired, revoked
+
+ attribute :certificate_number, :string
+ attribute :status, :string, default: 'pending'
+ attribute :issued_at, :datetime
+ attribute :expires_at, :datetime
+ attribute :issuing_authority, :string # state/province name
+
+ has_one_attached :document # uploaded certificate PDF/image
+
+ scope :active, -> { where(status: 'verified').where('expires_at IS NULL OR expires_at > ?', Time.current) }
+ scope :for_zone, ->(zone) { where(zone: zone).or(where(zone: nil)) }
+
+ def active?
+ status == 'verified' && (expires_at.nil? || expires_at > Time.current)
+ end
+end
+```
+
+The provider's `exempt?` method checks certificates:
+
+```ruby
+def exempt?(order)
+ return true if order.company&.tax_exempt?
+ return true if order.company_location&.tax_exempt?
+
+ # Check for active certificate covering the order's tax zone
+ if order.company
+ order.company.tax_exemption_certificates
+ .active
+ .for_zone(order.tax_zone)
+ .exists?
+ else
+ false
+ end
+end
+```
+
+## Migration Path
+
+### Phase 1: Provider interface + Internal provider
+
+- Create `Spree::TaxProvider::Base` and `Spree::TaxProvider::Internal`
+- Internal provider delegates to existing `TaxRate.adjust` — zero behavior change
+- Add `tax_provider` preference to Store
+- **No adjuster changes yet** — just the interface + default implementation
+
+### Phase 2: Wire into adjuster
+
+- Modify `Adjuster::Tax` to delegate to provider instead of calling TaxRate directly
+- Add `commit` call to `Checkout::Complete`
+- Add `void` call to `Orders::Cancel`
+- Add `refund` hook to returns flow
+- All existing behavior preserved via Internal provider
+
+### Phase 3: Tax exemption certificates
+
+```ruby
+class CreateSpreeTaxExemptionCertificates < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_tax_exemption_certificates do |t|
+ t.references :company, null: false
+ t.references :zone
+ t.string :certificate_number, null: false
+ t.string :status, null: false, default: 'pending'
+ t.datetime :issued_at
+ t.datetime :expires_at
+ t.string :issuing_authority
+ t.timestamps
+ end
+
+ add_index :spree_tax_exemption_certificates, [:company_id, :status]
+ end
+end
+```
+
+- Create `TaxExemptionCertificate` model
+- Add to Company: `has_many :tax_exemption_certificates`
+- Provider `exempt?` checks certificates
+- Admin API for certificate CRUD
+
+### Phase 4: Adapt to Split Adjustments
+
+When `6.0-split-adjustments.md` ships:
+- Internal provider writes `TaxLine` records instead of `Adjustment` records
+- External providers also write `TaxLine` records
+- Adjuster reads from `tax_lines` instead of `adjustments.tax`
+- `TaxRate.adjust` internally updated to create TaxLines
+
+### Phase 5: Reference external provider (separate gem)
+
+- Create `spree_tax_avalara` gem as reference implementation
+- Implements estimate/commit/void/refund against Avalara AvaTax API
+- Handles: nexus detection, exemption certificate validation, address validation
+- Documents how to build custom providers
+
+## Constraints on Current Work
+
+- **Don't add new tax logic to TaxRate.adjust.** New tax behavior should be designed for the provider interface. TaxRate.adjust stays as the Internal provider's implementation.
+- **Don't add tax-related configuration beyond `Spree::Config[:tax_using_ship_address]`.** Provider-specific config belongs on the provider (via Store preferences or metadata), not in global Spree config.
+- **Don't monkey-patch TaxRate for external tax services.** The provider interface is the intended seam.
+- **Tax exemption checks should use `provider.exempt?(order)`.** Don't add ad-hoc exemption checks in controllers or services.
+- **TaxCategory stays as the product-level tax classification.** External providers use tax category as the "tax code" mapping (e.g., TaxCategory "Clothing" → Avalara tax code "PC040100").
+
+## Open Questions
+
+1. **Shipping rate tax estimation.** `ShippingRate` currently computes tax via `shipping_rate.tax_rate.calculator.compute_shipping_rate(self)` for display during checkout. Should the provider also handle shipping rate tax estimation? Or keep it as-is since it's display-only and the real tax is computed when the shipment is created? Leaning toward provider handles all tax, including shipping rate display.
+
+2. **Caching for external providers.** External API calls during every recalculation could be expensive. Should the provider interface include a caching contract (e.g., "cache estimate for 5 minutes unless address changes")? Or leave caching to the provider implementation? Leaning toward leaving it to the implementation — different providers have different caching needs.
+
+3. **Tax document ID storage.** External providers need to store transaction IDs (for commit/void). Currently the Avalara example uses `order.metadata`. Should there be a dedicated `tax_document_id` column on Order, or is metadata sufficient? Leaning toward metadata — keeps the schema clean and provider-agnostic.
+
+4. **Multi-provider per store.** Some merchants use Avalara for US tax and internal rates for EU VAT. Should we support multiple providers per store (e.g., per-zone routing)? This adds significant complexity. Leaning toward single provider per store for 6.0 — the Avalara provider can internally handle multi-jurisdiction via Avalara's own zone logic.
+
+## References
+
+- Current tax rate: `spree/core/app/models/spree/tax_rate.rb`
+- Current calculator: `spree/core/app/models/spree/calculator/default_tax.rb`
+- Current VAT concern: `spree/core/app/models/concerns/spree/vat_price_calculation.rb`
+- Current tax adjuster: `spree/core/app/models/spree/adjustable/adjuster/tax.rb`
+- Current order updater: `spree/core/app/models/spree/order_updater.rb`
+- Current zone matching: `spree/core/app/models/spree/zone.rb`
+- AdjustmentSource concern: `spree/core/app/models/concerns/spree/adjustment_source.rb`
+- Related plan: `6.0-split-adjustments.md` (TaxLine model replaces polymorphic Adjustment for tax)
+- Related plan: `6.0-channels-catalogs-b2b.md` (Company.tax_exempt, CompanyLocation.tax_exempt)
+- Related plan: `6.0-returns-exchanges-claims.md` (Return flow triggers provider.refund)
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb b/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb
index 637fe9d214..69039e761e 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb
@@ -72,7 +72,7 @@ module Spree
# Includes: latest updated_at, total count, query params, pagination, expand, currency, locale
def collection_cache_key(collection)
# For ActiveRecord collections use updated_at, for plain arrays use store's updated_at as proxy
- latest_updated_at = if collection.first.respond_to?(:updated_at)
+ latest_updated_at = if collection.first&.respond_to?(:updated_at)
collection.map(&:updated_at).max&.to_i
else
current_store&.updated_at&.to_i
diff --git a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
index 4664c4df9a..6db1190cf0 100644
--- a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
@@ -5,32 +5,43 @@ module Spree
module Products
class FiltersController < Store::BaseController
def index
- aggregator = Spree::Api::V3::FiltersAggregator.new(
+ result = search_provider.search_and_filter(
scope: filters_scope,
- currency: current_currency,
- category: category
+ query: params.dig(:q, :search),
+ filters: search_filters.merge('_category' => category),
+ page: 1,
+ limit: 0
)
- render json: aggregator.call
+
+ render json: {
+ filters: result.filters,
+ sort_options: result.sort_options,
+ default_sort: result.default_sort,
+ total_count: result.total_count
+ }
end
private
- # Build scope from category and/or ransack params
- # @return [ActiveRecord::Relation]
def filters_scope
scope = current_store.products.active(current_currency)
scope = scope.in_category(category) if category.present?
- scope = scope.ransack(params[:q]).result if params[:q].present?
scope.accessible_by(current_ability, :show)
end
- # Fetches category from params
- # @param [String] category_id
- # @return [Spree::Category]
+ def search_filters
+ q = params[:q]&.to_unsafe_h || {}
+ q.except('search')
+ end
+
def category
category_id = params[:category_id]
@category ||= category_id.present? ? current_store.categories.find_by_param(category_id) : nil
end
+
+ def search_provider
+ @search_provider ||= Spree.search_provider.constantize.new(current_store)
+ end
end
end
end
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.rb
index 1bf1d83ac4..9345f8225c 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
@@ -5,13 +5,6 @@ module Spree
class ProductsController < ResourceController
include Spree::Api::V3::HttpCaching
- # Sort values that require special scopes (not plain Ransack column sorts).
- CUSTOM_SORT_SCOPES = {
- 'price' => :ascend_by_price,
- '-price' => :descend_by_price,
- 'best_selling' => :by_best_selling
- }.freeze
-
protected
def model_class
@@ -47,37 +40,39 @@ module Spree
]
end
- # Applies sorting from the unified `sort` param.
- # Custom values ('price', '-price', 'best_selling') use product-specific scopes.
- # Standard Ransack values ('name', '-created_at') are handled by base ResourceController.
- def apply_collection_sort(collection)
- sort_value = sort_param
- return collection unless sort_value.present?
+ # Override collection to use search provider.
+ # The provider handles search, filtering, sorting, pagination, and returns a Pagy object.
+ def collection
+ return @collection if @collection.present?
- scope_method = CUSTOM_SORT_SCOPES[sort_value]
- return collection unless scope_method
+ result = search_provider.search_and_filter(
+ scope: scope.includes(collection_includes).preload_associations_lazily.accessible_by(current_ability, :show),
+ query: search_query,
+ filters: search_filters,
+ sort: sort_param,
+ page: page,
+ limit: limit
+ )
- sorted = collection.reorder(nil)
- sorted.send(scope_method)
+ @search_result = result
+ @pagy = result.pagy
+ @collection = result.products
end
- # Skip base Ransack sort injection for custom sort scopes
- def ransack_params
- rp = super
-
- # Remove Ransack sort when a custom scope handles it
- if sort_param.present? && CUSTOM_SORT_SCOPES.key?(sort_param)
- rp = rp.is_a?(Hash) ? rp.dup : rp.to_unsafe_h
- rp.delete('s')
- end
+ private
- rp
+ def search_query
+ params.dig(:q, :search)
end
- private
+ def search_filters
+ q = params[:q]&.to_unsafe_h || params[:q] || {}
+ q = q.to_h if q.respond_to?(:to_h) && !q.is_a?(Hash)
+ q.except('search').presence
+ end
- def custom_sort_requested?
- CUSTOM_SORT_SCOPES.key?(sort_param)
+ def search_provider
+ @search_provider ||= Spree.search_provider.constantize.new(current_store)
end
end
end
diff --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.rb
index 18242fc02a..03d0ca1f48 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
@@ -424,5 +424,66 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
expect(controller.send(:current_currency)).to eq('USD')
end
end
+
+ context 'with Meilisearch search provider' do
+ let(:mock_client) { instance_double(::Meilisearch::Client) }
+ let(:mock_index) { double('Meilisearch::Index') }
+
+ before do
+ allow(Spree).to receive(:search_provider).and_return('Spree::SearchProvider::Meilisearch')
+ allow(::Meilisearch::Client).to receive(:new).and_return(mock_client)
+ allow(mock_client).to receive(:index).and_return(mock_index)
+ end
+
+ after do
+ allow(Spree).to receive(:search_provider).and_call_original
+ end
+
+ it 'searches via Meilisearch when q[search] is present' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'prefixed_id' => product.prefixed_id }],
+ 'estimatedTotalHits' => 1,
+ 'facetDistribution' => {}
+ })
+
+ get :index, params: { q: { search: 'shirt' } }
+
+ expect(response).to have_http_status(:ok)
+ expect(mock_index).to have_received(:search).with('shirt', hash_including(:limit, :offset))
+
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(product.prefixed_id)
+ expect(ids).not_to include(product2.prefixed_id)
+ end
+
+ it 'respects AR scope visibility (does not return draft products from Meilisearch)' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'prefixed_id' => product.prefixed_id }, { 'prefixed_id' => draft_product.prefixed_id }],
+ 'estimatedTotalHits' => 2,
+ 'facetDistribution' => {}
+ })
+
+ get :index, params: { q: { search: 'test' } }
+
+ expect(response).to have_http_status(:ok)
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(product.prefixed_id)
+ expect(ids).not_to include(draft_product.prefixed_id)
+ end
+
+ it 'uses Meilisearch for browsing without search query' do
+ allow(mock_index).to receive(:search).and_return({
+ 'hits' => [{ 'prefixed_id' => product.prefixed_id }, { 'prefixed_id' => product2.prefixed_id }],
+ 'estimatedTotalHits' => 2,
+ 'facetDistribution' => {}
+ })
+
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(mock_index).to have_received(:search)
+ expect(json_response['data'].size).to eq(2)
+ end
+ end
end
end
diff --git a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
index 0ff227b3d4..89e51197e7 100644
--- a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
+++ b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
@@ -110,5 +110,8 @@ Rails.application.config.after_initialize do
# - Spree::PermissionSets::RoleManagement
end
+# Search provider
+# Spree.search_provider = 'Spree::SearchProvider::Meilisearch'
+
Spree.user_class = <%= (options[:user_class].blank? ? 'Spree::LegacyUser' : options[:user_class]).inspect %>
Spree.admin_user_class = <%= (options[:admin_user_class].blank? ? (options[:user_class].blank? ? 'Spree::LegacyAdminUser' : options[:user_class]) : options[:admin_user_class]).inspect %>