Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add a Cash Flow Rings dashboard widget (#4986)

BenTriByte5e7c0282a556
diff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rb
index 4bb70d523f..e2e136d31d 100644
--- a/app/controllers/pages_controller.rb
+++ b/app/controllers/pages_controller.rb
@@ -17,6 +17,7 @@ class PagesController < ApplicationController
"money_flow" => { col_span: "single", grow: false, min_height: 0, width_toggle: true },
"spending_trend" => { col_span: "single", grow: true, min_height: 208, width_toggle: true },
"outflows_donut" => { col_span: "single", grow: false, min_height: 0 },
+ "cashflow_donut" => { col_span: "single", grow: false, min_height: 0 },
"investment_summary" => { col_span: "single", grow: false, min_height: 0, width_toggle: true },
"net_worth_chart" => { col_span: "single", grow: true, min_height: 208, width_toggle: true },
"balance_sheet" => { col_span: "single", grow: false, min_height: 0, width_toggle: true }
@@ -30,7 +31,7 @@ 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, { money_flow_account_ids: [], spending_category_ids: [] } ].freeze
+ 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
# Selectable height presets (px) for grow widgets.
DASHBOARD_HEIGHT_PRESETS = { "compact" => 208, "auto" => 288, "tall" => 416 }.freeze
@@ -229,6 +230,24 @@ class PagesController < ApplicationController
collapsible: true
}
},
+ "cashflow_donut" => -> {
+ accounts = dashboard_income_statement.eligible_accounts
+ {
+ key: "cashflow_donut",
+ title: "pages.dashboard.cashflow_donut.title",
+ partial: "pages/dashboard/cashflow_donut",
+ layout: section_layout("cashflow_donut"),
+ locals: {
+ cashflow_data: build_cashflow_donut_data(dashboard_month_param(:cashflow_month), dashboard_account_ids_param(:cashflow_account_ids, accounts), accounts),
+ accounts: accounts,
+ accessible_account_ids: Current.user.accessible_accounts.pluck(:id).map(&:to_s),
+ view_params: @dashboard_view_params
+ },
+ # Stays visible with no data so the month picker can lead back out.
+ visible: @accounts.any?,
+ collapsible: true
+ }
+ },
"investment_summary" => -> {
{
key: "investment_summary",
@@ -577,6 +596,105 @@ class PagesController < ApplicationController
{ categories: categories, total: total.to_f.round(2), currency: net_totals.currency, currency_symbol: currency_symbol }
end
+ # Two rings on one scale, read like a budget gauge with income as the
+ # budget: unspent income is a muted track on the outflows ring, spending
+ # beyond income is an "over" slice on the inflows ring. Either way both
+ # rings close and the gap between them is the difference.
+ #
+ # Like money_flow, the widget has its own month (capped at today while in
+ # progress) and account filter, independent of the dashboard period.
+ # nil account_ids means every eligible account.
+ def build_cashflow_donut_data(month, account_ids, eligible_accounts)
+ period = Period.custom(start_date: month, end_date: [ month.end_of_month, Date.current ].min)
+ statement = account_ids ? Current.family.income_statement(accounts: eligible_accounts.where(id: account_ids)) : dashboard_income_statement
+ net_totals = statement.net_category_totals(period: period)
+
+ total_income = net_totals.total_net_income
+ total_expense = net_totals.total_net_expense
+ net = total_income - total_expense
+ ring_total = [ total_income, total_expense ].max
+
+ inflows = cashflow_donut_segments(net_totals.net_income_categories, "income", ring_total)
+ outflows = cashflow_donut_segments(net_totals.net_expense_categories, "expense", ring_total)
+ has_categories = inflows.any? || outflows.any?
+
+ # "unused"/"overage" are the donut controller's special segment ids:
+ # colours pass through untouched, unused sorts last and overage first.
+ if net.positive?
+ outflows << cashflow_donut_balance_segment("unused", t("pages.dashboard.cashflow_donut.left"), net, ring_total, "var(--budget-unused-fill)", "piggy-bank", net_totals.currency)
+ elsif net.negative?
+ inflows << cashflow_donut_balance_segment("overage", t("pages.dashboard.cashflow_donut.over"), net.abs, ring_total, "var(--color-destructive)", "trending-down", net_totals.currency)
+ end
+
+ {
+ inflows: inflows,
+ outflows: outflows,
+ has_categories: has_categories,
+ total_income: total_income.to_f.round(2),
+ total_expense: total_expense.to_f.round(2),
+ net: net.to_f.round(2),
+ currency: net_totals.currency,
+ month: month,
+ period: period,
+ account_ids: account_ids
+ }
+ end
+
+ # A widget's own month param, clamped to the current month: a future
+ # month would end before it starts once capped at Date.current, which
+ # Period.custom rejects.
+ def dashboard_month_param(key)
+ current_month = Date.current.beginning_of_month
+ month = Date.strptime(params[key], "%Y-%m-%d").beginning_of_month
+ month > current_month ? current_month : month
+ rescue ArgumentError, TypeError
+ current_month
+ end
+
+ # nil means all of the widget's eligible accounts (its unfiltered state)
+ def dashboard_account_ids_param(key, eligible_accounts)
+ ids = Array(params[key]).reject(&:blank?)
+ ids &= eligible_accounts.map { |a| a.id.to_s }
+ ids.presence
+ end
+
+ # Percentages are shares of the ring (the larger of income and spending),
+ # so they match the arc each segment draws and sum to 100 with the
+ # unused/overage segment.
+ def cashflow_donut_segments(category_totals, id_prefix, ring_total)
+ category_totals
+ .reject { |ct| ct.total.zero? }
+ .sort_by { |ct| -ct.total }
+ .map do |ct|
+ clickable = !ct.category.other_investments?
+ {
+ id: "#{id_prefix}_#{IncomeStatement::CategoryNetting.key(ct.category)}",
+ name: ct.category.name,
+ filter_value: clickable ? ct.category.filter_value : nil,
+ amount: ct.total.to_f.round(2),
+ currency: ct.currency,
+ percentage: ring_total.zero? ? 0 : (ct.total.to_f / ring_total.to_f * 100).round(1),
+ color: ct.category.color.presence || Category::UNCATEGORIZED_COLOR,
+ icon: ct.category.lucide_icon,
+ clickable: clickable
+ }
+ end
+ end
+
+ def cashflow_donut_balance_segment(id, name, amount, ring_total, color, icon, currency)
+ {
+ id: id,
+ name: name,
+ filter_value: nil,
+ amount: amount.to_f.round(2),
+ currency: currency,
+ percentage: ring_total.zero? ? 0 : (amount.to_f / ring_total.to_f * 100).round(1),
+ color: color,
+ icon: icon,
+ clickable: false
+ }
+ end
+
def money_flow_month_param
current_month = Date.current.beginning_of_month
month = Date.strptime(params[:money_flow_month], "%Y-%m-%d").beginning_of_month
diff --git a/app/javascript/controllers/donut_chart_controller.js b/app/javascript/controllers/donut_chart_controller.js
index 7f0ef24d8e..d0bd0cd172 100644
--- a/app/javascript/controllers/donut_chart_controller.js
+++ b/app/javascript/controllers/donut_chart_controller.js
@@ -4,9 +4,17 @@ import { buildCategoryTransactionsUrl } from "utils/transactions_filter_url";
// Connects to data-controller="donut-chart"
export default class extends Controller {
- static targets = ["chartContainer", "contentContainer", "defaultContent", "amount"];
+ static targets = [
+ "chartContainer",
+ "contentContainer",
+ "defaultContent",
+ "amount",
+ ];
static values = {
segments: { type: Array, default: [] },
+ // Concentric rings, outermost first. When present, `segments` is ignored.
+ rings: { type: Array, default: [] },
+ ringGap: { type: Number, default: 1.5 },
unusedSegmentId: { type: String, default: "unused" },
overageSegmentId: { type: String, default: "overage" },
segmentHeight: { type: Number, default: 3 },
@@ -16,6 +24,10 @@ export default class extends Controller {
enableClick: { type: Boolean, default: false },
startDate: String,
endDate: String,
+ accountIds: { type: Array, default: [] },
+ // e.g. ["confirmed"] when the segment amounts exclude pending entries,
+ // so the drill-down lists only what the arc counted.
+ statuses: { type: Array, default: [] },
};
#viewBoxSize = 100;
@@ -37,7 +49,10 @@ export default class extends Controller {
this.#fitAmountTargets();
document.addEventListener("turbo:load", this.#redraw);
this.element.addEventListener("mouseleave", this.#clearSegmentHover);
- this.contentContainerTarget.addEventListener("mouseleave", this.#clearSegmentHover);
+ this.contentContainerTarget.addEventListener(
+ "mouseleave",
+ this.#clearSegmentHover,
+ );
if (typeof ResizeObserver !== "undefined" && this.hasChartContainerTarget) {
this.#resizeObserver = new ResizeObserver(() => this.#fitAmountTargets());
@@ -49,7 +64,10 @@ export default class extends Controller {
this.#teardown();
document.removeEventListener("turbo:load", this.#redraw);
this.element.removeEventListener("mouseleave", this.#clearSegmentHover);
- this.contentContainerTarget.removeEventListener("mouseleave", this.#clearSegmentHover);
+ this.contentContainerTarget.removeEventListener(
+ "mouseleave",
+ this.#clearSegmentHover,
+ );
if (this.#resizeObserver) {
this.#resizeObserver.disconnect();
@@ -57,21 +75,55 @@ export default class extends Controller {
}
}
- get #data() {
- const totalPieValue = this.segmentsValue.reduce(
+ get #rings() {
+ const rings = this.ringsValue.length
+ ? this.ringsValue
+ : [this.segmentsValue];
+ return rings.map((segments) => this.#ringData(segments));
+ }
+
+ get #ringCount() {
+ return this.ringsValue.length || 1;
+ }
+
+ // Radial depth taken up by every ring plus the gaps between them.
+ get #ringDepth() {
+ return (
+ this.#ringCount * this.segmentHeightValue +
+ (this.#ringCount - 1) * this.ringGapValue
+ );
+ }
+
+ #ringData(segments) {
+ const totalPieValue = segments.reduce(
(acc, s) => acc + Number(s.amount),
0,
);
+ const minAmount = totalPieValue * (this.#minSegmentAngle / (2 * Math.PI));
+ const visible = segments.filter((s) => s.amount > 0);
+
+ // Tiny segments are widened so they stay visible. With several rings on
+ // one scale the other segments shrink to absorb that widening, so every
+ // ring still closes at its real total and the rings stay comparable.
+ const widenedCount = visible.filter(
+ (s) => Number(s.amount) < minAmount,
+ ).length;
+ const keptTotal = visible.reduce(
+ (acc, s) => acc + (Number(s.amount) < minAmount ? 0 : Number(s.amount)),
+ 0,
+ );
+ const absorbedTotal = totalPieValue - widenedCount * minAmount;
+ const shrink =
+ this.ringsValue.length && keptTotal > 0 && absorbedTotal > 0
+ ? absorbedTotal / keptTotal
+ : 1;
// Overage is always first segment, unused is always last segment
- return this.segmentsValue
- .filter((s) => s.amount > 0)
+ return visible
.map((s) => ({
...s,
- amount: Math.max(
- Number(s.amount),
- totalPieValue * (this.#minSegmentAngle / (2 * Math.PI)),
- ),
+ amount:
+ Number(s.amount) < minAmount ? minAmount : Number(s.amount) * shrink,
}))
.sort((a, b) => {
if (a.id === this.overageSegmentIdValue) return -1;
@@ -109,13 +161,6 @@ export default class extends Controller {
.sortValues(null) // Preserve order of segments
.value((d) => d.amount);
- const mainArc = d3
- .arc()
- .innerRadius(this.#viewBoxSize / 2 - this.segmentHeightValue)
- .outerRadius(this.#viewBoxSize / 2)
- .cornerRadius(this.segmentHeightValue)
- .padAngle(this.#padAngle);
-
const g = svg
.append("g")
.attr(
@@ -123,47 +168,81 @@ export default class extends Controller {
`translate(${this.#viewBoxSize / 2}, ${this.#viewBoxSize / 2})`,
);
- const segmentGroups = g
- .selectAll("arc")
- .data(pie(this.#data))
- .enter()
- .append("g")
- .attr("class", "arc pointer-events-auto");
+ const rings = this.#rings;
+ const ringStep = this.segmentHeightValue + this.ringGapValue;
+ // Hover areas between rings share the gap so neither ring claims the other's pointer events.
+ const betweenRingsExtension = Math.min(
+ this.hoverExtensionValue,
+ this.ringGapValue / 2,
+ );
+
+ rings.forEach((data, ringIndex) => {
+ const outerRadius = this.#viewBoxSize / 2 - ringIndex * ringStep;
+ const innerRadius = outerRadius - this.segmentHeightValue;
- // Add invisible hover paths with extended area if enabled
- if (this.extendedHoverValue) {
- const hoverArc = d3
+ const mainArc = d3
.arc()
- .innerRadius(this.#viewBoxSize / 2 - this.segmentHeightValue - this.hoverExtensionValue)
- .outerRadius(this.#viewBoxSize / 2 + this.hoverExtensionValue)
+ .innerRadius(innerRadius)
+ .outerRadius(outerRadius)
+ .cornerRadius(this.segmentHeightValue)
.padAngle(this.#padAngle);
- segmentGroups
+ const segmentGroups = g
+ .append("g")
+ .attr("class", "ring")
+ .selectAll("arc")
+ .data(pie(data))
+ .enter()
+ .append("g")
+ .attr("class", "arc pointer-events-auto");
+
+ // Add invisible hover paths with extended area if enabled
+ if (this.extendedHoverValue) {
+ const outerExtension =
+ ringIndex === 0 ? this.hoverExtensionValue : betweenRingsExtension;
+ const innerExtension =
+ ringIndex === rings.length - 1
+ ? this.hoverExtensionValue
+ : betweenRingsExtension;
+ const hoverArc = d3
+ .arc()
+ .innerRadius(innerRadius - innerExtension)
+ .outerRadius(outerRadius + outerExtension)
+ .padAngle(this.#padAngle);
+
+ segmentGroups
+ .append("path")
+ .attr("class", "hover-path")
+ .attr("d", hoverArc)
+ .attr("fill", "transparent")
+ .attr("data-segment-id", (d) => d.data.id)
+ .style("pointer-events", "all");
+ }
+
+ // Add visible paths
+ const segmentArcs = segmentGroups
.append("path")
- .attr("class", "hover-path")
- .attr("d", hoverArc)
- .attr("fill", "transparent")
+ .attr("class", "visible-path")
.attr("data-segment-id", (d) => d.data.id)
- .style("pointer-events", "all");
- }
+ .attr("data-original-color", this.#transformRingColor)
+ .attr("fill", this.#transformRingColor)
+ .attr("d", mainArc);
- // Add visible paths
- const segmentArcs = segmentGroups
- .append("path")
- .attr("class", "visible-path")
- .attr("data-segment-id", (d) => d.data.id)
- .attr("data-original-color", this.#transformRingColor)
- .attr("fill", this.#transformRingColor)
- .attr("d", mainArc);
-
- // Disable pointer events on visible paths if extended hover is enabled
- if (this.extendedHoverValue) {
- segmentArcs.style("pointer-events", "none");
- }
+ // Disable pointer events on visible paths if extended hover is enabled
+ if (this.extendedHoverValue) {
+ segmentArcs.style("pointer-events", "none");
+ }
+
+ this.#bindSegmentEvents(segmentGroups);
+ });
// Cache the visible paths selection for performance
- this.#visiblePaths = d3.select(this.chartContainerTarget).selectAll("path.visible-path");
+ this.#visiblePaths = d3
+ .select(this.chartContainerTarget)
+ .selectAll("path.visible-path");
+ }
+ #bindSegmentEvents(segmentGroups) {
// Ensures that user can click on default content without triggering hover on a segment if that is their intent
let hoverTimeout = null;
@@ -177,7 +256,10 @@ export default class extends Controller {
.on("mouseleave", (event, d) => {
clearTimeout(hoverTimeout);
const leavingUnused = d.data.id === this.unusedSegmentIdValue;
- if (leavingUnused || !this.contentContainerTarget.contains(event.relatedTarget)) {
+ if (
+ leavingUnused ||
+ !this.contentContainerTarget.contains(event.relatedTarget)
+ ) {
this.#clearSegmentHover();
}
})
@@ -194,6 +276,9 @@ export default class extends Controller {
}
const reducedOpacityColor = d3.color(color);
+ // CSS variables can't be parsed, so they reach the fill as written.
+ if (!reducedOpacityColor) return color;
+
reducedOpacityColor.opacity = this.segmentOpacityValue;
return reducedOpacityColor;
};
@@ -207,7 +292,9 @@ export default class extends Controller {
if (!template) return;
// Use cached selection if available for better performance
- const paths = this.#visiblePaths || d3.select(this.chartContainerTarget).selectAll("path.visible-path");
+ const paths =
+ this.#visiblePaths ||
+ d3.select(this.chartContainerTarget).selectAll("path.visible-path");
paths.attr("fill", function () {
if (this.dataset.segmentId === segmentId) {
@@ -234,7 +321,9 @@ export default class extends Controller {
this.defaultContentTarget.classList.remove("hidden");
// Use cached selection if available for better performance
- const paths = this.#visiblePaths || d3.select(this.chartContainerTarget).selectAll("path.visible-path");
+ const paths =
+ this.#visiblePaths ||
+ d3.select(this.chartContainerTarget).selectAll("path.visible-path");
paths
.attr("fill", function () {
@@ -258,6 +347,8 @@ export default class extends Controller {
filterValue: segment.filter_value,
startDate: this.startDateValue,
endDate: this.endDateValue,
+ accountIds: this.accountIdsValue,
+ statuses: this.statusesValue,
}),
);
}
@@ -267,16 +358,20 @@ export default class extends Controller {
const segmentId = event.currentTarget.dataset.categoryId;
// Use cached selection if available for better performance
- const paths = this.#visiblePaths || d3.select(this.chartContainerTarget).selectAll("path.visible-path");
+ const paths =
+ this.#visiblePaths ||
+ d3.select(this.chartContainerTarget).selectAll("path.visible-path");
- paths.style("opacity", function() {
+ paths.style("opacity", function () {
return this.dataset.segmentId === segmentId ? 1 : 0.3;
});
}
unhighlightSegment() {
// Use cached selection if available for better performance
- const paths = this.#visiblePaths || d3.select(this.chartContainerTarget).selectAll("path.visible-path");
+ const paths =
+ this.#visiblePaths ||
+ d3.select(this.chartContainerTarget).selectAll("path.visible-path");
paths.style("opacity", null); // Clear inline opacity style
}
@@ -298,8 +393,9 @@ export default class extends Controller {
if (containerSize <= 0) return;
const innerDiameterRatio =
- (this.#viewBoxSize - 2 * this.segmentHeightValue) / this.#viewBoxSize;
- const availableWidth = containerSize * innerDiameterRatio * this.#innerRingTextWidthRatio;
+ (this.#viewBoxSize - 2 * this.#ringDepth) / this.#viewBoxSize;
+ const availableWidth =
+ containerSize * innerDiameterRatio * this.#innerRingTextWidthRatio;
if (availableWidth <= 0) return;
const targets = scope
diff --git a/app/javascript/utils/transactions_filter_url.mjs b/app/javascript/utils/transactions_filter_url.mjs
index d58d925247..b4290b9ef0 100644
--- a/app/javascript/utils/transactions_filter_url.mjs
+++ b/app/javascript/utils/transactions_filter_url.mjs
@@ -6,8 +6,9 @@ export function isNavigableCategoryNode(id) {
}
// Builds a relative deep link to the transactions index, filtered by a single
-// category and (optionally) a start/end date range. Mirrors the params the
-// transactions search form submits: q[categories][], q[start_date], q[end_date].
+// category and (optionally) a start/end date range, account ids and statuses.
+// Mirrors the params the transactions search form submits: q[categories][],
+// q[start_date], q[end_date], q[account_ids][], q[status][].
//
// filterValue must be the category's stable filter value (Category#filter_value:
// the persisted name for a real category, or Category::UNCATEGORIZED_FILTER_VALUE
@@ -18,11 +19,15 @@ export function buildCategoryTransactionsUrl({
filterValue,
startDate,
endDate,
+ accountIds = [],
+ statuses = [],
basePath = "/transactions",
}) {
const params = new URLSearchParams();
params.append("q[categories][]", filterValue);
if (startDate) params.append("q[start_date]", startDate);
if (endDate) params.append("q[end_date]", endDate);
+ for (const id of accountIds) params.append("q[account_ids][]", id);
+ for (const status of statuses) params.append("q[status][]", status);
return `${basePath}?${params.toString()}`;
}
diff --git a/app/views/pages/dashboard/_cashflow_donut.html.erb b/app/views/pages/dashboard/_cashflow_donut.html.erb
new file mode 100644
index 0000000000..79d4c991cd
--- /dev/null
+++ b/app/views/pages/dashboard/_cashflow_donut.html.erb
@@ -0,0 +1,212 @@
+<%# locals: (cashflow_data:, accounts:, accessible_account_ids:, view_params:) %>
+<%
+ pill_button_class = "inline-flex items-center gap-1.5 bg-container border border-secondary font-medium rounded-lg pl-3 pr-2 py-2 text-sm cursor-pointer text-primary hover:bg-container-inset-hover focus:outline-hidden focus:ring-0 whitespace-nowrap"
+ selected_account_ids = cashflow_data[:account_ids] || accounts.map { |a| a.id.to_s }
+ all_accounts_selected = selected_account_ids.size == accounts.size
+ # TransactionsController falls back to the user's full accessible-accounts
+ # set (broader than this widget's eligible accounts) when account_ids is
+ # absent, so the param can only be dropped when that default matches this
+ # widget's selection exactly.
+ drilldown_account_ids = selected_account_ids.sort == accessible_account_ids.sort ? nil : selected_account_ids
+ period = cashflow_data[:period]
+ # The ring amounts exclude pending entries (IncomeStatement scopes to
+ # excluding_pending), so both drill-down paths filter to confirmed too.
+ drilldown_statuses = [ "confirmed" ]
+ # The other widgets' months and filters, carried through this widget's
+ # links and form so changing it doesn't reset them.
+ other_view_params = view_params.except(:cashflow_month, :cashflow_account_ids)
+ groups = [
+ { key: "inflows", label: t(".inflows"), segments: cashflow_data[:inflows], total: cashflow_data[:total_income] },
+ { key: "outflows", label: t(".outflows"), segments: cashflow_data[:outflows], total: cashflow_data[:total_expense] }
+ ]
+ all_segments = cashflow_data[:inflows] + cashflow_data[:outflows]
+%>
+<div id="cashflow-donut-section" class="@container px-4 space-y-4">
+ <div class="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-3">
+ <p class="text-sm text-secondary">
+ <%= t(".date_range", start_date: l(period.date_range.begin, format: :long), end_date: l(period.date_range.end, format: :long)) %>
+ </p>
+
+ <div class="flex items-center gap-2">
+ <%= render DS::Tooltip.new(text: t(".period_scope_hint"), placement: "top-start") %>
+
+ <%= render DS::Menu.new(variant: :button, placement: "bottom-end", max_height: "18rem") do |menu| %>
+ <% menu.with_button(type: "button", class: pill_button_class, aria: { label: t(".month_picker_aria_label") }) do %>
+ <span class="capitalize"><%= I18n.l(cashflow_data[:month], format: :month_year) %></span>
+ <%= icon("chevron-down", size: "sm") %>
+ <% end %>
+
+ <% (0..11).each do |i| %>
+ <% month = Date.current.beginning_of_month - i.months %>
+ <% menu.with_item(
+ variant: :link,
+ text: I18n.l(month, format: :month_year).capitalize,
+ href: root_path(other_view_params.merge(cashflow_month: month.iso8601, cashflow_account_ids: cashflow_data[:account_ids]).compact),
+ frame: "dashboard_sections",
+ selected: month == cashflow_data[:month],
+ data: { turbo_action: "advance" }
+ ) %>
+ <% end %>
+ <% end %>
+
+ <%= render layout: "pages/dashboard/filter_popover", locals: {
+ button_text: all_accounts_selected ? t(".filter_accounts_all") : t(".filter_accounts", count: selected_account_ids.size),
+ search_label: t(".search_accounts"),
+ apply_text: t(".apply"),
+ hidden_fields: other_view_params.merge(cashflow_month: cashflow_data[:month].iso8601)
+ } do %>
+ <% accounts.each do |account| %>
+ <%= render layout: "pages/dashboard/filter_popover_option", locals: {
+ name: "cashflow_account_ids[]",
+ value: account.id,
+ checked: selected_account_ids.include?(account.id.to_s),
+ filter_name: account.name
+ } do %>
+ <span class="text-sm text-primary truncate"><%= account.name %></span>
+ <% end %>
+ <% end %>
+ <% end %>
+ </div>
+ </div>
+
+ <% if cashflow_data[:has_categories] %>
+ <%# The donut controller wraps the lists as well as the chart: the rows'
+ hover actions highlight ring segments, and Stimulus only binds
+ actions inside the controller's own element. %>
+ <div class="flex flex-col @2xl:flex-row gap-8 items-center"
+ data-controller="donut-chart"
+ data-donut-chart-rings-value="<%= [ cashflow_data[:inflows], cashflow_data[:outflows] ].to_json %>"
+ data-donut-chart-segment-opacity-value="0.9"
+ data-donut-chart-extended-hover-value="true"
+ data-donut-chart-hover-extension-value="3"
+ data-donut-chart-enable-click-value="true"
+ data-donut-chart-start-date-value="<%= period.date_range.first %>"
+ data-donut-chart-end-date-value="<%= period.date_range.last %>"
+ data-donut-chart-account-ids-value="<%= (drilldown_account_ids || []).to_json %>"
+ data-donut-chart-statuses-value="<%= drilldown_statuses.to_json %>">
+ <!-- Donut Chart: outer ring inflows, inner ring outflows -->
+ <div class="w-full @2xl:w-1/3 max-w-75 px-4">
+ <div class="h-75 relative">
+ <div data-donut-chart-target="chartContainer" class="absolute inset-0 pointer-events-none"></div>
+
+ <div data-donut-chart-target="contentContainer" class="flex justify-center items-center h-full">
+ <div data-donut-chart-target="defaultContent" class="flex flex-col items-center">
+ <div class="text-secondary text-sm mb-2">
+ <span><%= t(".spent") %></span>
+ </div>
+
+ <div data-donut-chart-target="amount" class="text-3xl font-medium text-primary privacy-sensitive whitespace-nowrap">
+ <%= format_money Money.new(cashflow_data[:total_expense], cashflow_data[:currency]) %>
+ </div>
+
+ <p class="text-sm text-secondary privacy-sensitive whitespace-nowrap mt-1">
+ <%= t(".of_income", amount: format_money(Money.new(cashflow_data[:total_income], cashflow_data[:currency]))) %>
+ </p>
+
+ <% if cashflow_data[:net].negative? %>
+ <p class="text-sm font-medium text-destructive privacy-sensitive whitespace-nowrap mt-2">
+ <%= t(".over_amount", amount: format_money(Money.new(cashflow_data[:net].abs, cashflow_data[:currency]))) %>
+ </p>
+ <% else %>
+ <p class="text-sm font-medium text-success privacy-sensitive whitespace-nowrap mt-2">
+ <%= t(".left_amount", amount: format_money(Money.new(cashflow_data[:net], cashflow_data[:currency]))) %>
+ </p>
+ <% end %>
+ </div>
+
+ <% all_segments.each do |segment| %>
+ <div id="segment_<%= segment[:id] %>" class="hidden">
+ <div class="flex flex-col gap-2 items-center">
+ <p class="text-sm text-secondary"><%= segment[:name] %></p>
+
+ <p data-donut-chart-target="amount" class="text-3xl font-medium text-primary privacy-sensitive whitespace-nowrap">
+ <%= format_money Money.new(segment[:amount], segment[:currency]) %>
+ </p>
+
+ <p class="text-sm text-secondary privacy-sensitive"><%= segment[:percentage] %>%</p>
+ </div>
+ </div>
+ <% end %>
+ </div>
+ </div>
+ </div>
+
+ <!-- Inflow and outflow lists -->
+ <div class="w-full @2xl:w-2/3 bg-container-inset rounded-xl p-1 space-y-1 overflow-x-auto">
+ <% groups.each do |group| %>
+ <div class="px-4 py-2 flex items-center uppercase text-xs font-medium text-secondary">
+ <div class="w-16 @2xl:w-40">
+ <p><%= group[:label] %><span class="text-subdued mx-1">&middot;</span><%= group[:segments].size %></p>
+ </div>
+ <div class="ml-auto text-right flex items-center gap-6">
+ <div class="w-16 @2xl:w-40">
+ <p class="privacy-sensitive normal-case text-primary"><%= format_money Money.new(group[:total], cashflow_data[:currency]) %></p>
+ </div>
+ <div class="w-16">
+ <p><%= t(".weight") %></p>
+ </div>
+ </div>
+ </div>
+ <% if group[:segments].any? %>
+ <div class="py-3 shadow-border-xs rounded-lg bg-container font-medium text-sm max-w-full">
+ <% group[:segments].each_with_index do |segment, idx| %>
+ <%
+ segment_content = capture do
+ %>
+ <div class="flex items-center gap-3 flex-1 min-w-0">
+ <div class="h-7 w-7 flex-shrink-0 group-hover:scale-105 transition-all duration-300 rounded-full flex justify-center items-center"
+ style="
+ background-color: color-mix(in oklab, <%= segment[:color] %> 10%, transparent);
+ border-color: color-mix(in oklab, <%= segment[:color] %> 10%, transparent);
+ color: <%= segment[:color] %>;">
+ <% if segment[:icon] %>
+ <%= icon(segment[:icon], color: "current", size: "sm") %>
+ <% else %>
+ <%= render DS::FilledIcon.new(
+ variant: :text,
+ hex_color: segment[:color],
+ text: segment[:name],
+ size: "sm",
+ rounded: true
+ ) %>
+ <% end %>
+ </div>
+ <span class="text-sm font-medium text-primary truncate"><%= segment[:name] %></span>
+ </div>
+ <div class="flex items-center gap-4 flex-shrink-0 text-right">
+ <span class="text-sm font-medium text-primary whitespace-nowrap privacy-sensitive"><%= format_money Money.new(segment[:amount], segment[:currency]) %></span>
+ <span class="text-sm text-secondary whitespace-nowrap w-10 @2xl:w-15 privacy-sensitive"><%= segment[:percentage] %>%</span>
+ </div>
+ <% end %>
+
+ <% if segment[:clickable] %>
+ <%= link_to transactions_path(q: { categories: [ segment[:filter_value] ], status: drilldown_statuses, start_date: period.date_range.first, end_date: period.date_range.last, account_ids: drilldown_account_ids }.compact),
+ class: "flex items-center justify-between mx-3 p-3 rounded-lg cursor-pointer group gap-3",
+ data: {
+ turbo_frame: "_top",
+ turbo_prefetch: false,
+ category_id: segment[:id],
+ action: "mouseenter->donut-chart#highlightSegment mouseleave->donut-chart#unhighlightSegment"
+ } do %>
+ <%= segment_content %>
+ <% end %>
+ <% else %>
+ <div class="flex items-center justify-between mx-3 p-3 rounded-lg group gap-3"
+ data-category-id="<%= segment[:id] %>"
+ data-action="mouseenter->donut-chart#highlightSegment mouseleave->donut-chart#unhighlightSegment">
+ <%= segment_content %>
+ </div>
+ <% end %>
+ <% if idx < group[:segments].size - 1 %>
+ <%= render "shared/ruler", classes: "mx-3 @2xl:mx-4" %>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ </div>
+ <% else %>
+ <p class="text-sm text-secondary text-center py-8"><%= t(".no_data") %></p>
+ <% end %>
+</div>
diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.yml
index 68200a55e9..00431fc605 100644
--- a/config/locales/views/pages/en.yml
+++ b/config/locales/views/pages/en.yml
@@ -132,6 +132,25 @@ en:
categories: "Categories"
value: "Value"
weight: "Weight"
+ cashflow_donut:
+ title: "Cash Flow Rings"
+ date_range: "%{start_date} to %{end_date}"
+ month_picker_aria_label: "Select month"
+ filter_accounts: "Filter accounts (%{count})"
+ filter_accounts_all: "All accounts"
+ period_scope_hint: "Shows the month you pick here — independent of the dashboard's time period at the top."
+ search_accounts: "Search accounts"
+ apply: "Apply"
+ no_data: "No cash flow for this month"
+ spent: "Spent"
+ of_income: "of %{amount} income"
+ left_amount: "%{amount} left"
+ over_amount: "%{amount} over"
+ left: "Left to spend"
+ over: "Over income"
+ inflows: "Inflows"
+ outflows: "Outflows"
+ weight: "Weight"
investment_summary:
title: "Investments"
total_return: "Total Return"
diff --git a/test/controllers/pages_controller_test.rb b/test/controllers/pages_controller_test.rb
index e2d214dee0..5aa310363c 100644
--- a/test/controllers/pages_controller_test.rb
+++ b/test/controllers/pages_controller_test.rb
@@ -245,7 +245,7 @@ class PagesControllerTest < ActionDispatch::IntegrationTest
end
test "dashboard skips the data queries of hidden widgets" do
- %w[cashflow_sankey outflows_donut money_flow spending_trend].each { |key| @user.update_dashboard_section_hidden(key, true) }
+ %w[cashflow_sankey outflows_donut cashflow_donut money_flow spending_trend].each { |key| @user.update_dashboard_section_hidden(key, true) }
IncomeStatement.any_instance.expects(:income_totals).never
IncomeStatement.any_instance.expects(:expense_totals).never
IncomeStatement.any_instance.expects(:net_category_totals).never
@@ -278,6 +278,10 @@ class PagesControllerTest < ActionDispatch::IntegrationTest
end
test "dashboard memoizes income statement period totals while rendering" do
+ # The cash flow rings have their own month, so they legitimately build a
+ # second period's totals; only the widgets sharing the dashboard period
+ # are under test here.
+ @user.update_dashboard_section_hidden("cashflow_donut", true)
income_statement = IncomeStatement.new(@family)
IncomeStatement.stubs(:new).returns(income_statement)
@@ -339,6 +343,116 @@ class PagesControllerTest < ActionDispatch::IntegrationTest
assert_select "[data-controller='sankey-chart']"
end
+ test "dashboard renders the cash flow rings with unspent income as a muted track on the outflows ring" do
+ create_transaction(account: @family.accounts.first, name: "Salary", amount: -100_000, category: categories(:income))
+ create_transaction(account: @family.accounts.first, name: "Groceries", amount: 100, category: categories(:food_and_drink))
+ create_transaction(account: @family.accounts.first, name: "Cash withdrawal", amount: 50)
+
+ get root_path
+
+ assert_response :ok
+ assert_select "#cashflow-donut-section"
+ assert_select "#segment_unused"
+ assert_select "#segment_overage", count: 0
+ assert_select "#cashflow-donut-section [data-donut-chart-target='defaultContent']", text: /Spent.*of .* income.* left/m
+
+ inflows, outflows = cashflow_donut_rings
+ assert inflows.any? { |s| s["id"] == "income_#{categories(:income).id}" }
+ assert outflows.any? { |s| s["id"] == "expense_uncategorized" }, "synthetic categories use their invariant key, not a localized name"
+ assert_equal "unused", outflows.last["id"]
+ assert_nil outflows.last["filter_value"]
+ assert_in_delta inflows.sum { |s| s["amount"] }, outflows.sum { |s| s["amount"] }, 0.01
+ # Percentages are shares of the common ring, so each ring's sum to 100.
+ assert_in_delta 100, inflows.sum { |s| s["percentage"] }, 1
+ assert_in_delta 100, outflows.sum { |s| s["percentage"] }, 1
+ end
+
+ test "dashboard renders the cash flow rings with overspend as an overage slice on the inflows ring" do
+ create_transaction(account: @family.accounts.first, name: "Salary", amount: -100, category: categories(:income))
+ create_transaction(account: @family.accounts.first, name: "Rent", amount: 100_000, category: categories(:food_and_drink))
+
+ get root_path
+
+ assert_response :ok
+ assert_select "#segment_overage"
+ assert_select "#segment_unused", count: 0
+ assert_select "#cashflow-donut-section [data-donut-chart-target='defaultContent']", text: /over/
+
+ inflows, outflows = cashflow_donut_rings
+ assert_equal "overage", inflows.last["id"]
+ assert_in_delta inflows.sum { |s| s["amount"] }, outflows.sum { |s| s["amount"] }, 0.01
+ end
+
+ test "dashboard scopes the cash flow rings to the selected month and accounts" do
+ account = @family.accounts.create!(name: "Rings Test Checking", currency: @family.currency, balance: 0, accountable: Depository.new)
+ other_account = @family.accounts.create!(name: "Rings Other Checking", currency: @family.currency, balance: 0, accountable: Depository.new)
+ other_category = @family.categories.create!(name: "Rings Other Category", color: "#123456")
+ selected_month = 1.month.ago.beginning_of_month.to_date
+ create_transaction(account: account, name: "Paycheck", amount: -3_000, date: selected_month + 1.day, category: categories(:income))
+ create_transaction(account: account, name: "Groceries", amount: 500, date: selected_month + 2.days, category: categories(:food_and_drink))
+ create_transaction(account: other_account, name: "Elsewhere", amount: 999, date: selected_month + 3.days, category: other_category)
+ create_transaction(account: account, name: "This month", amount: 777, date: Date.current, category: other_category)
+
+ get root_path, params: { cashflow_month: selected_month.iso8601, cashflow_account_ids: [ account.id ] }
+
+ assert_response :ok
+ inflows, outflows = cashflow_donut_rings
+ assert_equal 3000.0, inflows.find { |s| s["id"] == "income_#{categories(:income).id}" }["amount"]
+ assert_equal 500.0, outflows.find { |s| s["id"] == "expense_#{categories(:food_and_drink).id}" }["amount"]
+ assert_nil outflows.find { |s| s["id"] == "expense_#{other_category.id}" }, "other account's and other month's spending must be excluded"
+ assert_select "#cashflow-donut-section a[href*='account_ids%5D%5B%5D=#{account.id}']"
+ assert_select "#cashflow-donut-section [data-donut-chart-account-ids-value='#{[ account.id.to_s ].to_json}']"
+ end
+
+ test "the cash flow rings' drill-downs only list confirmed transactions, like the ring amounts" do
+ create_transaction(account: @family.accounts.first, name: "Salary", amount: -1_000, category: categories(:income))
+ create_transaction(account: @family.accounts.first, name: "Groceries", amount: 100, category: categories(:food_and_drink))
+
+ get root_path
+
+ assert_response :ok
+ assert_select "#cashflow-donut-section a[href*='q%5Bcategories%5D%5B%5D=#{CGI.escape(categories(:food_and_drink).filter_value)}'][href*='q%5Bstatus%5D%5B%5D=confirmed']"
+ assert_select "#cashflow-donut-section [data-donut-chart-statuses-value='#{[ "confirmed" ].to_json}']"
+ end
+
+ test "dashboard keeps the cash flow rings' controls when the selection has no data" do
+ empty_account = @family.accounts.create!(name: "Rings Empty Checking", currency: @family.currency, balance: 0, accountable: Depository.new)
+
+ get root_path, params: { cashflow_account_ids: [ empty_account.id ] }
+
+ assert_response :ok
+ assert_select "#cashflow-donut-section [data-controller='donut-chart']", count: 0
+ assert_select "#cashflow-donut-section", text: /#{I18n.t("pages.dashboard.cashflow_donut.no_data")}/
+ assert_select "#cashflow-donut-section form input[name='cashflow_account_ids[]']"
+ end
+
+ test "the cash flow rings' controls keep the other widgets' months and filters, and vice versa" do
+ account = accounts(:depository)
+ category = categories(:food_and_drink)
+ money_flow_month, cashflow_month, other_month = (1..3).map { |i| i.months.ago.beginning_of_month.to_date.iso8601 }
+
+ get root_path(money_flow_month: money_flow_month, money_flow_account_ids: [ account.id ], spending_category_ids: [ category.id ],
+ cashflow_month: cashflow_month, cashflow_account_ids: [ account.id ])
+ assert_response :ok
+
+ assert_select "#cashflow-donut-section form input[type='hidden'][name='money_flow_month'][value='#{money_flow_month}']"
+ assert_select "#cashflow-donut-section form input[type='hidden'][name='money_flow_account_ids[]'][value='#{account.id}']"
+ assert_select "#cashflow-donut-section form input[type='hidden'][name='spending_category_ids[]'][value='#{category.id}']"
+ assert_select "#cashflow-donut-section form input[type='hidden'][name='cashflow_account_ids[]']", count: 0
+
+ assert_select "#money-flow-section form input[type='hidden'][name='cashflow_month'][value='#{cashflow_month}']"
+ assert_select "#money-flow-section form input[type='hidden'][name='cashflow_account_ids[]'][value='#{account.id}']"
+
+ link = dashboard_link_params("#cashflow-donut-section a[href*='cashflow_month=#{other_month}']")
+ assert_equal money_flow_month, link["money_flow_month"]
+ assert_equal [ account.id ], link["cashflow_account_ids"]
+ end
+
+ def cashflow_donut_rings
+ chart = css_select("#cashflow-donut-section [data-controller='donut-chart']").first
+ JSON.parse(chart["data-donut-chart-rings-value"])
+ end
+
test "dashboard renders sankey chart zoom controls and stable node ids" do
parent_category = @family.categories.create!(name: "Shopping", color: "#FF5733")
subcategory = @family.categories.create!(name: "Groceries", parent: parent_category, color: "#33FF57")
diff --git a/test/javascript/utils/transactions_filter_url_test.mjs b/test/javascript/utils/transactions_filter_url_test.mjs
index 7406a9c051..809ed89b7a 100644
--- a/test/javascript/utils/transactions_filter_url_test.mjs
+++ b/test/javascript/utils/transactions_filter_url_test.mjs
@@ -48,6 +48,20 @@ test("passes the Uncategorized sentinel through unchanged, not a display name",
assert.match(url, /q%5Bcategories%5D%5B%5D=__uncategorized__/);
});
+test("appends account ids and statuses as array params", () => {
+ const url = buildCategoryTransactionsUrl({
+ filterValue: "Groceries",
+ startDate: "2026-05-01",
+ endDate: "2026-05-31",
+ accountIds: ["1", "2"],
+ statuses: ["confirmed"],
+ });
+ assert.equal(
+ url,
+ "/transactions?q%5Bcategories%5D%5B%5D=Groceries&q%5Bstart_date%5D=2026-05-01&q%5Bend_date%5D=2026-05-31&q%5Baccount_ids%5D%5B%5D=1&q%5Baccount_ids%5D%5B%5D=2&q%5Bstatus%5D%5B%5D=confirmed",
+ );
+});
+
test("omits date params when dates are blank", () => {
const url = buildCategoryTransactionsUrl({
filterValue: "Groceries",
diff --git a/test/system/dashboard_cashflow_donut_test.rb b/test/system/dashboard_cashflow_donut_test.rb
new file mode 100644
index 0000000000..0457132be7
--- /dev/null
+++ b/test/system/dashboard_cashflow_donut_test.rb
@@ -0,0 +1,33 @@
+require "application_system_test_case"
+
+class DashboardCashflowDonutTest < ApplicationSystemTestCase
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ account = @user.family.accounts.first
+ create_transaction(account: account, name: "Salary", amount: -100_000, category: categories(:income))
+ create_transaction(account: account, name: "Groceries", amount: 100, category: categories(:food_and_drink))
+ end
+
+ test "draws inflows and outflows as two concentric rings with unspent income closing the inner ring" do
+ sign_in @user
+
+ within "#cashflow-donut-section" do
+ rings = all("g.ring", visible: :all)
+ assert_equal 2, rings.size
+
+ assert rings.first.has_css?("path.visible-path[data-segment-id='income_#{categories(:income).id}']", visible: :all)
+ assert rings.last.has_no_css?("path.visible-path[data-segment-id='income_#{categories(:income).id}']", visible: :all)
+ assert rings.last.has_css?("path.visible-path[data-segment-id='unused']", visible: :all)
+ assert_text "Spent"
+ assert_text "left"
+
+ # Hovering a list row highlights its segment and dims the rest.
+ food_id = "expense_#{categories(:food_and_drink).id}"
+ find("[data-category-id='#{food_id}']").hover
+ assert_selector "path.visible-path[data-segment-id='#{food_id}'][style*='opacity: 1']", visible: :all
+ assert_selector "path.visible-path[data-segment-id='unused'][style*='opacity: 0.3']", visible: :all
+ end
+ end
+end