The personal finance app for everyone (by everyone)
Ruby
Add a Biggest Expenses section to Reports and the printed report (#5204)
CrossDrain3b057c031cf1
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rbindex 37a4e9e936..d552cdcf71 100644--- a/app/controllers/reports_controller.rb+++ b/app/controllers/reports_controller.rb@@ -1,6 +1,8 @@class ReportsController < ApplicationControllerinclude Periodable+ SIGN_AGNOSTIC_EXPENSE_KINDS = %w[loan_payment investment_contribution].freeze+# Allow API key authentication for exports (for Google Sheets integration)# Note: We run authentication_for_export which handles both session and API key authskip_authentication only: :export_transactions@@ -139,6 +141,9 @@ class ReportsController < ApplicationController# Transactions breakdown@transactions = build_transactions_breakdown+ @biggest_expenses_limit = Current.user.reports_biggest_expenses_limit+ @biggest_expenses = build_biggest_expenses(@biggest_expenses_limit)+# Investment metrics@investment_metrics = build_investment_metrics@@ -156,12 +161,14 @@ class ReportsController < ApplicationControllerenddef preferences_params- # Only the two reports keys are passed on; User#update_section_preferences- # drops any value that is not an array of keys or a hash of flags.+ # Only the reports keys are passed on; User#update_reports_preferences+ # drops any value that is not an array of keys, a hash of flags or an+ # offered limit.prefs = params.require(:preferences){"reports_collapsed_sections" => prefs[:reports_collapsed_sections],- "reports_section_order" => prefs[:reports_section_order]+ "reports_section_order" => prefs[:reports_section_order],+ "reports_biggest_expenses_limit" => prefs[:reports_biggest_expenses_limit]}end@@ -221,6 +228,16 @@ class ReportsController < ApplicationController},visible: @has_accounts,collapsible: true+ },+ {+ key: "biggest_expenses",+ title: "reports.biggest_expenses.title",+ partial: "reports/biggest_expenses",+ locals: { expenses: @biggest_expenses },+ header_partial: "reports/biggest_expenses_limit",+ header_locals: { limit: @biggest_expenses_limit },+ visible: @has_accounts && @biggest_expenses.any?,+ collapsible: true}]@@ -423,21 +440,51 @@ class ReportsController < ApplicationControllerendend- def build_transactions_breakdown- # Base query: all transactions in the period- # Exclude transfers, one-time, and CC payments (matching income_statement logic)+ # The period's reportable transactions with every Reports filter applied+ # (finance account scoping, tax-advantaged exclusion, tags, ...).+ def report_transactions_scope(excluded_kinds:)transactions = Transaction.joins(:entry).joins(entry: :account).where(accounts: { family_id: Current.family.id, status: [ "draft", "active" ] }).merge(Account.included_in_reports).where(entries: { entryable_type: "Transaction", excluded: false, date: @period.date_range })- .where.not(kind: Current.family.analytics_excluded_kinds)+ .where.not(kind: excluded_kinds).includes(entry: :account, category: :parent)transactions = exclude_tax_advantaged_accounts(transactions)- # Apply filters (includes finance account scoping)- transactions = apply_transaction_filters(transactions)+ apply_transaction_filters(transactions)+ end++ # The period's largest expenses in the family currency, largest first.+ # Unlike the breakdown it keeps one-time expenses (the view marks them):+ # a one-off is exactly what this list is for. Trades are left out, as in+ # the income statement.+ def build_biggest_expenses(limit)+ family_currency = Current.family.currency+ # Loan payments and investment contributions are expenses whatever their+ # sign (some importers store them negative), as in the income statement.+ expenses = report_transactions_scope(excluded_kinds: Current.family.analytics_excluded_kinds - [ "one_time" ])+ .where("entries.amount > 0 OR (entries.amount < 0 AND transactions.kind IN (?))", SIGN_AGNOSTIC_EXPENSE_KINDS)+ expense_amount_sql = Arel.sql(ActiveRecord::Base.sanitize_sql_array([+ "CASE WHEN transactions.kind IN (?) THEN ABS(entries.amount) ELSE entries.amount END DESC", SIGN_AGNOSTIC_EXPENSE_KINDS+ ]))++ # The overall top `limit` is always among the top `limit` in the family+ # currency plus the foreign-currency rows, so only those get loaded.+ candidates = expenses.where(entries: { currency: family_currency }).order(expense_amount_sql).limit(limit).to_a ++ expenses.where.not(entries: { currency: family_currency }).to_a++ convert = report_amount_converter(family_currency)+ candidates.filter_map do |transaction|+ amount = convert.call(transaction.entry)+ { transaction: transaction, entry: transaction.entry, amount: Money.new(amount, family_currency) } if amount+ end.sort_by { |expense| -expense[:amount].amount }.first(limit)+ end++ def build_transactions_breakdown+ # Exclude transfers, one-time, and CC payments (matching income_statement logic)+ transactions = report_transactions_scope(excluded_kinds: Current.family.analytics_excluded_kinds)# Get trades in the period (matching income_statement logic)trades = Tradediff --git a/app/javascript/controllers/reports_section_controller.js b/app/javascript/controllers/reports_section_controller.jsindex 4aa15e63f1..eb41251001 100644--- a/app/javascript/controllers/reports_section_controller.js+++ b/app/javascript/controllers/reports_section_controller.js@@ -26,20 +26,37 @@ export default class extends Controller {this.savePreference(collapsed);}- async savePreference(collapsed) {- const preferences = {+ savePreference(collapsed) {+ return this.patchPreferences({[`${this.preferenceKeyValue}_collapsed_sections`]: {[this.sectionKeyValue]: collapsed,},- };+ });+ }++ // A control inside a section that saves one preference value (given as+ // Stimulus action params) and reloads the page to show its effect.+ // Saves run one after another, so quick clicks reach the server in click+ // order and the last choice is the one stored; only the last save reloads.+ async savePreferenceValue({ params: { key, value } }) {+ const save = (this.pendingSave ?? Promise.resolve()).then(() =>+ this.patchPreferences({ [key]: value }),+ );+ this.pendingSave = save;++ if ((await save) && this.pendingSave === save) {+ window.Turbo.visit(window.location.href, { action: "replace" });+ }+ }+ async patchPreferences(preferences) {// Safely obtain CSRF tokenconst csrfToken = document.querySelector('meta[name="csrf-token"]');if (!csrfToken) {console.error("[Reports Section] CSRF token not found. Cannot save preferences.",);- return;+ return false;}try {@@ -60,11 +77,13 @@ export default class extends Controller {errorData,);}+ return response.ok;} catch (error) {console.error("[Reports Section] Network error saving preferences:",error,);+ return false;}}}diff --git a/app/models/user.rb b/app/models/user.rbindex 32591f79b7..85181fdba8 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -870,12 +870,26 @@ class User < ApplicationRecordsection_order("reports")end+ REPORTS_BIGGEST_EXPENSES_LIMITS = [ 5, 10, 25 ].freeze+ DEFAULT_REPORTS_BIGGEST_EXPENSES_LIMIT = 10++ def reports_biggest_expenses_limit+ stored = preferences&.[]("reports_biggest_expenses_limit")+ REPORTS_BIGGEST_EXPENSES_LIMITS.include?(stored) ? stored : DEFAULT_REPORTS_BIGGEST_EXPENSES_LIMIT+ end+def update_reports_preferences(prefs)- update_section_preferences(+ return false unless update_section_preferences("reports",order: prefs["reports_section_order"],collapsed: prefs["reports_collapsed_sections"])++ # A limit outside the offered choices is dropped, like any other bad value.+ limit = Integer(prefs["reports_biggest_expenses_limit"].to_s, exception: false)+ return true unless REPORTS_BIGGEST_EXPENSES_LIMITS.include?(limit)++ with_locked_preferences { |updated_prefs| updated_prefs["reports_biggest_expenses_limit"] = limit }end# Transactions preferences managementdiff --git a/app/views/reports/_biggest_expenses.html.erb b/app/views/reports/_biggest_expenses.html.erbnew file mode 100644index 0000000000..19f67805eb--- /dev/null+++ b/app/views/reports/_biggest_expenses.html.erb@@ -0,0 +1,32 @@+<%# locals: (expenses:) %>+<div>+ <%= render DS::Table.new(rows: expenses, inset: true, label: t("reports.biggest_expenses.title")) do |table| %>+ <% table.with_column(t("reports.biggest_expenses.table.name")) do |expense| %>+ <%# Name and details wrap rather than truncate, so the amount stays in view on a narrow screen. %>+ <div class="space-y-0.5">+ <div class="flex flex-wrap items-center gap-x-2 gap-y-1">+ <%= link_to expense[:entry].name, entry_path(expense[:entry]),+ class: "font-medium text-primary hover:underline",+ data: { turbo_frame: "drawer", turbo_prefetch: false } %>+ <% if expense[:transaction].one_time? %>+ <%= render DS::Pill.new(label: t("reports.biggest_expenses.one_time"), tone: :warning, marker: false) %>+ <% end %>+ </div>+ <div class="text-xs text-subdued">+ <%= format_date(expense[:entry].date) %> · <%= expense[:entry].account.name %>+ </div>+ </div>+ <% end %>+ <% table.with_column(t("reports.biggest_expenses.table.category")) do |expense| %>+ <div class="hidden lg:block">+ <%= render "categories/badge", category: expense[:transaction].category %>+ </div>+ <div class="flex lg:hidden">+ <%= render "categories/badge_mobile", category: expense[:transaction].category %>+ </div>+ <% end %>+ <% table.with_column(t("reports.biggest_expenses.table.amount"), numeric: true) do |expense| %>+ <span class="text-primary whitespace-nowrap privacy-sensitive"><%= expense[:amount].format %></span>+ <% end %>+ <% end %>+</div>diff --git a/app/views/reports/_biggest_expenses_limit.html.erb b/app/views/reports/_biggest_expenses_limit.html.erbnew file mode 100644index 0000000000..ba62fdcce0--- /dev/null+++ b/app/views/reports/_biggest_expenses_limit.html.erb@@ -0,0 +1,10 @@+<%# locals: (limit:) %>+<%= render DS::SegmentedControl.new(aria_label: t("reports.biggest_expenses.limit_aria")) do |sc| %>+ <% User::REPORTS_BIGGEST_EXPENSES_LIMITS.each do |option| %>+ <% sc.with_segment(option.to_s, active: option == limit, data: {+ action: "reports-section#savePreferenceValue",+ reports_section_key_param: "reports_biggest_expenses_limit",+ reports_section_value_param: option+ }) %>+ <% end %>+<% end %>diff --git a/app/views/reports/print.html.erb b/app/views/reports/print.html.erbindex bfbe76ddc3..5728cbff03 100644--- a/app/views/reports/print.html.erb+++ b/app/views/reports/print.html.erb@@ -357,6 +357,44 @@</section><% end %>+ <%# Biggest Expenses %>+ <% if @biggest_expenses.any? %>+ <section class="tufte-section tufte-keep-together">+ <h2 class="tufte-section-title"><%= t("reports.print.biggest_expenses.title") %></h2>+ <table class="tufte-table tufte-compact">+ <thead>+ <tr>+ <th><%= t("reports.print.biggest_expenses.date") %></th>+ <th><%= t("reports.print.biggest_expenses.name") %></th>+ <th><%= t("reports.print.biggest_expenses.category") %></th>+ <th><%= t("reports.print.biggest_expenses.account") %></th>+ <th class="tufte-right"><%= t("reports.print.biggest_expenses.amount") %></th>+ </tr>+ </thead>+ <tbody>+ <% @biggest_expenses.each do |expense| %>+ <% category = expense[:transaction].category || Category.uncategorized %>+ <tr>+ <td><%= format_date(expense[:entry].date) %></td>+ <td>+ <%= expense[:entry].name %>+ <% if expense[:transaction].one_time? %>+ <span class="tufte-muted"><%= t("reports.print.biggest_expenses.one_time") %></span>+ <% end %>+ </td>+ <td>+ <span class="tufte-dot" style="background: <%= category.color %>"></span>+ <%= category.display_name %>+ </td>+ <td><%= expense[:entry].account.name %></td>+ <td class="tufte-right"><%= expense[:amount].format %></td>+ </tr>+ <% end %>+ </tbody>+ </table>+ </section>+ <% end %>+<footer class="tufte-footer"><%= product_name %> · <%= @start_date.strftime("%B %Y") %> – <%= @end_date.strftime("%B %Y") %></footer>diff --git a/app/views/shared/_reorderable_sections.html.erb b/app/views/shared/_reorderable_sections.html.erbindex e620b7413c..ea33077622 100644--- a/app/views/shared/_reorderable_sections.html.erb+++ b/app/views/shared/_reorderable_sections.html.erb@@ -63,6 +63,13 @@<%= render DS::Pill.new(label: t("shared.preview")) %><% end %></div>+ <%# Optional controls on the title row. A click on a button in here+ activates the button, not the summary, so it doesn't collapse the section. %>+ <% if section[:header_partial] %>+ <div class="ml-auto flex items-center gap-2">+ <%= render partial: section[:header_partial], locals: section[:header_locals] || {} %>+ </div>+ <% end %><%# A mouse grab hint. Keys only grab the section itself, so thehint stays out of the tab order instead of being an invisiblestop. %>diff --git a/config/locales/views/reports/en.yml b/config/locales/views/reports/en.ymlindex 10c4c266b8..a1a9ff9f66 100644--- a/config/locales/views/reports/en.yml+++ b/config/locales/views/reports/en.yml@@ -93,6 +93,14 @@ en:description: Start tracking your finances by adding transactions or connecting your accounts to see comprehensive reportsadd_transaction: Add Transactionadd_account: Add Account+ biggest_expenses:+ title: Biggest Expenses+ one_time: One-time+ limit_aria: Number of expenses to show+ table:+ name: Name+ category: Category+ amount: Amounttransactions_breakdown:title: Activity Breakdownno_transactions: No activity found for the selected period and filters@@ -281,3 +289,11 @@ en:amount: Amountpercent: "%"more_categories: "+ %{count} more categories"+ biggest_expenses:+ title: Biggest Expenses+ date: Date+ name: Name+ category: Category+ account: Account+ amount: Amount+ one_time: One-timediff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rbindex e76c5b722a..8aa63a0fa8 100644--- a/test/controllers/reports_controller_test.rb+++ b/test/controllers/reports_controller_test.rb@@ -5,6 +5,7 @@ class ReportsControllerTest < ActionDispatch::IntegrationTestinclude SqlQueryCaptureTAGGED_MONTH = Date.new(2021, 3, 1)+ BIGGEST_MONTH = Date.new(2020, 6, 1)setup dosign_in @user = users(:family_admin)@@ -1314,7 +1315,143 @@ class ReportsControllerTest < ActionDispatch::IntegrationTestassert_no_match(/Export Untagged Spend/, @response.body)end+ test "biggest expenses lists the period's largest expenses first and marks one-time ones" do+ category = @family.categories.create!(name: "Big Repairs", color: "#222222")+ create_transaction(name: "Rent", amount: 900, date: BIGGEST_MONTH + 1)+ create_transaction(name: "Garage invoice", amount: 1_200, date: BIGGEST_MONTH + 2, category: category, kind: "one_time")+ create_transaction(name: "Coffee", amount: 4, date: BIGGEST_MONTH + 3)+ create_transaction(name: "Salary", amount: -3_000, date: BIGGEST_MONTH + 4)+ create_transaction(name: "Hidden refund", amount: 2_000, date: BIGGEST_MONTH + 5).update!(excluded: true)+ create_transaction(name: "Move to savings", amount: 2_500, date: BIGGEST_MONTH + 6, kind: "funds_movement")+ create_transaction(name: "Card payoff", amount: 2_600, date: BIGGEST_MONTH + 7, kind: "cc_payment")++ get biggest_expenses_reports_path++ assert_response :ok+ assert_equal [ "Garage invoice", "Rent", "Coffee" ], biggest_expense_names+ assert_select "[data-section-key=biggest_expenses] tbody tr:first-child", text: /One-time/+ assert_select "[data-section-key=biggest_expenses] tbody tr:first-child", text: /Big Repairs/+ assert_select "[data-section-key=biggest_expenses] tbody tr:nth-child(2)", text: /One-time/, count: 0+ end++ test "biggest expenses leaves out trades" do+ security = securities(:aapl)+ create_trade(security, account: accounts(:investment), qty: 100, date: BIGGEST_MONTH + 1, price: 500)+ create_transaction(name: "Rent", amount: 900, date: BIGGEST_MONTH + 1)++ get biggest_expenses_reports_path++ assert_equal [ "Rent" ], biggest_expense_names+ end++ test "biggest expenses follows the count investing as spending setting" do+ create_transaction(name: "Brokerage deposit", amount: 1_000, date: BIGGEST_MONTH + 1, kind: "investment_contribution")+ create_transaction(name: "Rent", amount: 900, date: BIGGEST_MONTH + 1)++ @family.update!(investment_contributions_as_spending: true)+ get biggest_expenses_reports_path+ assert_equal [ "Brokerage deposit", "Rent" ], biggest_expense_names++ @family.update!(investment_contributions_as_spending: false)+ get biggest_expenses_reports_path+ assert_equal [ "Rent" ], biggest_expense_names+ end++ # Some importers store loan payments and contributions as negative amounts;+ # the income statement counts them as expenses either way.+ test "biggest expenses keeps negative loan payments and contributions as expenses" do+ @family.update!(investment_contributions_as_spending: true)+ create_transaction(name: "Imported contribution", amount: -1_500, date: BIGGEST_MONTH + 1, kind: "investment_contribution")+ create_transaction(name: "Imported loan payment", amount: -700, date: BIGGEST_MONTH + 1, kind: "loan_payment")+ create_transaction(name: "Rent", amount: 900, date: BIGGEST_MONTH + 1)+ create_transaction(name: "Refund", amount: -2_000, date: BIGGEST_MONTH + 1)++ get biggest_expenses_reports_path++ assert_equal [ "Imported contribution", "Rent", "Imported loan payment" ], biggest_expense_names+ assert_select "[data-section-key=biggest_expenses] tbody tr:first-child", text: /\$1,500\.00/+ end++ test "biggest expenses ranks a foreign-currency expense by its converted amount" do+ eur = @family.accounts.create!(owner: @user, name: "Paris", balance: 0, currency: "EUR", accountable: Depository.new)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: BIGGEST_MONTH + 2, rate: 2)+ create_transaction(name: "Rent", amount: 900, date: BIGGEST_MONTH + 1)+ create_transaction(account: eur, name: "Paris hotel", amount: 600, currency: "EUR", date: BIGGEST_MONTH + 2)++ get biggest_expenses_reports_path++ assert_equal [ "Paris hotel", "Rent" ], biggest_expense_names+ assert_select "[data-section-key=biggest_expenses] tbody tr:first-child", text: /\$1,200\.00/+ end++ test "biggest expenses shows as many rows as the user chose" do+ 12.times { |i| create_transaction(name: "Expense #{i}", amount: 100 + i, date: BIGGEST_MONTH + 1) }++ get biggest_expenses_reports_path+ assert_equal 10, biggest_expense_names.size+ assert_select "[data-section-key=biggest_expenses] summary [aria-pressed=true]", text: "10"++ @user.update_columns(preferences: (@user.preferences || {}).merge("reports_biggest_expenses_limit" => 5))+ get biggest_expenses_reports_path+ assert_equal (7..11).map { |i| "Expense #{i}" }.reverse, biggest_expense_names+ end++ test "biggest expenses applies the tag filter" do+ tag = @family.tags.create!(name: "Holiday")+ create_transaction(name: "Flight", amount: 400, date: BIGGEST_MONTH + 1, tags: [ tag ])+ create_transaction(name: "Rent", amount: 900, date: BIGGEST_MONTH + 1)++ get biggest_expenses_reports_path(filter_tag_ids: [ tag.id ])++ assert_equal [ "Flight" ], biggest_expense_names+ end++ test "biggest expenses is hidden when the period has no expenses" do+ create_transaction(name: "Salary", amount: -3_000, date: BIGGEST_MONTH + 1)++ get biggest_expenses_reports_path++ assert_response :ok+ assert_select "[data-section-key=biggest_expenses]", count: 0+ end++ test "the printed report lists the biggest expenses" do+ create_transaction(name: "Garage invoice", amount: 1_200, date: BIGGEST_MONTH + 2, kind: "one_time")+ create_transaction(name: "Rent", amount: 900, date: BIGGEST_MONTH + 1)++ get print_reports_path(period_type: :custom, start_date: BIGGEST_MONTH, end_date: BIGGEST_MONTH.end_of_month)++ assert_response :ok+ section = css_select("section").find { |node| node.text.include?(I18n.t("reports.print.biggest_expenses.title")) }+ assert section, "the biggest expenses section is printed"+ rows = section.css("tbody tr").map(&:text)+ assert_match(/Garage invoice\s+One-time/, rows.first)+ assert_match(/Rent/, rows.second)+ end++ test "the reports preferences endpoint stores an offered biggest expenses limit only" do+ patch update_preferences_reports_path, params: { preferences: { reports_biggest_expenses_limit: 25 } }, as: :json+ assert_response :ok+ assert_equal 25, @user.reload.reports_biggest_expenses_limit++ patch update_preferences_reports_path, params: { preferences: { reports_biggest_expenses_limit: 7 } }, as: :json+ assert_response :ok+ assert_equal 25, @user.reload.preferences["reports_biggest_expenses_limit"]++ patch update_preferences_reports_path, params: { preferences: { reports_biggest_expenses_limit: "abc" } }, as: :json+ assert_response :ok+ assert_equal 25, @user.reload.preferences["reports_biggest_expenses_limit"]+ end+private+ def biggest_expenses_reports_path(**params)+ reports_path(period_type: :custom, start_date: BIGGEST_MONTH, end_date: BIGGEST_MONTH.end_of_month, **params)+ end++ def biggest_expense_names+ css_select("[data-section-key=biggest_expenses] tbody tr td:first-child a").map { |node| node.text.strip }+ end+# Travel, Work and Other tags on a month of their own, away from the# fixture transactions, with expenses of $30 (travel), $50 (work), $20# (both) and $1,000 (other), and income of $10 (travel) and $500 (none).diff --git a/test/models/user_test.rb b/test/models/user_test.rbindex 8d9849958e..9b3fa83c0e 100644--- a/test/models/user_test.rb+++ b/test/models/user_test.rb@@ -1678,4 +1678,26 @@ class UserTest < ActiveSupport::TestCaseassert_not @user.update_manual_account_order("transactions", [ accounts(:depository).id ])assert_equal({}, @user.reload.manual_account_order)end++ test "reports biggest expenses limit defaults to 10 and only returns an offered choice" do+ @user.update_columns(preferences: {})+ assert_equal 10, @user.reports_biggest_expenses_limit++ @user.update_columns(preferences: { "reports_biggest_expenses_limit" => 25 })+ assert_equal 25, @user.reload.reports_biggest_expenses_limit++ @user.update_columns(preferences: { "reports_biggest_expenses_limit" => 7 })+ assert_equal 10, @user.reload.reports_biggest_expenses_limit+ end++ test "update_reports_preferences stores an offered biggest expenses limit alongside the section keys" do+ @user.update_columns(preferences: { "reports_section_order" => %w[net_worth] })++ assert @user.update_reports_preferences("reports_biggest_expenses_limit" => "5")+ assert_equal 5, @user.reload.preferences["reports_biggest_expenses_limit"]+ assert_equal %w[net_worth], @user.preferences["reports_section_order"]++ assert @user.update_reports_preferences("reports_biggest_expenses_limit" => "1000")+ assert_equal 5, @user.reload.preferences["reports_biggest_expenses_limit"]+ endend