From a7de56460db2af35427270efdfa73a06d9698bb9 Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Tue, 27 Sep 2022 18:05:31 +1000 Subject: [PATCH] Further simplify Order by outsourcing to service class --- app/models/spree/order.rb | 11 +---------- app/services/customer_syncer.rb | 11 ++++++++++- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/app/models/spree/order.rb b/app/models/spree/order.rb index aaabdcb497..115d8593bd 100644 --- a/app/models/spree/order.rb +++ b/app/models/spree/order.rb @@ -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 diff --git a/app/services/customer_syncer.rb b/app/services/customer_syncer.rb index 3b770d0c93..35350583ae 100644 --- a/app/services/customer_syncer.rb +++ b/app/services/customer_syncer.rb @@ -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)