From a9900e3f2757d8d8d522b6d71588e6ac1ad2531c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Sun, 12 Jul 2020 23:39:01 +0200 Subject: [PATCH] Remove duplication calculating insufficient funds We were using the same logic twice. I've moved the logic to the Ballot model, which to me is a more natural place to calculate whether there's enough money left than the Investment model. After all, the remaining money is in the ballot, and not in the investment. --- app/models/budget/ballot.rb | 4 ++++ app/models/budget/ballot/line.rb | 2 +- app/models/budget/investment.rb | 7 +------ 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/app/models/budget/ballot.rb b/app/models/budget/ballot.rb index ccdf1b289..70f59fc05 100644 --- a/app/models/budget/ballot.rb +++ b/app/models/budget/ballot.rb @@ -33,6 +33,10 @@ class Budget budget.formatted_amount(amount_available(heading)) end + def enough_money?(investment) + investment.price.to_i <= amount_available(investment.heading) + end + def has_lines_in_group?(group) groups.include?(group) end diff --git a/app/models/budget/ballot/line.rb b/app/models/budget/ballot/line.rb index 091ceaea7..9d9805781 100644 --- a/app/models/budget/ballot/line.rb +++ b/app/models/budget/ballot/line.rb @@ -20,7 +20,7 @@ class Budget def check_sufficient_funds ballot.lock! - errors.add(:money, "insufficient funds") if ballot.amount_available(investment.heading) < investment.price.to_i + errors.add(:money, "insufficient funds") unless ballot.enough_money?(investment) end def check_valid_heading diff --git a/app/models/budget/investment.rb b/app/models/budget/investment.rb index 61d31b625..63f03441a 100644 --- a/app/models/budget/investment.rb +++ b/app/models/budget/investment.rb @@ -268,7 +268,7 @@ class Budget return :not_selected unless selected? return :no_ballots_allowed unless budget.balloting? return :different_heading_assigned unless ballot.valid_heading?(heading) - return :not_enough_money unless enough_money?(ballot) + return :not_enough_money unless ballot.enough_money?(self) return :casted_offline if ballot.casted_offline? end @@ -301,11 +301,6 @@ class Budget user.headings_voted_within_group(group).where(id: heading.id).exists? end - def enough_money?(ballot) - available_money = ballot.amount_available(heading) - price.to_i <= available_money - end - def register_selection(user) vote_by(voter: user, vote: "yes") if selectable_by?(user) end