The personal finance app for everyone (by everyone)
Ruby
fix IncomeStatement performance issue (#1947)
William Wei Mingf7b66d40ff09
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rbindex c31df1eb00..d1b76204e4 100644--- a/app/controllers/reports_controller.rb+++ b/app/controllers/reports_controller.rb@@ -111,17 +111,18 @@ class ReportsController < ApplicationController@previous_period = build_previous_period# Get aggregated data- @current_income_totals = Current.family.income_statement.income_totals(period: @period)- @current_expense_totals = Current.family.income_statement.expense_totals(period: @period)+ @income_statement = Current.family.income_statement(user: Current.user)+ @current_income_totals = @income_statement.income_totals(period: @period)+ @current_expense_totals = @income_statement.expense_totals(period: @period)- @previous_income_totals = Current.family.income_statement.income_totals(period: @previous_period)- @previous_expense_totals = Current.family.income_statement.expense_totals(period: @previous_period)+ @previous_income_totals = @income_statement.income_totals(period: @previous_period)+ @previous_expense_totals = @income_statement.expense_totals(period: @previous_period)# Calculate summary metrics@summary_metrics = build_summary_metrics# Build trend data (last 6 months)- @trends_data = build_trends_data+ @trends_data = build_trends_data(income_statement: @income_statement)# Net worth metrics@net_worth_metrics = build_net_worth_metrics@@ -320,7 +321,7 @@ class ReportsController < ApplicationControllernilend- def build_trends_data+ def build_trends_data(income_statement:)# Generate month-by-month data based on the current period filtertrends = []@@ -337,8 +338,8 @@ class ReportsController < ApplicationControllerperiod = Period.custom(start_date: month_start, end_date: month_end)- income = Current.family.income_statement.income_totals(period: period).total- expenses = Current.family.income_statement.expense_totals(period: period).total+ income = income_statement.income_totals(period: period).total+ expenses = income_statement.expense_totals(period: period).totaltrends << {month: month_start.strftime("%b %Y"),@@ -379,8 +380,12 @@ class ReportsController < ApplicationControllertrades = apply_entry_filters(trades)# Get sort parameters- sort_by = params[:sort_by] || "amount"- sort_direction = params[:sort_direction] || "desc"+ sort_by = %w[amount count].include?(params[:sort_by]) ? params[:sort_by] : "amount"+ sort_direction = %w[asc desc].include?(params[:sort_direction]) ? params[:sort_direction] : "desc"+ sort_logic = ->(item) do+ value = (sort_by == "count") ? item[:count] : item[:total]+ sort_direction == "asc" ? (value || 0) : -(value || 0)+ end# Group by category (tracking parent relationship) and type# Structure: { [parent_category_id, type] => { parent_data, subcategories: { subcategory_id => data } } }@@ -447,16 +452,12 @@ class ReportsController < ApplicationController# Convert to array and sort subcategoriesresult = grouped_data.values.map do |parent_data|- subcategories = parent_data[:subcategories].values.sort_by { |s| sort_direction == "asc" ? s[:total] : -s[:total] }+ subcategories = parent_data[:subcategories].values.sort_by(&sort_logic)parent_data.merge(subcategories: subcategories)end- # Sort by amount (total) with the specified direction- if sort_direction == "asc"- result.sort_by { |g| g[:total] }- else- result.sort_by { |g| -g[:total] }- end+ # Sort by the chosen key with the specified direction+ result.sort_by(&sort_logic)enddef build_investment_metrics@@ -466,7 +467,6 @@ class ReportsController < ApplicationControllerreturn { has_investments: false } unless investment_accounts.any?period_totals = investment_statement.totals(period: @period)-{has_investments: true,portfolio_value: investment_statement.portfolio_value_money,diff --git a/app/models/income_statement.rb b/app/models/income_statement.rbindex dd1cf459a3..ff3f3db56c 100644--- a/app/models/income_statement.rb+++ b/app/models/income_statement.rb@@ -143,7 +143,7 @@ class IncomeStatementdef build_period_total(classification:, period:)# Exclude pending transactions from budget calculations- totals = totals_query(transactions_scope: family.transactions.visible.excluding_pending.in_period(period), date_range: period.date_range).select { |t| t.classification == classification }+ totals = totals_for_period(period).select { |t| t.classification == classification }classification_total = totals.sum(&:total)uncategorized_category = family.categories.uncategorized@@ -186,6 +186,15 @@ class IncomeStatement)end+ def totals_for_period(period)+ @totals_for_period ||= {}+ @totals_for_period[period_cache_key(period)] ||=+ totals_query(+ transactions_scope: family.transactions.visible.excluding_pending.in_period(period),+ date_range: period.date_range+ )+ end+def family_stats(interval: "month")@family_stats ||= {}@family_stats[interval] ||= Rails.cache.fetch([diff --git a/db/schema.rb b/db/schema.rbindex ddaa60b710..513bd1abda 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -53,7 +53,6 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_31_153000) dot.string "content_type", limit: 100, null: falset.bigint "byte_size", null: falset.string "checksum", limit: 64, null: false- t.string "content_sha256"t.string "source", default: "manual_upload", null: falset.string "upload_status", default: "stored", null: falset.string "institution_name_hint", limit: 200@@ -70,6 +69,7 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_31_153000) dot.jsonb "sanitized_parser_output", default: {}, null: falset.datetime "created_at", null: falset.datetime "updated_at", null: false+ t.string "content_sha256"t.index ["account_id", "period_start_on", "period_end_on"], name: "index_account_statements_on_account_period"t.index ["account_id"], name: "index_account_statements_on_account_id"t.index ["family_id", "checksum"], name: "index_account_statements_on_family_checksum"@@ -117,6 +117,7 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_31_153000) dot.string "institution_domain"t.text "notes"t.uuid "owner_id"+ t.integer "account_providers_count", default: 0, null: falset.index ["accountable_id", "accountable_type"], name: "index_accounts_on_accountable_id_and_accountable_type"t.index ["accountable_type"], name: "index_accounts_on_accountable_type"t.index ["currency"], name: "index_accounts_on_currency"@@ -299,9 +300,9 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_31_153000) dot.string "institution_domain"t.string "institution_url"t.string "institution_color"- t.string "status", default: "good"- t.boolean "scheduled_for_deletion", default: false- t.boolean "pending_account_setup", default: false+ t.string "status", default: "good", null: false+ t.boolean "scheduled_for_deletion", default: false, null: false+ t.boolean "pending_account_setup", default: false, null: falset.datetime "sync_start_date"t.jsonb "raw_payload"t.text "api_key"@@ -637,12 +638,12 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_31_153000) dot.index ["account_id", "date"], name: "index_entries_on_account_id_and_date"t.index ["account_id", "source", "external_id"], name: "index_entries_on_account_source_and_external_id", unique: true, where: "((external_id IS NOT NULL) AND (source IS NOT NULL))"t.index ["account_id"], name: "index_entries_on_account_id"+ t.index ["currency", "amount", "date", "account_id"], name: "index_entries_on_transfer_match_lookup", where: "((entryable_type)::text = 'Transaction'::text)"t.index ["date"], name: "index_entries_on_date"t.index ["entryable_type"], name: "index_entries_on_entryable_type"t.index ["import_id"], name: "index_entries_on_import_id"t.index ["import_locked"], name: "index_entries_on_import_locked_true", where: "(import_locked = true)"t.index ["parent_entry_id"], name: "index_entries_on_parent_entry_id"- t.index ["currency", "amount", "date", "account_id"], name: "index_entries_on_transfer_match_lookup", where: "((entryable_type)::text = 'Transaction'::text)"t.index ["user_modified"], name: "index_entries_on_user_modified_true", where: "(user_modified = true)"end@@ -847,7 +848,7 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_31_153000) dot.index ["family_id", "state"], name: "index_goals_on_family_id_and_state"t.index ["family_id"], name: "index_goals_on_family_id"t.check_constraint "char_length(name::text) <= 255", name: "chk_savings_goals_name_length"- t.check_constraint "state::text = ANY (ARRAY['active'::character varying::text, 'paused'::character varying::text, 'completed'::character varying::text, 'archived'::character varying::text])", name: "chk_savings_goals_state_enum"+ t.check_constraint "state::text = ANY (ARRAY['active'::character varying, 'paused'::character varying, 'completed'::character varying, 'archived'::character varying]::text[])", name: "chk_savings_goals_state_enum"t.check_constraint "target_amount > 0::numeric", name: "chk_savings_goals_target_amount_positive"end@@ -884,9 +885,9 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_31_153000) dot.decimal "current_balance", precision: 19, scale: 4t.decimal "cash_balance", precision: 19, scale: 4t.jsonb "institution_metadata"- t.jsonb "raw_holdings_payload", default: [], null: false- t.jsonb "raw_activities_payload", default: {}, null: false- t.jsonb "raw_cash_report_payload", default: [], null: false+ t.jsonb "raw_holdings_payload", default: []+ t.jsonb "raw_activities_payload", default: {}+ t.jsonb "raw_cash_report_payload", default: []t.date "report_date"t.datetime "last_holdings_sync"t.datetime "last_activities_sync"@@ -900,8 +901,8 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_31_153000) docreate_table "ibkr_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.uuid "family_id", null: falset.string "name"- t.string "status", default: "good", null: false- t.boolean "scheduled_for_deletion", default: false, null: false+ t.string "status", default: "good"+ t.boolean "scheduled_for_deletion", default: falset.boolean "pending_account_setup", default: false, null: falset.jsonb "raw_payload"t.string "query_id"diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex 9e2b350f66..0f95fcff0b 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -170,8 +170,8 @@ class IncomeStatementTest < ActiveSupport::TestCase# NOTE: These tests now pass because kind filtering is working after the refactoring!test "excludes regular transfers from income statement calculations" do# Create a regular transfer between accounts- _outflow_transaction = create_transaction(account: @checking_account, amount: 500, kind: "funds_movement")- _inflow_transaction = create_transaction(account: @credit_card_account, amount: -500, kind: "funds_movement")+ create_transaction(account: @checking_account, amount: 500, kind: "funds_movement")+ create_transaction(account: @credit_card_account, amount: -500, kind: "funds_movement")income_statement = IncomeStatement.new(@family)totals = income_statement.totals(date_range: Period.last_30_days.date_range)@@ -184,7 +184,7 @@ class IncomeStatementTest < ActiveSupport::TestCasetest "includes loan payments as expenses in income statement" do# Create a loan payment transaction- _loan_payment = create_transaction(account: @checking_account, amount: 1000, category: nil, kind: "loan_payment")+ create_transaction(account: @checking_account, amount: 1000, category: nil, kind: "loan_payment")income_statement = IncomeStatement.new(@family)totals = income_statement.totals(date_range: Period.last_30_days.date_range)@@ -197,7 +197,7 @@ class IncomeStatementTest < ActiveSupport::TestCasetest "excludes one-time transactions from income statement calculations" do# Create a one-time transaction- _one_time_transaction = create_transaction(account: @checking_account, amount: 250, category: @groceries_category, kind: "one_time")+ create_transaction(account: @checking_account, amount: 250, category: @groceries_category, kind: "one_time")income_statement = IncomeStatement.new(@family)totals = income_statement.totals(date_range: Period.last_30_days.date_range)@@ -210,7 +210,7 @@ class IncomeStatementTest < ActiveSupport::TestCasetest "excludes payment transactions from income statement calculations" do# Create a payment transaction (credit card payment)- _payment_transaction = create_transaction(account: @checking_account, amount: 300, category: nil, kind: "cc_payment")+ create_transaction(account: @checking_account, amount: 300, category: nil, kind: "cc_payment")income_statement = IncomeStatement.new(@family)totals = income_statement.totals(date_range: Period.last_30_days.date_range)@@ -304,7 +304,7 @@ class IncomeStatementTest < ActiveSupport::TestCasetest "includes investment_contribution transactions as expenses in income statement" do# Create a transfer to investment account (marked as investment_contribution)- _investment_contribution = create_transaction(+ create_transaction(account: @checking_account,amount: 1000,category: nil,@@ -334,7 +334,7 @@ class IncomeStatementTest < ActiveSupport::TestCase# Provider-imported contribution shows as inflow (negative amount) to the investment account# kind is investment_contribution, which should be treated as expense regardless of sign- _provider_contribution = create_transaction(+ create_transaction(account: investment_account,amount: -500, # Negative = inflow to accountcategory: nil,@@ -653,4 +653,22 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal Money.new(0, "USD"), totals.income_moneyassert_equal Money.new(0, "USD"), totals.expense_moneyend++ test "reuses totals_query for income and expense in the same period" do+ income_statement = IncomeStatement.new(@family)+ period = Period.last_30_days++ totals_query_calls = 0+ income_statement.singleton_class.prepend(Module.new do+ define_method(:totals_query) do |**kwargs|+ totals_query_calls += 1+ super(**kwargs)+ end+ end)++ income_statement.income_totals(period: period)+ income_statement.expense_totals(period: period)++ assert_equal 1, totals_query_calls+ endend