diff --git a/app/models/spree/payment.rb b/app/models/spree/payment.rb index d16e428922..87c5d8955f 100644 --- a/app/models/spree/payment.rb +++ b/app/models/spree/payment.rb @@ -201,7 +201,19 @@ module Spree end def update_order - order.update! + if completed? + order.updater.update_payment_total + end + + if order.completed? + order.updater.update_payment_state + order.updater.update_shipments + order.updater.update_shipment_state + end + + if self.completed? || order.completed? + order.updater.persist_totals + end end # Necessary because some payment gateways will refuse payments with diff --git a/engines/order_management/app/services/order_management/order/updater.rb b/engines/order_management/app/services/order_management/order/updater.rb index c432214751..65742b67ad 100644 --- a/engines/order_management/app/services/order_management/order/updater.rb +++ b/engines/order_management/app/services/order_management/order/updater.rb @@ -38,7 +38,7 @@ module OrderManagement # - adjustment_total - total value of all adjustments # - total - order total, it's the equivalent to item_total plus adjustment_total def update_totals - order.payment_total = payments.completed.sum(:amount) + update_payment_total update_item_total update_adjustment_total update_order_total @@ -49,6 +49,10 @@ module OrderManagement shipments.each { |shipment| shipment.update!(order) } end + def update_payment_total + order.payment_total = payments.completed.sum(:amount) + end + def update_item_total order.item_total = line_items.sum('price * quantity') update_order_total diff --git a/spec/models/spree/payment_spec.rb b/spec/models/spree/payment_spec.rb index 03eb892b53..bde1fa3c5a 100644 --- a/spec/models/spree/payment_spec.rb +++ b/spec/models/spree/payment_spec.rb @@ -531,15 +531,29 @@ describe Spree::Payment do end context "#save" do - it "should call order#update!" do - gateway.name = 'Gateway' - gateway.distributors << create(:distributor_enterprise) - gateway.save! + context "completed payments" do + it "updates order payment total" do + payment = create(:payment, amount: 100, order: order, state: "completed") + expect(order.payment_total).to eq payment.amount + end + end - order = create(:order) - payment = Spree::Payment.create(amount: 100, order: order, payment_method: gateway) - expect(order).to receive(:update!) - payment.save + context "non-completed payments" do + it "doesn't update order payment total" do + expect { + create(:payment, amount: 100, order: order) + }.not_to change { order.payment_total } + end + end + + context "completed orders" do + before { allow(order).to receive(:completed?) { true } } + + it "updates payment_state and shipments" do + expect(order.updater).to receive(:update_payment_state) + expect(order.updater).to receive(:update_shipment_state) + create(:payment, amount: 100, order: order) + end end context "when profiles are supported" do