Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

perf: batch the reports trends chart into one month-grouped query (#2561)

Juan José Mata1556bdc779d0
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb
index fac1e02369..54658f72af 100644
--- a/app/controllers/reports_controller.rb
+++ b/app/controllers/reports_controller.rb
@@ -379,34 +379,35 @@ class ReportsController < ApplicationController
end
def build_trends_data(income_statement:)
- # Generate month-by-month data based on the current period filter
+ # Month-by-month data based on the current period filter, fetched with a
+ # single month-grouped totals query instead of two queries per month.
trends = []
- # Generate list of months within the period
current_month = @start_date.beginning_of_month
end_of_period = @end_date.end_of_month
- while current_month <= end_of_period
- month_start = current_month
- month_end = current_month.end_of_month
-
- # Ensure we don't go beyond the end date
- month_end = @end_date if month_end > @end_date
-
- period = Period.custom(start_date: month_start, end_date: month_end)
+ monthly_totals = if filter_tags.empty?
+ income_statement.monthly_income_expense_totals(
+ period: Period.custom(start_date: current_month, end_date: @end_date)
+ )
+ end
+ while current_month <= end_of_period
if filter_tags.any?
+ month_end = [ current_month.end_of_month, @end_date ].min
+ period = Period.custom(start_date: current_month, end_date: month_end)
totals = income_statement.totals_for(period, tag_ids: filter_tags.map(&:id))
income = totals.income_money.amount
expenses = totals.expense_money.amount
else
- income = income_statement.income_totals(period: period).total
- expenses = income_statement.expense_totals(period: period).total
+ totals = monthly_totals[current_month] || { income: 0.to_d, expense: 0.to_d }
+ income = totals[:income]
+ expenses = totals[:expense]
end
trends << {
- month: month_start.strftime("%b %Y"),
- is_current_month: (month_start.month == Date.current.month && month_start.year == Date.current.year),
+ month: current_month.strftime("%b %Y"),
+ is_current_month: (current_month.month == Date.current.month && current_month.year == Date.current.year),
income: income,
expenses: expenses,
net: income - expenses
diff --git a/app/models/income_statement.rb b/app/models/income_statement.rb
index 1376c4073e..86ccc794a3 100644
--- a/app/models/income_statement.rb
+++ b/app/models/income_statement.rb
@@ -36,6 +36,28 @@ class IncomeStatement
)
end
+ # Income/expense sums per calendar month over the period, computed in a
+ # single query. Returns a hash of { Date (first of month) => { income:, expense: } }
+ # with BigDecimal sums. Used by the reports trends chart, which previously
+ # issued a totals query per month of the period.
+ def monthly_income_expense_totals(period:)
+ key = period_cache_key(period)
+ @monthly_income_expense_totals ||= {}
+ @monthly_income_expense_totals[key] ||= begin
+ rows = monthly_totals_query(
+ transactions_scope: family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled).in_period(period),
+ date_range: period.date_range
+ )
+
+ rows.group_by(&:month).transform_values do |month_rows|
+ {
+ income: month_rows.select { |r| r.classification == "income" }.sum { |r| r.total.to_d },
+ expense: month_rows.select { |r| r.classification == "expense" }.sum { |r| r.total.to_d }
+ }
+ end
+ end
+ end
+
def expense_totals(period: Period.current_month)
# Memoized per instance so callers that also invoke `net_category_totals`
key = period_cache_key(period)
@@ -401,6 +423,14 @@ class IncomeStatement
]) { Totals.new(family, transactions_scope: transactions_scope, date_range: date_range, included_account_ids: included_account_ids).call }
end
+ def monthly_totals_query(transactions_scope:, date_range:)
+ sql_hash = Digest::MD5.hexdigest(transactions_scope.to_sql)
+
+ Rails.cache.fetch([
+ "income_statement", "monthly_totals_query", "v2", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, included_account_ids_hash, sql_hash, date_range.begin, date_range.end, *cache_freshness_key, family.accounts.maximum(:updated_at)&.to_i
+ ]) { Totals.new(family, transactions_scope: transactions_scope, date_range: date_range, included_account_ids: included_account_ids, group_by_month: true).call }
+ end
+
def monetizable_currency
family.currency
end
diff --git a/app/models/income_statement/totals.rb b/app/models/income_statement/totals.rb
index 61add0d8c5..4df69ea9d8 100644
--- a/app/models/income_statement/totals.rb
+++ b/app/models/income_statement/totals.rb
@@ -1,12 +1,15 @@
class IncomeStatement::Totals
include IncomeStatement::ScopedTransactionsQuery
- def initialize(family, transactions_scope:, date_range:, include_trades: true, included_account_ids: nil)
+ def initialize(family, transactions_scope:, date_range:, include_trades: true, included_account_ids: nil, group_by_month: false)
@family = family
@transactions_scope = transactions_scope
@date_range = date_range
@include_trades = include_trades
@included_account_ids = included_account_ids
+ @group_by_month = group_by_month
+
+ raise ArgumentError, "group_by_month requires include_trades" if @group_by_month && !@include_trades
validate_date_range!
end
@@ -22,13 +25,16 @@ class IncomeStatement::Totals
classification: row["classification"],
total: row["total"],
transactions_count: row["transactions_count"],
- is_uncategorized_investment: row["is_uncategorized_investment"]
+ is_uncategorized_investment: row["is_uncategorized_investment"],
+ month: row["month"]&.to_date
)
end
end
private
- TotalsRow = Data.define(:parent_category_id, :category_id, :classification, :total, :transactions_count, :is_uncategorized_investment)
+ TotalsRow = Data.define(:parent_category_id, :category_id, :classification, :total, :transactions_count, :is_uncategorized_investment, :month) do
+ def initialize(month: nil, **rest) = super
+ end
def query_sql
ActiveRecord::Base.sanitize_sql_array([
@@ -45,6 +51,7 @@ class IncomeStatement::Totals
parent_category_id,
classification,
is_uncategorized_investment,
+ #{"month," if @group_by_month}
SUM(total) as total,
SUM(entry_count) as transactions_count
FROM (
@@ -52,7 +59,7 @@ class IncomeStatement::Totals
UNION ALL
#{trades_subquery_sql}
) combined
- GROUP BY category_id, parent_category_id, classification, is_uncategorized_investment;
+ GROUP BY category_id, parent_category_id, classification, is_uncategorized_investment#{", month" if @group_by_month};
SQL
end
@@ -89,7 +96,7 @@ class IncomeStatement::Totals
#{classification_sql("at")} as classification,
ABS(COALESCE(SUM(#{converted_amount_sql("at")}), 0)) as total,
COUNT(ae.id) as entry_count,
- false as is_uncategorized_investment
+ false as is_uncategorized_investment#{",\n date_trunc('month', ae.date)::date as month" if @group_by_month}
FROM (#{@transactions_scope.to_sql}) at
#{entries_join_sql("at")}
#{accounts_join_sql}
@@ -102,7 +109,7 @@ class IncomeStatement::Totals
AND a.exclude_from_reports = false
#{exclude_tax_advantaged_sql}
#{include_finance_accounts_sql}
- GROUP BY c.id, c.parent_id, #{classification_sql("at")}
+ GROUP BY c.id, c.parent_id, #{classification_sql("at")}#{", date_trunc('month', ae.date)::date" if @group_by_month}
SQL
end
@@ -113,7 +120,7 @@ class IncomeStatement::Totals
# Contributions/withdrawals are tracked separately as Transactions with activity labels
<<~SQL
SELECT NULL as category_id, NULL as parent_category_id, NULL as classification,
- NULL as total, NULL as entry_count, NULL as is_uncategorized_investment
+ NULL as total, NULL as entry_count, NULL as is_uncategorized_investment#{",\n NULL::date as month" if @group_by_month}
WHERE false
SQL
end
diff --git a/test/models/income_statement/scoped_transactions_query_equivalence_test.rb b/test/models/income_statement/scoped_transactions_query_equivalence_test.rb
index 571ed9e6c1..26d392b94c 100644
--- a/test/models/income_statement/scoped_transactions_query_equivalence_test.rb
+++ b/test/models/income_statement/scoped_transactions_query_equivalence_test.rb
@@ -57,8 +57,13 @@ class IncomeStatement::ScopedTransactionsQueryEquivalenceTest < ActiveSupport::T
args = { transactions_scope: transactions_scope, date_range: @period.date_range,
include_trades: include_trades, included_account_ids: included_account_ids }
+ # Monthly grouping adds a dimension; ungrouped totals keep it nil.
+ expected_rows = LegacyIncomeStatementTotals.new(@family, **args).call.map do |row|
+ row.to_h.merge(month: nil)
+ end
+
assert_equal_rows(
- LegacyIncomeStatementTotals.new(@family, **args).call,
+ expected_rows,
IncomeStatement::Totals.new(@family, **args).call,
"Totals (include_trades: #{include_trades}, included_account_ids: #{included_account_ids.inspect})"
)
diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rb
index bc1eeda369..445a73501e 100644
--- a/test/models/income_statement_test.rb
+++ b/test/models/income_statement_test.rb
@@ -232,6 +232,73 @@ class IncomeStatementTest < ActiveSupport::TestCase
assert_equal expected_total_expense, expense_totals.category_totals.find { |ct| ct.category.id == @food_category.id }.total
end
+ test "monthly totals exclude scheduled entries until their date arrives" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ Entry.joins(:account).where(accounts: { family_id: @family.id }).destroy_all
+
+ travel_to Date.current.beginning_of_month + 14.days do
+ create_transaction(account: @checking_account, amount: 100, date: Date.current)
+ create_transaction(account: @checking_account, amount: 250, date: Date.tomorrow)
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ month = Date.current.beginning_of_month
+ statement = IncomeStatement.new(@family)
+
+ assert_equal 100, statement.monthly_income_expense_totals(period: period).fetch(month)[:expense]
+ assert_equal statement.expense_totals(period: period).total,
+ statement.monthly_income_expense_totals(period: period).fetch(month)[:expense]
+ end
+ end
+
+ test "monthly totals refresh when the family currency changes" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)
+ period = Period.current_month
+ month = Date.current.beginning_of_month
+
+ assert_equal 900, IncomeStatement.new(@family).monthly_income_expense_totals(period: period).fetch(month)[:expense]
+ @family.update!(currency: "EUR")
+ assert_equal 810, IncomeStatement.new(@family).monthly_income_expense_totals(period: period).fetch(month)[:expense]
+ end
+
+ test "monthly totals refresh when an exchange rate changes" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ @family.update!(currency: "EUR")
+ rate = ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)
+ period = Period.current_month
+ month = Date.current.beginning_of_month
+
+ assert_equal 810, IncomeStatement.new(@family).monthly_income_expense_totals(period: period).fetch(month)[:expense]
+ travel 1.second do
+ rate.update!(rate: 0.8)
+ assert_equal 720, IncomeStatement.new(@family).monthly_income_expense_totals(period: period).fetch(month)[:expense]
+ end
+ end
+
+ test "monthly income/expense totals match per-month period totals" do
+ # Spread entries over two months
+ create_transaction(account: @checking_account, amount: -500, category: @income_category, date: 40.days.ago.to_date)
+ create_transaction(account: @checking_account, amount: 250, category: @groceries_category, date: 40.days.ago.to_date)
+
+ income_statement = IncomeStatement.new(@family)
+ start_date = 60.days.ago.to_date.beginning_of_month
+ period = Period.custom(start_date: start_date, end_date: Date.current)
+
+ monthly = income_statement.monthly_income_expense_totals(period: period)
+
+ month = start_date
+ while month <= Date.current
+ month_end = [ month.end_of_month, Date.current ].min
+ expected_income = income_statement.income_totals(period: Period.custom(start_date: month, end_date: month_end)).total
+ expected_expense = income_statement.expense_totals(period: Period.custom(start_date: month, end_date: month_end)).total
+
+ actual = monthly[month] || { income: 0.to_d, expense: 0.to_d }
+ assert_equal expected_income.to_d, actual[:income].to_d, "income mismatch for #{month}"
+ assert_equal expected_expense.to_d, actual[:expense].to_d, "expense mismatch for #{month}"
+
+ month = month.next_month
+ end
+ end
+
test "orphaned categories still count as root category totals" do
orphan_category = @family.categories.create! name: "Orphaned Category"
orphan_category.update_column(:parent_id, SecureRandom.uuid)