Further simplify Order by outsourcing to service class

This commit is contained in:
Maikel Linke
2022-09-27 18:05:31 +10:00
committed by Konrad
parent 1f19642dad
commit a7de56460d
2 changed files with 11 additions and 11 deletions

View File

@@ -707,17 +707,8 @@ module Spree
persisted? && state != "cart"
end
def email_for_customer
(user&.email || email)&.downcase
end
def find_customer
user&.customers&.of(distributor)&.first ||
Customer.of(distributor).find_by(email: email_for_customer)
end
def ensure_customer
self.customer ||= find_customer
self.customer ||= CustomerSyncer.find_customer(self)
self.customer ||= CustomerSyncer.create_customer(self) if require_customer?
CustomerSyncer.new(self).synchronise_customer_email

View File

@@ -4,10 +4,15 @@
#
# P.S.: I almost couldn't resist to call this CustomerService.
class CustomerSyncer
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.create_customer(order)
Customer.create(
enterprise: order.distributor,
email: (order.user&.email || order.email)&.downcase,
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,
@@ -16,6 +21,10 @@ class CustomerSyncer
)
end
def self.customer_email(order)
(order.user&.email || order.email)&.downcase
end
attr_reader :customer, :distributor, :user
def initialize(order)