diff --git a/app/models/spree/order.rb b/app/models/spree/order.rb index ced4343455..3ea497287f 100644 --- a/app/models/spree/order.rb +++ b/app/models/spree/order.rb @@ -732,23 +732,7 @@ module Spree self.customer ||= find_customer self.customer ||= create_customer if require_customer? - synchronise_customer_email - end - - # Update the customer record if the user changed their email address. - def synchronise_customer_email - if 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 + 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 new file mode 100644 index 0000000000..44661bceef --- /dev/null +++ b/app/services/customer_syncer.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +# Create, find and update customer records. +# +# P.S.: I almost couldn't resist to call this CustomerService. +class CustomerSyncer + 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 + if 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 +end