The personal finance app for everyone (by everyone)
Ruby
Skip unconvertible months in category budget averages (#5068)
arnaurodondev53d4594b9179
diff --git a/app/models/income_statement.rb b/app/models/income_statement.rbindex e5bf6bab8d..0af5b4e6ae 100644--- a/app/models/income_statement.rb+++ b/app/models/income_statement.rb@@ -322,7 +322,7 @@ class IncomeStatementdef category_stats(interval: "month")@category_stats ||= {}@category_stats[interval] ||= Rails.cache.fetch([- "income_statement", "category_stats", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, interval, included_account_ids_hash, *cache_freshness_key+ "income_statement", "category_stats", CategoryStats::CACHE_VERSION, ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, interval, included_account_ids_hash, *cache_freshness_key]) { CategoryStats.new(family, interval:, account_ids: included_account_ids).call }enddiff --git a/app/models/income_statement/category_stats.rb b/app/models/income_statement/category_stats.rbindex 217041d766..f932cf5beb 100644--- a/app/models/income_statement/category_stats.rb+++ b/app/models/income_statement/category_stats.rb@@ -1,4 +1,7 @@class IncomeStatement::CategoryStats+ # Bump when the query's result changes, so cached stats are recomputed.+ CACHE_VERSION = 2+include IncomeStatement::ScopedTransactionsQuerydef initialize(family, interval: "month", account_ids: nil)@@ -58,24 +61,37 @@ class IncomeStatement::CategoryStats),bounds AS (SELECT COALESCE(MAX(period), date_trunc(:interval, CAST(:today AS date)) - CAST('1 ' || :interval AS interval)) AS last_p- FROM period_totals WHERE period < date_trunc(:interval, CAST(:today AS date))+ FROM period_totals WHERE period < date_trunc(:interval, CAST(:today AS date)) AND total IS NOT NULL)- -- end_p: the category's latest period with spending, or the latest past period in scope.+ -- A NULL total is a period whose only rows have no exchange rate (see+ -- converted_amount_sql). It has no measurable spending, so it neither+ -- starts, ends nor counts toward a category's run of periods.+ -- start_p: the category's first period with measurable spending.+ -- end_p: its latest one, or the latest past period in scope., windowed AS (- SELECT period_totals.*, GREATEST(MAX(period) OVER (PARTITION BY category_id, classification), (SELECT last_p FROM bounds)) AS end_p+ SELECT period_totals.*,+ MIN(period) FILTER (WHERE total IS NOT NULL) OVER (PARTITION BY category_id, classification) AS start_p,+ GREATEST(MAX(period) FILTER (WHERE total IS NOT NULL) OVER (PARTITION BY category_id, classification), (SELECT last_p FROM bounds)) AS end_pFROM period_totals)SELECTcategory_id,classification,ABS(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY total)) as median,- -- Average over every period from the category's first one to end_p,- -- at most 12 periods, so periods without spending count as zero. The- -- unfinished current period counts only once it has spending.- ABS(COALESCE(SUM(total) FILTER (WHERE period > end_p - CAST('12 ' || :interval AS interval)), 0) / (- SELECT COUNT(*) FROM generate_series(GREATEST(MIN(period), MAX(end_p) - CAST('11 ' || :interval AS interval)),- MAX(end_p), CAST('1 ' || :interval AS interval))- )) as avg+ -- Average over every period from start_p to end_p, at most 12+ -- periods, so periods without spending count as zero. The unfinished+ -- current period counts only once it has spending. Periods with+ -- nothing convertible are left out of the count, and a category with+ -- no measurable period has no average.+ CASE WHEN MAX(start_p) IS NOT NULL THEN+ ABS(COALESCE(SUM(total) FILTER (WHERE period > end_p - CAST('12 ' || :interval AS interval)), 0) / NULLIF((+ SELECT COUNT(*) FROM generate_series(GREATEST(MAX(start_p), MAX(end_p) - CAST('11 ' || :interval AS interval)),+ MAX(end_p), CAST('1 ' || :interval AS interval))+ ) - COUNT(*) FILTER (+ WHERE total IS NULL AND period > start_p AND period <= end_p+ AND period > end_p - CAST('12 ' || :interval AS interval)+ ), 0))+ END as avgFROM windowedGROUP BY category_id, classification;SQLdiff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex 7b2f6ac6ce..4d56505313 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -389,6 +389,20 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal 100.0, income_statement.avg_expense(interval: "month", category: @groceries_category)end+ test "a month with nothing convertible between measurable months is left out of the category average" do+ Entry.joins(:account).where(accounts: { family_id: @family.id }).destroy_all+ krw_account = @family.accounts.create! name: "KRW Checking", currency: "KRW", balance: 0, accountable: Depository.new+ this_month = Date.current.beginning_of_month++ create_transaction(account: @checking_account, amount: 100, category: @groceries_category, date: this_month.prev_month(2))+ create_transaction(account: krw_account, amount: 130_000, currency: "KRW", category: @groceries_category, date: this_month.prev_month)+ create_transaction(account: @checking_account, amount: 100, category: @groceries_category, date: this_month)++ income_statement = IncomeStatement.new(@family)+ assert_equal 100.0, income_statement.avg_expense(interval: "month", category: @groceries_category)+ assert_equal 100.0, income_statement.median_expense(interval: "month", category: @groceries_category)+ end+test "calculates category-specific median expense" do# Clear existing transactions by deleting entriesEntry.joins(:account).where(accounts: { family_id: @family.id }).destroy_all