The personal finance app for everyone (by everyone)
Ruby
Let the spending widget overlay up to five earlier months (#4502)
SalvoBfc524ae19f33
diff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rbindex 5e3d026b27..982bb3536e 100644--- a/app/controllers/pages_controller.rb+++ b/app/controllers/pages_controller.rb@@ -31,7 +31,10 @@ class PagesController < ApplicationController# anywhere. Customize mode, the period picker and each widget's own month# links and filter forms carry them along, so changing one control doesn't# jump the other widgets back to their defaults.- DASHBOARD_VIEW_PARAMS = [ :start_date, :end_date, :money_flow_month, :spending_month, :cashflow_month, { money_flow_account_ids: [], spending_category_ids: [], cashflow_account_ids: [] } ].freeze+ DASHBOARD_VIEW_PARAMS = [ :start_date, :end_date, :money_flow_month, :spending_month, :spending_compare_months, :cashflow_month, { money_flow_account_ids: [], spending_category_ids: [], cashflow_account_ids: [] } ].freeze++ # How many earlier months the spending chart can overlay.+ SPENDING_COMPARE_MONTHS = (1..5).freeze# Selectable height presets (px) for grow widgets.DASHBOARD_HEIGHT_PRESETS = { "compact" => 208, "auto" => 288, "tall" => 416 }.freeze@@ -159,6 +162,8 @@ class PagesController < ApplicationControllercategory_ids = Current.user.dashboard_hidden_sections.include?("spending_trend") ? spending_trend_category_ids_param : spending_trend_filter.category_idscategory_ids ? view_params[:spending_category_ids] = category_ids : view_params.delete(:spending_category_ids)end+ compare_months = spending_trend_compare_months_param+ compare_months == SPENDING_COMPARE_MONTHS.min ? view_params.delete(:spending_compare_months) : view_params[:spending_compare_months] = compare_months.to_sview_paramsend@@ -719,6 +724,13 @@ class PagesController < ApplicationControllercurrent_monthend+ # Earlier months overlaid on the chart; anything outside the offered range+ # falls back to just the previous month.+ def spending_trend_compare_months_param+ months = Integer(params[:spending_compare_months], exception: false)+ SPENDING_COMPARE_MONTHS.include?(months) ? months : SPENDING_COMPARE_MONTHS.min+ end+# Category ids (and the uncategorized sentinel) from the family's own# categories. Not narrowed to the categories with spending this month, so# a selection survives switching to a month where some of it is empty.@@ -731,16 +743,19 @@ class PagesController < ApplicationControllerids.presenceend- # The selected month (capped at today while it's in progress) and the- # month before it, which the widget compares against. Memoized: the+ # The selected month (capped at today while it's in progress) followed by+ # the full months before it that the chart overlays, newest first; the+ # first of those is the month the header compares against. Memoized: the# filter and the widget both need them.def spending_trend_periods(selected_month)month_start = selected_month.beginning_of_month(@spending_trend_periods ||= {})[month_start] ||= begincurrent_period = Period.custom(start_date: month_start, end_date: [ month_start.end_of_month, Date.current ].min)- previous_month_start = (month_start - 1.month).beginning_of_month- previous_period = Period.custom(start_date: previous_month_start, end_date: previous_month_start.end_of_month)- [ current_period, previous_period ]+ comparison_periods = (1..spending_trend_compare_months_param).map do |i|+ comparison_month_start = (month_start - i.months).beginning_of_month+ Period.custom(start_date: comparison_month_start, end_date: comparison_month_start.end_of_month)+ end+ [ current_period, *comparison_periods ]endend@@ -755,34 +770,43 @@ class PagesController < ApplicationControllerend# Cumulative daily spending for the selected month (capped at today while- # the month is in progress) against the previous month's full curve, so- # the two lines share one day-of-month axis. The header totals compare the- # same number of elapsed days; only the chart draws the previous month out- # to its final day.+ # the month is in progress) against each compared month's full curve, so+ # the lines share one day-of-month axis. The header compares only the+ # previous month, over the same number of elapsed days; only the chart+ # draws compared months out to their final day.## The category filter (an IncomeStatement::ExpenseCategoryFilter) narrows- # both months to the same categories, so the comparison stays+ # every month to the same categories, so the comparison stays# like-for-like.def build_spending_trend_data(income_statement, selected_month, category_filter)month_start = selected_month.beginning_of_monthmonth_end = month_start.end_of_month- current_period, previous_period = spending_trend_periods(month_start)+ current_period, *comparison_periods = spending_trend_periods(month_start)+ previous_period = comparison_periods.firstprevious_month_start = previous_period.start_datecategory_ids = category_filter.category_ids- current_daily = income_statement.daily_expense_series(period: current_period, category_ids: category_ids).index_by(&:date)- previous_daily = income_statement.daily_expense_series(period: previous_period, category_ids: category_ids).index_by(&:date)+ cumulative_series = ->(period) do+ daily = income_statement.daily_expense_series(period: period, category_ids: category_ids).index_by(&:date)+ cumulative_spending_series(period, daily)+ end- # The selected month always owns the axis: when the previous month is+ # The selected month always owns the axis: when a compared month is# longer, its extra days fold into the final visible point so the curve# still ends at the full-month total without the axis rolling into- # previous-month dates (e.g. a September view ends at "Sep 30", not+ # that month's dates (e.g. a September view ends at "Sep 30", not# "Aug 31").axis_days = month_end.day- current_series = cumulative_spending_series(current_period, current_daily)- previous_header_series = cumulative_spending_series(previous_period, previous_daily)- previous_series = fold_extra_days(previous_header_series, axis_days)+ current_series = cumulative_series.call(current_period)+ comparison_series = comparison_periods.map { |period| cumulative_series.call(period) }+ previous_header_series = comparison_series.first+ comparisons = comparison_periods.zip(comparison_series).map do |period, series|+ {+ label: I18n.l(period.start_date, format: :month_year).capitalize,+ series: fold_extra_days(series, axis_days)+ }+ endcurrent_total = current_series.last&.fetch(:value) || 0comparison_days = if month_start == Date.current.beginning_of_month@@ -803,7 +827,8 @@ class PagesController < ApplicationControllercurrent_days: month_end.day,axis_labels: spending_trend_axis_labels(month_start, axis_days),current: current_series,- previous: previous_series,+ comparisons: comparisons,+ compare_months: comparisons.size,current_total: Money.new(current_total, currency),previous_total: Money.new(previous_total, currency),delta: Money.new(current_total - previous_total, currency),diff --git a/app/javascript/controllers/spending_chart_controller.js b/app/javascript/controllers/spending_chart_controller.jsindex 63931789ba..2671b900c4 100644--- a/app/javascript/controllers/spending_chart_controller.js+++ b/app/javascript/controllers/spending_chart_controller.js@@ -5,12 +5,20 @@ import SettledResize from "utils/settled_resize";// Cumulative spending chart for the dashboard "spending" widget: the selected// month's running total (green, ending today while the month is in progress)-// overlaid on the previous month's complete curve (gray), sharing one+// overlaid on the complete curves of the months it's compared with (the+// previous month in gray, older ones in their own colors), sharing one// day-of-month axis. Lifecycle mirrors bar_chart/time_series_chart// (install/teardown, ResizeObserver, turbo:load reinstall, page-relative// tooltip positioning).const CURRENT_COLOR = "var(--color-success)";-const PREVIOUS_COLOR = "var(--color-gray-400)";+// Compared months, newest first; the server offers at most this many.+const COMPARISON_COLORS = [+ "var(--color-gray-400)",+ "var(--color-blue-500)",+ "var(--color-violet-500)",+ "var(--color-orange-500)",+ "var(--color-pink-500)",+];// The axis column on the right is part of the margin.const MARGIN = { top: 8, right: 48, bottom: 20, left: 4 };@@ -20,7 +28,6 @@ export default class extends Controller {data: Object,currency: { type: String, default: "USD" },currentLabel: { type: String, default: "Current" },- previousLabel: { type: String, default: "Previous" },};_settledResize = null;@@ -56,18 +63,28 @@ export default class extends Controller {}_install() {- const width = this.element.clientWidth;- const height = this.element.clientHeight;const {days = 30,current_days: currentDays = days,axis_labels: axisLabels = [],current = [],- previous = [],+ comparisons: rawComparisons = [],} = this.dataValue || {};+ const comparisons = rawComparisons.map((comparison, i) => ({+ ...comparison,+ color: COMPARISON_COLORS[i % COMPARISON_COLORS.length],+ }));+ const comparisonPoints = comparisons.flatMap((c) => c.series);++ const maxValue =+ d3.max([...current, ...comparisonPoints], (d) => d.value) || 0;+ if (maxValue <= 0) return;- if (width < 50 || height < 50) return;- if (current.length === 0 && previous.length === 0) return;+ // With one compared month the header already names both lines.+ if (comparisons.length > 1) this._drawLegend(comparisons);++ const width = this.element.clientWidth;+ const height = this.element.clientHeight - this._legendHeight();// Room on the right for the axis labels ($0, $1.5K, …), like the// reference design; the curves run to the axis, not the card edge.@@ -75,6 +92,12 @@ export default class extends Controller {const innerWidth = width - margin.left - margin.right;const innerHeight = height - margin.top - margin.bottom;+ // The legend must be in the DOM to be measured+ if (width < 50 || height < 50 || innerWidth <= 0 || innerHeight <= 0) {+ this._teardown();+ return;+ }+const svg = d3.select(this.element).append("svg")@@ -86,9 +109,6 @@ export default class extends Controller {.append("g").attr("transform", `translate(${margin.left},${margin.top})`);- const maxValue = d3.max([...current, ...previous], (d) => d.value) || 0;- if (maxValue <= 0) return;-const x = d3.scaleLinear().domain([1, days]).range([0, innerWidth]);const y = d3.scaleLinear()@@ -105,13 +125,15 @@ export default class extends Controller {.y((d) => y(d.value)).curve(d3.curveMonotoneX);- // Previous month first so the current month always draws on top.- if (previous.length > 0) {+ // Oldest month first so newer months, and the current month above all,+ // draw on top.+ for (const comparison of [...comparisons].reverse()) {+ if (comparison.series.length === 0) continue;group.append("path")- .datum(previous)+ .datum(comparison.series).attr("fill", "none")- .attr("stroke", PREVIOUS_COLOR)+ .attr("stroke", comparison.color).attr("stroke-width", 1.5).attr("stroke-linejoin", "round").attr("stroke-linecap", "round")@@ -144,12 +166,40 @@ export default class extends Controller {x,y,current,- previous,+ comparisons,innerWidth,innerHeight,);}+ _drawLegend(comparisons) {+ const legend = d3+ .select(this.element)+ .append("div")+ .attr(+ "class",+ "legend flex flex-wrap gap-x-3 gap-y-1 pb-2 text-xs text-secondary",+ );++ for (const { label, color } of [+ { label: this.currentLabelValue, color: CURRENT_COLOR },+ ...comparisons,+ ]) {+ const item = legend+ .append("span")+ .attr("class", "inline-flex items-center gap-1.5");+ item+ .append("span")+ .attr("class", "inline-block w-2 h-2 rounded-full")+ .style("background-color", color);+ item.append("span").text(label);+ }+ }++ _legendHeight() {+ return this.element.querySelector(".legend")?.offsetHeight ?? 0;+ }+_drawGridlines(group, y, innerWidth, innerHeight) {const ticks = y.ticks(4);@@ -219,16 +269,19 @@ export default class extends Controller {);}- _installTooltip(group, x, y, current, previous, innerWidth, innerHeight) {+ _installTooltip(group, x, y, current, comparisons, innerWidth, innerHeight) {const tooltip = d3.select(this.element).append("div").attr("class", `${CHART_TOOLTIP_CLASSES} opacity-0 top-0`);- const currentByDay = new Map(current.map((d) => [d.day, d]));- const previousByDay = new Map(previous.map((d) => [d.day, d]));+ const byDay = (series) => new Map(series.map((d) => [d.day, d]));+ const lines = [+ { label: this.currentLabelValue, color: CURRENT_COLOR, series: current },+ ...comparisons,+ ].map((line) => ({ ...line, pointsByDay: byDay(line.series) }));const hoverDays = [- ...new Set([...currentByDay.keys(), ...previousByDay.keys()]),+ ...new Set(lines.flatMap((line) => [...line.pointsByDay.keys()])),].sort((a, b) => a - b);const bisectDay = d3.bisector((d) => d).center;@@ -245,9 +298,9 @@ export default class extends Controller {const i = bisectDay(hoverDays, dayFloat);const day = hoverDays[Math.max(0, Math.min(i, hoverDays.length - 1))];- const currentPoint = currentByDay.get(day);- const previousPoint = previousByDay.get(day);- const labelPoint = currentPoint || previousPoint;+ const rows = lines+ .map((line) => ({ ...line, point: line.pointsByDay.get(day) }))+ .filter((row) => row.point);const estimatedTooltipWidth = 220;const pageWidth = document.body.clientWidth;@@ -269,11 +322,7 @@ export default class extends Controller {.attr("stroke", "currentColor").attr("stroke-dasharray", "4, 4");- for (const [point, color] of [- [currentPoint, CURRENT_COLOR],- [previousPoint, PREVIOUS_COLOR],- ]) {- if (!point) continue;+ for (const { point, color } of rows) {group.append("circle").attr("class", "data-point-circle")@@ -285,7 +334,7 @@ export default class extends Controller {}tooltip- .html(this._tooltipTemplate(labelPoint, currentPoint, previousPoint))+ .html(this._tooltipTemplate(rows)).style("opacity", 1).style("left", `${adjustedX}px`).style("top", `${event.pageY - 10}px`);@@ -302,22 +351,18 @@ export default class extends Controller {});}- _tooltipTemplate(labelPoint, currentPoint, previousPoint) {- const row = (point, color, label) => {- if (!point) return "";- return `- <div class="flex items-center gap-1.5 text-primary font-medium tabular-nums">- <span class="inline-block w-2 h-2 rounded-full" style="background-color: ${color};"></span>- ${label}: ${this._formatCurrency(point.value)}- </div>- `;- };+ _tooltipTemplate(rows) {+ const row = ({ point, color, label }) => `+ <div class="flex items-center gap-1.5 text-primary font-medium tabular-nums">+ <span class="inline-block w-2 h-2 rounded-full" style="background-color: ${color};"></span>+ ${label}: ${this._formatCurrency(point.value)}+ </div>+ `;return `- <div class="text-xs text-secondary mb-1">${labelPoint.date_formatted}</div>+ <div class="text-xs text-secondary mb-1">${rows[0].point.date_formatted}</div><div class="space-y-1">- ${row(currentPoint, CURRENT_COLOR, this.currentLabelValue)}- ${row(previousPoint, PREVIOUS_COLOR, this.previousLabelValue)}+ ${rows.map(row).join("")}</div>`;}diff --git a/app/views/pages/dashboard/_spending_trend.html.erb b/app/views/pages/dashboard/_spending_trend.html.erbindex 3093aa7870..f9804d8ec0 100644--- a/app/views/pages/dashboard/_spending_trend.html.erb+++ b/app/views/pages/dashboard/_spending_trend.html.erb@@ -3,13 +3,13 @@data = spending_trend_dataperiod = data[:current_period]pill_button_class = "inline-flex items-center gap-1.5 bg-container border border-secondary font-medium rounded-lg pl-3 pr-2 py-2 text-sm cursor-pointer text-primary hover:bg-container-inset-hover focus:outline-hidden focus:ring-0 whitespace-nowrap"- has_data = data[:current].any? { |p| p[:value].positive? } || data[:previous].any? { |p| p[:value].positive? }+ has_data = [ data[:current], *data[:comparisons].map { |c| c[:series] } ].any? { |series| series.any? { |p| p[:value].positive? } }chart_data = {days: data[:days],current_days: data[:current_days],axis_labels: data[:axis_labels],current: data[:current],- previous: data[:previous]+ comparisons: data[:comparisons]}previous_label = data[:previous_label]previous_comparison_day = data[:previous_comparison_day]@@ -52,6 +52,24 @@<% end %><% end %>+ <%= render DS::Menu.new(variant: :button, placement: "bottom-end") do |menu| %>+ <% menu.with_button(type: "button", class: pill_button_class, aria: { label: t(".compare_picker_aria_label") }) do %>+ <span><%= t(".compare_months", count: data[:compare_months]) %></span>+ <%= icon("chevron-down", size: "sm") %>+ <% end %>++ <% PagesController::SPENDING_COMPARE_MONTHS.each do |months| %>+ <% menu.with_item(+ variant: :link,+ text: t(".compare_months", count: months),+ href: root_path(other_view_params.merge(spending_month: data[:month].iso8601, spending_compare_months: (months if months > PagesController::SPENDING_COMPARE_MONTHS.min), spending_category_ids: data[:category_ids]).compact),+ frame: "dashboard_sections",+ selected: months == data[:compare_months],+ data: { turbo_action: "advance" }+ ) %>+ <% end %>+ <% end %>+<%= render layout: "pages/dashboard/filter_popover", locals: {button_text: data[:category_ids] ? t(".filter_categories", count: data[:selected_category_count]) : t(".filter_categories_all"),search_label: t(".search_categories"),@@ -122,8 +140,7 @@data-controller="spending-chart"data-spending-chart-data-value="<%= chart_data.to_json %>"data-spending-chart-currency-value="<%= Current.family.currency %>"- data-spending-chart-current-label-value="<%= I18n.l(data[:month], format: :month_year).capitalize %>"- data-spending-chart-previous-label-value="<%= previous_label %>">+ data-spending-chart-current-label-value="<%= I18n.l(data[:month], format: :month_year).capitalize %>"></div><% else %><div class="w-full h-52 flex items-center justify-center">diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.ymlindex 00431fc605..daffc24a3e 100644--- a/config/locales/views/pages/en.yml+++ b/config/locales/views/pages/en.yml@@ -183,6 +183,10 @@ en:date_range_short: "%{start_date} - %{end_day}, %{year}"date_range_short_single: "%{date}, %{year}"month_picker_aria_label: "Select month"+ compare_picker_aria_label: "Select months to compare"+ compare_months:+ one: "vs last month"+ other: "vs last %{count} months"filter_categories: "Filter categories (%{count})"filter_categories_all: "All categories"search_categories: "Search categories"diff --git a/test/controllers/pages_controller_test.rb b/test/controllers/pages_controller_test.rbindex 6f0c4455f3..270d170674 100644--- a/test/controllers/pages_controller_test.rb+++ b/test/controllers/pages_controller_test.rb@@ -802,7 +802,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestchart = spending_trend_chart_datacurrent = chart.fetch("current")- previous = chart.fetch("previous")+ previous = chart.fetch("comparisons").first.fetch("series")# Both months are past, so the selected month's curve runs its full# length; the previous curve runs its own length unless folded to the@@ -876,7 +876,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestassert_response :okchart = spending_trend_chart_data- previous = chart.fetch("previous")+ previous = chart.fetch("comparisons").first.fetch("series")# The January curve is clipped to February's 28-day axis, with day 31's# spend folded into the final visible point so it still lands on the@@ -910,7 +910,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestassert_response :okchart = spending_trend_chart_data- previous = chart.fetch("previous")+ previous = chart.fetch("comparisons").first.fetch("series")assert_equal 30, chart.fetch("days")assert_equal 30, previous.size@@ -934,8 +934,75 @@ class PagesControllerTest < ActionDispatch::IntegrationTest# truncated on mobile ("Previous mon…").expected_label = I18n.l(previous_month, format: :month_year).capitalizeassert_select "#spending-trend-section p", text: expected_label- chart_element = css_select("[data-controller='spending-chart']").first- assert_equal expected_label, chart_element["data-spending-chart-previous-label-value"]+ assert_equal expected_label, spending_trend_chart_data.fetch("comparisons").first.fetch("label")+ end++ test "dashboard spending trend compares against the previous month by default" do+ account, selected_month, _previous_month = spending_trend_filter_setup+ create_transaction(account: account, name: "Spend", amount: 10, date: selected_month)++ get root_path, params: { spending_month: selected_month.iso8601 }++ assert_response :ok+ assert_equal 1, spending_trend_chart_data.fetch("comparisons").size+ assert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.compare_months", count: 1)+ end++ test "dashboard spending trend overlays the last N months on the chart, keeping the header on the previous month" do+ account, selected_month, previous_month = spending_trend_filter_setup+ create_transaction(account: account, name: "Selected", amount: 10, date: selected_month)+ create_transaction(account: account, name: "Previous", amount: 20, date: previous_month)+ create_transaction(account: account, name: "Two back", amount: 30, date: selected_month - 2.months)+ create_transaction(account: account, name: "Three back", amount: 40, date: selected_month - 3.months)++ get root_path, params: { spending_month: selected_month.iso8601, spending_compare_months: 3 }++ assert_response :ok+ comparisons = spending_trend_chart_data.fetch("comparisons")+ # Newest first, each folded onto the selected month's axis.+ assert_equal (1..3).map { |i| I18n.l(selected_month - i.months, format: :month_year).capitalize }, comparisons.map { |c| c.fetch("label") }+ assert_equal [ 20.0, 30.0, 40.0 ], comparisons.map { |c| c.fetch("series").last.fetch("value") }+ comparisons.each { |c| assert_operator c.fetch("series").size, :<=, selected_month.end_of_month.day }+ assert_equal [ money_text(10), money_text(20) ], spending_trend_header_totals+ assert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.compare_months", count: 3)+ end++ test "dashboard spending trend falls back to the previous month for invalid compare values" do+ account, selected_month, _previous_month = spending_trend_filter_setup+ create_transaction(account: account, name: "Spend", amount: 10, date: selected_month)++ [ "0", "6", "-1", "abc", "2.5" ].each do |value|+ get root_path, params: { spending_month: selected_month.iso8601, spending_compare_months: value }++ assert_response :ok+ assert_equal 1, spending_trend_chart_data.fetch("comparisons").size, "for #{value.inspect}"+ end+ end++ test "dashboard spending trend keeps the compared months across its month links and category filter" do+ account, selected_month, _previous_month = spending_trend_filter_setup+ create_transaction(account: account, name: "Spend", amount: 10, date: selected_month)++ get root_path, params: { spending_month: selected_month.iso8601, spending_compare_months: 3 }++ other_month = selected_month - 1.month+ assert_select "#spending-trend-section a[href='#{root_path(spending_month: other_month.iso8601, spending_compare_months: 3)}']"+ assert_select "#spending-trend-section form input[type='hidden'][name='spending_compare_months'][value='3']"+ # Back to one month drops the param rather than pinning the default.+ assert_select "#spending-trend-section a[href='#{root_path(spending_month: selected_month.iso8601)}']"+ assert_select "#spending-trend-section a[href='#{root_path(spending_month: selected_month.iso8601, spending_compare_months: 5)}']"+ end++ test "dashboard spending trend category filter offers categories from every compared month" do+ account, selected_month, _previous_month = spending_trend_filter_setup+ older = @family.categories.create!(name: "Spending Filter Older Month")+ create_transaction(account: account, name: "Older", amount: 10, date: selected_month - 3.months, category: older)++ get root_path, params: { spending_month: selected_month.iso8601 }+ assert_not_includes spending_trend_category_values, older.id++ get root_path, params: { spending_month: selected_month.iso8601, spending_compare_months: 3 }+ assert_includes spending_trend_category_values, older.idendtest "dashboard spending trend renders a compact date range for mobile" do@@ -984,7 +1051,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestassert_response :okchart = spending_trend_chart_data- previous_series = chart.fetch("previous")+ previous_series = chart.fetch("comparisons").first.fetch("series")aligned = previous_series.fetch(Date.current.day - 1).fetch("value")full_month = previous_series.last.fetch("value")current_value = chart.fetch("current").last.fetch("value")@@ -1034,7 +1101,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestget root_path, params: { spending_month: selected_month.iso8601 }assert_response :ok- previous_series = spending_trend_chart_data.fetch("previous")+ previous_series = spending_trend_chart_data.fetch("comparisons").first.fetch("series")_current_total, previous_total = spending_trend_header_totalsassert_equal previous_month.end_of_month.iso8601, previous_series.last.fetch("date")@@ -1057,7 +1124,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestget root_path, params: { spending_month: selected_month.iso8601 }assert_response :ok- previous_series = spending_trend_chart_data.fetch("previous")+ previous_series = spending_trend_chart_data.fetch("comparisons").first.fetch("series")_current_total, previous_total = spending_trend_header_totals# A month that has fully elapsed is still compared whole-to-whole.@@ -1083,7 +1150,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestget root_path, params: { spending_month: selected_month.iso8601 }assert_response :ok- previous_series = spending_trend_chart_data.fetch("previous")+ previous_series = spending_trend_chart_data.fetch("comparisons").first.fetch("series")_current_total, previous_total = spending_trend_header_totals# Both months are over, so both are compared whole - the selected month@@ -1116,7 +1183,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestget root_path, params: { spending_month: selected_month.iso8601 }assert_response :ok- previous_series = spending_trend_chart_data.fetch("previous")+ previous_series = spending_trend_chart_data.fetch("comparisons").first.fetch("series")_current_total, previous_total = spending_trend_header_totals# There is no day 30 in February: the previous month has fully elapsed, so@@ -1184,7 +1251,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTestchart = spending_trend_chart_dataassert_equal 30.0, chart.fetch("current").last.fetch("value")- assert_equal 20.0, chart.fetch("previous").last.fetch("value")+ assert_equal 20.0, chart.fetch("comparisons").first.fetch("series").last.fetch("value")assert_equal [ money_text(30), money_text(20) ], spending_trend_header_totalsassert_equal money_text(10), spending_trend_header_deltaassert_select "#spending-trend-section button", text: I18n.t("pages.dashboard.spending_trend.filter_categories", count: 1)