The personal finance app for everyone (by everyone)
Ruby
feat(reports): spending vs normal section (preview) (#4002)
scragnog689b3dc4d8c7
diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rbindex 7fa36d56a1..eaa5b467f1 100644--- a/app/controllers/api/v1/base_controller.rb+++ b/app/controllers/api/v1/base_controller.rb@@ -281,6 +281,15 @@ class Api::V1::BaseController < ApplicationControllerrender_validation_error(exception.message)end+ # A strict YYYY-MM-DD date, or nil when the value is missing or invalid.+ def parse_date(value)+ return unless value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-\d{2}\z/)+ date = Date.iso8601(value)+ date if date.year.positive?+ rescue Date::Error+ nil+ end+def parse_date_param(key)Date.iso8601(params[key].to_s)rescue ArgumentErrordiff --git a/app/controllers/api/v1/cash_flows_controller.rb b/app/controllers/api/v1/cash_flows_controller.rbindex ee48135752..6a8130dba3 100644--- a/app/controllers/api/v1/cash_flows_controller.rb+++ b/app/controllers/api/v1/cash_flows_controller.rb@@ -44,12 +44,4 @@ class Api::V1::CashFlowsController < Api::V1::BaseControllerdef invalid_query(error, message)render json: { error: error, message: message }, status: :unprocessable_entityend-- def parse_date(value)- return unless value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-\d{2}\z/)- date = Date.iso8601(value)- date if date.year.positive?- rescue Date::Error- nil- endenddiff --git a/app/controllers/api/v1/spending_vs_normal_controller.rb b/app/controllers/api/v1/spending_vs_normal_controller.rbnew file mode 100644index 0000000000..f0af98ef1a--- /dev/null+++ b/app/controllers/api/v1/spending_vs_normal_controller.rb@@ -0,0 +1,35 @@+# Net spending per category for a period against each category's normal (the+# year before, scaled to the period): the data behind the Reports section+# "Spending vs normal".+class Api::V1::SpendingVsNormalController < Api::V1::BaseController+ before_action -> { authorize_scope!(:read) }++ def show+ response.headers["Cache-Control"] = "private, no-store"+ period = requested_period+ unless period+ return render json: { error: "invalid_period", message: "Pass both start_date and end_date as ISO dates in order, or neither for the current month" },+ status: :unprocessable_entity+ end++ statement = IncomeStatement.new(current_resource_owner.family, user: current_resource_owner)+ render json: IncomeStatement::SpendingComparison.new(+ statement,+ period: period,+ history_start: IncomeStatement::SpendingComparison.history_start(statement)+ )+ end++ private+ def requested_period+ # The whole current month; the comparison cuts an unfinished period to+ # today and compares it with the same days of earlier months.+ if params[:start_date].nil? && params[:end_date].nil?+ today = Date.current+ return Period.custom(start_date: today.beginning_of_month, end_date: today.end_of_month)+ end++ start_date, end_date = parse_date(params[:start_date]), parse_date(params[:end_date])+ Period.custom(start_date: start_date, end_date: end_date) if start_date && end_date && start_date <= end_date+ end+enddiff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rbindex b25e673c49..7779b6648b 100644--- a/app/controllers/reports_controller.rb+++ b/app/controllers/reports_controller.rb@@ -133,6 +133,9 @@ class ReportsController < ApplicationController# Investment metrics@investment_metrics = build_investment_metrics+ # Spending vs normal (preview): this period against the year before it+ @spending_comparison = build_spending_comparison+# Investment flows (contributions/withdrawals)@investment_flows = InvestmentFlowStatement.new(Current.family, user: Current.user).period_totals(period: @period)@@ -169,6 +172,15 @@ class ReportsController < ApplicationControllervisible: @has_accounts,collapsible: true},+ {+ key: "spending_vs_normal",+ title: "reports.spending_vs_normal.title",+ partial: "reports/spending_vs_normal",+ locals: { comparison: @spending_comparison, start_date: @start_date, end_date: @end_date },+ visible: @has_accounts && @spending_comparison.present?,+ collapsible: true,+ preview: true+ },{key: "investment_performance",title: "reports.investment_performance.title",@@ -321,6 +333,16 @@ class ReportsController < ApplicationControllernilend+ def build_spending_comparison+ return nil unless preview_features_enabled?++ IncomeStatement::SpendingComparison.new(+ @income_statement,+ period: @period,+ history_start: IncomeStatement::SpendingComparison.history_start(@income_statement)+ )+ end+def build_trends_data(income_statement:)# Generate month-by-month data based on the current period filtertrends = []diff --git a/app/helpers/reports_helper.rb b/app/helpers/reports_helper.rbindex adc964f7b8..15be9f2248 100644--- a/app/helpers/reports_helper.rb+++ b/app/helpers/reports_helper.rb@@ -43,4 +43,78 @@ module ReportsHelperdef has_sparkline_data?(trends_data)trends_data&.length.to_i >= 2end++ # Treemap nodes for the "Spending vs normal" section: each drawable row of+ # the comparison (IncomeStatement::SpendingComparison#row_json) plus the+ # formatted labels, the tooltip lines and the Transactions link.+ def spending_treemap_nodes(comparison, start_date:, end_date:)+ comparison.drawable_rows.map do |row|+ labelled = row.subcategories.size > 1+ spending_treemap_node(comparison, row, start_date:, end_date:).merge(+ children: row.subcategories.map do |sub|+ spending_treemap_node(comparison, sub, parent: row, direct_label: labelled, start_date:, end_date:)+ end+ )+ end+ end++ # The change list: rows that moved against normal, with the bar width as a+ # share of the largest change.+ def spending_changes(comparison, start_date:, end_date:)+ changes = comparison.changes+ max_change = changes.map { |row| row.change.abs }.max++ changes.map do |row|+ {+ row: row,+ width: (row.change.abs / max_change * 100).round(1),+ amount_label: "#{row.change.negative? ? "−" : "+"}#{spending_money(row.change.abs, precision: 0)}",+ href: spending_category_href(row.category, start_date:, end_date:)+ }+ end+ end++ private+ def spending_treemap_node(comparison, row, start_date:, end_date:, parent: nil, direct_label: false)+ name = row.direct && direct_label ? t("reports.spending_vs_normal.direct", category: row.category.name) : row.category.name++ comparison.row_json(row).merge(+ name: name,+ direct: row.direct,+ total: row.total.to_f,+ total_label: spending_money(row.total, precision: 0),+ ratio: row.ratio&.to_f,+ change_sign: row.change && (row.change.negative? ? -1 : 1),+ has_normal: comparison.comparable? && !row.normal.nil?,+ description: spending_description(comparison, row, parent && name != parent.category.name ? t("reports.spending_vs_normal.tooltip.path", parent: parent.category.name, category: name) : name),+ href: spending_category_href(row.category, start_date:, end_date:)+ )+ end++ def spending_description(comparison, row, name)+ lines = [ t("reports.spending_vs_normal.tooltip.total", category: name, amount: spending_money(row.total)) ]+ unless comparison.comparable? && row.normal+ return lines << t("reports.spending_vs_normal.tooltip.no_normal")+ end++ lines << t("reports.spending_vs_normal.tooltip.normal", amount: spending_money(row.normal))+ if row.change.abs >= IncomeStatement::SpendingComparison::MIN_CHANGE+ direction = row.change.negative? ? "less" : "more"+ amount = spending_money(row.change.abs)+ lines << if row.ratio+ t("reports.spending_vs_normal.tooltip.#{direction}", amount: amount, percent: number_to_percentage(row.ratio.abs * 100, precision: 0))+ else+ t("reports.spending_vs_normal.tooltip.#{direction}_no_percent", amount: amount)+ end+ end+ lines+ end++ def spending_money(amount, precision: 2)+ Money.new(amount, Current.family.currency).format(precision: precision)+ end++ def spending_category_href(category, start_date:, end_date:)+ transactions_path(q: { categories: [ category.filter_value ], start_date: start_date, end_date: end_date })+ endenddiff --git a/app/javascript/controllers/spending_treemap_controller.js b/app/javascript/controllers/spending_treemap_controller.jsnew file mode 100644index 0000000000..f489854c5f--- /dev/null+++ b/app/javascript/controllers/spending_treemap_controller.js@@ -0,0 +1,253 @@+import { Controller } from "@hotwired/stimulus";+import * as d3 from "d3";+import {+ CHART_TOOLTIP_CONTEXT_CLASSES,+ CHART_TOOLTIP_VALUE_CLASSES,+ createChartTooltip,+} from "utils/chart_tooltip";++// Connects to data-controller="spending-treemap"+//+// Box size is net spending in the period; fill is the change against the+// category's normal (green = less, red = more, inset surface = about normal),+// as the Reports summary cards colour lower and higher spending.+// Clicking a box opens Transactions filtered to that category and period.+function tint(token, percent) {+ return percent === 100+ ? `var(${token})`+ : `color-mix(in srgb, var(${token}) ${percent}%, var(--color-container))`;+}++export default class extends Controller {+ static targets = ["chart", "legend"];+ static values = {+ tree: { type: Array, default: [] },+ labels: { type: Object, default: {} },+ comparable: { type: Boolean, default: true },+ };++ // Functional tokens mixed into the container colour, so every step follows+ // the theme (light and dark remap --color-success / --color-destructive).+ // The strongest red stops at 80% and the strongest green at 50% (dark+ // mode's green is light), so the theme's text colour keeps AA contrast in+ // both themes. Totals are clamped at zero, so the lowest ratio is -1.+ static STEPS = [+ {+ key: "less",+ min: -1,+ max: -0.5,+ fill: tint("--color-success", 50),+ },+ {+ key: "slightly_less",+ min: -0.5,+ max: -0.15,+ fill: tint("--color-success", 30),+ },+ {+ key: "normal",+ min: -0.15,+ max: 0.15,+ fill: "var(--color-surface-inset)",+ },+ {+ key: "slightly_more",+ min: 0.15,+ max: 0.5,+ fill: tint("--color-destructive", 30),+ },+ {+ key: "more",+ min: 0.5,+ max: 1,+ fill: tint("--color-destructive", 60),+ },+ {+ key: "much_more",+ min: 1,+ max: Number.POSITIVE_INFINITY,+ fill: tint("--color-destructive", 80),+ },+ ];++ #resizeObserver = null;+ #tooltip = null;++ connect() {+ this.#draw();+ this.#drawLegend();+ this.#resizeObserver = new ResizeObserver(() => this.#draw());+ this.#resizeObserver.observe(this.chartTarget);+ }++ disconnect() {+ this.#resizeObserver?.disconnect();+ this.#tooltip?.remove();+ }++ // Without history every box is neutral. A normal of zero with spending is+ // new spending, so it takes the strongest step instead of reading as normal.+ #step(data) {+ const steps = this.constructor.STEPS;+ const normal = steps.find((s) => s.key === "normal");+ if (!this.comparableValue || !data.has_normal) return normal;+ if (data.ratio === null)+ return data.change_sign > 0 ? steps.at(-1) : normal;+ return (+ steps.find((s) => data.ratio >= s.min && data.ratio < s.max) || normal+ );+ }++ #draw() {+ const width = this.chartTarget.clientWidth;+ const height = this.chartTarget.clientHeight;+ if (!width || !height) return;++ d3.select(this.chartTarget).selectAll("*").remove();++ const root = d3+ .hierarchy({ children: this.treeValue })+ .sum((d) => (d.children ? 0 : d.total))+ .sort((a, b) => b.value - a.value);++ d3+ .treemap()+ .size([width, height])+ .paddingOuter(2)+ .paddingTop((d) => (d.depth === 1 ? 20 : 0))+ .paddingInner(2)+ .round(true)(root);++ const svg = d3+ .select(this.chartTarget)+ .append("svg")+ .attr("width", width)+ .attr("height", height)+ .attr("class", "block");++ const groups = svg+ .selectAll("g.group")+ .data(root.children || [])+ .join("g")+ .attr("class", "group");++ // A group with one box would print its label twice.+ groups+ .filter((d) => d.x1 - d.x0 > 48 && d.children.length > 1)+ .append("text")+ .attr("x", (d) => d.x0 + 4)+ .attr("y", (d) => d.y0 + 14)+ .attr("class", "text-primary fill-current text-xs font-medium")+ .text((d) =>+ this.#fit(`${d.data.name} ${d.data.total_label}`, d.x1 - d.x0 - 8, 7),+ );++ const leaves = svg+ .selectAll("g.leaf")+ .data(root.leaves())+ .join("g")+ .attr("class", "leaf cursor-pointer")+ .attr("tabindex", 0)+ .attr("role", "link")+ .attr("aria-label", (d) => d.data.description.join(". "))+ .on("click", (_, d) => this.#open(d))+ .on("keydown", (event, d) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ // The section's keydown would grab it for reordering+ event.stopPropagation();+ this.#open(d);+ }+ })+ .on("pointermove focus", (event, d) => this.#showTooltip(event, d))+ .on("pointerleave blur", () => this.#hideTooltip());++ leaves+ .append("rect")+ .attr("x", (d) => d.x0)+ .attr("y", (d) => d.y0)+ .attr("width", (d) => Math.max(0, d.x1 - d.x0))+ .attr("height", (d) => Math.max(0, d.y1 - d.y0))+ .attr("rx", 3)+ .attr("fill", (d) => this.#step(d.data).fill)+ .attr("class", "transition-opacity hover:opacity-80");++ const labelled = leaves.filter((d) => d.x1 - d.x0 > 56 && d.y1 - d.y0 > 34);+ labelled+ .append("text")+ .attr("x", (d) => d.x0 + 6)+ .attr("y", (d) => d.y0 + 16)+ .attr(+ "class",+ "text-xs font-medium text-primary fill-current pointer-events-none",+ )+ .text((d) => this.#fit(d.data.name, d.x1 - d.x0 - 12, 6.5));+ labelled+ .append("text")+ .attr("x", (d) => d.x0 + 6)+ .attr("y", (d) => d.y0 + 30)+ .attr("class", "text-xs text-primary fill-current pointer-events-none")+ .text((d) => d.data.total_label);+ }++ #drawLegend() {+ const legend = this.legendTarget;+ legend.replaceChildren();+ if (!this.comparableValue) return;++ for (const step of this.constructor.STEPS) {+ const item = document.createElement("span");+ item.className = "inline-flex items-center gap-1";+ const swatch = document.createElement("span");+ swatch.className = "inline-block w-3 h-3 rounded-sm shadow-border-xs";+ swatch.style.background = step.fill;+ const label = document.createElement("span");+ label.textContent = this.labelsValue.legend?.[step.key] || step.key;+ item.append(swatch, label);+ legend.appendChild(item);+ }+ }++ #showTooltip(event, d) {+ if (!this.#tooltip) {+ this.#tooltip = createChartTooltip(document.body);+ this.#tooltip.style.position = "fixed";+ this.#tooltip.setAttribute("role", "tooltip");+ }+ const [first, ...rest] = d.data.description;+ this.#tooltip.replaceChildren();+ const strong = document.createElement("div");+ strong.className = CHART_TOOLTIP_VALUE_CLASSES;+ strong.textContent = first;+ this.#tooltip.appendChild(strong);+ for (const line of [...rest, this.labelsValue.open]) {+ const row = document.createElement("div");+ row.className = CHART_TOOLTIP_CONTEXT_CLASSES;+ row.textContent = line;+ this.#tooltip.appendChild(row);+ }++ // Shown before measuring, so the edge clamps see its real size.+ this.#tooltip.style.display = "block";+ const rect = event.currentTarget.getBoundingClientRect();+ const x = event.clientX ?? rect.right;+ const y = event.clientY ?? rect.top;+ this.#tooltip.style.left = `${Math.min(x + 12, window.innerWidth - this.#tooltip.offsetWidth - 8)}px`;+ this.#tooltip.style.top = `${Math.max(8, y - this.#tooltip.offsetHeight - 12)}px`;+ }++ #hideTooltip() {+ if (this.#tooltip) this.#tooltip.style.display = "none";+ }++ #open(d) {+ if (d.data.href) window.Turbo.visit(d.data.href);+ }++ // Truncate to roughly fit `width` pixels at `charWidth` px per character.+ #fit(text, width, charWidth) {+ const max = Math.floor(width / charWidth);+ if (max < 2) return "";+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;+ }+}diff --git a/app/models/income_statement/spending_comparison.rb b/app/models/income_statement/spending_comparison.rbnew file mode 100644index 0000000000..8a17cca6a4--- /dev/null+++ b/app/models/income_statement/spending_comparison.rb@@ -0,0 +1,253 @@+# Net spending per category for a period, compared with what is normal for+# that category: its net spending over the year before the period, scaled to+# the period's length. An unfinished period (the default current month)+# counts spending so far and compares it with the same number of days from+# each of the 12 month starts before it. Feeds the "Spending vs normal"+# Reports section.+#+# Net means expense minus refunds in the same category, the way the cash flow+# Sankey nets them, so a refunded purchase doesn't count as spending. Totals+# come from the user-scoped IncomeStatement, so transfers, exclusions and+# account sharing follow the rest of Reports.+#+# as_json is the shared representation for the public API (for the mobile+# app); the Reports section renders the same rows.+class IncomeStatement::SpendingComparison+ BASELINE_LENGTH = 1.year+ # Below this much history before the period there is nothing meaningful to+ # compare against, so `normal` is nil.+ MIN_BASELINE_DAYS = 28++ # Changes smaller than this are left out of the change list.+ MIN_CHANGE = 1++ # direct: a parent's own spending (booked on the parent, not a+ # subcategory), listed among its subcategories.+ Row = Data.define(:category, :total, :normal, :subcategories, :direct) do+ def change+ normal && total - normal+ end++ # Fractional change against normal (0.5 = 50% more); nil without a normal.+ def ratio+ return nil unless normal&.positive?++ (total - normal) / normal+ end+ end++ attr_reader :period, :baseline_period++ # The first transaction these totals could count, filtered as+ # IncomeStatement::Totals filters: in the statement's eligible accounts, not+ # excluded, not pending, and not a kind analytics skip (transfers, card+ # payments, and investment contributions when investing isn't counted as+ # spending). Opening-balance valuations, an early transfer or an excluded+ # entry can predate real spending by years, and would dilute "normal" with+ # empty months.+ def self.history_start(income_statement)+ Entry.joins("JOIN transactions ON transactions.id = entries.entryable_id")+ .where(account_id: income_statement.eligible_accounts.select(:id), entryable_type: "Transaction", excluded: false)+ .merge(Transaction.excluding_pending)+ .where.not(transactions: { kind: income_statement.family.analytics_excluded_kinds })+ .minimum(:date)+ end++ def initialize(income_statement, period:, history_start:, as_of: Date.current)+ @income_statement = income_statement+ @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+ @baseline_period = build_baseline_period(history_start)+ end++ def in_progress?+ @in_progress+ end++ def comparable?+ baseline_period.present? && (!in_progress? || baseline_windows.any?)+ end++ # Parent categories (and the synthetic Uncategorized) with net spending in+ # the period or a normal above zero, largest first. Each row's subcategories+ # include one for spending booked on the parent itself, so the subcategory+ # totals add up to the row total.+ def rows+ @rows ||= begin+ current = net_by_category(period)+ baseline = comparable? ? baseline_net : {}++ parents = (current.values + baseline.values).map { |e| e[:category] }+ .reject(&:subcategory?).uniq { |c| key_for(c) }++ parents.filter_map { |parent| build_row(parent, current, baseline) }+ .sort_by { |row| -row.total }+ end+ end++ def total+ rows.sum(&:total)+ end++ def normal_total+ comparable? ? rows.sum { |row| row.normal || 0 } : nil+ end++ # Parent rows changed by at least MIN_CHANGE against normal, most increased+ # first. Empty without a normal.+ def changes+ rows.select { |row| row.change && row.change.abs >= MIN_CHANGE }.sort_by { |row| -row.change }+ end++ # Rows the treemap draws: positive totals only, at both levels.+ def drawable_rows+ rows.select { |row| row.total.positive? }.map do |row|+ row.with(subcategories: row.subcategories.select { |sub| sub.total.positive? })+ end+ end++ # Amounts are decimal strings in the family currency; ratio is a decimal+ # string too (0.5 = 50% more than normal). A parent's own spending, booked on+ # the parent rather than a subcategory, is listed among its subcategories+ # with the parent's id, so the subcategories add up to the parent.+ def as_json(*)+ {+ currency: income_statement.family.currency,+ period: period_json(period),+ in_progress: in_progress?,+ baseline_period: baseline_period && period_json(baseline_period),+ comparable: comparable?,+ total: decimal(total),+ normal_total: normal_total && decimal(normal_total),+ categories: rows.map { |row| row_json(row).merge(subcategories: row.subcategories.map { |sub| row_json(sub).merge(direct: sub.direct) }) }+ }+ end++ # One row in the shared representation (see as_json).+ def row_json(row)+ {+ id: row.category.id,+ name: row.category.name,+ color: row.category.color,+ filter_value: row.category.filter_value,+ total: decimal(row.total),+ normal: row.normal && decimal(row.normal),+ change: row.change && decimal(row.change),+ ratio: row.ratio && decimal(row.ratio.round(4))+ }+ end++ private+ attr_reader :income_statement++ def build_baseline_period(history_start)+ end_date = period.start_date - 1.day+ start_date = [ period.start_date - BASELINE_LENGTH, history_start || period.start_date ].max+ return nil if (end_date - start_date).to_i + 1 < MIN_BASELINE_DAYS++ Period.custom(start_date: start_date, end_date: end_date)+ end++ def build_row(parent, current, baseline)+ key = key_for(parent)+ children = (current.values + baseline.values).map { |e| e[:category] }+ .select { |c| c.subcategory? && c.parent_id == parent.id }.uniq(&:id)++ total = positive(current.dig(key, :net))+ normal = scaled_normal(baseline.dig(key, :net))+ return nil if total.zero? && !normal&.positive?++ subcategories = children.filter_map do |child|+ child_total = positive(current.dig(child.id, :net))+ child_normal = scaled_normal(baseline.dig(child.id, :net))+ next if child_total.zero? && !child_normal&.positive?++ Row.new(category: child, total: child_total, normal: child_normal, subcategories: [], direct: false)+ end++ # Refunds can push a subcategory's net below zero, which lowers the+ # parent total but is clamped out of the subcategories. When the rest+ # then add up to more than the parent, show the parent as one box so+ # the treemap never overstates it.+ subcategories = [] if subcategories.sum(&:total) > total++ direct_total = [ total - subcategories.sum(&:total), 0 ].max+ direct_normal = normal && [ normal - subcategories.sum { |s| s.normal || 0 }, 0 ].max+ if direct_total.positive? || direct_normal&.positive?+ subcategories << Row.new(category: parent, total: direct_total, normal: direct_normal, subcategories: [], direct: true)+ end++ Row.new(category: parent, total: total, normal: normal, subcategories: subcategories.sort_by { |s| -s.total }, direct: false)+ end++ # { 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+ end++ def scaled_normal(baseline_net)+ return nil unless comparable?+ return positive(baseline_net) if in_progress? # already an average of same-length windows++ positive(baseline_net) * period_days / baseline_days+ end++ # A whole period compares with the baseline year scaled to its length. An+ # unfinished one compares with the same number of days from each of the+ # 12 month starts before it, so a bill paid on the 1st counts the same in+ # both and early-month spending isn't measured against a whole month.+ def baseline_net+ return net_by_category(baseline_period) unless in_progress?++ baseline_windows.map { |w| net_by_category(w) }.each_with_object({}) do |net, avg|+ net.each { |key, e| (avg[key] ||= { category: e[:category], net: 0 })[:net] += e[:net] / baseline_windows.size }+ end+ end++ def baseline_windows+ @baseline_windows ||= (1..12).filter_map do |i|+ start = period.start_date - i.months+ finish = start + (period_days - 1).days+ # A window that runs into the period would count the spending it's compared with+ Period.custom(start_date: start, end_date: finish) if start >= baseline_period.start_date && finish <= baseline_period.end_date+ end+ end++ def period_days+ (period.end_date - period.start_date).to_i + 1+ end++ def baseline_days+ (baseline_period.end_date - baseline_period.start_date).to_i + 1+ end++ def positive(value)+ [ value || 0, 0 ].max+ end++ def period_json(p)+ { start_date: p.start_date.iso8601, end_date: p.end_date.iso8601 }+ end++ def decimal(value)+ value.to_d.to_s("F")+ end++ def key_for(category)+ return :uncategorized if category.uncategorized?+ return :other_investments if category.other_investments?++ category.id+ end+enddiff --git a/app/views/reports/_spending_vs_normal.html.erb b/app/views/reports/_spending_vs_normal.html.erbnew file mode 100644index 0000000000..ebdee2cab9--- /dev/null+++ b/app/views/reports/_spending_vs_normal.html.erb@@ -0,0 +1,76 @@+<%# locals: (comparison:, start_date:, end_date:) %>+<%+ whole = ->(amount) { Money.new(amount, Current.family.currency).format(precision: 0) }+ tree = spending_treemap_nodes(comparison, start_date: start_date, end_date: end_date)+ changes = spending_changes(comparison, start_date: start_date, end_date: end_date)+%>+<div class="@container space-y-4">+ <p class="text-sm text-secondary">+ <% if comparison.comparable? %>+ <%= t(comparison.in_progress? ? "reports.spending_vs_normal.summary_so_far_html" : "reports.spending_vs_normal.summary_html",+ total: tag.span(whole.call(comparison.total), class: "privacy-sensitive"),+ normal: tag.span(whole.call(comparison.normal_total), class: "privacy-sensitive"),+ baseline_start: l(comparison.baseline_period.start_date, format: :long),+ baseline_end: l(comparison.baseline_period.end_date, format: :long)) %>+ <% else %>+ <%= t("reports.spending_vs_normal.no_history_html", total: tag.span(whole.call(comparison.total), class: "privacy-sensitive")) %>+ <% end %>+ </p>++ <% if tree.empty? %>+ <p class="text-sm text-secondary py-6 text-center"><%= t("reports.spending_vs_normal.no_spending") %></p>+ <% else %>+ <div class="grid grid-cols-1 @3xl:grid-cols-5 gap-6">+ <div class="@3xl:col-span-3 min-w-0">+ <h3 id="spending-treemap-title" class="text-sm font-medium text-secondary mb-2"><%= t("reports.spending_vs_normal.treemap_title") %></h3>+ <div class="privacy-sensitive"+ data-controller="spending-treemap"+ data-spending-treemap-tree-value="<%= tree.to_json %>"+ data-spending-treemap-labels-value="<%= {+ open: t("reports.spending_vs_normal.tooltip.open"),+ legend: {+ less: t("reports.spending_vs_normal.legend.less"),+ slightly_less: t("reports.spending_vs_normal.legend.slightly_less"),+ normal: t("reports.spending_vs_normal.legend.normal"),+ slightly_more: t("reports.spending_vs_normal.legend.slightly_more"),+ more: t("reports.spending_vs_normal.legend.more"),+ much_more: t("reports.spending_vs_normal.legend.much_more")+ }+ }.to_json %>"+ data-spending-treemap-comparable-value="<%= comparison.comparable? %>"+ role="group"+ aria-labelledby="spending-treemap-title">+ <div class="h-90 @3xl:h-110 w-full" data-spending-treemap-target="chart"></div>+ <div class="flex flex-wrap items-center gap-x-3 gap-y-1 mt-3 text-xs text-secondary" data-spending-treemap-target="legend"></div>+ </div>+ </div>++ <div class="@3xl:col-span-2 min-w-0">+ <h3 class="text-sm font-medium text-secondary mb-2"><%= t("reports.spending_vs_normal.changes_title") %></h3>+ <% if changes.empty? %>+ <p class="text-sm text-secondary"><%= comparison.comparable? ? t("reports.spending_vs_normal.no_changes") : t("reports.spending_vs_normal.no_history_short") %></p>+ <% else %>+ <ul class="space-y-1" data-testid="spending-changes">+ <% changes.each do |change| %>+ <li>+ <%= link_to change[:href],+ class: "grid grid-cols-[minmax(0,9rem)_1fr_5rem] items-center gap-2 rounded-md px-1 py-1 hover:bg-container-inset text-sm" do %>+ <span class="truncate text-primary"><%= change[:row].category.name %></span>+ <span class="grid grid-cols-2 h-3" aria-hidden="true">+ <span class="flex justify-end">+ <% if change[:row].change.negative? %><span class="h-3 rounded-l bg-success" style="width: <%= change[:width] %>%"></span><% end %>+ </span>+ <span class="flex justify-start border-l border-secondary">+ <% if change[:row].change.positive? %><span class="h-3 rounded-r bg-destructive" style="width: <%= change[:width] %>%"></span><% end %>+ </span>+ </span>+ <span class="text-right text-secondary privacy-sensitive tabular-nums"><%= change[:amount_label] %></span>+ <% end %>+ </li>+ <% end %>+ </ul>+ <% end %>+ </div>+ </div>+ <% end %>+</div>diff --git a/app/views/reports/index.html.erb b/app/views/reports/index.html.erbindex 70e038cf4d..390c822f07 100644--- a/app/views/reports/index.html.erb+++ b/app/views/reports/index.html.erb@@ -188,6 +188,9 @@<h2 class="text-base font-medium"><%= t(section[:title]) %></h2>+ <% if section[:preview] %>+ <%= render DS::Pill.new(label: t("shared.preview")) %>+ <% end %></div><buttontype="button"diff --git a/config/locales/views/reports/en.yml b/config/locales/views/reports/en.ymlindex 8fa111f06d..6dd0f85629 100644--- a/config/locales/views/reports/en.yml+++ b/config/locales/views/reports/en.yml@@ -140,6 +140,34 @@ en:total_liabilities: Liabilitiesno_assets: No assetsno_liabilities: No liabilities+ spending_vs_normal:+ title: Spending vs normal+ summary_html: "%{total} spent in this period. Normal for a period this long is %{normal}, based on %{baseline_start} to %{baseline_end}."+ summary_so_far_html: "%{total} spent so far. Normal for this many days is %{normal}, based on %{baseline_start} to %{baseline_end}."+ no_history_html: "%{total} spent in this period. There isn't enough earlier history yet to say what's normal."+ no_history_short: Not enough earlier history to compare against yet.+ no_spending: No spending in this period.+ no_changes: Spending matched normal in every category.+ treemap_title: Where it went+ changes_title: What changed+ direct: "%{category} (no subcategory)"+ tooltip:+ path: "%{parent} › %{category}"+ total: "%{category}: %{amount}"+ normal: "Normal: %{amount}"+ more: "%{amount} more than normal (%{percent})"+ less: "%{amount} less than normal (%{percent})"+ more_no_percent: "%{amount} more than normal"+ less_no_percent: "%{amount} less than normal"+ no_normal: No earlier history to compare against+ open: Select to see these transactions+ legend:+ less: 50–100% less+ slightly_less: 15–50% less+ normal: About normal+ slightly_more: 15–50% more+ more: 50–100% more+ much_more: 100%+ moreinvestment_performance:title: Investment Performanceportfolio_value: Portfolio Valuediff --git a/config/routes.rb b/config/routes.rbindex 5194f67c97..070ed62fde 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -802,6 +802,7 @@ Rails.application.routes.draw doendresource :usage, only: [ :show ], controller: :usageresource :cash_flow, only: [ :show ], controller: :cash_flows+ resource :spending_vs_normal, only: [ :show ], controller: :spending_vs_normalresource :balance_sheet, only: [ :show ], controller: :balance_sheetresources :insights, only: [ :index ]resources :push_subscriptions, only: [ :create, :destroy ]diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex f3735da843..1fb10764e1 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -3464,6 +3464,109 @@ components:"$ref": "#/components/schemas/FinancialPeriod"sankey:"$ref": "#/components/schemas/CashFlowSankey"+ SpendingVsNormalCategory:+ type: object+ required:+ - id+ - name+ - color+ - filter_value+ - total+ - normal+ - change+ - ratio+ properties:+ id:+ type: string+ format: uuid+ nullable: true+ description: Null for the synthetic Uncategorized category. A parent's own+ spending is listed among its subcategories with the parent's id+ name:+ type: string+ color:+ type: string+ nullable: true+ filter_value:+ type: string+ description: Value for the transactions category filter+ total:+ type: string+ description: Net spending in the period (expense minus refunds), at least+ zero+ normal:+ type: string+ nullable: true+ description: 'Finished period: net spending over the baseline period, scaled+ to the period length. Unfinished period (in_progress): average net spending+ over the same number of days from earlier month starts. Null without enough+ history'+ change:+ type: string+ nullable: true+ description: total minus normal+ ratio:+ type: string+ nullable: true+ description: Fractional change against normal (0.5 = 50% more). Null without+ a positive normal+ direct:+ type: boolean+ description: 'Present on subcategories only: true for the parent''s own+ spending, booked on the parent rather than a subcategory'+ subcategories:+ type: array+ items:+ "$ref": "#/components/schemas/SpendingVsNormalCategory"+ description: Present on parent categories only; adds up to the parent total+ SpendingVsNormal:+ type: object+ required:+ - currency+ - period+ - in_progress+ - baseline_period+ - comparable+ - total+ - normal_total+ - categories+ properties:+ currency:+ type: string+ period:+ "$ref": "#/components/schemas/FinancialPeriod"+ in_progress:+ type: boolean+ description: 'The period has not ended: it is cut to today, and normal is+ the average of the same number of days from each of up to 12 earlier month+ starts'+ baseline_period:+ type: object+ nullable: true+ required:+ - start_date+ - end_date+ properties:+ start_date:+ type: string+ format: date+ end_date:+ type: string+ format: date+ description: Up to a year before the period, from the first counted transaction.+ Null with under 28 days of history+ comparable:+ type: boolean+ total:+ type: string+ normal_total:+ type: string+ nullable: true+ categories:+ type: array+ items:+ "$ref": "#/components/schemas/SpendingVsNormalCategory"+ description: Parent categories, largest total firstCashFlow:type: objectrequired:@@ -9216,6 +9319,56 @@ paths:application/json:schema:"$ref": "#/components/schemas/ErrorResponse"+ "/api/v1/spending_vs_normal":+ get:+ summary: Show spending per category against normal+ tags:+ - Reports+ description: 'Net spending per category in a period, compared with each category''s+ normal. For a finished period, normal is its net spending over the year before+ the period, scaled to the period length. An unfinished period (in_progress)+ is cut to today and compared with the average of the same number of days from+ each of up to 12 earlier month starts, counting only windows that end before+ the period. The data behind the Reports section "Spending vs normal". Uses+ the authenticated user''s finance accounts and Sure reporting rules. Experimental:+ the section is a preview feature, and how normal is defined may still change.'+ parameters:+ - name: start_date+ in: query+ required: false+ schema:+ type: string+ format: date+ description: Inclusive ISO date. Requires end_date; both omitted means the+ current month to date.+ - name: end_date+ in: query+ required: false+ schema:+ type: string+ format: date+ description: Inclusive ISO date at or after start_date.+ security:+ - apiKeyAuth: []+ responses:+ '200':+ description: comparison returned+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/SpendingVsNormal"+ '422':+ description: invalid period+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ '401':+ description: unauthorized+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse""/api/v1/transactions/{transaction_id}/split":parameters:- name: transaction_iddiff --git a/spec/requests/api/v1/spending_vs_normal_spec.rb b/spec/requests/api/v1/spending_vs_normal_spec.rbnew file mode 100644index 0000000000..10d5ba1215--- /dev/null+++ b/spec/requests/api/v1/spending_vs_normal_spec.rb@@ -0,0 +1,66 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'API V1 Spending vs Normal', type: :request do+ let(:family) do+ Family.create!(+ name: 'API Family',+ currency: 'USD',+ locale: 'en',+ date_format: '%m-%d-%Y'+ )+ end++ let(:user) do+ family.users.create!(+ email: '[email protected]',+ password: 'password123',+ password_confirmation: 'password123'+ )+ end++ let(:api_key) do+ key = ApiKey.generate_secure_key+ ApiKey.create!(+ user: user,+ name: 'API Docs Key',+ key: key,+ scopes: %w[read],+ source: 'web'+ )+ end++ let(:'X-Api-Key') { api_key.plain_key }++ path '/api/v1/spending_vs_normal' do+ get 'Show spending per category against normal' do+ tags 'Reports'+ description 'Net spending per category in a period, compared with each category\'s normal. For a finished period, normal is its net spending over the year before the period, scaled to the period length. An unfinished period (in_progress) is cut to today and compared with the average of the same number of days from each of up to 12 earlier month starts, counting only windows that end before the period. The data behind the Reports section "Spending vs normal". Uses the authenticated user\'s finance accounts and Sure reporting rules. Experimental: the section is a preview feature, and how normal is defined may still change.'+ parameter name: :start_date, in: :query, required: false, schema: { type: :string, format: :date }, description: 'Inclusive ISO date. Requires end_date; both omitted means the current month to date.'+ parameter name: :end_date, in: :query, required: false, schema: { type: :string, format: :date }, description: 'Inclusive ISO date at or after start_date.'+ security [ { apiKeyAuth: [] } ]+ produces 'application/json'++ response '200', 'comparison returned' do+ schema '$ref' => '#/components/schemas/SpendingVsNormal'++ run_test!+ end++ response '422', 'invalid period' do+ schema '$ref' => '#/components/schemas/ErrorResponse'+ let(:start_date) { '2024-03-01' }+ run_test!+ end++ response '401', 'unauthorized' do+ schema '$ref' => '#/components/schemas/ErrorResponse'++ let(:'X-Api-Key') { 'invalid-key' }++ run_test!+ end+ end+ end+enddiff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rbindex 71c692b9c5..de256ad2ca 100644--- a/spec/swagger_helper.rb+++ b/spec/swagger_helper.rb@@ -1849,6 +1849,36 @@ RSpec.configure do |config|sankey: { '$ref' => '#/components/schemas/CashFlowSankey' }}},+ SpendingVsNormalCategory: {+ type: :object, required: %w[id name color filter_value total normal change ratio],+ properties: {+ id: { type: :string, format: :uuid, nullable: true, description: 'Null for the synthetic Uncategorized category. A parent\'s own spending is listed among its subcategories with the parent\'s id' },+ name: { type: :string }, color: { type: :string, nullable: true },+ filter_value: { type: :string, description: 'Value for the transactions category filter' },+ total: { type: :string, description: 'Net spending in the period (expense minus refunds), at least zero' },+ normal: { type: :string, nullable: true, description: 'Finished period: net spending over the baseline period, scaled to the period length. Unfinished period (in_progress): average net spending over the same number of days from earlier month starts. Null without enough history' },+ change: { type: :string, nullable: true, description: 'total minus normal' },+ ratio: { type: :string, nullable: true, description: 'Fractional change against normal (0.5 = 50% more). Null without a positive normal' },+ direct: { type: :boolean, description: 'Present on subcategories only: true for the parent\'s own spending, booked on the parent rather than a subcategory' },+ subcategories: { type: :array, items: { '$ref' => '#/components/schemas/SpendingVsNormalCategory' }, description: 'Present on parent categories only; adds up to the parent total' }+ }+ },+ SpendingVsNormal: {+ type: :object, required: %w[currency period in_progress baseline_period comparable total normal_total categories],+ properties: {+ currency: { type: :string },+ period: { '$ref' => '#/components/schemas/FinancialPeriod' },+ in_progress: { type: :boolean, description: 'The period has not ended: it is cut to today, and normal is the average of the same number of days from each of up to 12 earlier month starts' },+ baseline_period: {+ type: :object, nullable: true, required: %w[start_date end_date],+ properties: { start_date: { type: :string, format: :date }, end_date: { type: :string, format: :date } },+ description: 'Up to a year before the period, from the first counted transaction. Null with under 28 days of history'+ },+ comparable: { type: :boolean },+ total: { type: :string }, normal_total: { type: :string, nullable: true },+ categories: { type: :array, items: { '$ref' => '#/components/schemas/SpendingVsNormalCategory' }, description: 'Parent categories, largest total first' }+ }+ },CashFlow: {type: :object,required: %w[month as_of time_zone currency period income spending net_savings savings_rate spending_comparison],diff --git a/test/controllers/api/v1/spending_vs_normal_controller_test.rb b/test/controllers/api/v1/spending_vs_normal_controller_test.rbnew file mode 100644index 0000000000..f02e963805--- /dev/null+++ b/test/controllers/api/v1/spending_vs_normal_controller_test.rb@@ -0,0 +1,76 @@+require "test_helper"++class Api::V1::SpendingVsNormalControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper++ setup do+ @user = users(:family_admin)+ @user.api_keys.active.destroy_all+ @auth = ApiKey.create!(user: @user, name: "Reports Read", scopes: [ "read" ],+ display_key: "test_ro_#{SecureRandom.hex(8)}", source: "mobile")+ Redis.new.del("api_rate_limit:#{@auth.id}")+ end++ test "requires authentication" do+ get "/api/v1/spending_vs_normal"+ assert_response :unauthorized+ end++ test "defaults to the current month to date" do+ travel_to Date.new(2024, 3, 15) do+ get "/api/v1/spending_vs_normal", headers: api_headers(@auth)++ assert_response :success+ assert_equal({ "start_date" => "2024-03-01", "end_date" => "2024-03-15" }, response.parsed_body["period"])+ assert response.parsed_body["in_progress"]+ assert_equal "private, no-store", response.headers["Cache-Control"]+ end+ end++ test "returns the period's spending per category against normal" do+ @user.family.entries.where(entryable_type: "Transaction").destroy_all+ account = accounts(:depository)+ category = categories(:food_and_drink)+ create_transaction(account: account, amount: 120, category: category, date: Date.new(2024, 2, 10))+ create_transaction(account: account, amount: 60, category: category, date: Date.new(2023, 11, 10))++ get "/api/v1/spending_vs_normal", params: { start_date: "2024-02-01", end_date: "2024-02-29" }, headers: api_headers(@auth)++ assert_response :success+ body = response.parsed_body+ food = body["categories"].find { |c| c["id"] == category.id }+ assert_equal "120.0", food["total"]+ # The 60 in the baseline, scaled from the baseline's length to February's 29 days+ baseline = body["baseline_period"]+ baseline_days = (Date.iso8601(baseline["end_date"]) - Date.iso8601(baseline["start_date"])).to_i + 1+ assert_equal "2024-01-31", baseline["end_date"]+ assert_in_delta 60.0 * 29 / baseline_days, food["normal"].to_f, 0.0001+ assert body["comparable"]+ assert_not body["in_progress"]+ end++ test "without enough history there is no baseline or normal" do+ category = categories(:food_and_drink)+ family = @user.family+ family.entries.where(entryable_type: "Transaction").destroy_all+ create_transaction(account: accounts(:depository), amount: 50, category: category, date: Date.new(2024, 2, 10))++ get "/api/v1/spending_vs_normal", params: { start_date: "2024-02-01", end_date: "2024-02-29" }, headers: api_headers(@auth)++ assert_response :success+ body = response.parsed_body+ assert_equal false, body["comparable"]+ assert_nil body["baseline_period"]+ assert_nil body["normal_total"]+ assert_nil body["categories"].find { |c| c["id"] == category.id }["normal"]+ end++ test "rejects invalid periods" do+ [ { start_date: "2024-02-01" }, { start_date: "2024-03-01", end_date: "2024-02-01" }, { start_date: "nope", end_date: "2024-02-01" } ].each do |params|+ get "/api/v1/spending_vs_normal", params: params, headers: api_headers(@auth)++ assert_response :unprocessable_entity+ assert_equal "invalid_period", response.parsed_body["error"]+ end+ end+enddiff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rbindex c3c4877ec9..6be2d97e10 100644--- a/test/controllers/reports_controller_test.rb+++ b/test/controllers/reports_controller_test.rb@@ -110,6 +110,33 @@ class ReportsControllerTest < ActionDispatch::IntegrationTestendend+ test "spending vs normal is a preview section" do+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => false))+ get reports_path+ assert_select "section[data-section-key='spending_vs_normal']", count: 0++ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))+ get reports_path+ assert_response :ok+ assert_select "section[data-section-key='spending_vs_normal']" do+ assert_select "[data-controller='spending-treemap']"+ end+ end++ test "the spending baseline starts at the first transaction in the user's own finances" do+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))+ @family.entries.where(entryable_type: "Transaction").destroy_all+ hidden = Account.create!(family: @family, owner: users(:family_member), name: "Not shared", currency: @family.currency, balance: 0, accountable: Depository.new)+ create_transaction(account: hidden, date: 200.days.ago.to_date, amount: 10)+ own_first = 100.days.ago.to_date+ create_transaction(account: accounts(:depository), date: own_first, amount: 10)++ get reports_path++ baseline = controller.instance_variable_get(:@spending_comparison).baseline_period+ assert_equal own_first, baseline.start_date+ end+# The desktop app clones these into the tray when a download such as the CSV# export ends, since it has no download list of its own, and reads their data# attributes for its native notification.diff --git a/test/helpers/reports_helper_spending_test.rb b/test/helpers/reports_helper_spending_test.rbnew file mode 100644index 0000000000..dd4fcf36f5--- /dev/null+++ b/test/helpers/reports_helper_spending_test.rb@@ -0,0 +1,52 @@+require "test_helper"++class ReportsHelperSpendingTest < ActionView::TestCase+ include ReportsHelper+ include EntriesTestHelper++ setup do+ @family = families(:empty)+ Current.session = users(:empty).sessions.create!+ @account = @family.accounts.create!(name: "Checking", currency: @family.currency, balance: 0, accountable: Depository.new)+ @food = @family.categories.create!(name: "Food")+ @groceries = @family.categories.create!(name: "Groceries", parent: @food)+ @period = Period.custom(start_date: Date.new(2026, 9, 1), end_date: Date.new(2026, 9, 30))+ end++ test "labels a parent's own spending when it sits beside subcategories" do+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 150, category: @groceries)+ create_transaction(account: @account, date: Date.new(2026, 9, 6), amount: 50, category: @food)++ food = nodes.sole+ direct = food[:children].find { |c| c[:direct] }++ assert_equal "Food (no subcategory)", direct[:name]+ assert_equal "Food › Food (no subcategory): $50.00", direct[:description].first+ assert_equal "No earlier history to compare against", direct[:description].second+ end++ test "a category drawn as a single box isn't described as its own parent" do+ create_transaction(account: @account, date: Date.new(2026, 9, 6), amount: 50, category: @food)++ box = nodes.sole[:children].sole++ assert_equal "Food", box[:name]+ assert_equal "Food: $50.00", box[:description].first+ end++ test "describes the change with an interpolated percent, and skips one under 1" do+ 12.times { |i| create_transaction(account: @account, date: Date.new(2025, 9, 4) + i.months, amount: 100, category: @groceries) }+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 200, category: @groceries)++ groceries = nodes(history_start: Date.new(2025, 9, 1)).sole[:children].sole++ assert_equal "Groceries", groceries[:name], "a lone subcategory needs no label"+ assert_match(/\A\$\d+\.\d\d more than normal \(\d+%\)\z/, groceries[:description].last)+ end++ private+ def nodes(history_start: @period.start_date)+ comparison = IncomeStatement::SpendingComparison.new(IncomeStatement.new(@family), period: @period, history_start: history_start, as_of: Date.new(2026, 10, 15))+ spending_treemap_nodes(comparison, start_date: @period.start_date, end_date: @period.end_date)+ end+enddiff --git a/test/models/income_statement/spending_comparison_test.rb b/test/models/income_statement/spending_comparison_test.rbnew file mode 100644index 0000000000..204383aa41--- /dev/null+++ b/test/models/income_statement/spending_comparison_test.rb@@ -0,0 +1,206 @@+require "test_helper"++class IncomeStatement::SpendingComparisonTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:empty)+ @account = @family.accounts.create!(name: "Checking", currency: @family.currency, balance: 5000, accountable: Depository.new)++ @salary = @family.categories.create!(name: "Salary")+ @food = @family.categories.create!(name: "Food")+ @groceries = @family.categories.create!(name: "Groceries", parent: @food)+ @travel = @family.categories.create!(name: "Travel")++ @period = Period.custom(start_date: Date.new(2026, 9, 1), end_date: Date.new(2026, 9, 30))+ @baseline_start = @period.start_date - 1.year+ end++ test "history starts at the first transaction that counts, not an excluded one or a valuation" do+ create_transaction(account: @account, date: Date.new(2024, 1, 10), amount: 40, category: @food, excluded: true)+ @account.entries.create!(date: Date.new(2023, 6, 1), amount: 5000, currency: @family.currency, name: "Opening balance",+ entryable: Valuation.new(kind: "opening_anchor"))+ create_transaction(account: @account, date: Date.new(2026, 3, 2), amount: 25, category: @food)++ assert_equal Date.new(2026, 3, 2), IncomeStatement::SpendingComparison.history_start(IncomeStatement.new(@family))+ end++ test "spending is net of refunds, and spending on the parent gets its own row" do+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 300, category: @groceries)+ create_transaction(account: @account, date: Date.new(2026, 9, 9), amount: -100, category: @groceries) # refund+ create_transaction(account: @account, date: Date.new(2026, 9, 12), amount: 50, category: @food)+ create_transaction(account: @account, date: Date.new(2026, 9, 15), amount: -2000, category: @salary)++ food = comparison.rows.find { |r| r.category == @food }++ assert_equal 250, food.total+ assert_equal({ "Groceries" => 200, "Food" => 50 }, food.subcategories.to_h { |s| [ s.category.name, s.total ] })+ assert_not comparison.rows.any? { |r| r.category == @salary }, "income categories are not spending"+ end++ test "as_json gives decimal strings, filter values and the parent's own spending" do+ 12.times { |i| create_transaction(account: @account, date: @baseline_start + i.months + 3.days, amount: 100, category: @groceries) }+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 150, category: @groceries)+ create_transaction(account: @account, date: Date.new(2026, 9, 12), amount: 50, category: @food)++ json = comparison(history_start: @baseline_start).as_json+ food = json[:categories].find { |c| c[:id] == @food.id }++ assert_equal @family.currency, json[:currency]+ assert_equal({ start_date: "2026-09-01", end_date: "2026-09-30" }, json[:period])+ assert json[:comparable]+ assert_equal "200.0", food[:total]+ assert_equal "Food", food[:filter_value]+ normal = 1200 * 30 / 365r+ assert_in_delta normal, BigDecimal(food[:normal]), 1e-12+ assert_equal ((200 - normal) / normal).to_d(20).round(4).to_s("F"), food[:ratio]+ assert_not json[:in_progress]+ assert_equal [ [ @groceries.id, "150.0", false ], [ @food.id, "50.0", true ] ], food[:subcategories].map { |s| [ s[:id], s[:total], s[:direct] ] }+ end++ test "as_json without history has no normal" do+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 80, category: nil)++ json = comparison.as_json+ uncategorized = json[:categories].sole++ assert_not json[:comparable]+ assert_nil json[:baseline_period]+ assert_nil json[:normal_total]+ assert_nil uncategorized[:normal]+ assert_equal Category::UNCATEGORIZED_FILTER_VALUE, uncategorized[:filter_value]+ end++ test "an unfinished period compares with the same days of earlier months" do+ # 10 a day for the year before September, and on pace by Sep 10+ (Date.new(2025, 9, 1)..Date.new(2026, 8, 31)).each { |d| create_transaction(account: @account, date: d, amount: 10, category: @travel) if d.day <= 30 }+ (1..10).each { |d| create_transaction(account: @account, date: Date.new(2026, 9, d), amount: 10, category: @travel) }++ result = comparison(history_start: @baseline_start, as_of: Date.new(2026, 9, 10))+ travel = result.rows.find { |r| r.category == @travel }++ assert result.in_progress?+ assert_equal Date.new(2026, 9, 10), result.period.end_date+ assert_equal 100, travel.total+ assert_in_delta 0, travel.ratio, 0.01+ end++ test "an unfinished quarter compares only with days before it" do+ # 10 a day for the year before the quarter, 30 a day in it: three times normal+ quarter = Period.custom(start_date: Date.new(2026, 10, 1), end_date: Date.new(2026, 12, 31))+ (Date.new(2025, 10, 1)...quarter.start_date).each { |d| create_transaction(account: @account, date: d, amount: 10, category: @travel) }+ (quarter.start_date..Date.new(2026, 12, 20)).each { |d| create_transaction(account: @account, date: d, amount: 30, category: @travel) }++ result = IncomeStatement::SpendingComparison.new(IncomeStatement.new(@family), period: quarter, history_start: Date.new(2025, 10, 1), as_of: Date.new(2026, 12, 20))++ assert_in_delta 2, result.rows.find { |r| r.category == @travel }.ratio, 0.01+ end++ test "a bill paid on the 1st reads as normal early in the month" do+ 12.times { |i| create_transaction(account: @account, date: Date.new(2025, 9, 1) + i.months, amount: 1000, category: @travel) }+ create_transaction(account: @account, date: Date.new(2026, 9, 1), amount: 1000, category: @travel)++ travel = comparison(history_start: @baseline_start, as_of: Date.new(2026, 9, 5)).rows.find { |r| r.category == @travel }++ assert_in_delta 1000, travel.normal, 0.01+ assert_in_delta 0, travel.ratio, 0.0001+ end++ test "history starts after early transfers and pending transactions" do+ create_transaction(account: @account, date: Date.new(2024, 1, 10), amount: 40, kind: "funds_movement")+ create_transaction(account: @account, date: Date.new(2024, 2, 10), amount: 40, category: @food).entryable.update!(extra: { "simplefin" => { "pending" => true } })+ create_transaction(account: @account, date: Date.new(2026, 3, 2), amount: 25, category: @food)++ assert_equal Date.new(2026, 3, 2), IncomeStatement::SpendingComparison.history_start(IncomeStatement.new(@family))+ end++ test "history skips early investment contributions when investing isn't spending" do+ create_transaction(account: @account, date: Date.new(2024, 1, 10), amount: 500, kind: "investment_contribution")+ create_transaction(account: @account, date: Date.new(2026, 3, 2), amount: 25, category: @food)++ assert_equal Date.new(2024, 1, 10), IncomeStatement::SpendingComparison.history_start(IncomeStatement.new(@family))++ @family.update!(investment_contributions_as_spending: false)+ assert_equal Date.new(2026, 3, 2), IncomeStatement::SpendingComparison.history_start(IncomeStatement.new(@family.reload))+ end++ test "changes list the parents that moved by at least 1, most increased first" do+ 12.times { |i| create_transaction(account: @account, date: @baseline_start + i.months + 3.days, amount: 100, category: @food) }+ 12.times { |i| create_transaction(account: @account, date: @baseline_start + i.months + 3.days, amount: 100, category: @travel) }+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 300, category: @food)++ changes = comparison(history_start: @baseline_start).changes++ assert_equal [ @food, @travel ], changes.map(&:category)+ assert changes.first.change.positive?+ assert changes.last.change.negative?+ end++ test "normal is the year before the period, scaled to the period's length" do+ 12.times { |i| create_transaction(account: @account, date: @baseline_start + i.months + 3.days, amount: 100, category: @groceries) }+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 300, category: @groceries)++ food = comparison(history_start: @baseline_start).rows.find { |r| r.category == @food }+ expected_normal = 1200 * 30 / 365r++ assert_in_delta expected_normal, food.normal, 0.01+ assert_in_delta 300 - expected_normal, food.change, 0.01+ assert_in_delta (300 - expected_normal) / expected_normal, food.ratio, 0.0001+ assert_equal Date.new(2025, 9, 1), comparison(history_start: @baseline_start).baseline_period.start_date+ end++ test "a short history shortens the baseline instead of diluting normal" do+ 3.times { |i| create_transaction(account: @account, date: Date.new(2026, 6, 10) + i.months, amount: 90, category: @travel) }+ create_transaction(account: @account, date: Date.new(2026, 9, 10), amount: 90, category: @travel)++ result = comparison(history_start: Date.new(2026, 6, 1))+ travel = result.rows.find { |r| r.category == @travel }++ assert_equal Date.new(2026, 6, 1), result.baseline_period.start_date+ assert_in_delta 270 * 30 / 92r, travel.normal, 0.01+ end++ test "without enough earlier history there is no normal" do+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 300, category: @groceries)++ result = comparison(history_start: Date.new(2026, 8, 20))++ assert_not result.comparable?+ assert_nil result.rows.first.normal+ assert_nil result.rows.first.ratio+ assert_nil result.normal_total+ end++ test "a category with spending only in the baseline shows as spending nothing now" do+ create_transaction(account: @account, date: Date.new(2026, 3, 1), amount: 600, category: @travel)+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 300, category: @groceries)++ travel = comparison(history_start: @baseline_start).rows.find { |r| r.category == @travel }++ assert_equal 0, travel.total+ assert travel.normal.positive?+ assert travel.change.negative?+ end++ test "a subcategory refunded below zero doesn't make the others overstate the parent" do+ bakery = @family.categories.create!(name: "Bakery", parent: @food)+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 100, category: @groceries)+ create_transaction(account: @account, date: Date.new(2026, 9, 6), amount: -60, category: bakery) # refund only++ food = comparison.rows.find { |r| r.category == @food }++ assert_equal 40, food.total+ assert_equal [ [ @food, 40 ] ], food.subcategories.map { |s| [ s.category, s.total ] }+ end++ test "uncategorized spending is its own row" do+ create_transaction(account: @account, date: Date.new(2026, 9, 5), amount: 40)++ assert comparison.rows.any? { |r| r.category.uncategorized? && r.total == 40 }+ end++ private+ def comparison(history_start: @period.start_date, as_of: Date.new(2026, 10, 15))+ IncomeStatement::SpendingComparison.new(IncomeStatement.new(@family), period: @period, history_start: history_start, as_of: as_of)+ end+enddiff --git a/test/system/reports_spending_vs_normal_test.rb b/test/system/reports_spending_vs_normal_test.rbnew file mode 100644index 0000000000..b802dd3a1d--- /dev/null+++ b/test/system/reports_spending_vs_normal_test.rb@@ -0,0 +1,48 @@+require "application_system_test_case"++class ReportsSpendingVsNormalTest < ApplicationSystemTestCase+ include EntriesTestHelper++ setup do+ @user = users(:family_admin)+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))+ @account = accounts(:depository)+ @category = @user.family.categories.create!(name: "Treemap Coffee")++ # A year of £10 a month, then £40 this month: four times normal.+ travel_to Date.current.beginning_of_month + 14.days+ 12.times { |i| create_transaction(account: @account, date: Date.current.beginning_of_month - (i + 1).months + 2.days, amount: 10, category: @category) }+ create_transaction(account: @account, date: Date.current.beginning_of_month + 1.day, amount: 40, category: @category)++ sign_in @user+ visit reports_path(period_type: :monthly)+ end++ test "the treemap shows spending against normal and opens a category's transactions" do+ within "section[data-section-key='spending_vs_normal']" do+ assert_selector "[data-controller='spending-treemap'] svg g.leaf rect", minimum: 1+ assert_selector "[data-testid='spending-changes'] li", text: "Treemap Coffee"++ box = find("g.leaf[aria-label^='Treemap Coffee']")+ box.hover+ end++ assert_selector "[role='tooltip']", text: "more than normal"++ find("g.leaf[aria-label^='Treemap Coffee']").click++ assert_current_path(/\/transactions\?/)+ assert_includes URI.decode_www_form_component(current_url), "Treemap Coffee"+ end++ test "Enter on a box opens its transactions without grabbing the section" do+ section = find("section[data-section-key='spending_vs_normal']")+ section.find("g.leaf[aria-label^='Treemap Coffee']").send_keys(:enter)++ assert_current_path(/\/transactions\?/)++ # Turbo restores the page as it was when Enter navigated away+ page.go_back+ assert_selector "section[data-section-key='spending_vs_normal'][aria-grabbed='false']"+ end+end