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
Fix multi search on the orders admin page (#12466)
Łukasz Adamczyk9e92ad2b5185
diff --git a/admin/app/helpers/spree/admin/orders_filters_helper.rb b/admin/app/helpers/spree/admin/orders_filters_helper.rbindex 04eb46d265..9f549e9974 100644--- a/admin/app/helpers/spree/admin/orders_filters_helper.rb+++ b/admin/app/helpers/spree/admin/orders_filters_helper.rb@@ -51,42 +51,13 @@ module Spreeenddef load_orders- base_scope = scope.preload(:user).accessible_by(current_ability, :index)-- if params.dig(:q, :multisearch).present?- shared_context = Ransack::Context.for(Spree::Order)-- search_by_number = Spree::Order.ransack(- { number_i_cont: params.dig(:q, :multisearch) }, context: shared_context- )-- search_by_email = Spree::Order.ransack(- { email_eq: params.dig(:q, :multisearch) }, context: shared_context- )-- search_by_firstname = Spree::Order.ransack(- { bill_address_firstname_i_cont_any: params.dig(:q, :multisearch) }, context: shared_context- )-- search_by_lastname = Spree::Order.ransack(- { bill_address_lastname_eq: params.dig(:q, :multisearch) }, context: shared_context- )-- shared_conditions = [search_by_number, search_by_email, search_by_firstname, search_by_lastname].map do |search|- Ransack::Visitor.new.accept(search.base)- end-- @multisearch_orders = base_scope.joins(shared_context.join_sources).where(shared_conditions.reduce(&:or)).distinct- end-- @search = base_scope.ransack(params_to_filters(search_params: params[:q].clone, vendor: @vendor, user: @user))+ @search = scope.preload(:user).accessible_by(current_ability, :index).+ ransack(params_to_filters(search_params: params[:q].clone, vendor: @vendor, user: @user))# lazy loading other models here (via includes) may result in an invalid query# e.g. SELECT DISTINCT DISTINCT "spree_orders".id, "spree_orders"."created_at" AS alias_0 FROM "spree_orders"# see https://github.com/spree/spree/pull/3919- @orders = @search.result(distinct: true)- @orders = @orders.merge(@multisearch_orders) if @multisearch_orders.present?- @orders = @orders.page(params[:page]).per(params[:per_page])+ @orders = @search.result(distinct: true).page(params[:page]).per(params[:per_page])enddef load_userdiff --git a/admin/app/views/spree/admin/orders/_filters.html.erb b/admin/app/views/spree/admin/orders/_filters.html.erbindex 57226b9d57..2903832324 100644--- a/admin/app/views/spree/admin/orders/_filters.html.erb+++ b/admin/app/views/spree/admin/orders/_filters.html.erb@@ -11,7 +11,7 @@<%= hidden_field_tag :frame_name, frame_name if frame_name.present? %><div class="d-flex flex-column flex-lg-row gap-2">- <%= render 'spree/admin/shared/filters_search_bar', param: :multisearch %>+ <%= render 'spree/admin/shared/filters_search_bar', param: :multi_search %><div class="d-flex align-items-center justify-content-between"><div class="mr-2 h-100">diff --git a/core/app/models/concerns/spree/multi_searchable.rb b/core/app/models/concerns/spree/multi_searchable.rbnew file mode 100644index 0000000000..1abe41a96c--- /dev/null+++ b/core/app/models/concerns/spree/multi_searchable.rb@@ -0,0 +1,21 @@+module Spree+ module MultiSearchable+ extend ActiveSupport::Concern++ included do+ def self.sanitize_query_for_multi_search(query)+ ActiveRecord::Base.sanitize_sql_like(query.to_s.downcase.strip)+ end++ def self.multi_search_condition(model_class, attribute, query)+ encrypted_attributes = model_class.encrypted_attributes.presence || []++ if encrypted_attributes.include?(attribute.to_sym)+ model_class.arel_table[attribute.to_sym].eq(query)+ else+ model_class.arel_table[attribute.to_sym].lower.matches("%#{query}%")+ end+ end+ end+ end+enddiff --git a/core/app/models/concerns/spree/user_methods.rb b/core/app/models/concerns/spree/user_methods.rbindex 2159e86b89..02601833f0 100644--- a/core/app/models/concerns/spree/user_methods.rb+++ b/core/app/models/concerns/spree/user_methods.rb@@ -6,7 +6,7 @@ module Spreeinclude Spree::UserReportinginclude Spree::UserRolesinclude Spree::RansackableAttributes-+ include Spree::MultiSearchableincluded do# we need to have this callback before any dependent: :destroy associations# https://github.com/rails/rails/issues/3458@@ -43,26 +43,24 @@ module Spree#attr_accessor :confirm_email, :terms_of_service- scope :multi_search, lambda { |query|- sanitized_query = ActiveRecord::Base.sanitize_sql_like(query.to_s.downcase.strip)+ def self.multi_search(query)+ sanitized_query = sanitize_query_for_multi_search(query)return none if query.blank?- query_pattern = "%#{sanitized_query}%"-name_conditions = []- name_conditions << arel_table[:first_name].lower.matches(query_pattern)- name_conditions << arel_table[:last_name].lower.matches(query_pattern)+ name_conditions << multi_search_condition(self, :first_name, sanitized_query)+ name_conditions << multi_search_condition(self, :last_name, sanitized_query)full_name = NameOfPerson::PersonName.full(sanitized_query)if full_name.first.present? && full_name.last.present?- name_conditions << arel_table[:first_name].lower.matches("%#{full_name.first}%")- name_conditions << arel_table[:last_name].lower.matches("%#{full_name.last}%")+ name_conditions << multi_search_condition(self, :first_name, full_name.first)+ name_conditions << multi_search_condition(self, :last_name, full_name.last)endwhere(email: sanitized_query).or(where(name_conditions.reduce(:or)))- }+ endself.whitelisted_ransackable_associations = %w[bill_address ship_address addresses tags]self.whitelisted_ransackable_attributes = %w[id email first_name last_name accepts_email_marketing]diff --git a/core/app/models/spree/order.rb b/core/app/models/spree/order.rbindex b5c04b6ab9..4b3022f121 100644--- a/core/app/models/spree/order.rb+++ b/core/app/models/spree/order.rb@@ -26,6 +26,7 @@ module Spreeinclude Spree::SingleStoreResourceinclude Spree::MemoizedDatainclude Spree::Metadata+ include Spree::MultiSearchableif defined?(Spree::Security::Orders)include Spree::Security::Ordersend@@ -79,7 +80,7 @@ module Spreecompleted_at email number state payment_state shipment_statetotal item_total item_count considered_risky channel]- self.whitelisted_ransackable_scopes = %w[refunded partially_refunded]+ self.whitelisted_ransackable_scopes = %w[refunded partially_refunded multi_search]attr_reader :coupon_codeattr_accessor :temporary_address, :temporary_credit_card@@ -202,6 +203,28 @@ module Spree# shows completed orders first, by their completed_at date, then uncompleted orders by their created_atscope :reverse_chronological, -> { order(Arel.sql('spree_orders.completed_at IS NULL'), completed_at: :desc, created_at: :desc) }+ def self.multi_search(query)+ sanitized_query = sanitize_query_for_multi_search(query)+ return none if query.blank?++ query_pattern = "%#{sanitized_query}%"++ conditions = []+ conditions << arel_table[:number].lower.matches(query_pattern)++ conditions << multi_search_condition(Spree::Address, :firstname, sanitized_query)+ conditions << multi_search_condition(Spree::Address, :lastname, sanitized_query)++ full_name = NameOfPerson::PersonName.full(sanitized_query)++ if full_name.first.present? && full_name.last.present?+ conditions << multi_search_condition(Spree::Address, :firstname, full_name.first)+ conditions << multi_search_condition(Spree::Address, :lastname, full_name.last)+ end++ left_joins(:bill_address).where(email: sanitized_query).or(where(conditions.reduce(:or)))+ end+# Use this method in other gems that wish to register their own custom logic# that should be called after Order#updatedef self.register_update_hook(hook)diff --git a/core/spec/models/spree/order_spec.rb b/core/spec/models/spree/order_spec.rbindex 8c71bff104..df58232db9 100644--- a/core/spec/models/spree/order_spec.rb+++ b/core/spec/models/spree/order_spec.rb@@ -34,6 +34,38 @@ describe Spree::Order, type: :model dodescribe '.not_canceled' doit { expect(Spree::Order.not_canceled).not_to include canceled_order }end++ describe '.multi_search' do+ let!(:order_1) { create(:order, number: 'R100', user: create(:user, email: '[email protected]'), bill_address: create(:address, first_name: 'Don', last_name: 'Roe')) }+ let!(:order_2) { create(:order, number: 'R101', user: create(:user, email: '[email protected]'), bill_address: create(:address, first_name: 'Jane', last_name: 'Gone')) }+ let!(:order_3) { create(:order, number: 'R200', user: create(:user, email: '[email protected]'), bill_address: create(:address, first_name: 'Mary', last_name: 'Moe')) }++ it 'returns orders based on an email' do+ expect(described_class.multi_search('[email protected]')).to eq([order_1])+ expect(described_class.multi_search('[email protected]')).to eq([order_2])+ expect(described_class.multi_search('mary.moe@')).to eq([])+ end++ it 'returns orders based on the first name' do+ expect(described_class.multi_search('don')).to eq([order_1])+ expect(described_class.multi_search('jan')).to eq([order_2])+ expect(described_class.multi_search('greg')).to eq([])+ end++ it 'returns orders based on the last name' do+ expect(described_class.multi_search('ro')).to eq([order_1])+ expect(described_class.multi_search('moe')).to eq([order_3])+ expect(described_class.multi_search('smith')).to eq([])+ end++ it 'returns orders based on the full name' do+ expect(described_class.multi_search('don ro')).to eq([order_1])+ expect(described_class.multi_search('ane gon')).to eq([order_2])+ expect(described_class.multi_search('mary moe')).to eq([order_3])+ expect(described_class.multi_search('jane moe')).to eq([order_2, order_3])+ expect(described_class.multi_search('greg smith')).to eq([])+ end+ endenddescribe 'Callbacks' do