Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added `Variant#search`
Damian Legawiec511de45219b4
diff --git a/spree/core/app/models/spree/price.rb b/spree/core/app/models/spree/price.rbindex be28be472c..89390832be 100644--- a/spree/core/app/models/spree/price.rb+++ b/spree/core/app/models/spree/price.rb@@ -57,6 +57,18 @@ module Spreeself.whitelisted_ransackable_attributes = %w[amount compare_at_amount currency price_list_id variant_id]self.whitelisted_ransackable_associations = %w[variant price_list]+ self.whitelisted_ransackable_scopes = %i[search]++ # Free-text search delegated to `Spree::Variant.search` (SKU + product+ # name + option-value presentation), wrapped in a subquery so that+ # multi-option-value variants don't produce duplicate Price rows —+ # the prices index has `collection_distinct?` off (PG DISTINCT ++ # ORDER BY incompat), so any join-based predicate would double up.+ scope :search, ->(query) {+ next all if query.blank?++ where(variant_id: Spree::Variant.search(query).select(:id))+ }attribute :eligible_for_taxon_matching, :boolean, default: falsebefore_validation -> { self.eligible_for_taxon_matching = new_record? ? discounted? : discounted? != was_discounted? }diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex becb640a8a..3e0dd96332 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -8,6 +8,7 @@ module Spreeinclude Spree::MemoizedDatainclude Spree::Metafieldsinclude Spree::Metadata+ include Spree::Searchableinclude Spree::Variant::Webhookspublishes_lifecycle_events@@ -140,11 +141,29 @@ module Spreescope :with_digital_assets, -> { joins(:digitals) }- scope :search, ->(query) {- next none if query.blank? || query.length < 3+ # Free-text variant search: SKU, parent product name, and any+ # option-value presentation (e.g. "Red", "XL"). The 3-char floor+ # keeps single-letter queries from triggering a full scan.+ def self.search(query)+ return none if query.blank? || query.length < 3- product_name_or_sku_cont(query)- }+ conditions = [+ search_condition(self, :sku, query),+ search_condition(Spree::OptionValue, :presentation, query),+ ]++ if Spree.use_translations?+ translation_table = Product::Translation.arel_table.alias(Product.translation_table_alias)+ sanitized = sanitize_query_for_search(query)+ conditions << translation_table[:name].lower.matches("%#{sanitized}%", '\\')+ else+ conditions << search_condition(Spree::Product, :name, query)+ end++ relation = joins(:product).left_joins(:option_values)+ relation = relation.join_translation_table(Product) if Spree.use_translations?+ relation.where(conditions.reduce(:or)).distinct+ end# Backward compatibility alias — remove in Spree 6.0scope :multi_search, ->(*args) { search(*args) }@@ -178,7 +197,7 @@ module Spreeself.whitelisted_ransackable_associations = %w[option_values product tax_category prices default_price]self.whitelisted_ransackable_attributes = %w[weight depth width height sku discontinue_on is_master cost_price cost_currency track_inventory- deleted_at]+ deleted_at product_id]self.whitelisted_ransackable_scopes = %i(product_name_or_sku_cont search_by_product_name_or_sku search)def self.product_name_or_sku_cont(query)diff --git a/spree/core/spec/models/spree/variant_spec.rb b/spree/core/spec/models/spree/variant_spec.rbindex a50fd657c7..acdc7ef05a 100644--- a/spree/core/spec/models/spree/variant_spec.rb+++ b/spree/core/spec/models/spree/variant_spec.rb@@ -372,6 +372,79 @@ describe Spree::Variant, type: :model doendend+ describe '.search' do+ # Free-text variant search used by the admin spreadsheet — ORs the+ # variant's SKU, parent product's name, and any option-value+ # presentation. Backed by `Spree::Searchable#search_condition`, so+ # LIKE-wildcard escaping is handled centrally.+ let(:product) { create(:product, name: 'Crewneck Sweater') }+ let(:color_type) do+ Spree::OptionType.find_by(name: 'spec-color') ||+ create(:option_type, name: 'spec-color', presentation: 'Color')+ end+ let(:size_type) do+ Spree::OptionType.find_by(name: 'spec-size') ||+ create(:option_type, name: 'spec-size', presentation: 'Size')+ end+ let(:red) do+ color_type.option_values.find_by(name: 'red') ||+ create(:option_value, option_type: color_type, name: 'red', presentation: 'Red')+ end+ let(:xl) do+ size_type.option_values.find_by(name: 'xl') ||+ create(:option_value, option_type: size_type, name: 'xl', presentation: 'XL')+ end+ let!(:red_xl_variant) do+ v = create(:variant, product: product, sku: 'SWEATER-RED-XL')+ v.option_values << [red, xl]+ v+ end+ let!(:other_product) { create(:product, name: 'Plain Tee') }+ let!(:other_variant) { create(:variant, product: other_product, sku: 'TEE-001') }++ it 'matches by SKU substring' do+ expect(described_class.search('SWEATER')).to include(red_xl_variant)+ expect(described_class.search('SWEATER')).not_to include(other_variant)+ end++ it 'matches by parent product name (case-insensitive)' do+ expect(described_class.search('crewneck')).to include(red_xl_variant)+ end++ it 'matches by option-value presentation' do+ # "Red" hits the SKU too; assert against an option-value-only+ # variant to prove the option-value branch fires independently.+ blue = color_type.option_values.find_by(name: 'blue') ||+ create(:option_value, option_type: color_type, name: 'blue', presentation: 'Blue')+ plain_blue = create(:variant, product: other_product, sku: 'TEE-002', option_values: [blue])+ expect(described_class.search('Blue')).to include(plain_blue)+ expect(described_class.search('Blue')).not_to include(other_variant)+ end++ it 'returns none for blank queries' do+ expect(described_class.search('')).to be_empty+ expect(described_class.search(nil)).to be_empty+ end++ it 'returns none for queries under the 3-char floor' do+ expect(described_class.search('Re')).to be_empty+ end++ it 'returns each matching variant exactly once even with multiple matching option values' do+ # Both "Red" and "XL" presentations live on the same variant; the+ # underlying join would return one row per option_value match+ # without the `.distinct` in the scope.+ results = described_class.search('SWEATER').to_a+ expect(results.count(red_xl_variant)).to eq(1)+ end++ it 'escapes LIKE wildcards in the query' do+ # `john_doe` should not be treated as `john<any>doe`.+ create(:variant, product: product, sku: 'JOHNxDOE')+ expect(described_class.search('john_doe').pluck(:sku)).not_to include('JOHNxDOE')+ end+ end+describe '.active' dolet!(:variants) { [variant] }let!(:currency) { 'EUR' }