diff --git a/lib/spree/chimpy/interface/customer_upserter.rb b/lib/spree/chimpy/interface/customer_upserter.rb index 59690d9..26af94c 100644 --- a/lib/spree/chimpy/interface/customer_upserter.rb +++ b/lib/spree/chimpy/interface/customer_upserter.rb @@ -39,6 +39,8 @@ def customer_id_from_eid(mc_eid) private def upsert_customer + return unless @order.user_id + customer_id = self.class.mailchimp_customer_id(@order.user_id) begin response = store_api_call diff --git a/lib/spree/chimpy/interface/order_upserter.rb b/lib/spree/chimpy/interface/order_upserter.rb index 5c7ec4c..a0ed0a1 100644 --- a/lib/spree/chimpy/interface/order_upserter.rb +++ b/lib/spree/chimpy/interface/order_upserter.rb @@ -7,8 +7,15 @@ def initialize(order) @order = order end + def customer_id + @customer_id ||= CustomerUpserter.new(@order).ensure_customer + end + def upsert + return unless customer_id + Products.ensure_products(@order) + perform_upsert end @@ -52,7 +59,6 @@ def order_variant_hash(line_item) end def order_hash - customer_id = CustomerUpserter.new(@order).ensure_customer source = @order.source lines = @order.line_items.map do |line| diff --git a/spec/lib/customers_interface_spec.rb b/spec/lib/customers_interface_spec.rb index 183f4ee..e7cca15 100644 --- a/spec/lib/customers_interface_spec.rb +++ b/spec/lib/customers_interface_spec.rb @@ -40,14 +40,23 @@ expect(interface.ensure_customer).to eq "customer_999" end - it "upserts the customer when not found by order source" do - allow(interface).to receive(:customer_id_from_eid) - .with('id-abcd') - .and_return(nil) + context "when no customer from order source" do + before(:each) do + allow(interface).to receive(:customer_id_from_eid) + .with('id-abcd') + .and_return(nil) + end - allow(interface).to receive(:upsert_customer) { "customer_998" } + it "upserts the customer" do + allow(interface).to receive(:upsert_customer) { "customer_998" } - expect(interface.ensure_customer).to eq "customer_998" + expect(interface.ensure_customer).to eq "customer_998" + end + + it "returns nil if guest checkout" do + order.user_id = nil + expect(interface.ensure_customer).to be_nil + end end end diff --git a/spec/lib/order_upserter_spec.rb b/spec/lib/order_upserter_spec.rb index fdb163c..e5be979 100644 --- a/spec/lib/order_upserter_spec.rb +++ b/spec/lib/order_upserter_spec.rb @@ -73,6 +73,15 @@ def check_hash(h, expected_customer_id) interface.upsert end + it "does not perform the order upsert if no customer_id exists" do + expect(customer_upserter).to receive(:ensure_customer) + .and_return(nil) + + expect(interface).to_not receive(:perform_upsert) + + interface.upsert + end + context "when order already exists" do before(:each) do allow(order_api).to receive(:retrieve)