The personal finance app for everyone (by everyone)
Ruby
Add a category filter to the dashboard spending widget (#4138)
Josh Sanders9272c843b6b3
diff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rbindex a1a6091e88..403a50e717 100644--- a/app/controllers/pages_controller.rb+++ b/app/controllers/pages_controller.rb@@ -27,9 +27,10 @@ class PagesController < ApplicationControllerMONEY_FLOW_CHART_MONTHS = 6# Query params that shape what the dashboard shows without being saved- # anywhere. Customize mode carries them through its links and hide/add- # buttons so the widgets don't jump back to their defaults.- DASHBOARD_VIEW_PARAMS = [ :start_date, :end_date, :money_flow_month, :spending_month, { money_flow_account_ids: [] } ].freeze+ # anywhere. Customize mode, the period picker and each widget's own month+ # links and filter forms carry them along, so changing one control doesn't+ # jump the other widgets back to their defaults.+ DASHBOARD_VIEW_PARAMS = [ :start_date, :end_date, :money_flow_month, :spending_month, { money_flow_account_ids: [], spending_category_ids: [] } ].freeze# Selectable height presets (px) for grow widgets.DASHBOARD_HEIGHT_PRESETS = { "compact" => 208, "auto" => 288, "tall" => 416 }.freeze@@ -47,9 +48,9 @@ class PagesController < ApplicationController@investment_statement = Current.family.investment_statement@accounts = Current.user.accessible_accounts.visible.with_attached_logo+ @dashboard_view_params = dashboard_view_params@dashboard_sections, @hidden_dashboard_sections = build_dashboard_sections@customizing_dashboard = params[:customize].present?- @dashboard_view_params = dashboard_view_params@just_hidden_section = params[:hidden_section]@just_shown_section = params[:shown_section]@@ -73,13 +74,16 @@ class PagesController < ApplicationControllerreturn head :not_found unless DASHBOARD_SECTION_LAYOUTS.key?(section_key)hidden = ActiveModel::Type::Boolean.new.cast(params[:hidden])+ # Resolved before the change: hiding the spending widget would otherwise+ # skip resolving its own filter on the way out.+ view_params = dashboard_view_paramsCurrent.user.update_dashboard_section_hidden(section_key, hidden)# Two param names rather than one, so hiding a widget and adding it back# never redirect to the same URL: Turbo morphs a same-URL visit as a# refresh, and a morph doesn't apply the autofocus that keeps keyboard# users on the widget they just changed.changed = hidden ? { hidden_section: section_key } : { shown_section: section_key }- redirect_to root_path(dashboard_view_params.merge(customize: true, **changed)), status: :see_other+ redirect_to root_path(view_params.merge(customize: true, **changed)), status: :see_otherenddef changelog@@ -128,8 +132,19 @@ class PagesController < ApplicationControllerendend+ # The spending filter is carried as the widget resolved it: a selection+ # that covers every category with spending is the unfiltered state, so it+ # is dropped here rather than re-sent by every other control, where it+ # would pin today's list and leave out categories another month or+ # period adds. While the widget is hidden its ids are only checked+ # against the family's categories, so its queries still never run.def dashboard_view_params- params.permit(*DASHBOARD_VIEW_PARAMS).to_h+ view_params = params.permit(*DASHBOARD_VIEW_PARAMS).to_h+ if view_params.key?(:spending_category_ids)+ category_ids = Current.user.dashboard_hidden_sections.include?("spending_trend") ? spending_trend_category_ids_param : spending_trend_filter.category_ids+ category_ids ? view_params[:spending_category_ids] = category_ids : view_params.delete(:spending_category_ids)+ end+ view_paramsend# Each widget builds its own data, so a hidden widget's builder is never@@ -162,6 +177,7 @@ class PagesController < ApplicationController# to this broader set, not `accounts`, so the view needs it to# know when the drill-down links can safely omit account_ids.accessible_account_ids: Current.user.accessible_accounts.pluck(:id).map(&:to_s),+ view_params: @dashboard_view_params,col_span: section_layout("money_flow")[:col_span]},visible: @accounts.any?,@@ -174,7 +190,10 @@ class PagesController < ApplicationControllertitle: "pages.dashboard.spending_trend.title",partial: "pages/dashboard/spending_trend",layout: section_layout("spending_trend"),- locals: { spending_trend_data: build_spending_trend_data(dashboard_income_statement, spending_trend_month_param) },+ locals: {+ spending_trend_data: build_spending_trend_data(dashboard_income_statement, spending_trend_month_param, spending_trend_filter),+ view_params: @dashboard_view_params+ },visible: @accounts.any?,collapsible: true}@@ -552,21 +571,59 @@ class PagesController < ApplicationControllercurrent_monthend+ # Category ids (and the uncategorized sentinel) from the family's own+ # categories. Not narrowed to the categories with spending this month, so+ # a selection survives switching to a month where some of it is empty.+ # nil means every category (the widget's default, unfiltered state).+ def spending_trend_category_ids_param+ ids = Array(params[:spending_category_ids]).reject(&:blank?).map(&:to_s)+ return nil if ids.empty?++ ids &= [ *Current.family.categories.pluck(:id), Category::UNCATEGORIZED_FILTER_VALUE ]+ ids.presence+ end++ # 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.+ def spending_trend_periods(selected_month)+ month_start = selected_month.beginning_of_month+ (@spending_trend_periods ||= {})[month_start] ||= begin+ current_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 ]+ end+ end++ # The widget's category filter (IncomeStatement::ExpenseCategoryFilter).+ # Memoized: the view params and the widget both read it.+ def spending_trend_filter+ @spending_trend_filter ||= IncomeStatement::ExpenseCategoryFilter.new(+ dashboard_income_statement,+ periods: spending_trend_periods(spending_trend_month_param),+ category_ids: spending_trend_category_ids_param+ )+ end+# 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.- def build_spending_trend_data(income_statement, selected_month)+ #+ # The category filter (an IncomeStatement::ExpenseCategoryFilter) narrows+ # both months 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 = Period.custom(start_date: month_start, end_date: [ month_end, 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 = spending_trend_periods(month_start)+ previous_month_start = previous_period.start_date+ category_ids = category_filter.category_ids- current_daily = income_statement.daily_expense_series(period: current_period).index_by(&:date)- previous_daily = income_statement.daily_expense_series(period: previous_period).index_by(&:date)+ current_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@@ -604,7 +661,10 @@ class PagesController < ApplicationControllerdelta: Money.new(current_total - previous_total, currency),previous_label: I18n.l(previous_month_start, format: :month_year).capitalize,previous_comparison_day: previous_comparison_day,- date_range_short: spending_trend_compact_date_range(current_period)+ date_range_short: spending_trend_compact_date_range(current_period),+ category_options: category_filter.options,+ selected_category_count: category_filter.selected_count,+ category_ids: category_ids}enddiff --git a/app/models/income_statement.rb b/app/models/income_statement.rbindex dd8479b89e..d038ac2228 100644--- a/app/models/income_statement.rb+++ b/app/models/income_statement.rb@@ -119,19 +119,25 @@ class IncomeStatement# periods and account combinations in one request.# Per-day expense totals (in family currency) across a period, powering the# dashboard's cumulative spending chart. Same scoping as `expense_totals`.- def daily_expense_series(period:)- Rails.cache.fetch([- "income_statement", "daily_expense_series", family.id, user&.id,- included_account_ids_hash, period.start_date, period.end_date,- *cache_freshness_key- ]) do- DailyExpenseTotals.new(- family,- transactions_scope: family.transactions.visible.excluding_pending.in_period(period),- date_range: period.date_range,- included_account_ids: included_account_ids- ).call- end+ # `category_ids` narrows the series to those categories: category ids,+ # plus Category::UNCATEGORIZED_FILTER_VALUE for uncategorized spending. As+ # in the transactions category filter, a parent category also covers its+ # subcategories. nil means every category.+ def daily_expense_series(period:, category_ids: nil)+ return unfiltered_daily_expense_series(period) if category_ids.nil?++ matches = expense_category_matcher(category_ids)+ daily_expense_by_category(period)+ .select { |row| matches.call(row.category_id) }+ .group_by(&:date)+ .map { |date, rows| DailyExpenseTotals::DailyTotal.new(date: date, total: rows.sum { |row| row.total.to_d }) }+ 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.+ def daily_expense_category_ids(period:)+ daily_expense_by_category(period).map(&:category_id).uniqenddef totals_for(period, account_ids: nil)@@ -246,6 +252,56 @@ class IncomeStatement)end+ def unfiltered_daily_expense_series(period)+ Rails.cache.fetch([+ "income_statement", "daily_expense_series", family.id, user&.id,+ included_account_ids_hash, period.start_date, period.end_date,+ *cache_freshness_key+ ]) do+ DailyExpenseTotals.new(+ family,+ transactions_scope: family.transactions.visible.excluding_pending.in_period(period),+ date_range: period.date_range,+ included_account_ids: included_account_ids+ ).call+ end+ end++ # Cached per period and never per filter: every category selection is+ # answered from these rows, so the filter doesn't belong in the key. Rows+ # carry only the category id, not its parent, so moving a subcategory+ # under another parent takes effect without busting the cache.+ def daily_expense_by_category(period)+ @daily_expense_by_category ||= {}+ @daily_expense_by_category[period_cache_key(period)] ||= Rails.cache.fetch([+ "income_statement", "daily_expense_by_category", family.id, user&.id,+ included_account_ids_hash, period.start_date, period.end_date,+ *cache_freshness_key+ ]) do+ DailyExpenseTotals.new(+ family,+ transactions_scope: family.transactions.visible.excluding_pending.in_period(period),+ date_range: period.date_range,+ included_account_ids: included_account_ids,+ by_category: true+ ).call+ end+ end++ # A predicate over a row's category_id for the given selection, expanding+ # each selected parent to its current subcategories (categories nest only+ # one level deep). Memoized per selection, since one request filters+ # several periods the same way.+ def expense_category_matcher(category_ids)+ key = category_ids.map(&:to_s).sort+ (@expense_category_matchers ||= {})[key] ||= begin+ selected = key.to_set+ selected.merge(categories.filter_map { |c| c.id.to_s if selected.include?(c.parent_id.to_s) })++ ->(category_id) { selected.include?(category_id.nil? ? Category::UNCATEGORIZED_FILTER_VALUE : category_id.to_s) }+ end+ end+def family_stats(interval: "month")@family_stats ||= {}@family_stats[interval] ||= Rails.cache.fetch([diff --git a/app/models/income_statement/daily_expense_totals.rb b/app/models/income_statement/daily_expense_totals.rbindex cefd559f7d..1e57b791f3 100644--- a/app/models/income_statement/daily_expense_totals.rb+++ b/app/models/income_statement/daily_expense_totals.rb@@ -8,11 +8,15 @@class IncomeStatement::DailyExpenseTotalsinclude IncomeStatement::ScopedTransactionsQuery- def initialize(family, transactions_scope:, date_range:, included_account_ids: nil)+ # `by_category: true` splits each day's total by the transactions'+ # category_id (nil for uncategorized), so callers can narrow the series to+ # some categories without another query.+ def initialize(family, transactions_scope:, date_range:, included_account_ids: nil, by_category: false)@family = family@transactions_scope = transactions_scope@date_range = date_range@included_account_ids = included_account_ids+ @by_category = by_categoryvalidate_date_range!end@@ -22,26 +26,33 @@ class IncomeStatement::DailyExpenseTotalsreturn [] if @included_account_ids&.empty?ActiveRecord::Base.connection.select_all(query_sql).map do |row|- DailyTotal.new(date: row["day"].to_date, total: row["total"])+ if @by_category+ CategoryDailyTotal.new(date: row["day"].to_date, category_id: row["category_id"], total: row["total"])+ else+ DailyTotal.new(date: row["day"].to_date, total: row["total"])+ endendendprivateDailyTotal = Data.define(:date, :total)+ CategoryDailyTotal = Data.define(:date, :category_id, :total)def query_sqlActiveRecord::Base.sanitize_sql_array([ query_sql_body, sql_params ])end# Mirrors IncomeStatement::Totals' transactions subquery, but groups by- # entry date instead of category and keeps only the expense rows. The- # classification CASE is repeated in the GROUP BY (rather than referenced- # by alias) because only some databases accept aliases there.+ # entry date (and category, when asked) instead of category alone, and+ # keeps only the expense rows. The classification CASE is repeated in the+ # GROUP BY (rather than referenced by alias) because only some databases+ # accept aliases there.def query_sql_body<<~SQL- SELECT day, total FROM (+ SELECT day, #{category_column_sql("category_id")}total FROM (SELECTae.date as day,+ #{category_column_sql("at.category_id as category_id")}#{classification_sql("at")} as classification,ABS(SUM(#{converted_amount_sql("at")})) as totalFROM (#{@transactions_scope.to_sql}) at@@ -56,13 +67,19 @@ class IncomeStatement::DailyExpenseTotalsAND a.exclude_from_reports = false#{exclude_tax_advantaged_sql}#{include_finance_accounts_sql}- GROUP BY ae.date, #{classification_sql("at")}+ GROUP BY ae.date, #{category_column_sql("at.category_id")}#{classification_sql("at")}) dailyWHERE classification = 'expense'ORDER BY daySQLend+ # The extra column (with its trailing comma) that splits rows by+ # category, or nothing for the plain per-day series.+ def category_column_sql(column)+ @by_category ? "#{column}, " : ""+ end+def sql_paramsparams = base_sql_params(start_date: @date_range.begin, end_date: @date_range.end)params[:included_account_ids] = @included_account_ids if @included_account_idsdiff --git a/app/models/income_statement/expense_category_filter.rb b/app/models/income_statement/expense_category_filter.rbnew file mode 100644index 0000000000..c92f772078--- /dev/null+++ b/app/models/income_statement/expense_category_filter.rb@@ -0,0 +1,62 @@+# A category filter over an IncomeStatement's daily expense series (the+# dashboard's spending widget): which categories it offers, which of them are+# checked, and what the selection resolves to.+#+# Options are listed by category group (a top-level category and its+# subcategories): every group with spending in the given periods, plus any+# group with a picked category. A group is listed whole, so a+# parent/subcategory cascade sees every child; picking a parent covers them+# all. Ordered like the transactions category filter, with Uncategorized+# first. An option is checked when it was picked, or its parent was, or+# nothing was picked at all; it's live when its group has spending.+#+# The selection resolves to nil (unfiltered) when every option is checked+# and live: that draws exactly what the unfiltered series does. A picked+# category with no spending keeps the filter, so it survives a period where+# it's empty.+class IncomeStatement::ExpenseCategoryFilter+ Option = Data.define(:category, :value, :checked, :live)++ attr_reader :options, :category_ids++ # `category_ids` holds category ids and/or+ # Category::UNCATEGORIZED_FILTER_VALUE, already limited to the family's+ # own; nil means nothing was picked.+ def initialize(income_statement, periods:, category_ids:)+ @income_statement = income_statement+ @options = build_options(periods, category_ids)+ @category_ids = category_ids unless @options.all? { |option| option.checked && option.live }+ end++ # How many categories the selection covers, counted where spending is+ # filed: a category with subcategories counts as its subcategories, not+ # itself as well. So a picked parent with all 8 subcategories counts 8,+ # and unchecking one of them lowers the count by one.+ def selected_count+ parent_ids = options.filter_map { |option| option.category.parent_id }+ options.count { |option| option.checked && !parent_ids.include?(option.category.id) }+ end++ private+ def build_options(periods, category_ids)+ used_ids = periods.flat_map { |period| @income_statement.daily_expense_category_ids(period: period) }.uniq+ selected_ids = Array(category_ids)++ categories = @income_statement.family.categories.alphabetically_by_hierarchy.to_a+ group_of = ->(category) { category.parent_id || category.id }+ live_groups = categories.select { |c| used_ids.include?(c.id) }.map(&group_of)+ shown_groups = live_groups + categories.select { |c| selected_ids.include?(c.id) }.map(&group_of)+ categories.select! { |c| shown_groups.include?(group_of.call(c)) }+ categories.unshift(Category.uncategorized) if used_ids.include?(nil) || selected_ids.include?(Category::UNCATEGORIZED_FILTER_VALUE)++ categories.map do |category|+ value = category.persisted? ? category.id : category.filter_value+ Option.new(+ category: category,+ value: value,+ checked: category_ids.nil? || category_ids.include?(value) || category_ids.include?(category.parent_id),+ live: category.persisted? ? live_groups.include?(group_of.call(category)) : used_ids.include?(nil)+ )+ end+ end+enddiff --git a/app/views/pages/dashboard.html.erb b/app/views/pages/dashboard.html.erbindex e50aa75697..4b61927498 100644--- a/app/views/pages/dashboard.html.erb+++ b/app/views/pages/dashboard.html.erb@@ -60,7 +60,8 @@<%= turbo_frame_tag "dashboard_sections", target: "_top" do %><% if accessible_accounts.any? %><div class="flex items-center justify-end mb-4">- <%= render UI::PeriodPicker.new(selected: @period, url: root_path, frame: "dashboard_sections") %>+ <%# Keeps the widgets' own months and filters; a preset replaces any custom range. %>+ <%= render UI::PeriodPicker.new(selected: @period, url: root_path, frame: "dashboard_sections", extra_params: @dashboard_view_params.except(:start_date, :end_date)) %></div><% end %>diff --git a/app/views/pages/dashboard/_filter_popover.html.erb b/app/views/pages/dashboard/_filter_popover.html.erbnew file mode 100644index 0000000000..b39672fe68--- /dev/null+++ b/app/views/pages/dashboard/_filter_popover.html.erb@@ -0,0 +1,47 @@+<%# locals: (button_text:, search_label:, apply_text:, hidden_fields: {}, list_controllers: "list-filter") %>+<%# The checklist filter a dashboard widget puts beside its month picker: a+ GET form back into the dashboard_sections frame, so the selection lives in+ the URL, with a searchable list of options (yielded by the caller, one+ pages/dashboard/filter_popover_option each) and an Apply button.+ hidden_fields carries every other dashboard view param (the widget's own+ month, the other widgets' months and filters) through the submit, so+ applying this filter doesn't reset the rest of the dashboard. The submit+ advances the address bar (as UI::PeriodPicker's links do), so the state+ survives a refresh, a bookmark and Back. %>+<%= render DS::Popover.new(variant: :button, no_padding: true) do |popover| %>+ <% popover.with_button(+ type: "button",+ text: button_text,+ variant: "outline",+ icon: "list-filter"+ ) %>++ <% popover.with_custom_content do %>+ <%= form_with url: root_path, method: :get, data: { turbo_frame: "dashboard_sections", turbo_action: "advance" }, class: "p-3 w-56 space-y-2" do %>+ <% hidden_fields.each do |name, value| %>+ <% if value.is_a?(Array) %>+ <% value.each do |item| %>+ <%= hidden_field_tag "#{name}[]", item, id: nil %>+ <% end %>+ <% else %>+ <%= hidden_field_tag name, value, id: nil %>+ <% end %>+ <% end %>++ <div data-controller="<%= list_controllers %>">+ <%= render DS::SearchInput.new(+ variant: :embedded,+ placeholder: search_label,+ aria_label: search_label,+ data: { list_filter_target: "input", action: "input->list-filter#filter" }+ ) %>++ <div class="my-2 max-h-64 overflow-y-auto space-y-1" data-list-filter-target="list">+ <%= yield %>+ </div>+ </div>++ <%= render DS::Button.new(type: "submit", text: apply_text, variant: "primary", full_width: true) %>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/pages/dashboard/_filter_popover_option.html.erb b/app/views/pages/dashboard/_filter_popover_option.html.erbnew file mode 100644index 0000000000..6de9212a9a--- /dev/null+++ b/app/views/pages/dashboard/_filter_popover_option.html.erb@@ -0,0 +1,7 @@+<%# locals: (name:, value:, checked:, filter_name:, checkbox_data: {}) %>+<%# One checkbox row in pages/dashboard/filter_popover. The caller yields the+ row's label; filter_name is what the popover's search matches against. %>+<label class="filterable-item flex items-center gap-2 p-1.5 rounded-md hover:bg-container-inset-hover cursor-pointer" data-filter-name="<%= filter_name %>">+ <%= check_box_tag name, value, checked, id: nil, class: "checkbox checkbox--light", data: checkbox_data %>+ <%= yield %>+</label>diff --git a/app/views/pages/dashboard/_money_flow.html.erb b/app/views/pages/dashboard/_money_flow.html.erbindex 0c84b9b429..9db75b2908 100644--- a/app/views/pages/dashboard/_money_flow.html.erb+++ b/app/views/pages/dashboard/_money_flow.html.erb@@ -1,4 +1,4 @@-<%# locals: (money_flow_data:, accounts:, accessible_account_ids:, col_span: "single") %>+<%# locals: (money_flow_data:, accounts:, accessible_account_ids:, view_params:, col_span: "single") %><%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"selected_account_ids = money_flow_data[:account_ids] || accounts.map { |a| a.id.to_s }@@ -13,6 +13,9 @@# At full width the chart and summary sit side by side; at single/half width# they stack so the chart gets the full column and the month labels don't crowd.stacked = col_span != "full"+ # The other widgets' months and filters, carried through this widget's+ # links and form so changing it doesn't reset them.+ other_view_params = view_params.except(:money_flow_month, :money_flow_account_ids)%><div id="money-flow-section" class="px-4 space-y-4"><div class="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-3">@@ -34,44 +37,28 @@<% menu.with_item(variant: :link,text: I18n.l(month, format: :month_year).capitalize,- href: root_path({ money_flow_month: month.iso8601, money_flow_account_ids: money_flow_data[:account_ids] }.compact),+ href: root_path(other_view_params.merge(money_flow_month: month.iso8601, money_flow_account_ids: money_flow_data[:account_ids]).compact),frame: "dashboard_sections",- selected: month == money_flow_data[:month]+ selected: month == money_flow_data[:month],+ data: { turbo_action: "advance" }) %><% end %><% end %>- <%= render DS::Popover.new(variant: :button, no_padding: true) do |popover| %>- <% popover.with_button(- type: "button",- text: all_accounts_selected ? t(".filter_accounts_all") : t(".filter_accounts", count: selected_account_ids.size),- variant: "outline",- icon: "list-filter"- ) %>-- <% popover.with_custom_content do %>- <%= form_with url: root_path, method: :get, data: { turbo_frame: "dashboard_sections" }, class: "p-3 w-56 space-y-2" do %>- <%= hidden_field_tag :money_flow_month, money_flow_data[:month].iso8601 %>-- <div data-controller="list-filter">- <%= render DS::SearchInput.new(- variant: :embedded,- placeholder: t(".search_accounts"),- aria_label: t(".search_accounts"),- data: { list_filter_target: "input", action: "input->list-filter#filter" }- ) %>-- <div class="my-2 max-h-64 overflow-y-auto space-y-1" data-list-filter-target="list">- <% accounts.each do |account| %>- <label class="filterable-item flex items-center gap-2 p-1.5 rounded-md hover:bg-container-inset-hover cursor-pointer" data-filter-name="<%= account.name %>">- <%= check_box_tag "money_flow_account_ids[]", account.id, selected_account_ids.include?(account.id.to_s), id: nil, class: "checkbox checkbox--light" %>- <span class="text-sm text-primary truncate"><%= account.name %></span>- </label>- <% end %>- </div>- </div>-- <%= render DS::Button.new(type: "submit", text: t(".apply"), variant: "primary", full_width: true) %>+ <%= render layout: "pages/dashboard/filter_popover", locals: {+ button_text: all_accounts_selected ? t(".filter_accounts_all") : t(".filter_accounts", count: selected_account_ids.size),+ search_label: t(".search_accounts"),+ apply_text: t(".apply"),+ hidden_fields: other_view_params.merge(money_flow_month: money_flow_data[:month].iso8601)+ } do %>+ <% accounts.each do |account| %>+ <%= render layout: "pages/dashboard/filter_popover_option", locals: {+ name: "money_flow_account_ids[]",+ value: account.id,+ checked: selected_account_ids.include?(account.id.to_s),+ filter_name: account.name+ } do %>+ <span class="text-sm text-primary truncate"><%= account.name %></span><% end %><% end %><% end %>diff --git a/app/views/pages/dashboard/_spending_trend.html.erb b/app/views/pages/dashboard/_spending_trend.html.erbindex 57fa881efc..3093aa7870 100644--- a/app/views/pages/dashboard/_spending_trend.html.erb+++ b/app/views/pages/dashboard/_spending_trend.html.erb@@ -1,4 +1,4 @@-<%# locals: (spending_trend_data:) %>+<%# locals: (spending_trend_data:, view_params:) %><%data = spending_trend_dataperiod = data[:current_period]@@ -14,9 +14,15 @@previous_label = data[:previous_label]previous_comparison_day = data[:previous_comparison_day]date_range_short = data[:date_range_short]+ category_options = data[:category_options]+ # The other widgets' months and filters, carried through this widget's+ # links and form so changing it doesn't reset them.+ other_view_params = view_params.except(:spending_month, :spending_category_ids)%><div id="spending-trend-section" class="px-4 space-y-4">- <div class="flex items-center justify-between gap-3">+ <%# Both rows wrap, so on narrow widths the controls drop below the date+ and then onto a second line instead of overflowing the card. %>+ <div class="flex flex-wrap items-center justify-between gap-3"><p class="text-sm text-secondary hidden sm:block"><%= t(".date_range", start_date: l(period.date_range.begin, format: :long), end_date: l(period.date_range.end, format: :long)) %></p>@@ -24,7 +30,7 @@<%= date_range_short %></p>- <div class="flex items-center gap-2">+ <div class="flex flex-wrap items-center gap-2"><%= render DS::Tooltip.new(text: t(".period_scope_hint"), placement: "top-start") %><%= render DS::Menu.new(variant: :button, placement: "bottom-end", max_height: "18rem") do |menu| %>@@ -38,12 +44,45 @@<% menu.with_item(variant: :link,text: I18n.l(month, format: :month_year).capitalize,- href: root_path({ spending_month: month.iso8601 }),+ href: root_path(other_view_params.merge(spending_month: month.iso8601, spending_category_ids: data[:category_ids]).compact),frame: "dashboard_sections",- selected: month == data[:month]+ selected: month == data[:month],+ data: { turbo_action: "advance" }) %><% end %><% end %>++ <%= render layout: "pages/dashboard/filter_popover", locals: {+ button_text: data[:category_ids] ? t(".filter_categories", count: data[:selected_category_count]) : t(".filter_categories_all"),+ search_label: t(".search_categories"),+ apply_text: t(".apply"),+ hidden_fields: other_view_params.merge(spending_month: data[:month].iso8601),+ list_controllers: "list-filter category-filter"+ } do %>+ <%# Same cascade as the transactions category filter: a parent is+ submitted only while all its subcategories are checked, and+ picking a parent covers its subcategories. %>+ <% category_options.each do |option| %>+ <% category = option.category %>+ <%= render layout: "pages/dashboard/filter_popover_option", locals: {+ name: "spending_category_ids[]",+ value: option.value,+ checked: option.checked,+ filter_name: category.display_name,+ checkbox_data: {+ category_filter_target: "checkbox",+ action: "change->category-filter#toggle",+ category_id: category.id,+ parent_id: category.parent_id+ }+ } do %>+ <% if category.parent_id.present? %>+ <%= icon("corner-down-right", size: "sm") %>+ <% end %>+ <%= render partial: "categories/badge", locals: { category: category } %>+ <% end %>+ <% end %>+ <% end %></div></div>diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.ymlindex 3ac0bb2045..c3d7f95ef2 100644--- a/config/locales/views/pages/en.yml+++ b/config/locales/views/pages/en.yml@@ -162,6 +162,10 @@ en:date_range_short: "%{start_date} - %{end_day}, %{year}"date_range_short_single: "%{date}, %{year}"month_picker_aria_label: "Select month"+ filter_categories: "Filter categories (%{count})"+ 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."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 227cba968d..2eed82a479 100644--- a/test/controllers/pages_controller_test.rb+++ b/test/controllers/pages_controller_test.rb@@ -159,7 +159,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestview_params = {start_date: "2026-08-01", end_date: "2026-08-31",money_flow_month: "2026-07-01", money_flow_account_ids: [ accounts(:depository).id ],- spending_month: "2026-06-01"+ spending_month: "2026-06-01", spending_category_ids: [ categories(:food_and_drink).id ]}patch dashboard_section_hidden_path("net_worth_chart"), params: view_params.merge(hidden: true)@@ -174,6 +174,56 @@ class PagesControllerTest < ActionDispatch::IntegrationTestassert_select "form[action='#{dashboard_section_hidden_path("balance_sheet")}'] input[name='spending_month'][value='2026-06-01']"end+ test "customize mode carries the spending trend category filter through its links and buttons" do+ category = categories(:food_and_drink)+ get root_path(customize: true, spending_month: "2026-06-01", spending_category_ids: [ category.id ])++ assert_select "a[href='#{root_path(spending_month: "2026-06-01", spending_category_ids: [ category.id ])}']", text: I18n.t("pages.dashboard.customize.done")+ assert_select "form[action='#{dashboard_section_hidden_path("balance_sheet")}'] input[name='spending_category_ids[]'][value='#{category.id}']"+ end++ test "each dashboard control keeps the other widgets' months and filters" do+ account = accounts(:depository)+ category = categories(:food_and_drink)+ # Relative months, so each stays inside the widgets' 12-month menus.+ money_flow_month, spending_month, other_month = (1..3).map { |i| i.months.ago.beginning_of_month.to_date.iso8601 }+ view_params = {+ start_date: "2026-08-01", end_date: "2026-08-31",+ money_flow_month: money_flow_month, money_flow_account_ids: [ account.id ],+ spending_month: spending_month, spending_category_ids: [ category.id ]+ }++ get root_path(view_params)+ assert_response :ok++ # Applying money flow's account filter keeps the spending trend's state+ # (and the custom period); its own accounts come from the checkboxes.+ assert_select "#money-flow-section form input[type='hidden'][name='spending_category_ids[]'][value='#{category.id}']"+ assert_select "#money-flow-section form input[type='hidden'][name='spending_month'][value='#{spending_month}']"+ assert_select "#money-flow-section form input[type='hidden'][name='start_date'][value='2026-08-01']"+ assert_select "#money-flow-section form input[type='hidden'][name='money_flow_account_ids[]']", count: 0++ # ...and the other way round.+ assert_select "#spending-trend-section form input[type='hidden'][name='money_flow_account_ids[]'][value='#{account.id}']"+ assert_select "#spending-trend-section form input[type='hidden'][name='money_flow_month'][value='#{money_flow_month}']"+ assert_select "#spending-trend-section form input[type='hidden'][name='spending_category_ids[]']", count: 0++ # Month links keep the other widget's state too.+ money_flow_link = dashboard_link_params("#money-flow-section a[href*='money_flow_month=#{other_month}']")+ assert_equal [ category.id ], money_flow_link["spending_category_ids"]+ assert_equal spending_month, money_flow_link["spending_month"]+ spending_link = dashboard_link_params("#spending-trend-section a[href*='spending_month=#{other_month}']")+ assert_equal [ account.id ], spending_link["money_flow_account_ids"]+ assert_equal money_flow_month, spending_link["money_flow_month"]++ # Picking a preset period keeps every widget's state but drops the custom range.+ period_link = dashboard_link_params("a[href*='period=last_90_days']")+ assert_equal [ account.id ], period_link["money_flow_account_ids"]+ assert_equal [ category.id ], period_link["spending_category_ids"]+ assert_nil period_link["start_date"]+ assert_nil period_link["end_date"]+ end+test "customize mode focuses the widget that was just added back, or its re-add button once hidden" do@user.update_dashboard_section_hidden("net_worth_chart", true)@@ -199,10 +249,12 @@ class PagesControllerTest < ActionDispatch::IntegrationTestIncomeStatement.any_instance.expects(:income_totals).neverIncomeStatement.any_instance.expects(:expense_totals).neverIncomeStatement.any_instance.expects(:net_category_totals).never+ IncomeStatement.any_instance.expects(:daily_expense_series).never+ IncomeStatement.any_instance.expects(:daily_expense_category_ids).neverPagesController.any_instance.expects(:build_money_flow_data).neverPagesController.any_instance.expects(:build_spending_trend_data).never- get root_path+ get root_path, params: { spending_category_ids: [ categories(:food_and_drink).id ] }assert_response :okassert_select "section[data-section-key='net_worth_chart']"@@ -908,6 +960,220 @@ class PagesControllerTest < ActionDispatch::IntegrationTestendend+ test "dashboard spending trend category filter narrows both months and the header totals" do+ account, selected_month, previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ rent = @family.categories.create!(name: "Spending Filter Rent")++ create_transaction(account: account, name: "Food now", amount: 30, date: selected_month, category: food)+ create_transaction(account: account, name: "Rent now", amount: 500, date: selected_month + 1.day, category: rent)+ create_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 ] }+ assert_response :ok++ chart = spending_trend_chart_data+ assert_equal 30.0, chart.fetch("current").last.fetch("value")+ assert_equal 20.0, chart.fetch("previous").last.fetch("value")+ assert_equal [ money_text(30), money_text(20) ], spending_trend_header_totals+ assert_equal money_text(10), spending_trend_header_delta+ assert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.filter_categories", count: 1)+ end++ test "dashboard spending trend category filter includes a picked parent's subcategories" do+ account, selected_month, _previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ groceries = @family.categories.create!(name: "Spending Filter Groceries", parent: food)+ rent = @family.categories.create!(name: "Spending Filter Rent")++ create_transaction(account: account, name: "Food", amount: 10, date: selected_month, category: food)+ create_transaction(account: account, name: "Groceries", amount: 40, date: selected_month, category: groceries)+ create_transaction(account: account, name: "Rent", amount: 500, date: selected_month, category: rent)++ get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: [ food.id ] }+ assert_equal 50.0, spending_trend_chart_data.fetch("current").last.fetch("value")+ assert_select "#spending-trend-section input[name='spending_category_ids[]'][value='#{groceries.id}'][checked]"+ # Food's only subcategory: Food itself isn't counted on top of it.+ assert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.filter_categories", count: 1)++ # A subcategory on its own counts only itself.+ get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: [ groceries.id ] }+ assert_equal 40.0, spending_trend_chart_data.fetch("current").last.fetch("value")+ end++ test "dashboard spending trend category filter offers the categories the chart is drawn from" do+ account, selected_month, previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ groceries = @family.categories.create!(name: "Spending Filter Groceries", parent: food)+ rent = @family.categories.create!(name: "Spending Filter Rent")+ unused = @family.categories.create!(name: "Spending Filter Unused")+ salary = @family.categories.create!(name: "Spending Filter Salary")++ create_transaction(account: account, name: "Groceries", amount: 40, date: selected_month, category: groceries)+ create_transaction(account: account, name: "Rent before", amount: 500, date: previous_month, category: rent)+ create_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 }+ assert_response :ok++ offered = spending_trend_category_values+ # Spending in either month, plus the parent that keeps a subcategory's+ # place in the list, with Uncategorized first.+ assert_equal Category::UNCATEGORIZED_FILTER_VALUE, offered.first+ assert_includes offered, groceries.id+ assert_includes offered, food.id+ assert_includes offered, rent.id+ # Income and categories with no spending play no part in the chart.+ assert_not_includes offered, salary.id+ assert_not_includes offered, unused.id+ assert_select "#spending-trend-section input[name='spending_category_ids[]']:not([checked])", count: 0+ assert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.filter_categories_all")+ end++ test "dashboard spending trend treats picking every offered category as unfiltered" do+ account, selected_month, previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ create_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 }+ unfiltered = spending_trend_chart_data+ every_option = spending_trend_category_values++ get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: every_option }++ assert_equal unfiltered, spending_trend_chart_data+ assert_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)}']"+ end++ test "dashboard spending trend filters uncategorized spending" do+ account, selected_month, _previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ create_transaction(account: account, name: "Food", amount: 30, date: selected_month, category: food)+ create_transaction(account: account, name: "No category", amount: 5, date: selected_month)++ get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: [ Category::UNCATEGORIZED_FILTER_VALUE ] }++ assert_equal 5.0, spending_trend_chart_data.fetch("current").last.fetch("value")+ end++ test "dashboard spending trend month links keep the category filter" do+ account, selected_month, _previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ rent = @family.categories.create!(name: "Spending Filter Rent")+ create_transaction(account: account, name: "Food", amount: 30, date: selected_month, category: food)+ create_transaction(account: account, name: "Rent", amount: 500, date: selected_month, category: rent)++ get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: [ food.id ] }++ other_month = selected_month - 1.month+ assert_select "#spending-trend-section a[href='#{root_path(spending_month: other_month.iso8601, spending_category_ids: [ food.id ])}']"+ assert_select "#spending-trend-section form input[type='hidden'][name='spending_month'][value='#{selected_month.iso8601}']"++ # A picked category keeps its option (and the filter) in a month where it+ # has no spending, rather than the filter silently resetting.+ get root_path, params: { spending_month: other_month.iso8601, spending_category_ids: [ food.id ] }+ assert_includes spending_trend_category_values, food.id+ assert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.filter_categories", count: 1)+ end++ test "dashboard spending trend ignores unknown and other families' category ids" do+ account, selected_month, _previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ create_transaction(account: account, name: "Food", amount: 30, date: selected_month, category: food)+ create_transaction(account: account, name: "No category", amount: 5, date: selected_month)++ other_family = Family.create!(name: "Other Family", currency: "USD")+ other_category = other_family.categories.create!(name: "Not mine")++ get root_path, params: { spending_month: selected_month.iso8601 }+ unfiltered = spending_trend_chart_data++ get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: [ other_category.id, "not-a-uuid", SecureRandom.uuid ] }++ assert_response :ok+ assert_equal unfiltered, spending_trend_chart_data+ assert_not_includes spending_trend_category_values, other_category.id+ assert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.filter_categories_all")+ end++ test "dashboard spending trend lists a category group whole, so picking one subcategory stays narrow" do+ account, selected_month, _previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ groceries = @family.categories.create!(name: "Spending Filter Groceries", parent: food)+ dining = @family.categories.create!(name: "Spending Filter Dining", parent: food)+ create_transaction(account: account, name: "Groceries", amount: 40, date: selected_month, category: groceries)++ get root_path, params: { spending_month: selected_month.iso8601 }+ # A sibling with no spending is still listed, so the parent/subcategory+ # cascade sees every child of Food...+ assert_includes spending_trend_category_values, dining.id++ get root_path, params: { spending_month: selected_month.iso8601, spending_category_ids: [ groceries.id ] }++ # ...and picking Groceries alone leaves Food (and so Dining) unpicked,+ # instead of the cascade checking Food and widening the filter.+ assert_select "#spending-trend-section input[name='spending_category_ids[]'][value='#{groceries.id}'][checked]"+ assert_select "#spending-trend-section input[name='spending_category_ids[]'][value='#{food.id}']:not([checked])"+ assert_select "#spending-trend-section input[name='spending_category_ids[]'][value='#{dining.id}']:not([checked])"+ assert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.filter_categories", count: 1)+ end++ test "dashboard controls drop a spending selection that covers every category" do+ account, selected_month, previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ create_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 ] }+ assert_response :ok++ # Every category with spending is picked, which is the unfiltered state,+ # so no other control re-sends today's list.+ assert_select "input[type='hidden'][name='spending_category_ids[]']", count: 0+ assert_nil dashboard_link_params("a[href*='period=last_90_days']")["spending_category_ids"]+ assert_nil dashboard_link_params("#money-flow-section a[href*='money_flow_month=']")["spending_category_ids"]+ end++ test "dashboard widget controls advance the address bar so their state survives a refresh" do+ get root_path++ assert_select "#money-flow-section form[data-turbo-frame='dashboard_sections'][data-turbo-action='advance']"+ assert_select "#spending-trend-section form[data-turbo-frame='dashboard_sections'][data-turbo-action='advance']"+ assert_select "#money-flow-section a[href*='money_flow_month='][data-turbo-action='advance']"+ assert_select "#spending-trend-section a[href*='spending_month='][data-turbo-action='advance']"+ end++ test "dashboard drops unknown spending category ids while the spending widget is hidden, without its queries" do+ @user.update_dashboard_section_hidden("spending_trend", true)+ other_family = Family.create!(name: "Other Family", currency: "USD")+ other_category = other_family.categories.create!(name: "Not mine")+ mine = categories(:food_and_drink)+ IncomeStatement.any_instance.expects(:daily_expense_category_ids).never++ get root_path, params: { spending_category_ids: [ other_category.id, mine.id ] }++ assert_response :ok+ assert_equal [ mine.id ], dashboard_link_params("a[href*='period=last_90_days']")["spending_category_ids"]+ end++ test "hiding the spending widget drops a selection that covers every category" do+ account, selected_month, previous_month = spending_trend_filter_setup+ food = @family.categories.create!(name: "Spending Filter Food")+ create_transaction(account: account, name: "Food", amount: 30, date: selected_month, category: food)+ create_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 ]+ }++ assert_redirected_to root_path(spending_month: selected_month.iso8601, customize: true, hidden_section: "spending_trend")+ end+privatedef money_flow_barsJSON.parse(css_select("[data-controller='bar-chart']").first["data-bar-chart-data-value"])@@ -917,6 +1183,21 @@ class PagesControllerTest < ActionDispatch::IntegrationTestJSON.parse(css_select("[data-controller='spending-chart']").first["data-spending-chart-data-value"])end+ def dashboard_link_params(selector)+ Rack::Utils.parse_nested_query(URI.parse(css_select(selector).first["href"]).query)+ end++ def spending_trend_category_values+ css_select("#spending-trend-section input[name='spending_category_ids[]']").map { |input| input["value"] }+ end++ # A dedicated account and two fully past months, so fixture transactions+ # (dated relative to today) stay out of the expected totals.+ def spending_trend_filter_setup+ account = @family.accounts.create!(name: "Spending Filter Checking", currency: @family.currency, balance: 0, accountable: Depository.new)+ [ account, 2.months.ago.beginning_of_month.to_date, 3.months.ago.beginning_of_month.to_date ]+ end+# The two large figures in the widget header: the selected month's# month-to-date total and the previous month's comparison total.def spending_trend_header_totalsdiff --git a/test/models/income_statement/daily_expense_totals_test.rb b/test/models/income_statement/daily_expense_totals_test.rbindex 1d93687b04..270b053a61 100644--- a/test/models/income_statement/daily_expense_totals_test.rb+++ b/test/models/income_statement/daily_expense_totals_test.rb@@ -74,6 +74,24 @@ class IncomeStatement::DailyExpenseTotalsTest < ActiveSupport::TestCaseassert_equal [ 3.days.ago.to_date, Date.current ], daily_series.map(&:date)end+ test "splits each day's expense total by category when asked" do+ food = @family.categories.create! name: "Food"+ create_transaction(account: @checking, amount: 100, date: Date.current, category: food)+ create_transaction(account: @checking, amount: 50, date: Date.current, category: food)+ create_transaction(account: @checking, amount: 25, date: Date.current)+ create_transaction(account: @checking, amount: -500, date: Date.current, category: food) # income++ rows = IncomeStatement::DailyExpenseTotals.new(+ @family,+ transactions_scope: @family.transactions.visible.excluding_pending.in_period(@period),+ date_range: @period.date_range,+ by_category: true+ ).call++ assert_equal({ food.id => 150, nil => 25 }, rows.to_h { |row| [ row.category_id, row.total ] })+ assert_equal daily_series.sum(&:total), rows.sum(&:total)+ end+privatedef daily_seriesIncomeStatement.new(@family).daily_expense_series(period: @period)diff --git a/test/models/income_statement/expense_category_filter_test.rb b/test/models/income_statement/expense_category_filter_test.rbnew file mode 100644index 0000000000..f31c35ba18--- /dev/null+++ b/test/models/income_statement/expense_category_filter_test.rb@@ -0,0 +1,67 @@+require "test_helper"++class IncomeStatement::ExpenseCategoryFilterTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:empty)+ @checking = @family.accounts.create! name: "Checking", currency: @family.currency, balance: 5000, accountable: Depository.new+ @period = Period.custom(start_date: Date.new(2026, 6, 1), end_date: Date.new(2026, 6, 30))++ @food = @family.categories.create! name: "Food"+ @groceries = @family.categories.create! name: "Groceries", parent: @food+ @dining = @family.categories.create! name: "Dining", parent: @food+ @rent = @family.categories.create! name: "Rent"+ @unused = @family.categories.create! name: "Unused"++ create_transaction(account: @checking, amount: 40, date: Date.new(2026, 6, 10), category: @groceries)+ create_transaction(account: @checking, amount: 900, date: Date.new(2026, 6, 1), category: @rent)+ create_transaction(account: @checking, amount: 5, date: Date.new(2026, 6, 2))+ end++ test "offers every group with spending whole, Uncategorized first, all checked when nothing is picked" do+ filter = build_filter(nil)++ assert_equal [ Category::UNCATEGORIZED_FILTER_VALUE, @food.id, @dining.id, @groceries.id, @rent.id ], filter.options.map(&:value)+ assert filter.options.all?(&:checked)+ assert filter.options.all?(&:live)+ assert_nil filter.category_ids+ end++ test "a selection covering every option resolves to unfiltered" do+ filter = build_filter([ Category::UNCATEGORIZED_FILTER_VALUE, @food.id, @rent.id ])++ assert filter.options.all?(&:checked)+ assert_nil filter.category_ids+ end++ test "a subcategory alone leaves its parent and siblings unchecked" do+ filter = build_filter([ @groceries.id ])++ checked = filter.options.select(&:checked).map(&:value)+ assert_equal [ @groceries.id ], checked+ assert_equal [ @groceries.id ], filter.category_ids+ end++ test "a picked category with no spending is listed, not live, and keeps the filter" do+ filter = build_filter([ @unused.id ])++ unused = filter.options.find { |option| option.value == @unused.id }+ assert unused.checked+ assert_not unused.live+ assert_equal [ @unused.id ], filter.category_ids+ end++ test "selected count counts a parent as its subcategories, so narrowing a group lowers it" do+ # Food (both subcategories) + Rent+ assert_equal 3, build_filter([ @food.id, @groceries.id, @dining.id, @rent.id ]).selected_count+ # ...one subcategory unchecked, which unchecks Food too+ assert_equal 2, build_filter([ @groceries.id, @rent.id ]).selected_count+ assert_equal 1, build_filter([ Category::UNCATEGORIZED_FILTER_VALUE ]).selected_count+ end++ private+ def build_filter(category_ids)+ IncomeStatement::ExpenseCategoryFilter.new(IncomeStatement.new(@family), periods: [ @period ], category_ids: category_ids)+ end+enddiff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex 9ca882b7b5..b1f7d71f9b 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -47,6 +47,60 @@ class IncomeStatementTest < ActiveSupport::TestCaseendend+ test "daily series narrows to categories, a parent covering its subcategories" do+ period = Period.last_30_days+ rent = @family.categories.create! name: "Rent"+ create_transaction(account: @checking_account, amount: 50, category: @food_category)+ create_transaction(account: @checking_account, amount: 700, category: rent)+ create_transaction(account: @checking_account, amount: 15)+ statement = IncomeStatement.new(@family)++ total = ->(category_ids) { statement.daily_expense_series(period: period, category_ids: category_ids).sum(&:total) }++ assert_equal 50 + 200 + 300 + 400, total.call([ @food_category.id ])+ assert_equal 200 + 300 + 400, total.call([ @groceries_category.id ])+ assert_equal 15, total.call([ Category::UNCATEGORIZED_FILTER_VALUE ])+ assert_equal 700 + 15, total.call([ rent.id, Category::UNCATEGORIZED_FILTER_VALUE ])+ assert_equal statement.daily_expense_series(period: period).sum(&:total),+ total.call([ @food_category.id, rent.id, Category::UNCATEGORIZED_FILTER_VALUE ])+ end++ test "daily expense category ids list the categories with spending, nil for uncategorized" do+ create_transaction(account: @checking_account, amount: 15)++ ids = IncomeStatement.new(@family).daily_expense_category_ids(period: Period.last_30_days)++ # The income category's only transaction is income, and Food has spending+ # only through its subcategory.+ assert_equal [ @groceries_category.id, nil ].to_set, ids.to_set+ end++ test "category-filtered daily series share one cached query per period, whatever the selection" do+ period = Period.last_30_days+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)++ IncomeStatement::DailyExpenseTotals.expects(:new).with(@family, has_entry(by_category: true)).once.returns(+ stub(call: [+ IncomeStatement::DailyExpenseTotals::CategoryDailyTotal.new(date: Date.current, category_id: @groceries_category.id, total: 900),+ IncomeStatement::DailyExpenseTotals::CategoryDailyTotal.new(date: Date.current, category_id: nil, total: 15)+ ])+ )++ assert_equal [ 900 ], IncomeStatement.new(@family).daily_expense_series(period: period, category_ids: [ @food_category.id ]).map(&:total)+ assert_equal [ 15 ], IncomeStatement.new(@family).daily_expense_series(period: period, category_ids: [ Category::UNCATEGORIZED_FILTER_VALUE ]).map(&:total)+ assert_equal [ @groceries_category.id, nil ], IncomeStatement.new(@family).daily_expense_category_ids(period: period)+ end++ test "a new statement invalidates category-filtered daily series when entries change" do+ period = Period.last_30_days+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)+ IncomeStatement::DailyExpenseTotals.expects(:new).twice.returns(stub(call: []))++ IncomeStatement.new(@family).daily_expense_series(period: period, category_ids: [ @food_category.id ])+ create_transaction(account: @checking_account, amount: 10, category: @food_category)+ IncomeStatement.new(@family).daily_expense_series(period: period, category_ids: [ @food_category.id ])+ end+test "calculates totals for transactions" doincome_statement = IncomeStatement.new(@family)totals = income_statement.totals(date_range: Period.last_30_days.date_range)