The personal finance app for everyone (by everyone)
Ruby
Compare the spending widget against the dashboard period's average month (#4139)
Josh Sanders0c4ff95222dc
diff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rbindex 14678bdda5..42c429804f 100644--- a/app/controllers/pages_controller.rb+++ b/app/controllers/pages_controller.rb@@ -600,15 +600,13 @@ class PagesController < ApplicationControllerend# The selected month (capped at today while it's in progress) and the- # month before it, which the widget compares against. Memoized: the- # filter and the widget both need them.+ # period the widget compares it against: the dashboard's time period.+ # Memoized: the filter and the widget both need them.def spending_trend_periods(selected_month)month_start = selected_month.beginning_of_month(@spending_trend_periods ||= {})[month_start] ||= begincurrent_period = Period.custom(start_date: month_start, end_date: [ month_start.end_of_month, Date.current ].min)- previous_month_start = (month_start - 1.month).beginning_of_month- previous_period = Period.custom(start_date: previous_month_start, end_date: previous_month_start.end_of_month)- [ current_period, previous_period ]+ [ current_period, @period ]endend@@ -623,59 +621,60 @@ class PagesController < ApplicationControllerend# Cumulative daily spending for the selected month (capped at today while- # the month is in progress) against the previous month's full curve, so- # the two lines share one day-of-month axis. The header totals compare the- # same number of elapsed days; only the chart draws the previous month out- # to its final day.+ # the month is in progress) against an average month drawn from the+ # dashboard's time period (IncomeStatement#average_month_expense_series:+ # MTD retraces this month, LM is last month's curve, 7D covers only its+ # own days and leaves the rest blank), so the two lines share one+ # day-of-month axis. The header compares the same number of elapsed days;+ # only the chart draws the comparison out to its last day.## The category filter (an IncomeStatement::ExpenseCategoryFilter) narrows- # both months to the same categories, so the comparison stays+ # both lines to the same categories, so the comparison stays# like-for-like.def build_spending_trend_data(income_statement, selected_month, category_filter)month_start = selected_month.beginning_of_monthmonth_end = month_start.end_of_month- current_period, previous_period = spending_trend_periods(month_start)- previous_month_start = previous_period.start_date+ current_period, comparison_period = spending_trend_periods(month_start)category_ids = category_filter.category_idscurrent_daily = income_statement.daily_expense_series(period: current_period, category_ids: category_ids).index_by(&:date)- previous_daily = income_statement.daily_expense_series(period: previous_period, category_ids: category_ids).index_by(&:date)- # The selected month always owns the axis: when the previous month is- # longer, its extra days fold into the final visible point so the curve- # still ends at the full-month total without the axis rolling into- # previous-month dates (e.g. a September view ends at "Sep 30", not- # "Aug 31").+ # The selected month always owns the axis: days of the month past its+ # end (an average's day 31 in a 30-day month) fold into the final+ # visible point, so the curve still ends at the full average.axis_days = month_end.day+ axis_labels = spending_trend_axis_labels(month_start, axis_days)current_series = cumulative_spending_series(current_period, current_daily)- previous_header_series = cumulative_spending_series(previous_period, previous_daily)+ previous_header_series = income_statement.average_month_expense_series(period: comparison_period, category_ids: category_ids)+ .map { |average_day| { day: average_day.day, value: average_day.total&.to_f&.round(2) } }previous_series = fold_extra_days(previous_header_series, axis_days)+ .map { |point| point.merge(date_formatted: axis_labels[point[:day] - 1]) }+ # While the selected month is running, compare the same elapsed days;+ # once it's over, the whole average. The comparison may have no point+ # on that day (a 7D period, or YTD in January), so take its last point+ # on or before it.current_total = current_series.last&.fetch(:value) || 0- comparison_days = if month_start == Date.current.beginning_of_month- [ current_series.size, previous_header_series.size ].min- else- previous_header_series.size- end- previous_total = comparison_days.positive? ? previous_header_series[comparison_days - 1][:value] : 0- previous_comparison_day = comparison_days if comparison_days.positive? && comparison_days < previous_header_series.size+ compare_through = month_start == Date.current.beginning_of_month ? current_series.size : previous_header_series.size+ compared_point = previous_header_series.first(compare_through).reverse.find { |point| point[:value] }+ previous_total = compared_point ? compared_point[:value] : 0+ final_point = previous_header_series.reverse.find { |point| point[:value] }+ previous_comparison_day = compared_point[:day] if compared_point && compared_point != final_pointcurrency = income_statement.family.currency-{month: month_start,current_period: current_period,- previous_period: previous_period,days: axis_days,current_days: month_end.day,- axis_labels: spending_trend_axis_labels(month_start, axis_days),+ axis_labels: axis_labels,current: current_series,previous: previous_series,current_total: Money.new(current_total, currency),previous_total: Money.new(previous_total, currency),delta: Money.new(current_total - previous_total, currency),- previous_label: I18n.l(previous_month_start, format: :month_year).capitalize,+ previous_label: t("pages.dashboard.spending_trend.average_label", period: comparison_period.key ? comparison_period.label : comparison_period.label_range),previous_comparison_day: previous_comparison_day,date_range_short: spending_trend_compact_date_range(current_period),category_options: category_filter.options,@@ -709,21 +708,16 @@ class PagesController < ApplicationControllerendend- # A longer previous month's curve is clipped to the axis, with the extra- # days' spend folded into the final visible point, so the curve still- # ends at the full-month total shown in the header. The folded point- # keeps its axis slot (day) for positioning but carries the true- # endpoint's date metadata, so the tooltip says what the value actually- # contains (e.g. "Jan 31" and the total through Jan 31).+ # A comparison running past the axis (day 31 against a 30-day month) is+ # clipped to it, with the rest folded into the final visible point, so+ # the curve still ends at the full total shown in the header. A final+ # point the period doesn't reach stays blank rather than carrying days+ # beyond the axis.def fold_extra_days(series, axis_days)return series if series.size <= axis_daysseries.first(axis_days).tap do |folded|- folded[-1] = folded[-1].merge(- value: series.last[:value],- date: series.last[:date],- date_formatted: series.last[:date_formatted]- )+ folded[-1] = folded[-1].merge(value: series.last[:value]) unless folded[-1][:value].nil?endenddiff --git a/app/javascript/controllers/spending_chart_controller.js b/app/javascript/controllers/spending_chart_controller.jsindex 6f1d761ca9..905fda0896 100644--- a/app/javascript/controllers/spending_chart_controller.js+++ b/app/javascript/controllers/spending_chart_controller.js@@ -4,8 +4,9 @@ import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";// Cumulative spending chart for the dashboard "spending" widget: the selected// month's running total (green, ending today while the month is in progress)-// overlaid on the previous month's complete curve (gray), sharing one-// day-of-month axis. Lifecycle mirrors bar_chart/time_series_chart+// overlaid on an average month from the dashboard's time period (gray),+// sharing one day-of-month axis. Days the period never reaches have a null+// value and leave a gap in the gray line. Lifecycle mirrors bar_chart/time_series_chart// (install/teardown, ResizeObserver, turbo:load reinstall, page-relative// tooltip positioning).const CURRENT_COLOR = "var(--color-success)";@@ -89,11 +90,12 @@ export default class extends Controller {const line = d3.line()+ .defined((d) => d.value !== null).x((d) => x(d.day)).y((d) => y(d.value)).curve(d3.curveMonotoneX);- // Previous month first so the current month always draws on top.+ // Comparison first so the current month always draws on top.if (previous.length > 0) {group.append("path")@@ -208,7 +210,9 @@ export default class extends Controller {.attr("class", `${CHART_TOOLTIP_CLASSES} opacity-0 top-0`);const currentByDay = new Map(current.map((d) => [d.day, d]));- const previousByDay = new Map(previous.map((d) => [d.day, d]));+ const previousByDay = new Map(+ previous.filter((d) => d.value !== null).map((d) => [d.day, d]),+ );const hoverDays = [...new Set([...currentByDay.keys(), ...previousByDay.keys()]),].sort((a, b) => a - b);diff --git a/app/models/income_statement.rb b/app/models/income_statement.rbindex 1dec491a68..430abe113c 100644--- a/app/models/income_statement.rb+++ b/app/models/income_statement.rb@@ -143,6 +143,25 @@ class IncomeStatement.map { |date, rows| DailyExpenseTotals::DailyTotal.new(date: date, total: rows.sum { |row| row.total.to_d }) }end+ # An average month of spending over `period`, to compare one month's+ # cumulative spend against: for each day of the month, the average spend+ # on the period's dates that fall on that day, accumulated across the+ # month. A day of the month the period never reaches has a nil total, so+ # a one-month period gives that month's own cumulative curve and a short+ # one (a week, say) covers only its own days. `category_ids` filters as in+ # daily_expense_series.+ def average_month_expense_series(period:, category_ids: nil)+ daily = daily_expense_series(period: period, category_ids: category_ids).index_by(&:date)+ dates_by_day = period.date_range.group_by(&:day)+ cumulative = 0.to_d++ (1..dates_by_day.keys.max).map do |day|+ dates = dates_by_day[day]+ cumulative += dates.sum { |date| daily[date] ? daily[date].total.to_d : 0 } / dates.size if dates+ AverageMonthDay.new(day: day, total: dates && cumulative)+ end+ end+# Categories with spending in the period's daily series, nil standing for# uncategorized spending. These are the categories a filter on that series# can usefully offer.@@ -195,6 +214,7 @@ class IncomeStatementprivateScopeTotals = Data.define(:transactions_count, :income_money, :expense_money, :invested_money)+ AverageMonthDay = Data.define(:day, :total)PeriodTotal = Data.define(:classification, :total, :currency, :category_totals)CategoryTotal = Data.define(:category, :total, :currency, :weight)NetCategoryTotals = Data.define(:net_expense_categories, :net_income_categories, :total_net_expense, :total_net_income, :currency)diff --git a/app/views/pages/dashboard/_spending_trend.html.erb b/app/views/pages/dashboard/_spending_trend.html.erbindex 3093aa7870..e15421e6ab 100644--- a/app/views/pages/dashboard/_spending_trend.html.erb+++ b/app/views/pages/dashboard/_spending_trend.html.erb@@ -3,7 +3,7 @@data = spending_trend_dataperiod = data[:current_period]pill_button_class = "inline-flex items-center gap-1.5 bg-container border border-secondary font-medium rounded-lg pl-3 pr-2 py-2 text-sm cursor-pointer text-primary hover:bg-container-inset-hover focus:outline-hidden focus:ring-0 whitespace-nowrap"- has_data = data[:current].any? { |p| p[:value].positive? } || data[:previous].any? { |p| p[:value].positive? }+ has_data = data[:current].any? { |p| p[:value].positive? } || data[:previous].any? { |p| p[:value]&.positive? }chart_data = {days: data[:days],current_days: data[:current_days],@@ -106,7 +106,7 @@<p class="text-sm text-secondary truncate"><span class="capitalize"><%= previous_label %></span><%# While the selected month is still running, the figure below covers %>- <%# the same elapsed days rather than the whole previous month. %>+ <%# the same elapsed days rather than the whole average month. %><% if previous_comparison_day %><span class="text-xs"><%= t(".previous_comparison_days", end_day: previous_comparison_day) %></span><% end %>diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.ymlindex 581359b20e..ee8b116560 100644--- a/config/locales/views/pages/en.yml+++ b/config/locales/views/pages/en.yml@@ -167,6 +167,7 @@ en:filter_categories_all: "All categories"search_categories: "Search categories"apply: "Apply"- period_scope_hint: "Shows the month you pick here — independent of the dashboard's time period at the top."+ period_scope_hint: "Shows the month you pick here, against an average month from the dashboard's time period at the top."+ average_label: "Avg. %{period}"no_data: "No spending data for this month"previous_comparison_days: "(1-%{end_day})"diff --git a/test/controllers/pages_controller_test.rb b/test/controllers/pages_controller_test.rbindex d744d61e86..7399091628 100644--- a/test/controllers/pages_controller_test.rb+++ b/test/controllers/pages_controller_test.rb@@ -673,6 +673,8 @@ class PagesControllerTest < ActionDispatch::IntegrationTestendtest "dashboard spending trend widget accumulates the selected month against the previous one" do+ # A top period of exactly the previous month averages that one month, so+ # the comparison is its own curve.account = @family.accounts.create!(name: "Spending Trend Test Checking", currency: @family.currency, balance: 0, accountable: Depository.new)# A fully past month: fixture transactions are dated relative to today and# would otherwise leak into the expected totals.@@ -683,7 +685,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Selected month again", amount: 25, date: selected_month + 1.day)create_transaction(account: account, name: "Previous month", amount: 200, date: previous_month)- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month) }assert_response :okchart = spending_trend_chart_data@@ -734,7 +736,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Spend", amount: 10, date: selected_month)create_transaction(account: account, name: "Prior spend", amount: 10, date: previous_month)- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month) }assert_response :okchart = spending_trend_chart_data@@ -759,7 +761,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Jan extra day", amount: 40, date: Date.new(2026, 1, 31))create_transaction(account: account, name: "Feb spend", amount: 25, date: Date.new(2026, 2, 10))- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(Date.new(2026, 1, 1)) }assert_response :okchart = spending_trend_chart_data@@ -775,8 +777,8 @@ class PagesControllerTest < ActionDispatch::IntegrationTest.sum { |row| row.total.to_d }.to_f.round(2)assert_equal 140.0, expected_total # sanity: no fixture transactions leaked into Januaryassert_equal expected_total, previous.last.fetch("value")- assert_equal "2026-01-31", previous.last.fetch("date")- assert_equal I18n.l(Date.new(2026, 1, 31), format: :short), previous.last.fetch("date_formatted")+ # Averaged points sit on the selected month's axis, so they carry its labels.+ assert_equal I18n.l(Date.new(2026, 2, 28), format: :short), previous.last.fetch("date_formatted")assert_equal 25.0, chart.fetch("current").last.fetch("value")labels = chart.fetch("axis_labels")@@ -793,7 +795,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "May extra day", amount: 60, date: Date.new(2026, 5, 31))create_transaction(account: account, name: "Jun spend", amount: 15, date: Date.new(2026, 6, 5))- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(Date.new(2026, 5, 1)) }assert_response :okchart = spending_trend_chart_data@@ -808,21 +810,24 @@ class PagesControllerTest < ActionDispatch::IntegrationTestassert_equal (1..30).map { |d| I18n.l(Date.new(2026, 6, d), format: :short) }, labelsend- test "dashboard spending trend names the compared month in the comparison header" do+ test "dashboard spending trend names the averaged period in the comparison header" doaccount = @family.accounts.create!(name: "Spending Trend Label Checking", currency: @family.currency, balance: 0, accountable: Depository.new)selected_month = 2.months.ago.beginning_of_month.to_date- previous_month = 3.months.ago.beginning_of_month.to_datecreate_transaction(account: account, name: "Spend", amount: 10, date: selected_month)- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, period: "last_90_days" }assert_response :ok- # The real month name replaces the generic "Previous month" label, which- # truncated on mobile ("Previous mon…").- expected_label = I18n.l(previous_month, format: :month_year).capitalize- assert_select "#spending-trend-section p", text: expected_label+ expected_label = I18n.t("pages.dashboard.spending_trend.average_label", period: Period.from_key("last_90_days").label)+ assert_select "#spending-trend-section p span", text: expected_labelchart_element = css_select("[data-controller='spending-chart']").firstassert_equal expected_label, chart_element["data-spending-chart-previous-label-value"]++ # A custom range (e.g. drag-selected on a chart) is named by its dates.+ range = Period.custom(start_date: 4.months.ago.to_date, end_date: 3.months.ago.to_date)+ get root_path, params: { spending_month: selected_month.iso8601, start_date: range.start_date.iso8601, end_date: range.end_date.iso8601 }+ assert_select "#spending-trend-section p span",+ text: I18n.t("pages.dashboard.spending_trend.average_label", period: range.label_range)endtest "dashboard spending trend renders a compact date range for mobile" do@@ -867,7 +872,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Prev late", amount: 999, date: previous_month.end_of_month)create_transaction(account: account, name: "Current", amount: 7, date: Date.current)- get root_path, params: { spending_month: Date.current.beginning_of_month.iso8601 }+ get root_path, params: { spending_month: Date.current.beginning_of_month.iso8601, **month_period_params(previous_month) }assert_response :okchart = spending_trend_chart_data@@ -893,8 +898,9 @@ class PagesControllerTest < ActionDispatch::IntegrationTesttravel_to Date.current.beginning_of_month + 14.days doaccount = @family.accounts.create!(name: "Spending Trend Label Days Checking", currency: @family.currency, balance: 0, accountable: Depository.new)create_transaction(account: account, name: "Spend", amount: 10, date: Date.current)+ previous_month = Date.current.beginning_of_month - 1.month- get root_path, params: { spending_month: Date.current.beginning_of_month.iso8601 }+ get root_path, params: { spending_month: Date.current.beginning_of_month.iso8601, **month_period_params(previous_month) }assert_response :okassert_select "#spending-trend-section span",@@ -914,13 +920,13 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Prev extra day", amount: 999, date: previous_month.end_of_month)create_transaction(account: account, name: "Current", amount: 7, date: Date.current)- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month) }assert_response :okprevious_series = spending_trend_chart_data.fetch("previous")_current_total, previous_total = spending_trend_header_totals- assert_equal previous_month.end_of_month.iso8601, previous_series.last.fetch("date")+ assert_equal 1110.0, previous_series.last.fetch("value")assert_equal money_text(111), previous_totalrefute_equal money_text(previous_series.last.fetch("value")), previous_totalassert_select "#spending-trend-section span",@@ -937,7 +943,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Previous early", amount: 111, date: previous_month)create_transaction(account: account, name: "Previous late", amount: 999, date: previous_month.end_of_month)- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month) }assert_response :okprevious_series = spending_trend_chart_data.fetch("previous")@@ -963,7 +969,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Previous early", amount: 111, date: previous_month)create_transaction(account: account, name: "Previous last day", amount: 999, date: previous_month.end_of_month)- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month) }assert_response :okprevious_series = spending_trend_chart_data.fetch("previous")@@ -971,7 +977,6 @@ class PagesControllerTest < ActionDispatch::IntegrationTest# Both months are over, so both are compared whole - the selected month# being shorter must not truncate the previous month's total.- assert_equal previous_month.end_of_month.iso8601, previous_series.last.fetch("date")assert_equal 1110.0, previous_series.last.fetch("value")assert_equal money_text(previous_series.last.fetch("value")), previous_totalassert_select "#spending-trend-section span",@@ -996,7 +1001,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestassert_operator Date.current.day, :>, previous_month.end_of_month.dayassert_operator Date.current, :<, selected_month.end_of_month- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month) }assert_response :okprevious_series = spending_trend_chart_data.fetch("previous")@@ -1010,6 +1015,84 @@ class PagesControllerTest < ActionDispatch::IntegrationTestendend+ test "dashboard spending trend compares against an average month over the dashboard period" do+ account = @family.accounts.create!(name: "Spending Trend Average Checking", currency: @family.currency, balance: 0, accountable: Depository.new)+ create_transaction(account: account, name: "Jun 1", amount: 100, date: Date.new(2026, 6, 1))+ create_transaction(account: account, name: "Jul 1", amount: 300, date: Date.new(2026, 7, 1))+ create_transaction(account: account, name: "Jul 31", amount: 50, date: Date.new(2026, 7, 31))+ create_transaction(account: account, name: "Aug 2", amount: 10, date: Date.new(2026, 8, 2))++ get root_path, params: { spending_month: "2026-08-01", start_date: "2026-06-01", end_date: "2026-07-31" }+ assert_response :ok++ previous = spending_trend_chart_data.fetch("previous")+ # Day 1 averages June's and July's day 1; day 31 exists only in July, so+ # it averages July alone.+ assert_equal 200.0, previous.first.fetch("value")+ assert_equal 200.0, previous.fetch(29).fetch("value")+ assert_equal 250.0, previous.last.fetch("value")+ assert_equal [ money_text(10), money_text(250) ], spending_trend_header_totals+ end++ test "dashboard spending trend leaves the last axis day blank when the period only covers later days" do+ account = @family.accounts.create!(name: "Spending Trend Late Days Checking", currency: @family.currency, balance: 0, accountable: Depository.new)+ create_transaction(account: account, name: "Feb spend", amount: 10, date: Date.new(2026, 2, 3))+ create_transaction(account: account, name: "Mar 31", amount: 70, date: Date.new(2026, 3, 31))++ # A 28-day axis against a period of only March 30-31: nothing to draw.+ get root_path, params: { spending_month: "2026-02-01", start_date: "2026-03-30", end_date: "2026-03-31" }+ assert_response :ok++ previous = spending_trend_chart_data.fetch("previous")+ assert_equal 28, previous.size+ assert previous.all? { |point| point["value"].nil? }+ end++ test "dashboard spending trend lines match when the dashboard period is month to date" do+ travel_to Date.current.beginning_of_month + 14.days do+ account = @family.accounts.create!(name: "Spending Trend MTD Checking", currency: @family.currency, balance: 0, accountable: Depository.new)+ create_transaction(account: account, name: "Early", amount: 20, date: Date.current.beginning_of_month)+ create_transaction(account: account, name: "Today", amount: 5, date: Date.current)++ get root_path, params: { spending_month: Date.current.beginning_of_month.iso8601, period: "current_month" }+ assert_response :ok++ chart = spending_trend_chart_data+ assert_equal chart.fetch("current").map { |point| point.fetch("value") }, chart.fetch("previous").map { |point| point.fetch("value") }+ assert_equal money_text(0), spending_trend_header_delta+ end+ end++ test "dashboard spending trend truncates the average to the days the dashboard period reaches" do+ # YTD in January: only days 1 to today exist to average.+ travel_to Date.new(2027, 1, 11) do+ account = @family.accounts.create!(name: "Spending Trend YTD Checking", currency: @family.currency, balance: 0, accountable: Depository.new)+ create_transaction(account: account, name: "Spend", amount: 30, date: Date.new(2027, 1, 3))++ get root_path, params: { spending_month: "2027-01-01", period: "current_year" }+ assert_response :ok++ previous = spending_trend_chart_data.fetch("previous")+ assert_equal 11, previous.size+ assert_equal 30.0, previous.last.fetch("value")+ end+ end++ test "dashboard spending trend leaves days outside a short dashboard period blank" do+ travel_to Date.current.beginning_of_month + 14.days do+ account = @family.accounts.create!(name: "Spending Trend 7D Checking", currency: @family.currency, balance: 0, accountable: Depository.new)+ create_transaction(account: account, name: "Spend", amount: 12, date: Date.current)++ get root_path, params: { spending_month: Date.current.beginning_of_month.iso8601, period: "last_7_days" }+ assert_response :ok++ previous = spending_trend_chart_data.fetch("previous")+ period_days = Period.from_key("last_7_days").date_range.map(&:day)+ assert_equal period_days.sort, previous.reject { |point| point["value"].nil? }.map { |point| point.fetch("day") }+ assert_nil previous.first.fetch("value")+ end+ end+test "dashboard spending trend category filter narrows both months and the header totals" doaccount, selected_month, previous_month = spending_trend_filter_setupfood = @family.categories.create!(name: "Spending Filter Food")@@ -1020,7 +1103,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Food before", amount: 20, date: previous_month, category: food)create_transaction(account: account, name: "Rent before", amount: 500, date: previous_month + 1.day, category: rent)- get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: [ food.id ] }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month), spending_category_ids: [ food.id ] }assert_response :okchart = spending_trend_chart_data@@ -1065,7 +1148,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "No category", amount: 5, date: selected_month)create_transaction(account: account, name: "Paycheck", amount: -900, date: selected_month, category: salary)- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month) }assert_response :okoffered = spending_trend_category_values@@ -1088,16 +1171,16 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Food", amount: 30, date: selected_month, category: food)create_transaction(account: account, name: "No category", amount: 5, date: previous_month)- get root_path, params: { spending_month: selected_month.iso8601 }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month) }unfiltered = spending_trend_chart_dataevery_option = spending_trend_category_values- get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: every_option }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month), spending_category_ids: every_option }assert_equal unfiltered, spending_trend_chart_dataassert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.filter_categories_all")# Nothing is pinned, so another month's categories aren't left out.- assert_select "#spending-trend-section a[href='#{root_path(spending_month: (selected_month - 1.month).iso8601)}']"+ assert_select "#spending-trend-section a[href='#{root_path(**month_period_params(previous_month), spending_month: (selected_month - 1.month).iso8601)}']"endtest "dashboard spending trend filters uncategorized spending" do@@ -1179,7 +1262,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "Food", amount: 30, date: selected_month, category: food)create_transaction(account: account, name: "No category", amount: 5, date: previous_month)- get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: [ food.id, Category::UNCATEGORIZED_FILTER_VALUE ] }+ get root_path, params: { spending_month: selected_month.iso8601, **month_period_params(previous_month), spending_category_ids: [ food.id, Category::UNCATEGORIZED_FILTER_VALUE ] }assert_response :ok# Every category with spending is picked, which is the unfiltered state,@@ -1218,10 +1301,11 @@ class PagesControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: account, name: "No category", amount: 5, date: previous_month)patch dashboard_section_hidden_path("spending_trend"), params: {- hidden: true, spending_month: selected_month.iso8601, spending_category_ids: [ food.id, Category::UNCATEGORIZED_FILTER_VALUE ]+ hidden: true, spending_month: selected_month.iso8601, **month_period_params(previous_month),+ spending_category_ids: [ food.id, Category::UNCATEGORIZED_FILTER_VALUE ]}- assert_redirected_to root_path(spending_month: selected_month.iso8601, customize: true, hidden_section: "spending_trend")+ assert_redirected_to root_path(spending_month: selected_month.iso8601, **month_period_params(previous_month), customize: true, hidden_section: "spending_trend")endprivate@@ -1237,6 +1321,12 @@ class PagesControllerTest < ActionDispatch::IntegrationTestRack::Utils.parse_nested_query(URI.parse(css_select(selector).first["href"]).query)end+ # A custom dashboard period covering exactly one month, whose average+ # month is that month's own curve.+ def month_period_params(month)+ { start_date: month.beginning_of_month.iso8601, end_date: month.end_of_month.iso8601 }+ end+def spending_trend_category_valuescss_select("#spending-trend-section input[name='spending_category_ids[]']").map { |input| input["value"] }enddiff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex 40f12848d5..88753b9f5a 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -193,6 +193,36 @@ class IncomeStatementTest < ActiveSupport::TestCaseIncomeStatement.new(@family).daily_expense_series(period: period, category_ids: [ @food_category.id ])end+ test "average month series averages each day of the month over the period" do+ june_1 = Date.new(2026, 6, 1)+ create_transaction(account: @checking_account, amount: 100, date: june_1, category: @groceries_category)+ create_transaction(account: @checking_account, amount: 300, date: Date.new(2026, 7, 1), category: @groceries_category)+ create_transaction(account: @checking_account, amount: 50, date: Date.new(2026, 7, 31))++ series = IncomeStatement.new(@family).average_month_expense_series(period: Period.custom(start_date: june_1, end_date: Date.new(2026, 7, 31)))++ assert_equal (1..31).to_a, series.map(&:day)+ # Day 1 averages June's and July's; day 31 exists only in July.+ assert_equal 200, series.first.total+ assert_equal 200, series[29].total+ assert_equal 250, series.last.total+ end++ test "average month series leaves days the period never reaches blank, and filters by category" do+ create_transaction(account: @checking_account, amount: 40, date: Date.new(2026, 6, 10), category: @groceries_category)+ create_transaction(account: @checking_account, amount: 9, date: Date.new(2026, 6, 11))+ period = Period.custom(start_date: Date.new(2026, 6, 9), end_date: Date.new(2026, 6, 12))+ statement = IncomeStatement.new(@family)++ series = statement.average_month_expense_series(period: period)+ assert_equal (1..12).to_a, series.map(&:day)+ assert_equal [ nil ] * 8, series.first(8).map(&:total)+ assert_equal [ 0, 40, 49, 49 ], series.last(4).map(&:total)++ filtered = statement.average_month_expense_series(period: period, category_ids: [ @food_category.id ])+ assert_equal [ 0, 40, 40, 40 ], filtered.last(4).map(&:total)+ end+test "calculates totals for transactions" doincome_statement = IncomeStatement.new(@family)totals = income_statement.totals(date_range: Period.last_30_days.date_range)