From a0260c4ff78cddc1e9da7e17d137930d65143bdf Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Tue, 27 Sep 2022 17:53:04 +1000 Subject: [PATCH] Move customer update logic to own service file The Order class is too big already. We can move more code in the next commits. --- app/models/spree/order.rb | 18 +----------------- app/services/customer_syncer.rb | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 17 deletions(-) create mode 100644 app/services/customer_syncer.rb 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