diff --git a/app/models/spree/order.rb b/app/models/spree/order.rb index 115d8593bd..2c2df175cd 100644 --- a/app/models/spree/order.rb +++ b/app/models/spree/order.rb @@ -708,10 +708,8 @@ module Spree end def ensure_customer - self.customer ||= CustomerSyncer.find_customer(self) + self.customer ||= CustomerSyncer.find_and_update_customer(self) self.customer ||= CustomerSyncer.create_customer(self) if require_customer? - - CustomerSyncer.new(self).synchronise_customer_email end def update_adjustment!(adjustment) diff --git a/app/services/customer_syncer.rb b/app/services/customer_syncer.rb index 35350583ae..f97b845c64 100644 --- a/app/services/customer_syncer.rb +++ b/app/services/customer_syncer.rb @@ -4,11 +4,32 @@ # # P.S.: I almost couldn't resist to call this CustomerService. class CustomerSyncer + def self.find_and_update_customer(order) + find_customer(order).tap { |customer| synchronise_email(order, customer) } + end + def self.find_customer(order) order.user&.customers&.of(order.distributor)&.first || Customer.of(order.distributor).find_by(email: customer_email(order)) end + def self.synchronise_email(order, customer) + email = order.user&.email + + return unless email && customer && email != customer.email + + duplicate = Customer.find_by(email: email, enterprise: order.distributor) + + if duplicate.present? + Spree::Order.where(customer_id: duplicate.id).update_all(customer_id: customer.id) + Subscription.where(customer_id: duplicate.id).update_all(customer_id: customer.id) + + duplicate.destroy + end + + customer.update(email: email) + end + def self.create_customer(order) Customer.create( enterprise: order.distributor, @@ -24,28 +45,4 @@ class CustomerSyncer def self.customer_email(order) (order.user&.email || order.email)&.downcase end - - attr_reader :customer, :distributor, :user - - def initialize(order) - @customer = order.customer - @distributor = order.distributor - @user = order.user - end - - # Update the customer record if the user changed their email address. - def synchronise_customer_email - return unless user && customer && user.email != customer.email - - duplicate = Customer.find_by(email: user.email, enterprise: distributor) - - if duplicate.present? - Spree::Order.where(customer_id: duplicate.id).update_all(customer_id: customer.id) - Subscription.where(customer_id: duplicate.id).update_all(customer_id: customer.id) - - duplicate.destroy - end - - customer.update(email: user.email) - end end