diff --git a/app/furniture/tobias/payout.rb b/app/furniture/tobias/payout.rb index 1d37b0e28..0541fcac5 100644 --- a/app/furniture/tobias/payout.rb +++ b/app/furniture/tobias/payout.rb @@ -9,6 +9,8 @@ class Payout < ApplicationRecord monetize :amount_cents def issue + return if payments.present? + per_beneficiary_amount = (amount / beneficiaries.count) beneficiaries.each do |beneficiary| payments.create_with(amount: per_beneficiary_amount).find_or_create_by(beneficiary_id: beneficiary.id) diff --git a/spec/tobias/payout_spec.rb b/spec/tobias/payout_spec.rb index 53556bfe7..29e18003c 100644 --- a/spec/tobias/payout_spec.rb +++ b/spec/tobias/payout_spec.rb @@ -29,5 +29,23 @@ end end end + + context "when running twice" do + it "does not issue multiple payouts, even when beneficiaries are added" do + payout = create(:tobias_payout, amount_cents: 100_00) + + create_list(:tobias_beneficiary, 2, trust: payout.trust) + + payout.issue + + create(:tobias_beneficiary, trust: payout.trust) + + # ActiveRecord appears to be caching the `payout.beneficiaries` results + # Reload busts that cache. + payout.reload + + expect { payout.issue }.not_to(change(payout.payments, :count)) + end + end end end