Clarify updating only pre-existing customers

This commit is contained in:
Maikel Linke
2022-09-28 14:23:01 +10:00
committed by Konrad
parent a7de56460d
commit 8011d85968
2 changed files with 22 additions and 27 deletions

View File

@@ -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)

View File

@@ -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