From 65f08ee8f49b8609d292338ba2e887da256245c0 Mon Sep 17 00:00:00 2001 From: Matt-Yorkley <9029026+Matt-Yorkley@users.noreply.github.com> Date: Mon, 4 Oct 2021 17:55:27 +0100 Subject: [PATCH] Deal with edge cases where an adjustment is left referencing a deleted item --- app/models/spree/adjustment.rb | 5 +++++ spec/models/spree/adjustment_spec.rb | 17 +++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/app/models/spree/adjustment.rb b/app/models/spree/adjustment.rb index 8312229736..34044dcc31 100644 --- a/app/models/spree/adjustment.rb +++ b/app/models/spree/adjustment.rb @@ -100,6 +100,11 @@ module Spree def update_adjustment!(calculable = nil, force: false) return amount if immutable? && !force + if calculable.nil? && adjustable.nil? + self.delete + return 0.0 + end + if originator.present? amount = originator.compute_amount(calculable || adjustable) update_columns( diff --git a/spec/models/spree/adjustment_spec.rb b/spec/models/spree/adjustment_spec.rb index 7ae26c83c6..009f1ccecf 100644 --- a/spec/models/spree/adjustment_spec.rb +++ b/spec/models/spree/adjustment_spec.rb @@ -64,6 +64,23 @@ module Spree expect(adjustment).not_to receive(:update_columns) adjustment.update_adjustment! end + + context "where the adjustable has been deleted" do + let(:line_item) { create(:line_item, price: 10) } + let!(:adjustment) { create(:adjustment, adjustable: line_item) } + + it "returns zero" do + line_item.delete + expect(adjustment.reload.update_adjustment!).to eq 0.0 + end + + it "removes orphaned adjustments" do + expect { + line_item.delete + adjustment.reload.update_adjustment! + }.to change{ Spree::Adjustment.count }.by -1 + end + end end context "adjustment state" do