mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-02-26 01:33:22 +00:00
Clarify updating only pre-existing customers
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user