Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add pluggable SearchProvider interface with Database provider

Damian Legawieca2ef6e1746d6
diff --git a/spree/core/app/jobs/spree/search_provider/index_job.rb b/spree/core/app/jobs/spree/search_provider/index_job.rb
new file mode 100644
index 0000000000..b4e2e19484
--- /dev/null
+++ b/spree/core/app/jobs/spree/search_provider/index_job.rb
@@ -0,0 +1,22 @@
+module Spree
+ module SearchProvider
+ class IndexJob < Spree::BaseJob
+ queue_as Spree.queues.search
+
+ retry_on StandardError, wait: :polynomially_longer, attempts: 5
+ discard_on ActiveRecord::RecordNotFound
+
+ # @param resource_class [String] e.g. 'Spree::Product'
+ # @param resource_id [String] always pass as string for UUID support
+ # @param store_id [String] always pass as string for UUID support
+ def perform(resource_class, resource_id, store_id)
+ resource = resource_class.constantize.find_by(id: resource_id)
+ store = Spree::Store.find_by(id: store_id)
+ return unless resource && store
+
+ provider = Spree.search_provider.constantize.new(store)
+ provider.index(resource)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/jobs/spree/search_provider/remove_job.rb b/spree/core/app/jobs/spree/search_provider/remove_job.rb
new file mode 100644
index 0000000000..b4796c9810
--- /dev/null
+++ b/spree/core/app/jobs/spree/search_provider/remove_job.rb
@@ -0,0 +1,19 @@
+module Spree
+ module SearchProvider
+ class RemoveJob < Spree::BaseJob
+ queue_as Spree.queues.search
+
+ retry_on StandardError, wait: :polynomially_longer, attempts: 5
+
+ # @param prefixed_id [String] prefixed ID of the document to remove (e.g. 'prod_abc')
+ # @param store_id [String] always pass as string for UUID support
+ def perform(prefixed_id, store_id)
+ store = Spree::Store.find_by(id: store_id)
+ return unless store
+
+ provider = Spree.search_provider.constantize.new(store)
+ provider.remove_by_id(prefixed_id)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/search_indexable.rb b/spree/core/app/models/concerns/spree/search_indexable.rb
new file mode 100644
index 0000000000..1acd93e385
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/search_indexable.rb
@@ -0,0 +1,83 @@
+module Spree
+ module SearchIndexable
+ extend ActiveSupport::Concern
+
+ included do
+ after_commit :enqueue_search_index, on: [:create, :update]
+ after_commit :enqueue_search_removal, on: :destroy
+ end
+
+ # Index this record synchronously (inline, no job).
+ # Useful for bulk imports, rake tasks, or when you need immediate indexing.
+ def add_to_search_index
+ return unless search_indexing_enabled?
+
+ store_ids_for_indexing.each do |store_id|
+ store = Spree::Store.find_by(id: store_id)
+ next unless store
+
+ provider = Spree.search_provider.constantize.new(store)
+ provider.index(self)
+ end
+ end
+
+ # Returns the hash that would be sent to the search provider for indexing.
+ # Useful for debugging and previewing what gets indexed.
+ #
+ # product.search_presentation # uses Spree::Current.store
+ # product.search_presentation(store) # explicit store
+ # => { id: 1, name: "Shirt", price_USD: 19.99, ... }
+ def search_presentation(store = nil)
+ store ||= Spree::Current.store
+ Spree::SearchProvider::ProductPresenter.new(self, store).call
+ end
+
+ # Remove this record from search index synchronously (inline, no job).
+ def remove_from_search_index
+ return unless search_indexing_enabled?
+
+ store_ids_for_indexing.each do |store_id|
+ store = Spree::Store.find_by(id: store_id)
+ next unless store
+
+ provider = Spree.search_provider.constantize.new(store)
+ provider.remove(self)
+ end
+ end
+
+ private
+
+ def enqueue_search_index
+ return unless search_indexing_enabled?
+
+ store_ids_for_indexing.each do |store_id|
+ Spree::SearchProvider::IndexJob.perform_later(self.class.name, id.to_s, store_id.to_s)
+ end
+ end
+
+ def enqueue_search_removal
+ return unless search_indexing_enabled?
+
+ pid = prefixed_id
+ store_ids_for_indexing.each do |store_id|
+ Spree::SearchProvider::RemoveJob.perform_later(pid, store_id.to_s)
+ end
+ end
+
+ def search_indexing_enabled?
+ Spree.search_provider.constantize.indexing_required?
+ rescue NameError
+ false
+ end
+
+ def store_ids_for_indexing
+ if respond_to?(:store_ids)
+ store_ids
+ elsif respond_to?(:store_id)
+ [store_id].compact
+ else
+ Spree::Store.pluck(:id)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/search_provider/base.rb b/spree/core/app/models/spree/search_provider/base.rb
new file mode 100644
index 0000000000..d6daf25a3e
--- /dev/null
+++ b/spree/core/app/models/spree/search_provider/base.rb
@@ -0,0 +1,71 @@
+module Spree
+ module SearchProvider
+ class Base
+ attr_reader :store
+
+ # Whether this provider requires background indexing jobs.
+ # Override in subclasses. Database provider returns false.
+ def self.indexing_required?
+ false
+ end
+
+ 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]
+ 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
+
+ # Remove a document from the index by prefixed ID (used when record is already deleted).
+ #
+ # @param prefixed_id [String] the prefixed ID (e.g. 'prod_abc')
+ def remove_by_id(prefixed_id)
+ # no-op by default
+ end
+
+ # Index a batch of documents. Called by rake task with pre-serialized documents.
+ #
+ # @param documents [Array<Hash>] serialized product documents
+ def index_batch(documents)
+ # no-op by default
+ end
+
+ # Configure index settings (filterable, sortable, searchable attributes).
+ # Called by rake task before indexing. No-op for database provider.
+ def ensure_index_settings!
+ # 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
+ end
+end
diff --git a/spree/core/app/models/spree/search_provider/database.rb b/spree/core/app/models/spree/search_provider/database.rb
new file mode 100644
index 0000000000..2b0ad6a652
--- /dev/null
+++ b/spree/core/app/models/spree/search_provider/database.rb
@@ -0,0 +1,95 @@
+module Spree
+ module SearchProvider
+ class Database < Base
+ CUSTOM_SORT_SCOPES = {
+ 'price' => :ascend_by_price,
+ '-price' => :descend_by_price,
+ 'best_selling' => :by_best_selling
+ }.freeze
+
+ def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)
+ # 1. Text search
+ scope = scope.search(query) if query.present?
+
+ # 2. Extract internal params before passing to Ransack
+ category = filters.is_a?(Hash) ? filters.delete('_category') || filters.delete(:_category) : nil
+
+ # 3. Structured filtering via Ransack
+ ransack_filters = sanitize_filters(filters)
+ if ransack_filters.present?
+ search = scope.ransack(ransack_filters)
+ scope = search.result(distinct: true)
+ end
+
+ # 4. Facets (before sorting to avoid computed column conflicts with count)
+ filter_facets = build_facets(scope, category: category)
+
+ # 4. Total count (before sorting to avoid computed column conflicts with count)
+ total = scope.distinct.count
+
+ # 5. Sorting + pagination
+ scope = apply_sort(scope, sort)
+ page = [page.to_i, 1].max
+ limit = limit.to_i.clamp(1, 100)
+ products = scope.offset((page - 1) * limit).limit(limit)
+
+ SearchResult.new(
+ products: products,
+ filters: filter_facets[:filters],
+ sort_options: filter_facets[:sort_options],
+ default_sort: filter_facets[:default_sort],
+ total_count: total,
+ pagy: build_pagy(total, page, limit)
+ )
+ end
+
+ private
+
+ def build_pagy(count, page, limit)
+ require 'pagy'
+ Pagy::Offset.new(count: count, page: page, limit: limit)
+ end
+
+ def build_facets(scope, category: nil)
+ return { filters: [], sort_options: available_sort_options, default_sort: 'manual' } unless defined?(Spree::Api::V3::FiltersAggregator)
+
+ Spree::Api::V3::FiltersAggregator.new(
+ scope: scope,
+ currency: Spree::Current.currency || store.default_currency,
+ category: category
+ ).call
+ end
+
+ def sanitize_filters(filters)
+ return {} if filters.blank?
+
+ filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
+ filters.except('search', :search, '_category', :_category)
+ end
+
+ def apply_sort(scope, sort)
+ return scope if sort.blank?
+
+ scope_method = CUSTOM_SORT_SCOPES[sort]
+ if scope_method
+ scope.reorder(nil).send(scope_method)
+ else
+ # Standard Ransack sort: 'name' → 'name asc', '-name' → 'name desc'
+ ransack_sort = sort.split(',').map { |field|
+ if field.start_with?('-')
+ "#{field[1..]} desc"
+ else
+ "#{field} asc"
+ end
+ }.join(',')
+
+ scope.ransack(s: ransack_sort).result
+ end
+ end
+
+ def available_sort_options
+ %w[price -price best_selling name -name -available_on available_on].map { |id| { id: id } }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/search_provider/search_result.rb b/spree/core/app/models/spree/search_provider/search_result.rb
new file mode 100644
index 0000000000..fa4739ac63
--- /dev/null
+++ b/spree/core/app/models/spree/search_provider/search_result.rb
@@ -0,0 +1,5 @@
+module Spree
+ module SearchProvider
+ SearchResult = Struct.new(:products, :filters, :sort_options, :default_sort, :total_count, :pagy, keyword_init: true)
+ end
+end
diff --git a/spree/core/app/presenters/spree/search_provider/product_presenter.rb b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
new file mode 100644
index 0000000000..dd21676086
--- /dev/null
+++ b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
@@ -0,0 +1,101 @@
+module Spree
+ module SearchProvider
+ class ProductPresenter
+ attr_reader :product, :store
+
+ def initialize(product, store)
+ @product = product
+ @store = store
+ end
+
+ def call
+ {
+ prefixed_id: product.prefixed_id,
+ name: product.name,
+ description: product.description,
+ slug: product.slug,
+ status: product.status,
+ sku: product.sku,
+ in_stock: product.in_stock?,
+ store_ids: product.store_ids.map(&:to_s),
+ currency_codes: product.prices_including_master.base_prices.where.not(amount: nil).pluck(:currency).uniq,
+ category_ids: product.taxons.map(&:prefixed_id),
+ category_names: product.taxons.pluck(:name),
+ option_type_ids: product.option_types.map(&:prefixed_id),
+ option_type_names: product.option_types.pluck(:presentation),
+ option_value_ids: variant_option_value_ids,
+ option_values: variant_option_value_presentations,
+ tags: product.tag_list || [],
+ thumbnail_url: product.primary_media&.url(:large),
+ units_sold_count: product.store_products.find_by(store: store)&.units_sold_count || 0,
+ discontinue_on: product.discontinue_on&.to_i || 0,
+ available_on: product.available_on&.iso8601,
+ created_at: product.created_at&.iso8601,
+ updated_at: product.updated_at&.iso8601,
+ # Multi-currency prices
+ **prices_by_currency,
+ # Multi-language translations
+ **translations_by_locale
+ }
+ end
+
+ private
+
+ # Indexes base prices (no price list overrides) for all currencies:
+ # { price_USD: 19.99, price_EUR: 17.50, compare_at_price_USD: 24.99 }
+ def prices_by_currency
+ result = {}
+
+ product.prices_including_master.base_prices.where.not(amount: nil).each do |price|
+ currency = price.currency
+ amount = price.amount.to_f
+
+ # Keep the lowest price per currency across all variants
+ key = "price_#{currency}"
+ if result[key].nil? || amount < result[key]
+ result[key] = amount
+ end
+
+ if price.compare_at_amount.present?
+ result["compare_at_price_#{currency}"] = price.compare_at_amount.to_f
+ end
+ end
+
+ result
+ end
+
+ # Indexes translations for all locales: { name_en: "Shirt", name_fr: "Chemise", description_en: "...", ... }
+ def translations_by_locale
+ result = {}
+
+ if product.respond_to?(:translations)
+ product.translations.each do |translation|
+ locale = translation.locale
+ result["name_#{locale}"] = translation.name if translation.name.present?
+ result["description_#{locale}"] = translation.description if translation.description.present?
+ result["slug_#{locale}"] = translation.slug if translation.slug.present?
+ end
+ end
+
+ # Ensure current locale is always indexed
+ result["name_#{I18n.locale}"] ||= product.name
+ result["description_#{I18n.locale}"] ||= product.description
+ result["slug_#{I18n.locale}"] ||= product.slug
+
+ result
+ end
+
+ def variant_option_value_ids
+ variant_option_values_data.map { |ov| ov.prefixed_id }.uniq
+ end
+
+ def variant_option_value_presentations
+ variant_option_values_data.map { |ov| ov.presentation }.uniq
+ end
+
+ def variant_option_values_data
+ @variant_option_values_data ||= product.variants.includes(:option_values).flat_map { |v| v.option_values }
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index e0a83ecc8b..877ae535d9 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -110,13 +110,14 @@ module Spree
gift_cards: :default,
webhooks: :default,
payment_webhooks: :default,
- api_keys: :default
+ api_keys: :default,
+ search: :default
)
end
- # @deprecated Spree.searcher_class is deprecated and will be removed in Spree 5.5.
+ # @deprecated Spree.searcher_class is deprecated and will be removed in Spree 5.5. Use Spree.search_provider instead.
def self.searcher_class=(value)
- Spree::Deprecation.warn('Spree.searcher_class is deprecated and will be removed in Spree 5.5. Please remove it from your initializer.')
+ Spree::Deprecation.warn('Spree.searcher_class is deprecated and will be removed in Spree 5.5. Use Spree.search_provider instead.')
@@searcher_class = value
end
@@ -124,6 +125,18 @@ module Spree
@@searcher_class
end
+ # Search provider class name. Controls product search, filtering, and faceted navigation.
+ #
+ # Spree.search_provider = 'Spree::SearchProvider::Meilisearch'
+ #
+ def self.search_provider
+ @@search_provider ||= 'Spree::SearchProvider::Database'
+ end
+
+ def self.search_provider=(value)
+ @@search_provider = value.to_s
+ end
+
# Returns the events adapter class used for publishing and subscribing to events.
#
# @example Using a custom adapter
diff --git a/spree/core/lib/tasks/search.rake b/spree/core/lib/tasks/search.rake
new file mode 100644
index 0000000000..12167fe26a
--- /dev/null
+++ b/spree/core/lib/tasks/search.rake
@@ -0,0 +1,29 @@
+namespace :spree do
+ namespace :search do
+ desc 'Reindex all products in the search provider'
+ task reindex: :environment do
+ Spree::Store.all.find_each do |store|
+ provider = Spree.search_provider.constantize.new(store)
+ total = store.products.count
+
+ puts "Reindexing #{store.name} (#{total} products)..."
+
+ # Configure index settings (filterable, sortable, searchable attributes)
+ provider.ensure_index_settings! if provider.respond_to?(:ensure_index_settings!)
+
+ indexed = 0
+ store.products.reorder(id: :asc)
+ .preload(:taxons, :option_types, :primary_media,
+ variants_including_master: [:prices, :option_values])
+ .find_in_batches(batch_size: 500) do |batch|
+ documents = batch.map { |product| Spree::SearchProvider::ProductPresenter.new(product, store).call }
+ provider.index_batch(documents) if provider.respond_to?(:index_batch)
+ indexed += batch.size
+ print "\r #{indexed}/#{total} products indexed"
+ end
+
+ puts "\nDone."
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/jobs/spree/search_provider/index_job_spec.rb b/spree/core/spec/jobs/spree/search_provider/index_job_spec.rb
new file mode 100644
index 0000000000..96fb6d8b38
--- /dev/null
+++ b/spree/core/spec/jobs/spree/search_provider/index_job_spec.rb
@@ -0,0 +1,28 @@
+require 'spec_helper'
+
+RSpec.describe Spree::SearchProvider::IndexJob, type: :job do
+ let(:store) { @default_store }
+ let(:product) { create(:product, stores: [store]) }
+
+ describe '#perform' do
+ it 'calls index on the search provider' do
+ provider = instance_double(Spree::SearchProvider::Database)
+ allow(Spree::SearchProvider::Database).to receive(:new).with(store).and_return(provider)
+ expect(provider).to receive(:index).with(product)
+
+ described_class.new.perform('Spree::Product', product.id.to_s, store.id.to_s)
+ end
+
+ it 'does nothing if product is not found' do
+ expect {
+ described_class.new.perform('Spree::Product', '0', store.id.to_s)
+ }.not_to raise_error
+ end
+
+ it 'does nothing if store is not found' do
+ expect {
+ described_class.new.perform('Spree::Product', product.id.to_s, '0')
+ }.not_to raise_error
+ end
+ end
+end
diff --git a/spree/core/spec/jobs/spree/search_provider/remove_job_spec.rb b/spree/core/spec/jobs/spree/search_provider/remove_job_spec.rb
new file mode 100644
index 0000000000..6df56fa451
--- /dev/null
+++ b/spree/core/spec/jobs/spree/search_provider/remove_job_spec.rb
@@ -0,0 +1,21 @@
+require 'spec_helper'
+
+RSpec.describe Spree::SearchProvider::RemoveJob, type: :job do
+ let(:store) { @default_store }
+
+ describe '#perform' do
+ it 'calls remove_by_id on the search provider with prefixed_id' do
+ provider = instance_double(Spree::SearchProvider::Database)
+ allow(Spree::SearchProvider::Database).to receive(:new).with(store).and_return(provider)
+ expect(provider).to receive(:remove_by_id).with('prod_abc')
+
+ described_class.new.perform('prod_abc', store.id.to_s)
+ end
+
+ it 'does nothing if store is not found' do
+ expect {
+ described_class.new.perform('prod_abc', '0')
+ }.not_to raise_error
+ end
+ end
+end
diff --git a/spree/core/spec/models/concerns/spree/search_indexable_spec.rb b/spree/core/spec/models/concerns/spree/search_indexable_spec.rb
new file mode 100644
index 0000000000..d6a0943dc6
--- /dev/null
+++ b/spree/core/spec/models/concerns/spree/search_indexable_spec.rb
@@ -0,0 +1,123 @@
+require 'spec_helper'
+
+RSpec.describe Spree::SearchIndexable, type: :concern do
+ include ActiveJob::TestHelper
+
+ let(:store) { @default_store }
+ let(:product) { create(:product, stores: [store]) }
+
+ describe '#search_presentation' do
+ it 'returns the presenter hash' do
+ result = product.search_presentation(store)
+ expect(result).to be_a(Hash)
+ expect(result[:prefixed_id]).to eq(product.prefixed_id)
+ expect(result[:name]).to eq(product.name)
+ end
+ end
+
+ context 'with database provider (default)' do
+ it 'does not enqueue index jobs on update' do
+ expect {
+ product.update!(name: 'Updated Name')
+ }.not_to have_enqueued_job(Spree::SearchProvider::IndexJob)
+ end
+
+ it 'does not enqueue remove jobs on destroy' do
+ expect {
+ product.destroy
+ }.not_to have_enqueued_job(Spree::SearchProvider::RemoveJob)
+ end
+
+ describe '#add_to_search_index' do
+ it 'is a no-op' do
+ expect_any_instance_of(Spree::SearchProvider::Database).not_to receive(:index)
+ product.add_to_search_index
+ end
+ end
+
+ describe '#remove_from_search_index' do
+ it 'is a no-op' do
+ expect_any_instance_of(Spree::SearchProvider::Database).not_to receive(:remove)
+ product.remove_from_search_index
+ end
+ end
+ end
+
+ context 'with external search provider' do
+ before do
+ allow(Spree).to receive(:search_provider).and_return('Spree::SearchProvider::Meilisearch')
+ end
+
+ after do
+ allow(Spree).to receive(:search_provider).and_call_original
+ end
+
+ it 'enqueues index job on create' do
+ expect {
+ create(:product, stores: [store])
+ }.to have_enqueued_job(Spree::SearchProvider::IndexJob).at_least(1).times
+ end
+
+ it 'enqueues index job on update' do
+ product
+ clear_enqueued_jobs
+ expect {
+ product.update!(name: 'Updated Name')
+ }.to have_enqueued_job(Spree::SearchProvider::IndexJob)
+ end
+
+ it 'enqueues remove job on destroy' do
+ product
+ clear_enqueued_jobs
+ expect {
+ product.destroy
+ }.to have_enqueued_job(Spree::SearchProvider::RemoveJob)
+ end
+
+ it 'passes model class name and stringified IDs for index job' do
+ expect {
+ create(:product, stores: [store])
+ }.to have_enqueued_job(Spree::SearchProvider::IndexJob).with('Spree::Product', anything, store.id.to_s).at_least(1).times
+ end
+
+ describe '#add_to_search_index' do
+ it 'calls provider.index synchronously' do
+ provider = instance_double(Spree::SearchProvider::Meilisearch)
+ allow(Spree::SearchProvider::Meilisearch).to receive(:new).with(store).and_return(provider)
+ expect(provider).to receive(:index).with(product)
+
+ product.add_to_search_index
+ end
+
+ it 'does not enqueue a job' do
+ allow_any_instance_of(Spree::SearchProvider::Meilisearch).to receive(:index)
+ product # trigger create jobs
+ clear_enqueued_jobs
+
+ expect {
+ product.add_to_search_index
+ }.not_to have_enqueued_job(Spree::SearchProvider::IndexJob)
+ end
+ end
+
+ describe '#remove_from_search_index' do
+ it 'calls provider.remove synchronously' do
+ provider = instance_double(Spree::SearchProvider::Meilisearch)
+ allow(Spree::SearchProvider::Meilisearch).to receive(:new).with(store).and_return(provider)
+ expect(provider).to receive(:remove).with(product)
+
+ product.remove_from_search_index
+ end
+
+ it 'does not enqueue a job' do
+ allow_any_instance_of(Spree::SearchProvider::Meilisearch).to receive(:remove)
+ product # trigger create jobs
+ clear_enqueued_jobs
+
+ expect {
+ product.remove_from_search_index
+ }.not_to have_enqueued_job(Spree::SearchProvider::RemoveJob)
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/search_provider/base_spec.rb b/spree/core/spec/models/spree/search_provider/base_spec.rb
new file mode 100644
index 0000000000..58eee95ad9
--- /dev/null
+++ b/spree/core/spec/models/spree/search_provider/base_spec.rb
@@ -0,0 +1,44 @@
+require 'spec_helper'
+
+module Spree
+ RSpec.describe SearchProvider::Base do
+ let(:store) { @default_store }
+ let(:provider) { described_class.new(store) }
+
+ describe '#initialize' do
+ it 'stores the store' do
+ expect(provider.store).to eq(store)
+ end
+ end
+
+ describe '#search_and_filter' do
+ it 'raises NotImplementedError' do
+ expect { provider.search_and_filter(scope: Spree::Product.all) }.to raise_error(NotImplementedError)
+ end
+ end
+
+ describe '#index' do
+ it 'is a no-op by default' do
+ expect { provider.index(build(:product)) }.not_to raise_error
+ end
+ end
+
+ describe '#remove' do
+ it 'is a no-op by default' do
+ expect { provider.remove(build(:product)) }.not_to raise_error
+ end
+ end
+
+ describe '#remove_by_id' do
+ it 'is a no-op by default' do
+ expect { provider.remove_by_id(1) }.not_to raise_error
+ end
+ end
+
+ describe '#reindex' do
+ it 'is a no-op by default' do
+ expect { provider.reindex }.not_to raise_error
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/search_provider/database_spec.rb b/spree/core/spec/models/spree/search_provider/database_spec.rb
new file mode 100644
index 0000000000..4a4264ba04
--- /dev/null
+++ b/spree/core/spec/models/spree/search_provider/database_spec.rb
@@ -0,0 +1,147 @@
+require 'spec_helper'
+
+module Spree
+ RSpec.describe SearchProvider::Database do
+ let(:store) { @default_store }
+ let(:provider) { described_class.new(store) }
+
+ let!(:product_1) { create(:product, name: 'Blue Shirt', stores: [store]) }
+ let!(:product_2) { create(:product, name: 'Red Pants', stores: [store]) }
+ let!(:product_3) { create(:product, name: 'Blue Jacket', stores: [store]) }
+
+ describe '#search_and_filter' do
+ let(:scope) { store.products }
+
+ context 'with text search' do
+ subject(:result) { provider.search_and_filter(scope: scope, query: 'blue') }
+
+ it 'returns matching products' do
+ expect(result.products).to include(product_1, product_3)
+ expect(result.products).not_to include(product_2)
+ end
+
+ it 'returns a SearchResult' do
+ expect(result).to be_a(SearchProvider::SearchResult)
+ end
+
+ it 'returns total count' do
+ expect(result.total_count).to eq(2)
+ end
+
+ it 'returns sort options as objects' do
+ expect(result.sort_options).to be_an(Array)
+ ids = result.sort_options.map { |o| o[:id] }
+ expect(ids).to include('price', '-price', 'best_selling')
+ end
+ end
+
+ context 'without search query' do
+ subject(:result) { provider.search_and_filter(scope: scope) }
+
+ it 'returns all products' do
+ expect(result.products).to include(product_1, product_2, product_3)
+ end
+
+ it 'returns correct total count' do
+ expect(result.total_count).to eq(3)
+ end
+ end
+
+ context 'with blank query' do
+ subject(:result) { provider.search_and_filter(scope: scope, query: '') }
+
+ it 'returns all products' do
+ expect(result.total_count).to eq(3)
+ end
+ end
+
+ context 'with pagination' do
+ subject(:result) { provider.search_and_filter(scope: scope, page: 1, limit: 2) }
+
+ it 'limits results' do
+ expect(result.products.length).to eq(2)
+ end
+
+ it 'returns full total count' do
+ expect(result.total_count).to eq(3)
+ end
+ end
+
+ context 'with page 2' do
+ subject(:result) { provider.search_and_filter(scope: scope, page: 2, limit: 2) }
+
+ it 'offsets results' do
+ expect(result.products.length).to eq(1)
+ end
+ end
+
+ context 'with sorting' do
+ subject(:result) { provider.search_and_filter(scope: scope, sort: 'name') }
+
+ it 'sorts by name ascending' do
+ names = result.products.map(&:name)
+ expect(names).to eq(names.sort)
+ end
+ end
+
+ context 'with descending sort' do
+ subject(:result) { provider.search_and_filter(scope: scope, sort: '-name') }
+
+ it 'sorts by name descending' do
+ names = result.products.map(&:name)
+ expect(names).to eq(names.sort.reverse)
+ end
+ end
+
+ context 'with custom price sort' do
+ subject(:result) { provider.search_and_filter(scope: scope, sort: 'price') }
+
+ it 'returns all products' do
+ expect(result.total_count).to eq(3)
+ end
+ end
+
+ context 'with ransack filters' do
+ subject(:result) { provider.search_and_filter(scope: scope, filters: { 'name_cont' => 'Shirt' }) }
+
+ it 'filters by ransack params' do
+ expect(result.products).to include(product_1)
+ expect(result.products).not_to include(product_2, product_3)
+ end
+ end
+
+ context 'with search and filters combined' do
+ subject(:result) { provider.search_and_filter(scope: scope, query: 'blue', filters: { 'name_cont' => 'Shirt' }) }
+
+ it 'applies both search and filters' do
+ expect(result.products).to include(product_1)
+ expect(result.products).not_to include(product_2, product_3)
+ end
+ end
+ end
+
+ describe '#index' do
+ it 'is a no-op' do
+ expect { provider.index(product_1) }.not_to raise_error
+ end
+ end
+
+ describe '#remove' do
+ it 'is a no-op' do
+ expect { provider.remove(product_1) }.not_to raise_error
+ end
+ end
+
+ describe '#remove_by_id' do
+ it 'is a no-op' do
+ expect { provider.remove_by_id(product_1.id) }.not_to raise_error
+ end
+ end
+
+ describe '#reindex' do
+ it 'is a no-op' do
+ expect { provider.reindex(store.products) }.not_to raise_error
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb b/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
new file mode 100644
index 0000000000..b1f4910ff1
--- /dev/null
+++ b/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
@@ -0,0 +1,94 @@
+require 'spec_helper'
+
+module Spree
+ RSpec.describe SearchProvider::ProductPresenter do
+ let(:store) { @default_store }
+ let(:product) { create(:product, name: 'Test Shirt', stores: [store]) }
+ let(:presenter) { described_class.new(product, store) }
+
+ describe '#call' do
+ subject(:result) { presenter.call }
+
+ it 'returns a hash' do
+ expect(result).to be_a(Hash)
+ end
+
+ it 'includes core product attributes' do
+ expect(result[:prefixed_id]).to eq(product.prefixed_id)
+ expect(result[:name]).to eq('Test Shirt')
+ expect(result[:slug]).to eq(product.slug)
+ expect(result[:status]).to eq(product.status)
+ expect(result[:sku]).to eq(product.sku)
+ end
+
+ it 'includes timestamps' do
+ expect(result[:created_at]).to be_present
+ expect(result[:updated_at]).to be_present
+ end
+
+ it 'includes stock status' do
+ expect(result).to have_key(:in_stock)
+ end
+
+ it 'includes category data' do
+ expect(result[:category_ids]).to be_an(Array)
+ expect(result[:category_names]).to be_an(Array)
+ end
+
+ context 'with categories' do
+ let(:taxonomy) { create(:taxonomy, store: store) }
+ let(:taxon) { create(:taxon, taxonomy: taxonomy) }
+ let(:product) { create(:product, name: 'Test Shirt', stores: [store], taxons: [taxon]) }
+
+ it 'indexes category_ids as prefixed IDs' do
+ expect(result[:category_ids]).to eq([taxon.prefixed_id])
+ expect(result[:category_ids].first).to start_with('ctg_')
+ end
+ end
+
+ it 'includes option data as prefixed IDs' do
+ expect(result[:option_type_ids]).to be_an(Array)
+ expect(result[:option_value_ids]).to be_an(Array)
+ end
+
+ context 'with prices in multiple currencies' do
+ before do
+ product.master.prices.find_by(currency: 'USD')&.update!(amount: 19.99)
+ create(:price, variant: product.master, amount: 17.50, currency: 'EUR')
+ end
+
+ it 'indexes prices for each currency' do
+ expect(result['price_USD']).to eq(19.99)
+ expect(result['price_EUR']).to eq(17.50)
+ end
+ end
+
+ context 'with compare_at_price' do
+ before do
+ product.master.prices.find_by(currency: 'USD')&.update!(amount: 19.99, compare_at_amount: 29.99)
+ end
+
+ it 'indexes compare_at_price' do
+ expect(result['compare_at_price_USD']).to eq(29.99)
+ end
+ end
+
+ context 'with translations' do
+ it 'indexes translations for the current locale' do
+ expect(result["name_#{I18n.locale}"]).to eq('Test Shirt')
+ end
+ end
+
+ context 'with option values' do
+ let(:product) { create(:product_with_option_types, stores: [store]) }
+
+ it 'includes option value prefixed IDs' do
+ expect(result[:option_value_ids]).to be_an(Array)
+ result[:option_value_ids].each do |ov_id|
+ expect(ov_id).to start_with('optval_')
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/spree_core.gemspec b/spree/core/spree_core.gemspec
index 375f98743f..1168d9649c 100644
--- a/spree/core/spree_core.gemspec
+++ b/spree/core/spree_core.gemspec
@@ -68,4 +68,5 @@ Gem::Specification.new do |s|
s.add_dependency 'bcrypt', '~> 3.1'
s.add_dependency 'sqids', '~> 0.2'
s.add_dependency 'ssrf_filter', '~> 1.0'
+ s.add_dependency 'pagy', '~> 43.0'
end