Merge pull request #9710 from mkllnk/9002-customer-association-updates

Associate and update customer records when ordering
This commit is contained in:
jibees
2022-09-30 16:36:01 +02:00
committed by GitHub
5 changed files with 112 additions and 70 deletions

View File

@@ -704,43 +704,12 @@ module Spree
end
def require_customer?
return false if new_record? || state == 'cart'
true
end
def customer_is_valid?
return true unless require_customer?
customer.present? && customer.enterprise_id == distributor_id && customer.email == email_for_customer
end
def email_for_customer
(user&.email || email)&.downcase
end
def associate_customer
return customer if customer.present?
Customer.of(distributor).find_by(email: email_for_customer)
end
def create_customer
return if customer_is_valid?
Customer.create(
enterprise: distributor,
email: email_for_customer,
user: user,
first_name: bill_address&.first_name.to_s,
last_name: bill_address&.last_name.to_s,
bill_address: bill_address&.clone,
ship_address: ship_address&.clone
)
persisted? && state != "cart"
end
def ensure_customer
self.customer = associate_customer || create_customer
self.customer ||= CustomerSyncer.find_and_update_customer(self)
self.customer ||= CustomerSyncer.create_customer(self) if require_customer?
end
def update_adjustment!(adjustment)

View File

@@ -0,0 +1,48 @@
# frozen_string_literal: true
# Create, find and update customer records.
#
# 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,
email: customer_email(order),
user: order.user,
first_name: order.bill_address&.first_name.to_s,
last_name: order.bill_address&.last_name.to_s,
bill_address: order.bill_address&.clone,
ship_address: order.ship_address&.clone
)
end
def self.customer_email(order)
(order.user&.email || order.email)&.downcase
end
end

View File

@@ -30,7 +30,6 @@ class OrderCartReset
return unless current_user
order.associate_user!(current_user) if order.user.blank? || order.email.blank?
order.__send__(:associate_customer) if order.customer.nil? # Only associates existing customers
end
def reset_order_cycle(current_customer)