From f35b70e9363bbf352445dbd40423b6301d989e49 Mon Sep 17 00:00:00 2001 From: Tony Vincent Date: Mon, 17 Feb 2025 17:42:30 +0100 Subject: [PATCH] fix: Transfers should always total to zero (#1859) --- app/helpers/application_helper.rb | 10 +++++++++- app/views/account/entries/_entry_group.html.erb | 4 +++- test/system/transactions_test.rb | 16 ++++++++++++++-- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 7549b6b5..424ed539 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -154,7 +154,7 @@ module ApplicationHelper def totals_by_currency(collection:, money_method:, separator: " | ", negate: false) collection.group_by(&:currency) - .transform_values { |item| negate ? item.sum(&money_method) * -1 : item.sum(&money_method) } + .transform_values { |item| calculate_total(item, money_method, negate) } .map { |_currency, money| format_money(money) } .join(separator) end @@ -166,4 +166,12 @@ module ApplicationHelper cookies[:admin] == "true" end + + private + + def calculate_total(item, money_method, negate) + items = item.reject { |i| i.respond_to?(:entryable) && i.entryable.transfer? } + total = items.sum(&money_method) + negate ? -total : total + end end diff --git a/app/views/account/entries/_entry_group.html.erb b/app/views/account/entries/_entry_group.html.erb index 4006b070..beec5893 100644 --- a/app/views/account/entries/_entry_group.html.erb +++ b/app/views/account/entries/_entry_group.html.erb @@ -17,7 +17,9 @@ <% if totals %> - <%= totals_by_currency(collection: entries, money_method: :amount_money, negate: true) %> +
+ <%= totals_by_currency(collection: entries, money_method: :amount_money, negate: true) %> +
<% end %>
diff --git a/test/system/transactions_test.rb b/test/system/transactions_test.rb index 3fc0b5e1..3c9dd3fd 100644 --- a/test/system/transactions_test.rb +++ b/test/system/transactions_test.rb @@ -196,10 +196,22 @@ class TransactionsTest < ApplicationSystemTestCase end end + test "transfers should always sum to zero" do + asset_account = accounts(:other_asset) + investment_account = accounts(:investment) + outflow_entry = create_transaction("outflow", Date.current, 500, account: asset_account) + inflow_entry = create_transaction("inflow", 1.day.ago.to_date, -500, account: investment_account) + asset_account.auto_match_transfers! + visit transactions_url + within "#entry-group-" + Date.current.to_s + "-totals" do + assert_text "-$100.00" # transaction eleven from setup + end + end + private - def create_transaction(name, date, amount, category: nil, merchant: nil, tags: []) - account = accounts(:depository) + def create_transaction(name, date, amount, category: nil, merchant: nil, tags: [], account: nil) + account ||= accounts(:depository) account.entries.create! \ name: name,