Skip to content

Commit

Permalink
fix: fail to load budget page due to nan in category % calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
eduardosimonpicon committed Jun 17, 2023
1 parent 2c41e60 commit 44c0970
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
5 changes: 4 additions & 1 deletion app/models/category.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ def in_spending?(month_date)
end

def spent_percentage_in_month(month_date)
(spent_amount_cents_in_month(month_date).to_f / assigned_amount_in(month_date).cents.to_f) * 100.0
assigned_amount_in_month_cents = assigned_amount_in(month_date).cents.to_f
return assigned_amount_in_month_cents if assigned_amount_in_month_cents.zero?

(spent_amount_cents_in_month(month_date).to_f / assigned_amount_in_month_cents ) * 100.0
end


Expand Down
11 changes: 11 additions & 0 deletions test/models/category_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,17 @@ class CategoryTest < ActiveSupport::TestCase
assert_equal(@category.spent_percentage_in_month(beginning_of_month), (20000.to_f / 30000.to_f) * 100)
end

test "spent_percentage returns 0 when the assigned amount is 0" do
movement_date = Time.now.utc
beginning_of_month = movement_date.beginning_of_month

movement_1 = Movement.create!(payer: "payer_1", amount_cents: -10000, account: @account, category: @category, created_at: movement_date)
movement_2 = Movement.create!(payer: "payer_2", amount_cents: -10000, account: @account, category: @category, created_at: movement_date)
MonthlyAssignment.create!(category: @category, start_date: beginning_of_month, end_date: beginning_of_month.next_month, amount: Money.new(0, "EUR"))

assert_equal(@category.spent_percentage_in_month(beginning_of_month), 0.0)
end

test "in_spending? returns true when spent_percentage is GREATER than 0%" do
movement_date = Time.now.utc
beginning_of_month = movement_date.beginning_of_month
Expand Down

0 comments on commit 44c0970

Please sign in to comment.