Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add category trends chart to Reports (#4514)

Shibu M341fd33c7a8c
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb
index 50eb12aecb..81a1c3421a 100644
--- a/app/controllers/reports_controller.rb
+++ b/app/controllers/reports_controller.rb
@@ -4,14 +4,13 @@ class ReportsController < ApplicationController
SIGN_AGNOSTIC_EXPENSE_KINDS = %w[loan_payment investment_contribution].freeze
# Bump when the body's markup changes, so a deploy never serves the old one.
- REPORT_BODY_CACHE_VERSION = 5
+ REPORT_BODY_CACHE_VERSION = 6
# Every parameter the body is built from, as a background rebuild repeats
- # it and as part of the cache key: the period, the tag and entry filters
- # and the breakdown's sort. Blank ones are dropped, so a default period
- # keeps one key.
+ # it and as part of the cache key: the period, the tag and entry filters,
+ # the breakdown's sort and the trend chart's selection.
REPORT_BODY_PARAMS = %i[
period_type start_date end_date sort_by sort_direction filter_category_id filter_account_id
- filter_amount_min filter_amount_max filter_date_start filter_date_end
+ filter_amount_min filter_amount_max filter_date_start filter_date_end trend_granularity
].freeze
# The views warmed after each sync, as their URLs carry them.
WARMED_PERIOD_TYPES = %i[monthly quarterly ytd last_6_months all_time].freeze
@@ -51,7 +50,8 @@ class ReportsController < ApplicationController
end
def print
- setup_report_data(show_flash: false)
+ # The print view does not render the chart, so skip its bucket queries.
+ setup_report_data(show_flash: false, include_trend: false)
render layout: "print"
end
@@ -159,6 +159,8 @@ class ReportsController < ApplicationController
def picker
@period_type = params[:period_type]&.to_sym || :monthly
@start_date = parse_date_param(:start_date) || Date.current.beginning_of_month
+ @category_selection = category_selection
+ @trend_granularity = trend_granularity
render partial: "reports/period_picker", locals: {
period_type: @period_type,
start_date: @start_date
@@ -181,11 +183,16 @@ class ReportsController < ApplicationController
@tags = Current.family.tags.alphabetically
@filter_tags = filter_tags
+ # Trend chart selection. It scopes the chart only, not the report totals.
+ # The page header draws it too, so it is read before the body is served.
+ @category_selection = category_selection
+ @trend_granularity = trend_granularity
+
# Build navigation links for period switching
@nav = build_period_navigation
end
- def setup_report_data(show_flash: false)
+ def setup_report_data(show_flash: false, include_trend: true)
setup_report_period(show_flash: show_flash)
# Get aggregated data
@@ -207,6 +214,7 @@ class ReportsController < ApplicationController
# Transactions breakdown
@transactions = build_transactions_breakdown
+ @category_trend = include_trend ? build_category_trend : nil
@biggest_expenses_limit = Current.user.reports_biggest_expenses_limit
@biggest_expenses = build_biggest_expenses(@biggest_expenses_limit)
@@ -254,9 +262,11 @@ class ReportsController < ApplicationController
end
def report_query
- query = params.permit(*REPORT_BODY_PARAMS, filter_tag_ids: []).to_h.symbolize_keys
+ query = params.permit(*REPORT_BODY_PARAMS, filter_tag_ids: [], trend_category_ids: []).to_h.symbolize_keys
query[:filter_tag_ids] = filter_tags.map(&:id).sort if filter_tags.any?
query.except!(:filter_tag_ids) if filter_tags.none?
+ query[:trend_category_ids] = Array(query[:trend_category_ids]).sort if query[:trend_category_ids].present?
+ query.except!(:trend_category_ids) if query[:trend_category_ids].blank?
# The page opens on this month when no period is given; naming it keeps one
# key for /reports and its warmed ?period_type=monthly build.
query[:period_type] = "monthly" if query[:period_type].blank?
@@ -361,7 +371,7 @@ class ReportsController < ApplicationController
key: "trends_insights",
title: "reports.trends.title",
partial: "reports/trends_insights",
- locals: { trends_data: @trends_data },
+ locals: trend_section_locals,
visible: @has_accounts,
collapsible: true
},
@@ -468,6 +478,8 @@ class ReportsController < ApplicationController
Date.current.beginning_of_year.to_date
when :last_6_months
(Date.current.end_of_month + 1.day - 6.months).beginning_of_month.to_date
+ when :last_12_months
+ (Date.current.end_of_month + 1.day - 12.months).beginning_of_month.to_date
when :all_time
earliest_report_activity_date || Date.current.beginning_of_month.to_date
when :custom
@@ -489,7 +501,7 @@ class ReportsController < ApplicationController
def default_end_date
case @period_type
- when :monthly, :last_6_months
+ when :monthly, :last_6_months, :last_12_months
Date.current.end_of_month.to_date
when :quarterly
Date.current.end_of_quarter.to_date
@@ -803,6 +815,61 @@ class ReportsController < ApplicationController
result.sort_by(&sort_logic)
end
+ def category_selection
+ @category_selection ||= Reports::CategorySelection.new(Current.family, params[:trend_category_ids])
+ end
+
+ def trend_granularity
+ @trend_granularity ||= begin
+ requested = params[:trend_granularity]
+ if %w[month year].include?(requested)
+ requested
+ else
+ long_period? ? "year" : "month"
+ end
+ end
+ end
+
+ # Two years of monthly points is still readable. Longer ranges default to
+ # years, and the user can override the choice.
+ def long_period?
+ @start_date.present? && @end_date.present? && @start_date.advance(months: 24) < @end_date
+ end
+
+ # Category trends are a preview. The model scopes only the chart; the
+ # report totals and tables stay unfiltered.
+ def build_category_trend
+ return nil unless preview_features_enabled?
+
+ Reports::CategoryTrend.new(
+ @income_statement,
+ period: @period,
+ selection: category_selection,
+ granularity: trend_granularity,
+ tag_ids: filter_tags.map(&:id)
+ )
+ end
+
+ # Preview users get the trend locals. Building the category options for
+ # everyone costs a query and objects that the view never renders.
+ def trend_section_locals
+ locals = {
+ trends_data: @trends_data,
+ period_type: @period_type,
+ start_date: @start_date,
+ end_date: @end_date,
+ trend_granularity: trend_granularity
+ }
+ return locals unless @category_trend
+
+ locals.merge(
+ category_trend: @category_trend,
+ category_options: category_selection.options,
+ selected_category_values: category_selection.selected_values,
+ selected_category_count: category_selection.selected_count
+ )
+ end
+
def build_investment_metrics
investment_statement = Current.family.investment_statement
investment_accounts = investment_statement.investment_accounts
@@ -1546,6 +1613,18 @@ class ReportsController < ApplicationController
next_end = next_start + 6.months - 1.day
end
at_latest = @end_date >= Date.current.end_of_month
+ when :last_12_months
+ prev_start = @start_date.beginning_of_month - 12.months
+ prev_end = prev_start + 12.months - 1.day
+ candidate_start = @start_date.beginning_of_month + 12.months
+ if candidate_start + 12.months >= Date.current.beginning_of_month
+ next_end = Date.current.end_of_month
+ next_start = (next_end + 1.day - 12.months).beginning_of_month
+ else
+ next_start = candidate_start
+ next_end = next_start + 12.months - 1.day
+ end
+ at_latest = @end_date >= Date.current.end_of_month
else
return nil
end
@@ -1569,6 +1648,10 @@ class ReportsController < ApplicationController
t("reports.index.period_label.last_6_months",
start: I18n.l(@start_date, format: :short_month_year),
end: I18n.l(@end_date, format: :short_month_year))
+ when :last_12_months
+ t("reports.index.period_label.last_12_months",
+ start: I18n.l(@start_date, format: :short_month_year),
+ end: I18n.l(@end_date, format: :short_month_year))
end
end
end
diff --git a/app/helpers/reports_helper.rb b/app/helpers/reports_helper.rb
index 6aedd3a7b5..2b8c523bef 100644
--- a/app/helpers/reports_helper.rb
+++ b/app/helpers/reports_helper.rb
@@ -1,4 +1,39 @@
module ReportsHelper
+ # Report links keep the report filters, the trend selection and the
+ # granularity. Without this, changing period or sort would drop them.
+ def report_view_path(**overrides)
+ base = trend_link_params.merge(
+ period_type: @period_type,
+ start_date: @start_date,
+ end_date: @end_date,
+ sort_by: params[:sort_by],
+ sort_direction: params[:sort_direction]
+ )
+
+ reports_path(base.merge(overrides).compact)
+ end
+
+ # Picker links only carry the period start; end_date would pin the end and
+ # fight the picker's own period.
+ def report_picker_view_path(**overrides)
+ base = trend_link_params.merge(period_type: @period_type, start_date: @start_date)
+
+ picker_reports_path(base.merge(overrides).compact)
+ end
+
+ # Preserve a granularity the user chose, even when it matches the range's
+ # automatic default. Without the explicit check, Year on a long range would
+ # be dropped and a later short-range link would fall back to Month.
+ def trend_granularity_param
+ @trend_granularity if %w[month year].include?(params[:trend_granularity])
+ end
+
+ def trend_link_params
+ base = { trend_category_ids: @category_selection&.selected_values.presence, **reports_filter_params }
+ base[:trend_granularity] = trend_granularity_param if trend_granularity_param.present?
+ base
+ end
+
# Where a breakdown row links: its category's transactions in the period.
# /transactions only lists Transaction rows, so trade-only rows (e.g. Other
# Investments) link nowhere rather than to an empty list.
diff --git a/app/javascript/controllers/multi_series_chart_controller.js b/app/javascript/controllers/multi_series_chart_controller.js
new file mode 100644
index 0000000000..f04e50a780
--- /dev/null
+++ b/app/javascript/controllers/multi_series_chart_controller.js
@@ -0,0 +1,411 @@
+import { Controller } from "@hotwired/stimulus";
+import * as d3 from "d3";
+import {
+ CHART_TOOLTIP_CLASSES,
+ CHART_TOOLTIP_CONTEXT_CLASSES,
+ CHART_TOOLTIP_VALUE_CLASSES,
+} from "utils/chart_tooltip";
+
+// One line per selected category for the Reports activity breakdown. The
+// dashboard charts are single-series or fixed two-series, so this controller
+// keeps the same lifecycle (ResizeObserver, turbo:load reinstall, page-relative
+// tooltip) but takes an arbitrary number of category series.
+export default class extends Controller {
+ static values = {
+ data: Object,
+ currency: { type: String, default: "USD" },
+ };
+
+ _resizeObserver = null;
+
+ connect() {
+ this._install();
+ document.addEventListener("turbo:load", this._reinstall);
+ this._resizeObserver = new ResizeObserver(() => this._reinstall());
+ this._resizeObserver.observe(this.element);
+ }
+
+ disconnect() {
+ this._teardown();
+ document.removeEventListener("turbo:load", this._reinstall);
+ this._resizeObserver?.disconnect();
+ }
+
+ _reinstall = () => {
+ this._teardown();
+ this._install();
+ };
+
+ _teardown() {
+ d3.select(this.element).selectAll("*").remove();
+ }
+
+ _install() {
+ const width = this.element.clientWidth;
+ const height = this.element.clientHeight;
+ const series = this.dataValue?.series || [];
+ const points = series[0]?.values?.length || 0;
+ const granularity = this.dataValue?.granularity || "month";
+
+ if (width < 50 || height < 50 || series.length === 0 || points < 1) return;
+
+ // A month axis that crosses a year boundary needs a year row; otherwise
+ // "Jan" repeats with no clue which year it belongs to.
+ const years = new Set(
+ (series[0]?.values || []).map((v) => v.date.slice(0, 4)),
+ );
+ const showYearRow = granularity === "month" && years.size > 1;
+
+ const margin = {
+ top: 12,
+ right: 12,
+ bottom: showYearRow ? 44 : 28,
+ left: 56,
+ };
+ const innerWidth = width - margin.left - margin.right;
+ const innerHeight = height - margin.top - margin.bottom;
+
+ const svg = d3
+ .select(this.element)
+ .append("svg")
+ .attr("width", width)
+ .attr("height", height)
+ .attr("viewBox", [0, 0, width, height]);
+
+ const group = svg
+ .append("g")
+ .attr("transform", `translate(${margin.left},${margin.top})`);
+
+ const x = d3
+ .scalePoint()
+ .domain(d3.range(points))
+ .range([0, innerWidth])
+ .padding(0.15);
+
+ // One bucket (for example Year on a one-year period) has no line to draw.
+ // Centre its dot and label so the total is still visible.
+ const xAt = (index) => (points === 1 ? innerWidth / 2 : x(index));
+
+ const maxValue =
+ d3.max(series, (s) => d3.max(s.values, (v) => Number(v.value) || 0)) || 0;
+ const minValue =
+ d3.min(series, (s) => d3.min(s.values, (v) => Number(v.value) || 0)) || 0;
+ // Netted totals can be negative, for example a month with only refunds.
+ // Keep zero on the axis so the sign of each point is readable.
+ const y = d3
+ .scaleLinear()
+ .domain([
+ minValue < 0 ? minValue * 1.1 : 0,
+ maxValue > 0 ? maxValue * 1.1 : minValue < 0 ? 0 : 1,
+ ])
+ .nice()
+ .range([innerHeight, 0]);
+
+ this._drawGrid(group, y, innerWidth);
+
+ if (minValue < 0) {
+ group
+ .append("line")
+ .attr("x1", 0)
+ .attr("x2", innerWidth)
+ .attr("y1", y(0))
+ .attr("y2", y(0))
+ .attr("stroke", "currentColor")
+ .attr("stroke-opacity", 0.6)
+ .attr("class", "text-subdued");
+ }
+
+ const line = d3
+ .line()
+ .x((_value, index) => xAt(index))
+ .y((value) => y(Number(value.value) || 0));
+
+ series.forEach((category) => {
+ if (points > 1) {
+ group
+ .append("path")
+ .datum(category.values)
+ .attr("fill", "none")
+ .attr("stroke", category.color || "var(--color-gray-400)")
+ .attr("stroke-width", 2)
+ .attr("stroke-linejoin", "round")
+ .attr("stroke-linecap", "round")
+ .attr("d", line);
+ }
+
+ // Dense series read better without a dot on every point. Hover still
+ // shows the focus dot and the exact value.
+ if (points <= 12) {
+ group
+ .append("g")
+ .selectAll("circle")
+ .data(category.values)
+ .join("circle")
+ .attr("cx", (_value, index) => xAt(index))
+ .attr("cy", (value) => y(Number(value.value) || 0))
+ .attr("r", points === 1 ? 4 : 2.5)
+ .attr("fill", category.color || "var(--color-gray-400)");
+ }
+ });
+
+ this._drawXAxisLabels(
+ group,
+ xAt,
+ series[0].values,
+ innerWidth,
+ innerHeight,
+ showYearRow,
+ );
+
+ const guideline = group
+ .append("line")
+ .attr("y1", 0)
+ .attr("y2", innerHeight)
+ .attr("stroke", "currentColor")
+ .attr("stroke-dasharray", "4, 4")
+ .attr("class", "text-subdued")
+ .style("display", "none");
+
+ const focus = group.append("g").style("display", "none");
+ const focusDots = series.map((category) =>
+ focus
+ .append("circle")
+ .attr("r", 4)
+ .attr("fill", category.color || "var(--color-gray-400)")
+ .attr("stroke", "var(--color-container)")
+ .attr("stroke-width", 1.5),
+ );
+
+ const tooltip = d3
+ .select(this.element)
+ .append("div")
+ .attr("class", `${CHART_TOOLTIP_CLASSES} opacity-0 top-0`);
+
+ const hide = () => {
+ tooltip.style("opacity", 0);
+ guideline.style("display", "none");
+ focus.style("display", "none");
+ };
+
+ const overlay = group
+ .append("rect")
+ .attr("width", innerWidth)
+ .attr("height", innerHeight)
+ .attr("fill", "none")
+ .attr("pointer-events", "all");
+
+ overlay
+ .on("mousemove", (event) => {
+ const [pointerX] = d3.pointer(event);
+ const index = this._nearestIndex(xAt, pointerX, points);
+ const datum = series[0].values[index];
+
+ guideline
+ .attr("x1", xAt(index))
+ .attr("x2", xAt(index))
+ .style("display", null);
+ focus.style("display", null);
+ focusDots.forEach((dot, seriesIndex) => {
+ dot
+ .attr("cx", xAt(index))
+ .attr(
+ "cy",
+ y(Number(series[seriesIndex].values[index]?.value) || 0),
+ );
+ });
+
+ tooltip
+ .html(this._tooltipTemplate(index, series, datum))
+ .style("opacity", 1)
+ .style("left", `${this._tooltipX(event.pageX)}px`)
+ .style("top", `${event.pageY - 10}px`);
+ })
+ .on("mouseleave", hide);
+ }
+
+ _drawGrid(group, y, innerWidth) {
+ const ticks = y.ticks(4);
+
+ group
+ .append("g")
+ .selectAll("line")
+ .data(ticks)
+ .join("line")
+ .attr("x1", 0)
+ .attr("x2", innerWidth)
+ .attr("y1", (tick) => y(tick))
+ .attr("y2", (tick) => y(tick))
+ .attr("stroke", "var(--color-gray-300)")
+ .attr("stroke-opacity", 0.5);
+
+ group
+ .append("g")
+ .selectAll("text")
+ .data(ticks)
+ .join("text")
+ .attr("x", -8)
+ .attr("y", (tick) => y(tick))
+ .attr("dy", "0.32em")
+ .attr("text-anchor", "end")
+ .attr("class", "text-secondary fill-current")
+ .style("font-size", "11px")
+ .text((tick) => this._formatCompact(tick));
+ }
+
+ _drawXAxisLabels(group, xAt, values, innerWidth, innerHeight, showYearRow) {
+ const points = values.length;
+ const maxLabels = Math.max(2, Math.floor(innerWidth / 64));
+ const step = Math.max(1, Math.ceil(points / maxLabels));
+ const labelled = new Set();
+
+ // Keep January visible even when the step skips it: it marks the start of
+ // the year that the row below names.
+ values.forEach((value, index) => {
+ const isYearStart = value.date.slice(5) === "01-01";
+ if (
+ index === 0 ||
+ index === points - 1 ||
+ index % step === 0 ||
+ (showYearRow && isYearStart)
+ ) {
+ labelled.add(index);
+ }
+ });
+
+ group
+ .append("g")
+ .selectAll("text")
+ .data(values)
+ .join("text")
+ .attr("x", (_value, index) => xAt(index))
+ .attr("y", innerHeight + 16)
+ .attr("text-anchor", "middle")
+ .attr("class", "text-secondary fill-current")
+ .style("font-size", "11px")
+ .style("display", (_value, index) =>
+ labelled.has(index) ? null : "none",
+ )
+ .text((value) => value.short_label || value.label);
+
+ if (!showYearRow) return;
+
+ const runs = [];
+ values.forEach((value, index) => {
+ const year = value.date.slice(0, 4);
+ const current = runs[runs.length - 1];
+
+ if (current && current.year === year) {
+ current.end = index;
+ } else {
+ runs.push({ year, start: index, end: index });
+ }
+ });
+
+ // A faint rule at each new year, through the plot, so the eye can separate
+ // the two periods even where the month labels are sparse.
+ runs.slice(1).forEach((run) => {
+ group
+ .append("line")
+ .attr("x1", xAt(run.start))
+ .attr("x2", xAt(run.start))
+ .attr("y1", 0)
+ .attr("y2", innerHeight + 22)
+ .attr("stroke", "var(--color-gray-300)")
+ .attr("stroke-opacity", 0.7)
+ .attr("stroke-dasharray", "3, 3");
+ });
+
+ group
+ .append("g")
+ .selectAll("text")
+ .data(runs)
+ .join("text")
+ .attr("x", (run) => (xAt(run.start) + xAt(run.end)) / 2)
+ .attr("y", innerHeight + 34)
+ .attr("text-anchor", "middle")
+ .attr("class", "text-primary fill-current")
+ .style("font-size", "10px")
+ .style("font-weight", "600")
+ .style("letter-spacing", "0.02em")
+ .text((run) => run.year);
+ }
+
+ _nearestIndex(xAt, pointerX, points) {
+ let nearest = 0;
+
+ for (let index = 1; index < points; index += 1) {
+ if (Math.abs(xAt(index) - pointerX) < Math.abs(xAt(nearest) - pointerX)) {
+ nearest = index;
+ }
+ }
+
+ return nearest;
+ }
+
+ _tooltipX(pageX) {
+ const estimatedTooltipWidth = 240;
+ const tooltipX = pageX + 10;
+ const overflowX =
+ tooltipX + estimatedTooltipWidth - document.body.clientWidth;
+
+ return overflowX > 0 ? pageX - overflowX - 20 : tooltipX;
+ }
+
+ _tooltipTemplate(index, series, datum) {
+ const rows = series
+ .map((category) => {
+ const value = Number(category.values[index]?.value) || 0;
+ return `
+ <div class="flex items-center justify-between gap-4 ${CHART_TOOLTIP_VALUE_CLASSES}">
+ <span class="flex items-center gap-1.5 text-secondary">
+ <span class="inline-block h-2 w-2 rounded-full" style="background-color: ${category.color || "var(--color-gray-400)"};"></span>
+ ${this._escape(category.name)}
+ </span>
+ <span class="text-primary">${this._formatCurrency(value)}</span>
+ </div>
+ `;
+ })
+ .join("");
+
+ return `<div class="${CHART_TOOLTIP_CONTEXT_CLASSES}">${this._escape(datum.label)}</div>${rows}`;
+ }
+
+ _formatCurrency(value) {
+ try {
+ return new Intl.NumberFormat(undefined, {
+ style: "currency",
+ currency: this.currencyValue,
+ maximumFractionDigits: 2,
+ }).format(value);
+ } catch {
+ return value;
+ }
+ }
+
+ _formatCompact(value) {
+ try {
+ return new Intl.NumberFormat(undefined, {
+ style: "currency",
+ currency: this.currencyValue,
+ notation: "compact",
+ maximumFractionDigits: 1,
+ }).format(value);
+ } catch {
+ return value;
+ }
+ }
+
+ _escape(value) {
+ return String(value ?? "").replace(
+ /[&<>"']/g,
+ (character) =>
+ ({
+ "&": "&amp;",
+ "<": "&lt;",
+ ">": "&gt;",
+ '"': "&quot;",
+ "'": "&#39;",
+ })[character],
+ );
+ }
+}
diff --git a/app/models/income_statement.rb b/app/models/income_statement.rb
index 736c6648a7..cb7c332e00 100644
--- a/app/models/income_statement.rb
+++ b/app/models/income_statement.rb
@@ -58,12 +58,12 @@ class IncomeStatement
end
end
- def expense_totals(period: Period.current_month)
+ def expense_totals(period: Period.current_month, tag_ids: nil)
# Memoized per instance so callers that also invoke `net_category_totals`
- key = period_cache_key(period)
+ key = period_total_cache_key(period, tag_ids)
@expense_totals_by_period ||= {}
return @expense_totals_by_period[key] if @expense_totals_by_period.key?(key)
- @expense_totals_by_period[key] = build_period_total(classification: "expense", period: period)
+ @expense_totals_by_period[key] = build_period_total(classification: "expense", period: period, tag_ids: tag_ids)
end
# The part of expense_totals that paid the family's bills: the same
@@ -88,11 +88,11 @@ class IncomeStatement
@bill_expense_totals_by_period[key] = build_period_total(classification: "expense", period: period, rows: rows)
end
- def income_totals(period: Period.current_month)
- key = period_cache_key(period)
+ def income_totals(period: Period.current_month, tag_ids: nil)
+ key = period_total_cache_key(period, tag_ids)
@income_totals_by_period ||= {}
return @income_totals_by_period[key] if @income_totals_by_period.key?(key)
- @income_totals_by_period[key] = build_period_total(classification: "income", period: period)
+ @income_totals_by_period[key] = build_period_total(classification: "income", period: period, tag_ids: tag_ids)
end
# Money moved into investment accounts during the period, for a family that
@@ -253,8 +253,13 @@ class IncomeStatement
[ period.start_date, period.end_date ]
end
- def build_period_total(classification:, period:, rows: totals_for_period(period))
+ def period_total_cache_key(period, tag_ids)
+ [ period_cache_key(period), Array(tag_ids).map(&:to_s).sort ]
+ end
+
+ def build_period_total(classification:, period:, rows: nil, tag_ids: nil)
# Exclude pending transactions from budget calculations
+ rows ||= totals_for_period(period, tag_ids: tag_ids)
totals = rows.select { |t| t.classification == classification }
classification_total = totals.sum(&:total)
@@ -298,13 +303,14 @@ class IncomeStatement
)
end
- def totals_for_period(period)
+ def totals_for_period(period, tag_ids: nil)
@totals_for_period ||= {}
- @totals_for_period[period_cache_key(period)] ||=
- totals_query(
- transactions_scope: family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled).in_period(period),
- date_range: period.date_range
- )
+ key = period_total_cache_key(period, tag_ids)
+ @totals_for_period[key] ||= begin
+ scope = family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled).in_period(period)
+ scope = scope.with_any_tag(tag_ids) if tag_ids.present?
+ totals_query(transactions_scope: scope, date_range: period.date_range)
+ end
end
def unfiltered_daily_expense_series(period)
diff --git a/app/models/income_statement/net_by_category.rb b/app/models/income_statement/net_by_category.rb
new file mode 100644
index 0000000000..7d2c002f54
--- /dev/null
+++ b/app/models/income_statement/net_by_category.rb
@@ -0,0 +1,43 @@
+# Net spending per category for one period: expense minus income booked to the
+# category. A refund lowers its category instead of counting as more spending.
+#
+# Shared by SpendingComparison and the Reports category trend, so both net a
+# statement the same way.
+class IncomeStatement::NetByCategory
+ def initialize(statement, period:, tag_ids: nil)
+ @statement = statement
+ @period = period
+ @tag_ids = tag_ids
+ end
+
+ # { key => { category:, net: } } for every category with activity.
+ def call
+ result = {}
+ period_totals = [
+ [ statement.expense_totals(period: period, tag_ids: tag_ids), 1 ],
+ [ statement.income_totals(period: period, tag_ids: tag_ids), -1 ]
+ ]
+
+ period_totals.each do |totals, sign|
+ totals.category_totals.each do |category_total|
+ next if category_total.total.zero?
+
+ entry = result[self.class.key(category_total.category)] ||= { category: category_total.category, net: 0 }
+ entry[:net] += sign * category_total.total
+ end
+ end
+
+ result
+ end
+
+ # A stable key for synthetic categories, or the persisted id.
+ def self.key(category)
+ return :uncategorized if category.uncategorized?
+ return :other_investments if category.other_investments?
+
+ category.id
+ end
+
+ private
+ attr_reader :statement, :period, :tag_ids
+end
diff --git a/app/models/income_statement/spending_comparison.rb b/app/models/income_statement/spending_comparison.rb
index 8a17cca6a4..b2a1a38af7 100644
--- a/app/models/income_statement/spending_comparison.rb
+++ b/app/models/income_statement/spending_comparison.rb
@@ -53,8 +53,9 @@ class IncomeStatement::SpendingComparison
.minimum(:date)
end
- def initialize(income_statement, period:, history_start:, as_of: Date.current)
+ def initialize(income_statement, period:, history_start:, as_of: Date.current, tag_ids: nil)
@income_statement = income_statement
+ @tag_ids = tag_ids
@in_progress = period.start_date <= as_of && as_of < period.end_date
# An unfinished period counts spending so far.
@period = @in_progress ? Period.custom(start_date: period.start_date, end_date: as_of) : period
@@ -139,7 +140,7 @@ class IncomeStatement::SpendingComparison
end
private
- attr_reader :income_statement
+ attr_reader :income_statement, :tag_ids
def build_baseline_period(history_start)
end_date = period.start_date - 1.day
@@ -184,16 +185,7 @@ class IncomeStatement::SpendingComparison
# { key => { category:, net: } } for every category with activity, where
# net = expense - income booked to that category in the period.
def net_by_category(p)
- result = {}
- { income_statement.expense_totals(period: p) => 1, income_statement.income_totals(period: p) => -1 }.each do |totals, sign|
- totals.category_totals.each do |ct|
- next if ct.total.zero?
-
- entry = result[key_for(ct.category)] ||= { category: ct.category, net: 0 }
- entry[:net] += sign * ct.total
- end
- end
- result
+ IncomeStatement::NetByCategory.new(income_statement, period: p, tag_ids: tag_ids).call
end
def scaled_normal(baseline_net)
@@ -245,9 +237,6 @@ class IncomeStatement::SpendingComparison
end
def key_for(category)
- return :uncategorized if category.uncategorized?
- return :other_investments if category.other_investments?
-
- category.id
+ IncomeStatement::NetByCategory.key(category)
end
end
diff --git a/app/models/reports/category_selection.rb b/app/models/reports/category_selection.rb
new file mode 100644
index 0000000000..8a504a44da
--- /dev/null
+++ b/app/models/reports/category_selection.rb
@@ -0,0 +1,81 @@
+# Which categories the Activity Breakdown trend chart draws. Selection only:
+# the report totals and tables stay unfiltered. Values are category ids plus
+# the stable Uncategorized sentinel, so a renamed category keeps working.
+class Reports::CategorySelection
+ Option = Data.define(:category, :value, :checked)
+
+ UNCATEGORIZED = Category::UNCATEGORIZED_FILTER_VALUE
+
+ attr_reader :selected_values
+
+ def initialize(family, values)
+ @family = family
+ @selected_values = normalize(values)
+ end
+
+ def active?
+ selected_values.any?
+ end
+
+ # One line per selected group: a selected parent covers its children, so the
+ # child is not drawn a second time. Order follows the submitted selection.
+ def group_values
+ @group_values ||= begin
+ ids = selected_values.reject { |value| value == UNCATEGORIZED }
+ selected_ids = ids.to_set
+ roots = family.categories.where(id: ids).reject do |category|
+ category.parent_id.present? && selected_ids.include?(category.parent_id.to_s)
+ end
+
+ values = roots.map { |category| category.id.to_s }
+ values << UNCATEGORIZED if selected_values.include?(UNCATEGORIZED)
+ values
+ end
+ end
+
+ def selected_count
+ group_values.size
+ end
+
+ def options
+ @options ||= begin
+ categories = [ Category.uncategorized, *family.categories.alphabetically_by_hierarchy ]
+ categories.map do |category|
+ value = value_for(category)
+ Option.new(category: category, value: value, checked: checked?(category, value))
+ end
+ end
+ end
+
+ private
+ attr_reader :family
+
+ def normalize(values)
+ raw = if values.is_a?(Array)
+ values
+ elsif values.is_a?(String)
+ [ values ]
+ else
+ []
+ end
+
+ return [] if raw.empty?
+
+ allowed = family.categories.pluck(:id).map(&:to_s)
+ raw.reject(&:blank?).map(&:to_s).uniq.select do |value|
+ value == UNCATEGORIZED || allowed.include?(value)
+ end
+ end
+
+ def value_for(category)
+ category.persisted? ? category.id.to_s : UNCATEGORIZED
+ end
+
+ # A parent selection cascades to its children, matching the checkbox
+ # behaviour in category_filter_controller.js.
+ def checked?(category, value)
+ return true if selected_values.include?(value)
+
+ category.parent_id.present? && selected_values.include?(category.parent_id.to_s)
+ end
+end
diff --git a/app/models/reports/category_trend.rb b/app/models/reports/category_trend.rb
new file mode 100644
index 0000000000..c3d6995832
--- /dev/null
+++ b/app/models/reports/category_trend.rb
@@ -0,0 +1,123 @@
+# Net totals per category for each month or year in a report period, for the
+# Reports category trend chart. A value is expense minus income booked to the
+# category in the bucket, the rule IncomeStatement::SpendingComparison and the
+# Sankeys use, so a refund lowers its category instead of plotting as more
+# spending. A bucket with more refunds than purchases plots below zero.
+#
+# Totals come from the user-scoped IncomeStatement, so pending transactions,
+# exclusions, transfers, tax-advantaged accounts and exchange rates follow the
+# rest of Reports. The selection and the report's tag filter scope only this
+# chart.
+class Reports::CategoryTrend
+ GRANULARITIES = %w[month year].freeze
+
+ attr_reader :granularity
+
+ def initialize(statement, period:, selection:, granularity:, tag_ids: nil)
+ @statement = statement
+ @period = period
+ @selection = selection
+ @tag_ids = tag_ids
+ @granularity = GRANULARITIES.include?(granularity.to_s) ? granularity.to_s : "month"
+ end
+
+ def currency
+ statement.family.currency
+ end
+
+ # One series per selected group, largest activity first. A parent total
+ # already includes its subcategories, and the selection drops a child when
+ # its parent is selected, so each value sums once. The name breaks ties, so
+ # the legend order does not move between requests.
+ def series
+ @series ||= selection.group_values.filter_map { |value| series_for(value) }
+ .sort_by { |entry| [ -entry[:values].sum { |point| point[:value].abs }, entry[:name] ] }
+ end
+
+ # Chart payload. Every series has one value per bucket.
+ def as_json(*)
+ { granularity: granularity, currency: currency, series: series }
+ end
+
+ private
+ attr_reader :statement, :period, :selection, :tag_ids
+
+ def series_for(value)
+ category = category_for(value)
+ return nil unless category
+
+ {
+ name: category.name_with_parent,
+ color: category.color.presence || Category::UNCATEGORIZED_COLOR,
+ values: values_for(category)
+ }
+ end
+
+ def category_for(value)
+ return Category.uncategorized if value == Reports::CategorySelection::UNCATEGORIZED
+
+ statement.family.categories.find_by(id: value)
+ end
+
+ def values_for(category)
+ nets = net_by_key
+ key = IncomeStatement::NetByCategory.key(category)
+
+ bucket_starts.map do |start|
+ {
+ date: start.iso8601,
+ label: bucket_label(start),
+ short_label: bucket_short_label(start),
+ value: (nets.dig(key, start) || 0).to_f
+ }
+ end
+ end
+
+ # { category key => { bucket start => expense - income } } for the period.
+ def net_by_key
+ @net_by_key ||= bucket_starts.each_with_object({}) do |start, nets|
+ net = IncomeStatement::NetByCategory.new(statement, period: bucket_period(start), tag_ids: tag_ids).call
+ net.each do |key, entry|
+ (nets[key] ||= {})[start] = entry[:net]
+ end
+ end
+ end
+
+ def bucket_starts
+ @bucket_starts ||= begin
+ starts = []
+ cursor = bucket_start(period.start_date)
+ last = bucket_start(period.end_date)
+
+ while cursor <= last
+ starts << cursor
+ cursor = granularity == "year" ? cursor.next_year : cursor.next_month
+ end
+
+ starts
+ end
+ end
+
+ def bucket_start(date)
+ granularity == "year" ? date.to_date.beginning_of_year : date.to_date.beginning_of_month
+ end
+
+ # Clamp each bucket to the report period, so a custom range counts only
+ # its own days.
+ def bucket_period(start)
+ finish = granularity == "year" ? start.end_of_year : start.end_of_month
+
+ Period.custom(
+ start_date: [ start, period.start_date ].max,
+ end_date: [ finish, period.end_date ].min
+ )
+ end
+
+ def bucket_label(start)
+ granularity == "year" ? start.year.to_s : I18n.l(start, format: :short_month_year)
+ end
+
+ def bucket_short_label(start)
+ granularity == "year" ? start.year.to_s : I18n.l(start, format: "%b")
+ end
+end
diff --git a/app/views/reports/_breakdown_table.html.erb b/app/views/reports/_breakdown_table.html.erb
index 1800bff732..aefd85765a 100644
--- a/app/views/reports/_breakdown_table.html.erb
+++ b/app/views/reports/_breakdown_table.html.erb
@@ -18,7 +18,7 @@
rows = groups.flat_map do |group|
[ group.merge(level: :category), *Array(group[:subcategories]).map { |subcategory| subcategory.merge(level: :subcategory) } ]
end.map { |item| item.merge(href: breakdown_transactions_path(item, start_date, end_date, tags: local_assigns[:filter_tags] || [])) }
- amount_header = link_to reports_path(amount_sort_params), class: "inline-flex items-center gap-1 hover:text-primary" do
+ amount_header = link_to report_view_path(**amount_sort_params), class: "inline-flex items-center gap-1 hover:text-primary" do
concat t("reports.transactions_breakdown.table.amount")
concat icon(current_sort_direction == "desc" ? "chevron-down" : "chevron-up", class: "w-3 h-3") if current_sort_by == "amount"
end
diff --git a/app/views/reports/_period_picker.html.erb b/app/views/reports/_period_picker.html.erb
index 5d13a9a046..982d6d2417 100644
--- a/app/views/reports/_period_picker.html.erb
+++ b/app/views/reports/_period_picker.html.erb
@@ -8,7 +8,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-left",
- href: picker_reports_path(period_type: :monthly, start_date: start_date.beginning_of_year - 1.year, **reports_filter_params),
+ href: report_picker_view_path(period_type: :monthly, start_date: start_date.beginning_of_year - 1.year),
aria: { label: t("reports.index.previous_year") },
frame: "reports_picker"
) %>
@@ -22,7 +22,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-right",
- href: picker_reports_path(period_type: :monthly, start_date: next_year_start, **reports_filter_params),
+ href: report_picker_view_path(period_type: :monthly, start_date: next_year_start),
aria: { label: t("reports.index.next_year") },
frame: "reports_picker"
) %>
@@ -41,7 +41,7 @@
<%= render DS::Link.new(
variant: date.month == start_date.month ? "secondary" : "ghost",
text: month_name,
- href: reports_path(period_type: :monthly, start_date: date, end_date: date.end_of_month, **reports_filter_params),
+ href: report_view_path(period_type: :monthly, start_date: date, end_date: date.end_of_month),
full_width: true,
frame: :_top
) %>
@@ -56,7 +56,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-left",
- href: picker_reports_path(period_type: :quarterly, start_date: Date.new(start_date.year - 1, 1, 1), **reports_filter_params),
+ href: report_picker_view_path(period_type: :quarterly, start_date: Date.new(start_date.year - 1, 1, 1)),
aria: { label: t("reports.index.previous_year") },
frame: "reports_picker"
) %>
@@ -70,7 +70,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-right",
- href: picker_reports_path(period_type: :quarterly, start_date: next_year_start, **reports_filter_params),
+ href: report_picker_view_path(period_type: :quarterly, start_date: next_year_start),
aria: { label: t("reports.index.next_year") },
frame: "reports_picker"
) %>
@@ -89,7 +89,7 @@
<%= render DS::Link.new(
variant: quarter_start.quarter == start_date.quarter && start_date.year == quarter_start.year ? "secondary" : "ghost",
text: t("reports.index.period_picker.quarter", quarter: q, year: start_date.year),
- href: reports_path(period_type: :quarterly, start_date: quarter_start, end_date: quarter_end, **reports_filter_params),
+ href: report_view_path(period_type: :quarterly, start_date: quarter_start, end_date: quarter_end),
full_width: true,
frame: :_top
) %>
@@ -107,7 +107,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-left",
- href: picker_reports_path(period_type: :ytd, start_date: Date.new(decade_start - 1, 1, 1), **reports_filter_params),
+ href: report_picker_view_path(period_type: :ytd, start_date: Date.new(decade_start - 1, 1, 1)),
aria: { label: t("reports.index.previous_decade") },
frame: "reports_picker"
) %>
@@ -120,7 +120,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-right",
- href: picker_reports_path(period_type: :ytd, start_date: Date.new(decade_start + 10, 1, 1), **reports_filter_params),
+ href: report_picker_view_path(period_type: :ytd, start_date: Date.new(decade_start + 10, 1, 1)),
aria: { label: t("reports.index.next_decade") },
frame: "reports_picker"
) %>
@@ -139,7 +139,7 @@
<%= render DS::Link.new(
variant: year == start_date.year ? "secondary" : "ghost",
text: year == Date.current.year ? t("reports.index.period_picker.ytd", year: year) : year.to_s,
- href: reports_path(period_type: :ytd, start_date: year_start, end_date: year_end, **reports_filter_params),
+ href: report_view_path(period_type: :ytd, start_date: year_start, end_date: year_end),
full_width: true,
frame: :_top
) %>
diff --git a/app/views/reports/_transactions_breakdown.html.erb b/app/views/reports/_transactions_breakdown.html.erb
index ca45adc3e0..2fb47e7fae 100644
--- a/app/views/reports/_transactions_breakdown.html.erb
+++ b/app/views/reports/_transactions_breakdown.html.erb
@@ -1,19 +1,19 @@
<%# locals: (transactions:, period_type:, start_date:, end_date:, filter_tags:) %>
<div>
+ <%
+ # Params every link back to this report keeps.
+ base_params = {
+ period_type: period_type,
+ start_date: start_date,
+ end_date: end_date,
+ sort_by: params[:sort_by],
+ sort_direction: params[:sort_direction],
+ filter_tag_ids: filter_tags.map(&:id).presence
+ }.compact
+ %>
+
<%# Export Controls %>
<div class="flex items-center justify-end mb-4 flex-wrap gap-3">
- <%
- # Build params hash for links
- base_params = {
- period_type: period_type,
- start_date: start_date,
- end_date: end_date,
- sort_by: params[:sort_by],
- sort_direction: params[:sort_direction],
- filter_tag_ids: filter_tags.map(&:id).presence
- }.compact
- %>
-
<%# Export Options %>
<div class="flex flex-wrap items-center justify-end gap-2">
<%= link_to export_transactions_reports_path(base_params.merge(format: :csv)),
@@ -48,8 +48,9 @@
# Toggle sort direction: if currently sorting by amount desc, switch to asc; otherwise default to desc
next_sort_direction = (current_sort_by == "amount" && current_sort_direction == "desc") ? "asc" : "desc"
- # Build params for amount sort link
- amount_sort_params = base_params.merge(sort_by: "amount", sort_direction: next_sort_direction)
+ # Build params for amount sort link. The helper keeps the period, trend
+ # selection, and granularity, so sorting does not drop the chart.
+ amount_sort_params = { sort_by: "amount", sort_direction: next_sort_direction }
%>
<div class="space-y-8">
diff --git a/app/views/reports/_trends_insights.html.erb b/app/views/reports/_trends_insights.html.erb
index 5a2747b976..3d6c292715 100644
--- a/app/views/reports/_trends_insights.html.erb
+++ b/app/views/reports/_trends_insights.html.erb
@@ -1,4 +1,156 @@
+<%# locals: (trends_data:, period_type:, start_date:, end_date:, trend_granularity:, category_trend: nil, category_options: nil, selected_category_values: nil, selected_category_count: nil) %>
<div class="@container space-y-8">
+ <% if preview_features_enabled? && category_trend %>
+ <%# Category trends. The category selection and tag filter scope this chart only, not the tables below. %>
+ <div>
+ <div class="flex items-start justify-between gap-3 flex-wrap mb-3">
+ <div class="space-y-1">
+ <div class="flex items-center gap-2">
+ <h3 class="text-lg font-medium">
+ <%= t("reports.trends.category_trend.title") %>
+ </h3>
+ <%= render DS::Pill.new(label: t("shared.preview")) %>
+ </div>
+ <p class="text-sm text-secondary">
+ <%= t("reports.trends.category_trend.subtitle") %>
+ </p>
+ <% if filter_tags.any? %>
+ <div class="flex flex-wrap items-center gap-2 pt-1" data-testid="category-trend-tags">
+ <span class="text-xs text-secondary"><%= t("reports.trends.category_trend.filtered_by_tags") %></span>
+ <% filter_tags.each do |tag| %>
+ <%= render "tags/badge", tag: tag %>
+ <% end %>
+ </div>
+ <% end %>
+ </div>
+
+ <div class="flex items-center gap-2 flex-wrap">
+ <%# Only an explicit granularity survives Apply. The chart's own default
+ must not turn into a user choice. %>
+ <% explicit_granularity_field = trend_granularity_param.present? ? { trend_granularity: trend_granularity_param } : {} %>
+ <%= render layout: "pages/dashboard/filter_popover", locals: {
+ button_text: selected_category_values.any? ?
+ t("reports.trends.category_trend.selected", count: selected_category_count) :
+ t("reports.trends.category_trend.select"),
+ search_label: t("reports.trends.category_trend.search"),
+ apply_text: t("reports.trends.category_trend.apply"),
+ hidden_fields: {
+ period_type: period_type,
+ start_date: start_date,
+ end_date: end_date,
+ **explicit_granularity_field,
+ sort_by: params[:sort_by],
+ sort_direction: params[:sort_direction],
+ **reports_filter_params
+ },
+ url: reports_path,
+ method: :get,
+ form_data: {},
+ list_controllers: "list-filter category-filter"
+ } do %>
+ <% category_options.each do |option| %>
+ <%= render layout: "pages/dashboard/filter_popover_option", locals: {
+ name: "trend_category_ids[]",
+ value: option.value,
+ checked: option.checked,
+ filter_name: option.category.display_name,
+ checkbox_data: {
+ category_filter_target: "checkbox",
+ action: "change->category-filter#toggle",
+ category_id: option.category.id,
+ parent_id: option.category.parent_id
+ }
+ } do %>
+ <% if option.category.parent_id.present? %>
+ <%= icon("corner-down-right", size: "sm") %>
+ <% end %>
+ <%= render partial: "categories/badge", locals: { category: option.category } %>
+ <% end %>
+ <% end %>
+ <% end %>
+
+ <% if selected_category_values.any? %>
+ <%= link_to t("reports.trends.category_trend.clear"),
+ report_view_path(trend_category_ids: nil),
+ class: "text-xs font-medium text-secondary hover:text-primary" %>
+ <% end %>
+
+ <%= render DS::SegmentedControl.new(aria_label: t("reports.trends.category_trend.granularity_aria")) do |sc| %>
+ <% sc.with_segment(t("reports.trends.category_trend.month"),
+ active: trend_granularity == "month",
+ href: report_view_path(trend_granularity: "month")) %>
+ <% sc.with_segment(t("reports.trends.category_trend.year"),
+ active: trend_granularity == "year",
+ href: report_view_path(trend_granularity: "year")) %>
+ <% end %>
+ </div>
+ </div>
+
+ <% trend_series = category_trend.series %>
+ <% if trend_series.any? %>
+ <div class="rounded-xl bg-container-inset p-4">
+ <div class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-secondary mb-3">
+ <% trend_series.each do |series| %>
+ <span class="inline-flex items-center gap-1.5">
+ <span class="h-2 w-2 rounded-full" style="background-color: <%= series[:color] %>"></span>
+ <%= series[:name] %>
+ </span>
+ <% end %>
+ </div>
+ <div class="w-full h-64 privacy-sensitive"
+ data-controller="multi-series-chart"
+ data-multi-series-chart-data-value="<%= category_trend.to_json %>"
+ data-multi-series-chart-currency-value="<%= Current.family.currency %>"></div>
+
+ <%# The chart shows exact values only in a pointer tooltip. The table
+ gives keyboard and screen-reader users the same numbers. %>
+ <%= render DS::Disclosure.new(
+ variant: :inline,
+ align: :left,
+ title: t("reports.trends.category_trend.data_table"),
+ body_class: "mt-3"
+ ) do %>
+ <div class="overflow-x-auto privacy-sensitive">
+ <table class="w-full text-xs">
+ <caption class="sr-only"><%= t("reports.trends.category_trend.data_table_caption") %></caption>
+ <thead>
+ <tr>
+ <th scope="col" class="py-1 pr-3 text-left font-medium text-secondary">
+ <%= t("reports.trends.category_trend.data_table_period") %>
+ </th>
+ <% trend_series.each do |series| %>
+ <th scope="col" class="py-1 pl-3 text-right font-medium text-secondary"><%= series[:name] %></th>
+ <% end %>
+ </tr>
+ </thead>
+ <tbody>
+ <% trend_series.first[:values].each_with_index do |point, index| %>
+ <tr>
+ <th scope="row" class="py-1 pr-3 text-left font-normal text-secondary whitespace-nowrap"><%= point[:label] %></th>
+ <% trend_series.each do |series| %>
+ <td class="py-1 pl-3 text-right text-primary whitespace-nowrap">
+ <%= format_money(Money.new(series[:values][index][:value], Current.family.currency)) %>
+ </td>
+ <% end %>
+ </tr>
+ <% end %>
+ </tbody>
+ </table>
+ </div>
+ <% end %>
+ </div>
+ <% elsif selected_category_values.any? %>
+ <div class="rounded-xl bg-container-inset p-4 text-sm text-secondary">
+ <%= t("reports.trends.category_trend.no_data") %>
+ </div>
+ <% else %>
+ <div class="rounded-xl bg-container-inset p-4 text-sm text-secondary">
+ <%= t("reports.trends.category_trend.prompt") %>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+
<%# Month-over-Month Trends %>
<div>
<h3 class="text-lg font-medium mb-4">
diff --git a/app/views/reports/index.html.erb b/app/views/reports/index.html.erb
index 057272cc4e..d4d9be8652 100644
--- a/app/views/reports/index.html.erb
+++ b/app/views/reports/index.html.erb
@@ -31,10 +31,10 @@
<%# Period Navigation Tabs %>
<div class="flex flex-wrap items-center justify-between gap-4">
<%= render DS::SegmentedControl.new(aria_label: t("reports.index.period_aria", default: "Report period"), class: "max-w-full overflow-x-auto no-scrollbar") do |sc| %>
- <% %i[monthly quarterly ytd last_6_months all_time custom].each do |ptype| %>
+ <% %i[monthly quarterly ytd last_6_months last_12_months all_time custom].each do |ptype| %>
<% sc.with_segment(t("reports.index.periods.#{ptype}"),
active: @period_type == ptype,
- href: reports_path(period_type: ptype, **reports_filter_params),
+ href: report_view_path(period_type: ptype, start_date: nil, end_date: nil),
class: "whitespace-nowrap") %>
<% end %>
<% end %>
@@ -44,7 +44,13 @@
button_text: @filter_tags.empty? ? t("reports.index.tag_filter.all") : t("reports.index.tag_filter.selected", count: @filter_tags.size),
search_label: t("reports.index.tag_filter.search"),
apply_text: t("reports.index.tag_filter.apply"),
- hidden_fields: { period_type: @period_type, start_date: @start_date, end_date: @end_date },
+ hidden_fields: {
+ period_type: @period_type,
+ start_date: @start_date,
+ end_date: @end_date,
+ trend_category_ids: @category_selection.selected_values.presence,
+ trend_granularity: trend_granularity_param
+ }.compact,
url: reports_path,
form_data: { turbo_action: "advance" }
} do %>
@@ -71,6 +77,14 @@
<%= hidden_field_tag "#{key}[]", value, id: nil %>
<% end %>
<% end %>
+ <% @category_selection.selected_values.each do |value| %>
+ <%= hidden_field_tag "trend_category_ids[]", value, id: nil %>
+ <% end %>
+ <%# Only an explicit choice is forwarded. An automatic default must not
+ become sticky when the next submit shrinks the range. %>
+ <% if trend_granularity_param.present? %>
+ <%= hidden_field_tag :trend_granularity, trend_granularity_param %>
+ <% end %>
<div class="flex items-center gap-2">
<label class="text-sm font-medium text-secondary"><%= t("reports.index.date_range.from") %></label>
@@ -109,7 +123,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-left",
- href: reports_path(period_type: @period_type, start_date: @nav[:prev_start], end_date: @nav[:prev_end], **reports_filter_params),
+ href: report_view_path(period_type: @period_type, start_date: @nav[:prev_start], end_date: @nav[:prev_end]),
aria: { label: t("reports.index.previous_period"), keyshortcuts: "ArrowLeft" },
data: { controller: "hotkey", hotkey: "ArrowLeft" },
) %>
@@ -126,7 +140,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-right",
- href: reports_path(period_type: @period_type, start_date: @nav[:next_start], end_date: @nav[:next_end], **reports_filter_params),
+ href: report_view_path(period_type: @period_type, start_date: @nav[:next_start], end_date: @nav[:next_end]),
aria: { label: t("reports.index.next_period"), keyshortcuts: "ArrowRight" },
data: { controller: "hotkey", hotkey: "ArrowRight" },
) %>
@@ -154,7 +168,7 @@
<%= render DS::Link.new(
text: t("reports.index.today"),
variant: "outline",
- href: reports_path(period_type: @period_type, **reports_filter_params),
+ href: report_view_path(period_type: @period_type, start_date: nil, end_date: nil),
) %>
</div>
</div>
diff --git a/config/locales/views/reports/en.yml b/config/locales/views/reports/en.yml
index b038dfd3cd..ba9f9463f4 100644
--- a/config/locales/views/reports/en.yml
+++ b/config/locales/views/reports/en.yml
@@ -23,6 +23,7 @@ en:
quarterly: Quarterly
ytd: Yearly
last_6_months: Last 6 Months
+ last_12_months: Last 12 Months
all_time: All Time
custom: Custom Range
date_range:
@@ -38,6 +39,7 @@ en:
ytd: "YTD %{year}"
past_year: "%{year}"
last_6_months: "%{start} – %{end}"
+ last_12_months: "%{start} – %{end}"
all_time: "%{start} – %{end}"
period_picker:
quarter: "Q%{quarter} %{year}"
@@ -71,6 +73,25 @@ en:
over: Over Budget
trends:
title: Trends & Insights
+ category_trend:
+ title: Category trends
+ subtitle: Monthly or yearly totals for the selected categories, net of refunds.
+ filtered_by_tags: Filtered by tags
+ select: Select categories
+ selected:
+ one: "%{count} category"
+ other: "%{count} categories"
+ search: Search categories
+ apply: Apply
+ clear: Clear
+ month: Month
+ year: Year
+ granularity_aria: Trend granularity
+ data_table: Show data table
+ data_table_caption: Trend values by period
+ data_table_period: Period
+ no_data: Choose a longer period to see a trend.
+ prompt: Select categories to see their trend.
monthly_breakdown: Monthly Breakdown
month: Month
income: Income
diff --git a/test/controllers/pages_controller_test.rb b/test/controllers/pages_controller_test.rb
index 270d170674..d018c656fd 100644
--- a/test/controllers/pages_controller_test.rb
+++ b/test/controllers/pages_controller_test.rb
@@ -300,12 +300,12 @@ class PagesControllerTest < ActionDispatch::IntegrationTest
)
income_statement.expects(:build_period_total)
- .with(classification: "expense", period: kind_of(Period))
+ .with(classification: "expense", period: kind_of(Period), tag_ids: nil)
.once
.returns(fake_expense_period_total)
income_statement.expects(:build_period_total)
- .with(classification: "income", period: kind_of(Period))
+ .with(classification: "income", period: kind_of(Period), tag_ids: nil)
.once
.returns(fake_income_period_total)
diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rb
index df353d9edf..ba45ab47f0 100644
--- a/test/controllers/reports_controller_test.rb
+++ b/test/controllers/reports_controller_test.rb
@@ -739,6 +739,50 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
assert_not_includes @response.body, next_month.strftime("%b %Y")
end
+ test "last 12 months uses a twelve month window" do
+ get reports_path(period_type: :last_12_months)
+ assert_response :ok
+
+ expected_end = Date.current.end_of_month
+ expected_start = (expected_end + 1.day - 12.months).beginning_of_month
+
+ assert_includes @response.body, expected_start.strftime("%b %Y")
+ assert_includes @response.body, expected_end.strftime("%b %Y")
+ end
+
+ test "last 12 months navigation shifts by twelve months" do
+ latest_start = (Date.current.end_of_month + 1.day - 12.months).beginning_of_month
+ start_date = latest_start - 24.months
+ end_date = start_date + 12.months - 1.day
+
+ get reports_path(period_type: :last_12_months, start_date: start_date, end_date: end_date)
+ assert_response :ok
+
+ prev_end = start_date - 1.day
+ next_start = start_date + 12.months
+ next_end = next_start + 12.months - 1.day
+
+ assert_select "a[href*='start_date=#{(start_date - 12.months).iso8601}'][href*='end_date=#{prev_end.iso8601}']", minimum: 1
+ assert_select "a[href*='start_date=#{next_start.iso8601}'][href*='end_date=#{next_end.iso8601}']", minimum: 1
+ end
+
+ test "last 12 months next link clamps at the latest window" do
+ latest_start = (Date.current.end_of_month + 1.day - 12.months).beginning_of_month
+ # A start inside the latest window: a plain twelve-month step would end
+ # after today, so the link has to clamp.
+ start_date = latest_start - 5.months
+ end_date = start_date + 12.months - 1.day
+
+ get reports_path(period_type: :last_12_months, start_date: start_date, end_date: end_date)
+ assert_response :ok
+
+ unclamped_start = start_date + 12.months
+ unclamped_end = unclamped_start + 12.months - 1.day
+
+ assert_select "a[href*='start_date=#{latest_start.iso8601}'][href*='end_date=#{Date.current.end_of_month.iso8601}']", minimum: 1
+ assert_select "a[href*='start_date=#{unclamped_start.iso8601}'][href*='end_date=#{unclamped_end.iso8601}']", count: 0
+ end
+
test "last 6 months default start date is consistent with navigation" do
# First load (no params) should produce the same start/end as the navigation arrows would
get reports_path(period_type: :last_6_months)
@@ -1718,6 +1762,365 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
assert lines.none? { |text| text.include?(excluded.ticker) }, "the excluded disposal must not be listed"
end
+ test "activity breakdown draws one trend line per selected category" do
+ account = accounts(:depository)
+ groceries = @family.categories.create!(name: "Trend groceries", color: "#ABCDEF")
+ dining = @family.categories.create!(name: "Trend dining", color: "#FEDCBA")
+ period_start = 2.months.ago.beginning_of_month.to_date
+
+ create_transaction(account: account, name: "Groceries now", amount: 40, category: groceries, date: Date.current)
+ create_transaction(account: account, name: "Groceries before", amount: 10, category: groceries, date: period_start + 2.days)
+ create_transaction(account: account, name: "Dining now", amount: 25, category: dining, date: Date.current)
+
+ enable_preview!
+ get reports_path(
+ period_type: :custom,
+ start_date: period_start,
+ end_date: Date.current.end_of_month,
+ trend_category_ids: [ groceries.id, dining.id ]
+ )
+
+ assert_response :ok
+ data = trend_chart_data
+
+ assert_select "section[data-section-key='trends_insights'] [data-controller='multi-series-chart']"
+ assert_equal [ "Trend dining", "Trend groceries" ], data["series"].map { |series| series["name"] }.sort
+ groceries_series = data["series"].find { |series| series["name"] == "Trend groceries" }
+
+ assert_equal 3, groceries_series["values"].size
+ assert_equal 40.0, groceries_series["values"].last["value"]
+ assert_equal Date.current.beginning_of_month.iso8601, groceries_series["values"].last["date"]
+ end
+
+ test "a selected parent trend includes its subcategory spending" do
+ parent = @family.categories.create!(name: "Trend parent", color: "#123123")
+ child = @family.categories.create!(name: "Trend child", parent: parent, color: "#321321")
+
+ create_transaction(account: accounts(:depository), name: "Child spend", amount: 30,
+ category: child, date: Date.current)
+
+ enable_preview!
+ get reports_path(
+ period_type: :custom,
+ start_date: 1.month.ago.beginning_of_month.to_date,
+ end_date: Date.current.end_of_month,
+ trend_category_ids: [ parent.id ]
+ )
+
+ assert_response :ok
+ series = trend_chart_data["series"].sole
+
+ assert_equal "Trend parent", series["name"]
+ assert_equal 2, series["values"].size
+ assert_equal 30.0, series["values"].last["value"]
+ end
+
+ test "year granularity sums the months in each year" do
+ category = @family.categories.create!(name: "Trend yearly", color: "#0F0F0F")
+ last_year_start = 1.year.ago.beginning_of_year.to_date
+ this_year_start = Date.current.beginning_of_year.to_date
+
+ create_transaction(account: accounts(:depository), name: "Last year", amount: 10,
+ category: category, date: last_year_start + 10.days)
+ create_transaction(account: accounts(:depository), name: "Year first", amount: 10,
+ category: category, date: this_year_start + 10.days)
+ create_transaction(account: accounts(:depository), name: "Year second", amount: 15,
+ category: category, date: this_year_start + 70.days)
+
+ enable_preview!
+ get reports_path(
+ period_type: :custom,
+ start_date: last_year_start,
+ end_date: Date.current.end_of_year.to_date,
+ trend_category_ids: [ category.id ],
+ trend_granularity: "year"
+ )
+
+ assert_response :ok
+ series = trend_chart_data["series"].sole
+
+ assert_equal 2, series["values"].size
+ assert_equal 10.0, series["values"].first["value"]
+ assert_equal 25.0, series["values"].last["value"]
+ assert_equal this_year_start.year.to_s, series["values"].last["label"]
+ end
+
+ test "year granularity keeps a one-year period visible as a single point" do
+ category = @family.categories.create!(name: "Trend single year", color: "#0A0A0A")
+ create_transaction(account: accounts(:depository), name: "Single year spend", amount: 12,
+ category: category, date: Date.current.beginning_of_year)
+
+ enable_preview!
+ get reports_path(
+ period_type: :ytd,
+ trend_category_ids: [ category.id ],
+ trend_granularity: "year"
+ )
+
+ assert_response :ok
+ series = trend_chart_data["series"].sole
+
+ assert_equal 1, series["values"].size
+ assert_equal 12.0, series["values"].sole["value"]
+ assert_equal Date.current.year.to_s, series["values"].sole["label"]
+ end
+
+ test "a category from another family never reaches the trend chart" do
+ foreign = Category.create!(family: families(:empty), name: "Foreign trend category",
+ color: "#333333", lucide_icon: "shapes")
+
+ enable_preview!
+ get reports_path(
+ period_type: :custom,
+ start_date: 1.month.ago.beginning_of_month.to_date,
+ end_date: Date.current.end_of_month,
+ trend_category_ids: [ foreign.id ]
+ )
+
+ assert_response :ok
+ assert_select "[data-controller='multi-series-chart']", count: 0
+ end
+
+ test "uncategorized can be selected for the trend" do
+ create_transaction(account: accounts(:depository), name: "No category spend",
+ amount: 12, date: Date.current)
+
+ enable_preview!
+ get reports_path(
+ period_type: :custom,
+ start_date: 1.month.ago.beginning_of_month.to_date,
+ end_date: Date.current.end_of_month,
+ trend_category_ids: [ Category::UNCATEGORIZED_FILTER_VALUE ]
+ )
+
+ assert_response :ok
+ names = trend_chart_data["series"].map { |series| series["name"] }
+
+ assert_includes names, Category.uncategorized.name
+ end
+
+ test "no trend chart renders without a category selection" do
+ enable_preview!
+ get reports_path(
+ period_type: :custom,
+ start_date: 1.month.ago.beginning_of_month.to_date,
+ end_date: Date.current.end_of_month
+ )
+
+ assert_response :ok
+ assert_select "[data-controller='multi-series-chart']", count: 0
+ end
+
+ test "the trend chart stays hidden without preview access" do
+ category = @family.categories.create!(name: "Trend gated", color: "#707070")
+ create_transaction(account: accounts(:depository), name: "Gated spend", amount: 20,
+ category: category, date: Date.current)
+
+ get reports_path(period_type: :monthly, trend_category_ids: [ category.id ])
+
+ assert_response :ok
+ assert_select "[data-controller='multi-series-chart']", count: 0
+ assert_select "[data-section-key='trends_insights']", count: 1
+ assert_no_match(/#{Regexp.escape(I18n.t("reports.trends.category_trend.title"))}/, @response.body)
+ end
+
+ test "a refund lowers its category in the same bucket" do
+ category = @family.categories.create!(name: "Trend refunded", color: "#717171")
+
+ create_transaction(account: accounts(:depository), name: "Purchase", amount: 100,
+ category: category, date: Date.current)
+ create_transaction(account: accounts(:depository), name: "Refund", amount: -100,
+ category: category, date: Date.current)
+
+ enable_preview!
+ get reports_path(period_type: :monthly, trend_category_ids: [ category.id ])
+
+ assert_response :ok
+ series = trend_chart_data["series"].sole
+
+ assert_equal 0.0, series["values"].sum { |point| point["value"] }
+ end
+
+ test "the trend leaves out an entry in a currency with no rate" do
+ category = @family.categories.create!(name: "Trend won rent", color: "#727272")
+ krw = @family.accounts.create!(owner: @user, name: "Seoul trend", balance: 0,
+ currency: "KRW", accountable: Depository.new)
+ create_transaction(account: krw, name: "Rent", amount: 130_000, currency: "KRW",
+ category: category)
+
+ enable_preview!
+ get reports_path(period_type: :monthly, trend_category_ids: [ category.id ])
+
+ assert_response :ok
+ series = trend_chart_data["series"].sole
+
+ assert_equal 0.0, series["values"].sum { |point| point["value"] }
+ end
+
+ test "the category trend uses the selected tags" do
+ category = @family.categories.create!(name: "Trend tagged", color: "#131313")
+ tag = @family.tags.create!(name: "Trend tag")
+ create_transaction(account: accounts(:depository), name: "Tagged spend", amount: 40,
+ category: category, tags: [ tag ], date: TAGGED_MONTH + 9.days)
+ create_transaction(account: accounts(:depository), name: "Untagged spend", amount: 60,
+ category: category, date: TAGGED_MONTH + 9.days)
+
+ enable_preview!
+ get reports_path(period_type: :custom, start_date: TAGGED_MONTH,
+ end_date: TAGGED_MONTH.end_of_month,
+ filter_tag_ids: [ tag.id ], trend_category_ids: [ category.id ])
+
+ assert_response :ok
+ series = trend_chart_data["series"].sole
+
+ assert_equal 40.0, series["values"].sole["value"]
+ end
+
+ test "the category trend header shows the active tags" do
+ category = @family.categories.create!(name: "Trend header", color: "#141414")
+ tag = @family.tags.create!(name: "Trend header tag")
+
+ enable_preview!
+ get reports_path(period_type: :monthly, filter_tag_ids: [ tag.id ],
+ trend_category_ids: [ category.id ])
+
+ assert_response :ok
+ assert_select "[data-testid='category-trend-tags']", text: /#{Regexp.escape(tag.name)}/
+ end
+
+ test "the category trend Apply keeps the tag filter" do
+ category = @family.categories.create!(name: "Trend apply", color: "#151515")
+ tag = @family.tags.create!(name: "Trend apply tag")
+
+ enable_preview!
+ get reports_path(period_type: :monthly, filter_tag_ids: [ tag.id ],
+ trend_category_ids: [ category.id ])
+
+ assert_response :ok
+ form = css_select("form[action='#{reports_path}']").find do |node|
+ node.at_css("input[type=checkbox][name='trend_category_ids[]']")
+ end
+
+ assert form, "the category filter form must render"
+ assert form.at_css("input[type=hidden][name='filter_tag_ids[]'][value='#{tag.id}']"),
+ "the category filter Apply drops the tag filter"
+ end
+
+ test "the tag filter Apply keeps the trend selection and granularity" do
+ category = @family.categories.create!(name: "Trend tag filter", color: "#161616")
+ tag = @family.tags.create!(name: "Trend tag filter tag")
+
+ enable_preview!
+ get reports_path(period_type: :monthly, filter_tag_ids: [ tag.id ],
+ trend_category_ids: [ category.id ], trend_granularity: "year")
+
+ assert_response :ok
+ form = css_select("form[action='#{reports_path}']").find do |node|
+ node.at_css("input[type=checkbox][name='filter_tag_ids[]']")
+ end
+
+ assert form, "the tag filter form must render"
+ assert form.at_css("input[type=hidden][name='trend_category_ids[]'][value='#{category.id}']"),
+ "the tag filter Apply drops the trend selection"
+ assert form.at_css("input[type=hidden][name='trend_granularity'][value='year']"),
+ "the tag filter Apply drops the trend granularity"
+ end
+
+ test "period links keep the trend selection and granularity" do
+ category = @family.categories.create!(name: "Trend link", color: "#444444")
+
+ get reports_path(period_type: :monthly, trend_category_ids: [ category.id ],
+ trend_granularity: "year")
+
+ assert_response :ok
+ assert_select "a[href*='trend_category_ids']", minimum: 1
+ assert_select "a[href*='trend_granularity=year']", minimum: 1
+ end
+
+ test "period links keep an explicit month on a long range" do
+ category = @family.categories.create!(name: "Trend long month", color: "#555555")
+
+ get reports_path(
+ period_type: :custom,
+ start_date: 3.years.ago.beginning_of_year.to_date,
+ end_date: Date.current.end_of_month.to_date,
+ trend_category_ids: [ category.id ],
+ trend_granularity: "month"
+ )
+
+ assert_response :ok
+ assert_select "a[href*='trend_granularity=month']", minimum: 1
+ end
+
+ test "period links keep an explicit year on a long range" do
+ category = @family.categories.create!(name: "Trend long year", color: "#575757")
+
+ get reports_path(
+ period_type: :custom,
+ start_date: 3.years.ago.beginning_of_year.to_date,
+ end_date: Date.current.end_of_month.to_date,
+ trend_category_ids: [ category.id ],
+ trend_granularity: "year"
+ )
+
+ assert_response :ok
+ assert_select "a[href*='period_type=monthly'][href*='trend_granularity=year']", minimum: 1
+ end
+
+ test "the custom date form omits an automatic granularity" do
+ enable_preview!
+ get reports_path(
+ period_type: :custom,
+ start_date: 3.years.ago.beginning_of_year.to_date,
+ end_date: Date.current.end_of_month.to_date
+ )
+
+ assert_response :ok
+ assert_select "form input[name='trend_granularity']", count: 0
+ end
+
+ test "the custom date form keeps an explicit granularity" do
+ enable_preview!
+ get reports_path(
+ period_type: :custom,
+ start_date: 3.years.ago.beginning_of_year.to_date,
+ end_date: Date.current.end_of_month.to_date,
+ trend_granularity: "year"
+ )
+
+ assert_response :ok
+ assert_select "form[data-controller='auto-submit-form'] input[name='trend_granularity'][value='year']", count: 1
+ # The category filter and tag filter forms also carry the explicit choice.
+ assert_select "form input[name='trend_granularity'][value='year']", count: 3
+ end
+
+ test "the trend chart lists its values in a data table" do
+ category = @family.categories.create!(name: "Trend table", color: "#787878")
+ create_transaction(account: accounts(:depository), name: "Table spend", amount: 40,
+ category: category, date: Date.current)
+
+ enable_preview!
+ get reports_path(period_type: :last_6_months, trend_category_ids: [ category.id ])
+
+ assert_response :ok
+ assert_select "details table caption", text: I18n.t("reports.trends.category_trend.data_table_caption")
+ assert_select "details table th[scope='col']", text: "Trend table"
+ assert_select "details table th[scope='row']", minimum: 6
+ end
+
+ test "the amount sort link keeps the trend selection and granularity" do
+ category = @family.categories.create!(name: "Trend sort", color: "#666666")
+ create_transaction(account: accounts(:depository), name: "Sort spend", amount: 25,
+ category: category, date: Date.current)
+
+ get reports_path(period_type: :last_6_months, trend_category_ids: [ category.id ],
+ trend_granularity: "year")
+
+ assert_response :ok
+ assert_select "a[href*='sort_by=amount'][href*='trend_category_ids']", minimum: 1
+ assert_select "a[href*='sort_by=amount'][href*='trend_granularity=year']", minimum: 1
+ end
+
# POSTing to settings_api_keys_path is create, which needs api_key params.
test "google sheets instructions link to the API keys page" do
get google_sheets_instructions_reports_url
@@ -1993,6 +2396,17 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
css_select("[data-section-key=biggest_expenses] tbody tr td:first-child a").map { |node| node.text.strip }
end
+ def enable_preview!
+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))
+ end
+
+ def trend_chart_data
+ chart = css_select("[data-controller='multi-series-chart']").first
+
+ assert chart, "the trend chart must render"
+ JSON.parse(chart["data-multi-series-chart-data-value"])
+ end
+
# Travel, Work and Other tags on a month of their own, away from the
# fixture transactions, with expenses of $30 (travel), $50 (work), $20
# (both) and $1,000 (other), and income of $10 (travel) and $500 (none).
diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rb
index bd1195a805..d6f6dcb552 100644
--- a/test/models/income_statement_test.rb
+++ b/test/models/income_statement_test.rb
@@ -358,8 +358,8 @@ class IncomeStatementTest < ActiveSupport::TestCase
expense_period_total = IncomeStatement::PeriodTotal.new("expense", 900, @family.currency, [])
income_period_total = IncomeStatement::PeriodTotal.new("income", 1000, @family.currency, [])
- income_statement.expects(:build_period_total).with(classification: "expense", period: period).once.returns(expense_period_total)
- income_statement.expects(:build_period_total).with(classification: "income", period: period).once.returns(income_period_total)
+ income_statement.expects(:build_period_total).with(classification: "expense", period: period, tag_ids: nil).once.returns(expense_period_total)
+ income_statement.expects(:build_period_total).with(classification: "income", period: period, tag_ids: nil).once.returns(income_period_total)
income_statement.net_category_totals(period: period)
income_statement.expense_totals(period: period)
diff --git a/test/models/reports/category_selection_test.rb b/test/models/reports/category_selection_test.rb
new file mode 100644
index 0000000000..b35960846d
--- /dev/null
+++ b/test/models/reports/category_selection_test.rb
@@ -0,0 +1,71 @@
+require "test_helper"
+
+class Reports::CategorySelectionTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @parent = categories(:food_and_drink)
+ @child = categories(:subcategory)
+ end
+
+ test "a blank selection is inactive" do
+ selection = Reports::CategorySelection.new(@family, [])
+
+ assert_not selection.active?
+ assert_empty selection.group_values
+ assert_equal 0, selection.selected_count
+ end
+
+ test "accepts a single id as a string" do
+ selection = Reports::CategorySelection.new(@family, @parent.id.to_s)
+
+ assert selection.active?
+ assert_equal [ @parent.id.to_s ], selection.selected_values
+ end
+
+ test "a parent selection checks its subcategories" do
+ selection = Reports::CategorySelection.new(@family, [ @parent.id.to_s ])
+ option = selection.options.find { |entry| entry.category.id == @child.id }
+
+ assert option.checked
+ assert_equal [ @parent.id.to_s ], selection.group_values
+ assert_equal 1, selection.selected_count
+ end
+
+ test "a child inherits checked state from its selected parent" do
+ selection = Reports::CategorySelection.new(@family, [ @parent.id.to_s ])
+ child_option = selection.options.find { |entry| entry.category.id == @child.id }
+
+ assert child_option.checked
+ end
+
+ test "a selected child without its parent stays its own line" do
+ selection = Reports::CategorySelection.new(@family, [ @child.id.to_s ])
+
+ assert_equal [ @child.id.to_s ], selection.group_values
+ assert_equal 1, selection.selected_count
+ end
+
+ test "the uncategorized sentinel is kept and never treated as an id" do
+ selection = Reports::CategorySelection.new(@family, [ Category::UNCATEGORIZED_FILTER_VALUE ])
+
+ assert selection.active?
+ assert_equal [ Category::UNCATEGORIZED_FILTER_VALUE ], selection.group_values
+ assert_equal 1, selection.selected_count
+ end
+
+ test "ids from another family are ignored" do
+ foreign = Category.create!(family: families(:empty), name: "Foreign report category",
+ color: "#123456", lucide_icon: "shapes")
+ selection = Reports::CategorySelection.new(@family, [ foreign.id.to_s ])
+
+ assert_not selection.active?
+ assert_empty selection.group_values
+ end
+
+ test "malformed params are ignored" do
+ selection = Reports::CategorySelection.new(@family, { "bad" => "shape" })
+
+ assert_not selection.active?
+ assert_empty selection.selected_values
+ end
+end
diff --git a/test/models/reports/category_trend_test.rb b/test/models/reports/category_trend_test.rb
new file mode 100644
index 0000000000..2f7bfda6f2
--- /dev/null
+++ b/test/models/reports/category_trend_test.rb
@@ -0,0 +1,100 @@
+require "test_helper"
+
+class Reports::CategoryTrendTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = families(:empty)
+ @account = @family.accounts.create!(name: "Checking", currency: @family.currency,
+ balance: 5000, accountable: Depository.new)
+ @food = @family.categories.create!(name: "Food", color: "#111111")
+ @groceries = @family.categories.create!(name: "Groceries", parent: @food, color: "#222222")
+ @period = Period.custom(start_date: Date.new(2026, 1, 1), end_date: Date.new(2026, 3, 31))
+ end
+
+ test "nets a refund in the month it lands in" do
+ create_transaction(account: @account, date: Date.new(2026, 1, 10), amount: 100, category: @groceries)
+ create_transaction(account: @account, date: Date.new(2026, 1, 20), amount: -100, category: @groceries)
+ create_transaction(account: @account, date: Date.new(2026, 3, 5), amount: 40, category: @groceries)
+
+ series = trend(@groceries).series.sole
+
+ assert_equal [ 0.0, 0.0, 40.0 ], series[:values].map { |point| point[:value] }
+ end
+
+ test "a refund without a purchase in the bucket plots below zero" do
+ create_transaction(account: @account, date: Date.new(2026, 2, 5), amount: -30, category: @groceries)
+
+ assert_equal(-30.0, trend(@groceries).series.sole[:values][1][:value])
+ end
+
+ test "tag ids limit the series to tagged transactions" do
+ tag = @family.tags.create!(name: "Travel")
+ create_transaction(account: @account, date: Date.new(2026, 1, 10), amount: 100, category: @groceries)
+ create_transaction(account: @account, date: Date.new(2026, 1, 10), amount: 40, category: @groceries, tags: [ tag ])
+
+ series = trend(@groceries, tag_ids: [ tag.id ]).series.sole
+
+ assert_equal [ 40.0, 0.0, 0.0 ], series[:values].map { |point| point[:value] }
+ end
+
+ test "a parent series includes its subcategories, and a child alone does not" do
+ create_transaction(account: @account, date: Date.new(2026, 1, 10), amount: 30, category: @groceries)
+ create_transaction(account: @account, date: Date.new(2026, 1, 20), amount: 20, category: @food)
+
+ parent = trend(@food).series.sole
+ child = trend(@groceries).series.sole
+
+ assert_equal 50.0, parent[:values].first[:value]
+ assert_equal 30.0, child[:values].first[:value]
+ end
+
+ test "a custom range counts only the days inside it" do
+ period = Period.custom(start_date: Date.new(2026, 1, 15), end_date: Date.new(2026, 3, 10))
+ create_transaction(account: @account, date: Date.new(2026, 1, 5), amount: 70, category: @groceries)
+ create_transaction(account: @account, date: Date.new(2026, 1, 20), amount: 10, category: @groceries)
+ create_transaction(account: @account, date: Date.new(2026, 3, 20), amount: 70, category: @groceries)
+
+ series = trend(@groceries, period: period).series.sole
+
+ assert_equal [ 10.0, 0.0, 0.0 ], series[:values].map { |point| point[:value] }
+ end
+
+ test "year granularity sums the months in each calendar year" do
+ period = Period.custom(start_date: Date.new(2025, 1, 1), end_date: Date.new(2026, 12, 31))
+ create_transaction(account: @account, date: Date.new(2025, 2, 10), amount: 10, category: @groceries)
+ create_transaction(account: @account, date: Date.new(2026, 2, 10), amount: 20, category: @groceries)
+
+ series = trend(@groceries, period: period, granularity: "year").series.sole
+
+ assert_equal [ 10.0, 20.0 ], series[:values].map { |point| point[:value] }
+ assert_equal %w[2025 2026], series[:values].map { |point| point[:label] }
+ end
+
+ test "an entry in a currency with no rate is left out" do
+ krw = @family.accounts.create!(name: "Seoul", currency: "KRW", balance: 0,
+ accountable: Depository.new)
+ create_transaction(account: krw, date: Date.new(2026, 1, 10), amount: 130_000,
+ currency: "KRW", category: @groceries)
+
+ assert_equal 0.0, trend(@groceries).series.sole[:values].first[:value]
+ end
+
+ test "as_json carries the currency, granularity and one value per bucket" do
+ create_transaction(account: @account, date: Date.new(2026, 1, 10), amount: 10, category: @groceries)
+
+ json = trend(@groceries).as_json
+
+ assert_equal @family.currency, json[:currency]
+ assert_equal "month", json[:granularity]
+ assert_equal 3, json[:series].sole[:values].size
+ assert_equal "2026-01-01", json[:series].sole[:values].first[:date]
+ end
+
+ private
+ def trend(*categories, period: @period, granularity: "month", tag_ids: nil)
+ selection = Reports::CategorySelection.new(@family, categories.map { |category| category.id.to_s })
+ Reports::CategoryTrend.new(IncomeStatement.new(@family), period: period, selection: selection,
+ granularity: granularity, tag_ids: tag_ids)
+ end
+end
diff --git a/test/system/reports_category_trend_test.rb b/test/system/reports_category_trend_test.rb
new file mode 100644
index 0000000000..b3394dc8bf
--- /dev/null
+++ b/test/system/reports_category_trend_test.rb
@@ -0,0 +1,82 @@
+require "application_system_test_case"
+
+class ReportsCategoryTrendTest < ApplicationSystemTestCase
+ setup do
+ user = users(:family_admin)
+ user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => true))
+ sign_in user
+ page.driver.browser.manage.window.resize_to(1400, 900)
+ visit reports_path(
+ period_type: :custom,
+ start_date: 2.years.ago.beginning_of_year.to_date,
+ end_date: Date.current.end_of_month.to_date
+ )
+ end
+
+ test "a selected category draws a trend that survives a period change" do
+ click_button I18n.t("reports.trends.category_trend.select")
+
+ find("label", text: categories(:food_and_drink).display_name).click
+ click_button I18n.t("reports.trends.category_trend.apply")
+
+ assert_selector "[data-controller='multi-series-chart'] svg"
+ assert_selector "h3", text: I18n.t("reports.trends.category_trend.title")
+ assert_current_path(/trend_category_ids/)
+
+ click_link I18n.t("reports.trends.category_trend.year")
+
+ assert_current_path(/trend_granularity=year/)
+ assert_selector "[data-controller='multi-series-chart'] svg"
+ end
+
+ test "the category trend controls work at a mobile width" do
+ page.driver.browser.manage.window.resize_to(390, 844)
+ visit reports_path(
+ period_type: :custom,
+ start_date: 2.years.ago.beginning_of_year.to_date,
+ end_date: Date.current.end_of_month.to_date
+ )
+
+ within "section[data-section-key='trends_insights']" do
+ click_button I18n.t("reports.trends.category_trend.select")
+ find("label", text: categories(:food_and_drink).display_name).click
+ click_button I18n.t("reports.trends.category_trend.apply")
+
+ assert_selector "[data-controller='multi-series-chart'] svg"
+ end
+
+ assert_current_path(/trend_category_ids/)
+ end
+
+ test "a monthly trend spanning two years labels both years" do
+ visit reports_path(
+ period_type: :custom,
+ start_date: (Date.current - 12.months).beginning_of_month.to_date,
+ end_date: Date.current.end_of_month.to_date
+ )
+
+ click_button I18n.t("reports.trends.category_trend.select")
+ find("label", text: categories(:food_and_drink).display_name).click
+ click_button I18n.t("reports.trends.category_trend.apply")
+
+ within "[data-controller='multi-series-chart']" do
+ assert_selector "svg text", text: Date.current.year.to_s
+ assert_selector "svg text", text: (Date.current.year - 1).to_s
+ end
+ end
+
+ test "year view on a one-year period shows a dot per category" do
+ visit reports_path(period_type: :ytd)
+
+ click_button I18n.t("reports.trends.category_trend.select")
+ find("label", text: categories(:food_and_drink).display_name).click
+ click_button I18n.t("reports.trends.category_trend.apply")
+
+ assert_selector "[data-controller='multi-series-chart'] svg", minimum: 1
+ assert_current_path(/trend_category_ids/)
+ click_link I18n.t("reports.trends.category_trend.year")
+
+ assert_current_path(/trend_granularity=year/)
+ assert_selector "[data-controller='multi-series-chart'] svg circle", minimum: 1
+ end
+end