Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(dashboard): show the preview cash-flow Sankey by account (#3799)

scragnog3a57d3fd80e7
diff --git a/app/controllers/api/v1/cash_flows_controller.rb b/app/controllers/api/v1/cash_flows_controller.rb
index f3b4e71f16..ee48135752 100644
--- a/app/controllers/api/v1/cash_flows_controller.rb
+++ b/app/controllers/api/v1/cash_flows_controller.rb
@@ -11,6 +11,13 @@ class Api::V1::CashFlowsController < Api::V1::BaseController
unless [ nil, "sankey" ].include?(params[:include]) && [ nil, "sankey" ].include?(params[:view])
return invalid_query("invalid_view", "include and view support only sankey")
end
+ if params[:group_by] && params[:view] != "sankey"
+ return invalid_query("invalid_group_by", "group_by requires view=sankey")
+ end
+ group_by = params[:group_by] || "category"
+ unless IncomeStatement::CashFlowGraph::GROUPINGS.key?(group_by)
+ return invalid_query("invalid_group_by", "group_by must be category or account")
+ end
if params[:start_date] || params[:end_date]
start_date, end_date = parse_date(params[:start_date]), parse_date(params[:end_date])
unless params[:view] == "sankey" && params[:month].nil? && start_date && end_date && start_date <= end_date
@@ -27,7 +34,7 @@ class Api::V1::CashFlowsController < Api::V1::BaseController
if params[:view] == "sankey"
# Arbitrary graph ranges must not allocate a daily comparison series.
- render json: IncomeStatement::CashFlowGraph.new(statement, period: period, as_of: today)
+ render json: IncomeStatement::CashFlowGraph.new(statement, period: period, group_by: group_by, as_of: today)
else
render json: IncomeStatement::CashFlow.new(statement, month: month, as_of: today, include_sankey: params[:include] == "sankey")
end
diff --git a/app/controllers/cash_flows_controller.rb b/app/controllers/cash_flows_controller.rb
index 86b7801070..08fb4b0acf 100644
--- a/app/controllers/cash_flows_controller.rb
+++ b/app/controllers/cash_flows_controller.rb
@@ -8,11 +8,16 @@ class CashFlowsController < ApplicationController
return render json: { error: "invalid_period" }, status: :unprocessable_entity
end
+ group_by = params[:group_by].presence || "category"
+ unless IncomeStatement::CashFlowGraph::GROUPINGS.key?(group_by)
+ return render json: { error: "invalid_group_by" }, status: :unprocessable_entity
+ end
+
statement = IncomeStatement.new(Current.family, user: Current.user)
period = Period.custom(start_date: start_date, end_date: end_date)
# Resolve reporting dates after ordinary session authentication has set Current.
Time.use_zone(resolved_timezone) do
- render json: IncomeStatement::CashFlowGraph.new(statement, period: period)
+ render json: IncomeStatement::CashFlowGraph.new(statement, period: period, group_by: group_by)
end
end
diff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rb
index ea97828d3e..a1a6091e88 100644
--- a/app/controllers/pages_controller.rb
+++ b/app/controllers/pages_controller.rb
@@ -124,6 +124,7 @@ class PagesController < ApplicationController
permitted["collapsed_sections"] = prefs[:collapsed_sections].to_unsafe_h if prefs[:collapsed_sections].respond_to?(:to_unsafe_h)
permitted["section_order"] = prefs[:section_order] if prefs[:section_order].is_a?(Array)
permitted["dashboard_section_layout"] = prefs[:dashboard_section_layout].to_unsafe_h if prefs[:dashboard_section_layout].respond_to?(:to_unsafe_h)
+ permitted["cashflow_sankey_group_by"] = prefs[:cashflow_sankey_group_by] if User::CASHFLOW_SANKEY_GROUPINGS.include?(prefs[:cashflow_sankey_group_by])
end
end
diff --git a/app/javascript/controllers/cash_flow_controller.js b/app/javascript/controllers/cash_flow_controller.js
index c5ec53ccab..b20ca942af 100644
--- a/app/javascript/controllers/cash_flow_controller.js
+++ b/app/javascript/controllers/cash_flow_controller.js
@@ -4,13 +4,36 @@ import { cashFlowChartData } from "utils/cash_flow_chart_data";
// One request supplies the inline and expanded renderers. No persistent browser
// cache: Turbo snapshots must not retain a prior session's financial graph.
export default class extends Controller {
- static targets = ["chart", "loading", "error", "empty", "content"];
- static values = { url: String };
+ static targets = [
+ "chart",
+ "loading",
+ "error",
+ "empty",
+ "content",
+ "groupBySegment",
+ ];
+ static values = {
+ url: String,
+ groupBy: { type: String, default: "category" },
+ };
connect() {
this.load();
}
+ // Switches the graph between flows by category and through each account.
+ // The choice is saved to the user's dashboard preferences; the graph is
+ // refetched straight away whether or not that save succeeds.
+ groupBy(event) {
+ const groupBy = event.currentTarget.dataset.groupBy;
+ if (groupBy === this.groupByValue) return;
+
+ this.groupByValue = groupBy;
+ this.#syncGroupBySegments();
+ this.#saveGroupBy(groupBy);
+ this.load();
+ }
+
disconnect() {
this.clear();
}
@@ -30,7 +53,9 @@ export default class extends Controller {
const request = new AbortController();
this.request = request;
try {
- const response = await fetch(this.urlValue, {
+ const url = new URL(this.urlValue, window.location.origin);
+ url.searchParams.set("group_by", this.groupByValue);
+ const response = await fetch(url, {
headers: { Accept: "application/json" },
credentials: "same-origin",
cache: "no-store",
@@ -56,6 +81,32 @@ export default class extends Controller {
}
}
+ #syncGroupBySegments() {
+ this.groupBySegmentTargets.forEach((segment) => {
+ const active = segment.dataset.groupBy === this.groupByValue;
+ segment.classList.toggle("segmented-control__segment--active", active);
+ segment.setAttribute("aria-pressed", active ? "true" : "false");
+ });
+ }
+
+ #saveGroupBy(groupBy) {
+ const csrfToken = document.querySelector(
+ 'meta[name="csrf-token"]',
+ )?.content;
+ fetch("/dashboard/preferences", {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ "X-CSRF-Token": csrfToken,
+ },
+ body: JSON.stringify({
+ preferences: { cashflow_sankey_group_by: groupBy },
+ }),
+ }).catch(() => {
+ // The chart already shows the new grouping; only the default is lost.
+ });
+ }
+
show(state, graph = null) {
for (const name of ["loading", "error", "empty", "content"]) {
this[`${name}Target`].hidden = name !== state;
diff --git a/app/javascript/controllers/sankey_preview_controller.js b/app/javascript/controllers/sankey_preview_controller.js
index b17e65e352..f4111e3946 100644
--- a/app/javascript/controllers/sankey_preview_controller.js
+++ b/app/javascript/controllers/sankey_preview_controller.js
@@ -81,9 +81,11 @@ export default class extends Controller {
this.comparisonDone = false;
}
this.state = detail.state;
- this.comparisonResult = detail.graph
- ? compareSankeyData(this.legacyDataValue, detail.graph)
- : null;
+ // The legacy chart is by category only, so only that view can be compared.
+ this.comparisonResult =
+ detail.graph?.basis === "net_by_category"
+ ? compareSankeyData(this.legacyDataValue, detail.graph)
+ : null;
this.element.dataset.sankeyComparison = this.comparisonResult || "";
this.expandButtonTarget.disabled = !detail.ready;
this.trackDisplay();
diff --git a/app/javascript/utils/cash_flow_chart_data.mjs b/app/javascript/utils/cash_flow_chart_data.mjs
index 3534738732..4ebb15cac7 100644
--- a/app/javascript/utils/cash_flow_chart_data.mjs
+++ b/app/javascript/utils/cash_flow_chart_data.mjs
@@ -4,7 +4,7 @@ export function cashFlowChartData(body) {
const graph = body.sankey;
if (
!/^[A-Z]{3,5}$/.test(body.currency) ||
- graph?.basis !== "net_by_category" ||
+ !["net_by_category", "net_by_account"].includes(graph?.basis) ||
!Array.isArray(graph.nodes) ||
!Array.isArray(graph.links)
) {
@@ -26,9 +26,14 @@ export function cashFlowChartData(body) {
typeof node.id !== "string" ||
ids.has(node.id) ||
typeof node.name !== "string" ||
- !["income", "expense", "cash_flow", "surplus", "deficit"].includes(
- node.kind,
- )
+ ![
+ "income",
+ "expense",
+ "cash_flow",
+ "account",
+ "surplus",
+ "deficit",
+ ].includes(node.kind)
) {
throw new Error("Invalid cash flow node");
}
@@ -75,7 +80,7 @@ export function cashFlowChartData(body) {
});
}
if (queue.length !== nodes.length) throw new Error("Cyclic cash flow graph");
- return { nodes, links };
+ return { basis: graph.basis, nodes, links };
}
// Sure also supports currencies (such as DOGE/USDC) outside Intl's three-letter
diff --git a/app/models/income_statement/account_sankey.rb b/app/models/income_statement/account_sankey.rb
new file mode 100644
index 0000000000..b76c412573
--- /dev/null
+++ b/app/models/income_statement/account_sankey.rb
@@ -0,0 +1,121 @@
+# Cash-flow Sankey grouped by account: income categories -> accounts -> expense
+# categories. Each account's categories are netted with IncomeStatement::
+# CategoryNetting, scoped to that account. What an account takes in beyond what
+# it spends flows on to Surplus; an account that spends more than it takes in
+# (a credit card paid off by transfer, savings being drawn down) is fed from
+# Deficit. Transfers between accounts are neither income nor spending, so they
+# never appear as flows between accounts.
+#
+# Same schema as IncomeStatement::Sankey, with basis "net_by_account" and an
+# "account" node kind in place of the single Cash Flow node.
+class IncomeStatement::AccountSankey
+ ACCOUNT_COLOR = "#737373".freeze
+
+ def initialize(statement, period:)
+ @statement, @period = statement, period
+ end
+
+ def as_json(*)
+ @nodes, @links, @node_index = [], [], {}
+ flows = account_flows
+ income = flows.sum { |flow| flow[:income] }.to_d
+ spending = flows.sum { |flow| flow[:spending] }.to_d
+ capacity = [ income, spending ].max
+ unless capacity.zero?
+ subcategory_flows = Hash.new(0.to_d)
+ flows.each { |flow| add_account(flow, income, spending, capacity, subcategory_flows) }
+ add_subcategories(subcategory_flows)
+ end
+ { basis: "net_by_account", income: decimal(income), spending: decimal(spending),
+ net_savings: decimal(income - spending), nodes: @nodes.map { |node| serialize(node) }, links: @links }
+ end
+
+ private
+ # Accounts the statement reports on, each with its own netting. One scoped
+ # statement per account keeps the netting identical to the category view.
+ def account_flows
+ @statement.eligible_accounts.order(:name).filter_map do |account|
+ statement = @statement.family.income_statement(user: @statement.user, accounts: Account.where(id: account.id))
+ groups = IncomeStatement::CategoryNetting.new(statement, period: @period).groups
+ income = groups.sum { |group| side_total(group, :income) }.to_d
+ spending = groups.sum { |group| side_total(group, :expense) }.to_d
+ next if income.zero? && spending.zero?
+
+ { account: account, groups: groups, income: income, spending: spending }
+ end
+ end
+
+ def add_account(flow, income, spending, capacity, subcategory_flows)
+ account = flow[:account]
+ size = [ flow[:income], flow[:spending] ].max
+ center = node("account_#{account.id}", account.name, :account, color: ACCOUNT_COLOR)
+ center[:value] = size
+ center[:percentage] = percentage(size, capacity)
+
+ flow[:groups].each do |group|
+ { income: income, expense: spending }.each do |side, side_total|
+ amount = side_total(group, side)
+ next if amount.zero?
+
+ category = group[:category]
+ root = node("#{side}_#{category_key(category)}", category.name, side, category: category)
+ root[:value] += amount
+ root[:percentage] = percentage(root[:value], side_total)
+ link(*(side == :income ? [ root, center ] : [ center, root ]), amount, percentage(amount, side_total))
+ group[:children].each do |child|
+ value = side_amount(child[:net], side)
+ subcategory_flows[[ side, root[:id], child[:category] ]] += value unless value.zero?
+ end
+ end
+ end
+
+ net = flow[:income] - flow[:spending]
+ return if net.zero?
+
+ kind = net.positive? ? :surplus : :deficit
+ balance = node("#{kind}_node", kind.to_s.capitalize, kind)
+ balance[:value] += net.abs
+ balance[:percentage] = percentage(balance[:value], capacity)
+ link(*(net.positive? ? [ center, balance ] : [ balance, center ]), net.abs, percentage(net.abs, capacity))
+ end
+
+ # Subcategories are summed across accounts, then hang off their parent.
+ def add_subcategories(subcategory_flows)
+ subcategory_flows.each do |(side, root_id, category), value|
+ root = @node_index.fetch(root_id)
+ child = node("#{side}_sub_#{category.id}", category.name, side, category: category)
+ child[:value] += value
+ child[:percentage] = percentage(child[:value], root[:value])
+ link(*(side == :income ? [ child, root ] : [ root, child ]), value, percentage(value, root[:value]))
+ end
+ end
+
+ def node(id, name, kind, category: nil, color: category&.color)
+ @node_index[id] ||= begin
+ @nodes << { id: id, index: @nodes.size, name: name, kind: kind.to_s, value: 0.to_d, percentage: 0,
+ category_id: category&.id, filter_value: category && !category.other_investments? ? category.filter_value : nil,
+ color: color }
+ @nodes.last
+ end
+ end
+
+ def link(source, target, value, percentage)
+ @links << { source: source[:index], target: target[:index], value: decimal(value), percentage: decimal(percentage) }
+ end
+
+ def serialize(node)
+ node.except(:index).merge(value: decimal(node[:value]), percentage: decimal(node[:percentage]))
+ end
+
+ def category_key(category) = IncomeStatement::CategoryNetting.key(category)
+ def side_amount(net, side) = IncomeStatement::CategoryNetting.side_amount(net, side)
+ def side_total(group, side) = IncomeStatement::CategoryNetting.side_total(group, side)
+
+ def percentage(value, total)
+ total.zero? ? 0 : (value.to_d / total * 100).round(1)
+ end
+
+ def decimal(value)
+ value.to_d.to_s("F")
+ end
+end
diff --git a/app/models/income_statement/cash_flow_graph.rb b/app/models/income_statement/cash_flow_graph.rb
index 7d36efaa61..a5b5d4a204 100644
--- a/app/models/income_statement/cash_flow_graph.rb
+++ b/app/models/income_statement/cash_flow_graph.rb
@@ -1,15 +1,23 @@
# Shared graph representation for the public API and session-authenticated web UI.
# Aggregation stays in Sankey; neither controller builds its own financial totals.
class IncomeStatement::CashFlowGraph
- def initialize(statement, period:, as_of: Date.current, time_zone: Time.zone.tzinfo.identifier)
- @statement, @period, @as_of, @time_zone = statement, period, as_of, time_zone
+ # group_by values: flows through one Cash Flow node by category (the default),
+ # or through each account.
+ GROUPINGS = {
+ "category" => "IncomeStatement::Sankey",
+ "account" => "IncomeStatement::AccountSankey"
+ }.freeze
+
+ def initialize(statement, period:, group_by: "category", as_of: Date.current, time_zone: Time.zone.tzinfo.identifier)
+ raise ArgumentError, "unknown group_by: #{group_by}" unless GROUPINGS.key?(group_by)
+ @statement, @period, @group_by, @as_of, @time_zone = statement, period, group_by, as_of, time_zone
end
def as_json(*)
{
as_of: @as_of.iso8601, time_zone: @time_zone, currency: @statement.family.currency,
period: { start_date: @period.start_date.iso8601, end_date: @period.end_date.iso8601 },
- sankey: IncomeStatement::Sankey.new(@statement, period: @period).as_json
+ sankey: GROUPINGS.fetch(@group_by).constantize.new(@statement, period: @period).as_json
}
end
end
diff --git a/app/models/income_statement/category_netting.rb b/app/models/income_statement/category_netting.rb
new file mode 100644
index 0000000000..3b2b21a8a2
--- /dev/null
+++ b/app/models/income_statement/category_netting.rb
@@ -0,0 +1,45 @@
+# Nets refunds within each category before arranging flows. Parent totals already
+# include children: subtract those children before partitioning by direction, so
+# a refund in a child cannot be counted again in its parent's net amount.
+#
+# Shared by the category and account Sankeys, so both net a statement the same way.
+class IncomeStatement::CategoryNetting
+ def initialize(statement, period:)
+ @statement, @period = statement, period
+ end
+
+ # One group per top-level category: its own net (`direct`) and its
+ # subcategories' nets (`children`), positive meaning spending.
+ #
+ # Keep this hierarchy-aware netting separate from IncomeStatement#net_category_totals
+ # while the original dashboard Sankey remains available for preview comparisons.
+ def groups
+ expense = @statement.expense_totals(period: @period).category_totals.index_by { |ct| self.class.key(ct.category) }
+ income = @statement.income_totals(period: @period).category_totals.index_by { |ct| self.class.key(ct.category) }
+ entries = (expense.keys | income.keys).sort.map do |key|
+ category = (expense[key] || income[key]).category
+ { category: category, net: (expense[key]&.total || 0).to_d - (income[key]&.total || 0).to_d }
+ end
+ children = entries.select { |entry| entry[:category].subcategory? }.group_by { |entry| entry[:category].parent_id }
+ entries.reject { |entry| entry[:category].subcategory? }.map do |root|
+ subs = children.fetch(root[:category].id, [])
+ { category: root[:category], direct: root[:net] - subs.sum { |sub| sub[:net] }, children: subs }
+ end
+ end
+
+ class << self
+ def key(category)
+ return "uncategorized" if category.uncategorized?
+ return "other_investments" if category.other_investments?
+ category.id
+ end
+
+ def side_amount(net, side)
+ [ side == :expense ? net : -net, 0 ].max
+ end
+
+ def side_total(group, side)
+ side_amount(group[:direct], side) + group[:children].sum { |child| side_amount(child[:net], side) }
+ end
+ end
+end
diff --git a/app/models/income_statement/sankey.rb b/app/models/income_statement/sankey.rb
index 4522c055d5..2147d892e2 100644
--- a/app/models/income_statement/sankey.rb
+++ b/app/models/income_statement/sankey.rb
@@ -1,6 +1,5 @@
-# Nets refunds within each category before arranging flows. Parent totals already
-# include children: subtract those children before partitioning by direction, so
-# a refund in a child cannot be counted again in its parent's net amount.
+# Cash-flow Sankey by category: income categories -> Cash Flow -> expense
+# categories. Netting is IncomeStatement::CategoryNetting's.
class IncomeStatement::Sankey
def initialize(statement, period:)
@statement, @period = statement, period
@@ -8,7 +7,7 @@ class IncomeStatement::Sankey
def as_json(*)
@nodes, @links = [], []
- groups = category_groups
+ groups = IncomeStatement::CategoryNetting.new(@statement, period: @period).groups
income = groups.sum { |group| side_total(group, :income) }.to_d
spending = groups.sum { |group| side_total(group, :expense) }.to_d
capacity = [ income, spending ].max
@@ -31,35 +30,9 @@ class IncomeStatement::Sankey
end
private
- # Keep this hierarchy-aware netting separate from IncomeStatement#net_category_totals
- # while the original dashboard Sankey remains available for preview comparisons.
- def category_groups
- expense = @statement.expense_totals(period: @period).category_totals.index_by { |ct| category_key(ct.category) }
- income = @statement.income_totals(period: @period).category_totals.index_by { |ct| category_key(ct.category) }
- entries = (expense.keys | income.keys).sort.map do |key|
- category = (expense[key] || income[key]).category
- { category: category, net: (expense[key]&.total || 0).to_d - (income[key]&.total || 0).to_d }
- end
- children = entries.select { |entry| entry[:category].subcategory? }.group_by { |entry| entry[:category].parent_id }
- entries.reject { |entry| entry[:category].subcategory? }.map do |root|
- subs = children.fetch(root[:category].id, [])
- { category: root[:category], direct: root[:net] - subs.sum { |sub| sub[:net] }, children: subs }
- end
- end
-
- def category_key(category)
- return "uncategorized" if category.uncategorized?
- return "other_investments" if category.other_investments?
- category.id
- end
-
- def side_amount(net, side)
- [ side == :expense ? net : -net, 0 ].max
- end
-
- def side_total(group, side)
- side_amount(group[:direct], side) + group[:children].sum { |child| side_amount(child[:net], side) }
- end
+ def category_key(category) = IncomeStatement::CategoryNetting.key(category)
+ def side_amount(net, side) = IncomeStatement::CategoryNetting.side_amount(net, side)
+ def side_total(group, side) = IncomeStatement::CategoryNetting.side_total(group, side)
def add_group(group, side, total, center)
amount = side_total(group, side)
diff --git a/app/models/user.rb b/app/models/user.rb
index 587ea839ae..ec71ad07be 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -653,6 +653,14 @@ class User < ApplicationRecord
preferences&.dig("dashboard_section_layout", section_key, "height")
end
+ CASHFLOW_SANKEY_GROUPINGS = IncomeStatement::CashFlowGraph::GROUPINGS.keys.freeze
+
+ # Preview cash-flow Sankey: flows by category (default) or through each account.
+ def cashflow_sankey_group_by
+ group_by = preferences&.dig("cashflow_sankey_group_by")
+ CASHFLOW_SANKEY_GROUPINGS.include?(group_by) ? group_by : "category"
+ end
+
# Per-widget column-span override ("single" | "full"); nil = use default.
def dashboard_section_width(section_key)
preferences&.dig("dashboard_section_layout", section_key, "col_span")
diff --git a/app/views/pages/dashboard/_cashflow_preview.html.erb b/app/views/pages/dashboard/_cashflow_preview.html.erb
index ce7bcef676..71bf2d183d 100644
--- a/app/views/pages/dashboard/_cashflow_preview.html.erb
+++ b/app/views/pages/dashboard/_cashflow_preview.html.erb
@@ -22,7 +22,22 @@
</header>
<div data-controller="cash-flow" data-sankey-preview-target="display" class="ph-no-capture"
data-action="turbo:before-cache@document->cash-flow#clear"
- data-cash-flow-url-value="<%= dashboard_cash_flow_path(start_date: period.start_date.iso8601, end_date: period.end_date.iso8601) %>">
+ data-cash-flow-url-value="<%= dashboard_cash_flow_path(start_date: period.start_date.iso8601, end_date: period.end_date.iso8601) %>"
+ data-cash-flow-group-by-value="<%= Current.user.cashflow_sankey_group_by %>">
+ <%# Outside the loading/content states, so the grouping can be switched back from an empty graph. %>
+ <div class="px-4 flex flex-wrap items-center justify-end gap-2">
+ <span class="text-xs text-secondary"><%= t("pages.dashboard.cashflow_preview.group_by_label") %></span>
+ <%= render DS::SegmentedControl.new(aria_label: t("pages.dashboard.cashflow_preview.group_by_label")) do |sc| %>
+ <% User::CASHFLOW_SANKEY_GROUPINGS.each do |group_by| %>
+ <% sc.with_segment(
+ t("pages.dashboard.cashflow_preview.group_by_#{group_by}"),
+ active: Current.user.cashflow_sankey_group_by == group_by,
+ class: "text-xs",
+ data: { cash_flow_target: "groupBySegment", group_by: group_by, action: "cash-flow#groupBy" }
+ ) %>
+ <% end %>
+ <% end %>
+ </div>
<p data-cash-flow-target="loading" role="status" class="p-4 text-secondary"><%= t("pages.dashboard.cashflow_sankey.loading") %></p>
<div data-cash-flow-target="error" hidden role="alert" class="p-4 space-y-3">
<p><%= t("pages.dashboard.cashflow_sankey.load_error") %></p>
diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.yml
index d42874228a..3ac0bb2045 100644
--- a/config/locales/views/pages/en.yml
+++ b/config/locales/views/pages/en.yml
@@ -95,6 +95,9 @@ en:
title: "New Sankey chart"
preview: "Preview"
preview_tooltip: "This will replace the above visualization as it uses a new shared API with the mobile Swift client."
+ group_by_label: "Show flows by"
+ group_by_category: "Category"
+ group_by_account: "Account"
feedback_prompt: "Compare this chart with the original above and let us know if it looks different other than sorting."
positive: "Looks right"
negative: "Something looks wrong"
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 3fc01d16bf..d2e694b615 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -3263,6 +3263,9 @@ components:
type: string
enum:
- net_by_category
+ - net_by_account
+ description: net_by_account (group_by=account) replaces the Cash Flow node
+ with one account node per account, each balanced by Surplus or Deficit
income:
type: string
spending:
@@ -3295,6 +3298,7 @@ components:
- income
- expense
- cash_flow
+ - account
- surplus
- deficit
value:
@@ -5492,6 +5496,18 @@ paths:
- sankey
description: Graph-only envelope; omits daily comparison. Accepts month or
an explicit date range; cannot combine with include.
+ - name: group_by
+ in: query
+ required: false
+ schema:
+ type: string
+ enum:
+ - category
+ - account
+ default: category
+ description: 'Requires view=sankey. category: flows through one Cash Flow
+ node; account: income categories flow through each account to expense categories
+ (basis net_by_account).'
- name: start_date
in: query
required: false
diff --git a/spec/requests/api/v1/cash_flow_spec.rb b/spec/requests/api/v1/cash_flow_spec.rb
index bb77896ad1..e76213bf43 100644
--- a/spec/requests/api/v1/cash_flow_spec.rb
+++ b/spec/requests/api/v1/cash_flow_spec.rb
@@ -40,6 +40,7 @@ RSpec.describe 'API V1 Cash Flow', type: :request do
parameter name: :month, in: :query, required: false, schema: { type: :string, format: :date }, description: 'Non-future first day YYYY-MM-01; defaults to the current month in the family time zone.'
parameter name: :include, in: :query, required: false, schema: { type: :string, enum: [ 'sankey' ] }, description: 'Append server-calculated graph to the monthly summary; cannot combine with view.'
parameter name: :view, in: :query, required: false, schema: { type: :string, enum: [ 'sankey' ] }, description: 'Graph-only envelope; omits daily comparison. Accepts month or an explicit date range; cannot combine with include.'
+ parameter name: :group_by, in: :query, required: false, schema: { type: :string, enum: %w[category account], default: 'category' }, description: 'Requires view=sankey. category: flows through one Cash Flow node; account: income categories flow through each account to expense categories (basis net_by_account).'
parameter name: :start_date, in: :query, required: false, schema: { type: :string, format: :date }, description: 'Inclusive ISO date. Requires end_date and view=sankey; cannot combine with month.'
parameter name: :end_date, in: :query, required: false, schema: { type: :string, format: :date }, description: 'Inclusive ISO date at or after start_date. Explicit ranges preserve their bounds, including future dates.'
security [ { apiKeyAuth: [] } ]
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 7fc44227cd..d9c2ff723b 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -1760,13 +1760,13 @@ RSpec.configure do |config|
type: :object, required: %w[basis income spending net_savings nodes links],
description: 'Refunds net within each category. Parent direct amounts exclude child totals before partitioning by direction. Graph income/spending may differ from gross monthly totals; net savings agrees. Decimal strings retain FX precision. Empty flow has empty nodes and links.',
properties: {
- basis: { type: :string, enum: [ 'net_by_category' ] },
+ basis: { type: :string, enum: %w[net_by_category net_by_account], description: 'net_by_account (group_by=account) replaces the Cash Flow node with one account node per account, each balanced by Surplus or Deficit' },
income: { type: :string }, spending: { type: :string }, net_savings: { type: :string },
nodes: { type: :array, items: {
type: :object, required: %w[id name kind value percentage category_id filter_value color],
properties: {
id: { type: :string, description: 'Stable direction-prefixed category identifier or structural identifier' },
- name: { type: :string }, kind: { type: :string, enum: %w[income expense cash_flow surplus deficit] },
+ name: { type: :string }, kind: { type: :string, enum: %w[income expense cash_flow account surplus deficit] },
value: { type: :string, description: 'Nonnegative decimal in envelope currency' },
percentage: { type: :string, description: 'Percentage of parent, or side total for root categories; structural balancing nodes use central capacity' },
category_id: { type: :string, format: :uuid, nullable: true },
diff --git a/test/controllers/api/v1/cash_flows_controller_test.rb b/test/controllers/api/v1/cash_flows_controller_test.rb
index 58b163bd08..78d9b4e32b 100644
--- a/test/controllers/api/v1/cash_flows_controller_test.rb
+++ b/test/controllers/api/v1/cash_flows_controller_test.rb
@@ -78,6 +78,18 @@ class Api::V1::CashFlowsControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "the sankey view can be grouped by account" do
+ get "/api/v1/cash_flow", params: { view: "sankey", group_by: "account" }, headers: api_headers(@auth)
+ assert_response :success
+ assert_equal "net_by_account", response.parsed_body.dig("sankey", "basis")
+
+ [ { view: "sankey", group_by: "merchant" }, { group_by: "account" }, { include: "sankey", group_by: "account" } ].each do |query|
+ get "/api/v1/cash_flow", params: query, headers: api_headers(@auth)
+ assert_response :unprocessable_entity
+ assert_equal "invalid_group_by", response.parsed_body["error"]
+ end
+ end
+
test "rejects conflicting graph modes" do
[ {}, { month: "2024-01-01" }, { start_date: "2024-01-01", end_date: "2024-01-02" } ].each do |period|
get "/api/v1/cash_flow", params: period.merge(include: "sankey", view: "sankey"), headers: api_headers(@auth)
diff --git a/test/controllers/cash_flows_controller_test.rb b/test/controllers/cash_flows_controller_test.rb
index d679bba704..0ede369d6e 100644
--- a/test/controllers/cash_flows_controller_test.rb
+++ b/test/controllers/cash_flows_controller_test.rb
@@ -58,6 +58,20 @@ class CashFlowsControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "groups the graph by account on request and rejects unknown groupings" do
+ sign_in @user
+ get dashboard_cash_flow_path(@dates.merge(group_by: "account"))
+ assert_response :success
+ assert_equal "net_by_account", response.parsed_body.dig("sankey", "basis")
+
+ get dashboard_cash_flow_path(@dates)
+ assert_equal "net_by_category", response.parsed_body.dig("sankey", "basis")
+
+ get dashboard_cash_flow_path(@dates.merge(group_by: "merchant"))
+ assert_response :unprocessable_entity
+ assert_equal "invalid_group_by", response.parsed_body["error"]
+ end
+
test "rejects incomplete malformed and reversed date ranges" do
sign_in @user
[ {}, { start_date: "2024-01-01" }, { start_date: "2024-02-30", end_date: "2024-03-01" },
diff --git a/test/controllers/pages_controller_test.rb b/test/controllers/pages_controller_test.rb
index e1da9aacc5..1a77f73011 100644
--- a/test/controllers/pages_controller_test.rb
+++ b/test/controllers/pages_controller_test.rb
@@ -40,6 +40,15 @@ class PagesControllerTest < ActionDispatch::IntegrationTest
assert_equal "compact", @user.reload.dashboard_section_height("net_worth_chart")
end
+ test "update_preferences saves the preview Sankey grouping and ignores unknown ones" do
+ patch "/dashboard/preferences", params: { preferences: { cashflow_sankey_group_by: "account" } }, as: :json
+ assert_response :success
+ assert_equal "account", @user.reload.cashflow_sankey_group_by
+
+ patch "/dashboard/preferences", params: { preferences: { cashflow_sankey_group_by: "merchant" } }, as: :json
+ assert_equal "account", @user.reload.cashflow_sankey_group_by
+ end
+
test "update_preferences persists dashboard section width" do
patch "/dashboard/preferences", params: {
preferences: { dashboard_section_layout: { cashflow_sankey: { col_span: "single" } } }
diff --git a/test/javascript/utils/cash_flow_chart_data_test.mjs b/test/javascript/utils/cash_flow_chart_data_test.mjs
index ecea158fd2..838fe5efe9 100644
--- a/test/javascript/utils/cash_flow_chart_data_test.mjs
+++ b/test/javascript/utils/cash_flow_chart_data_test.mjs
@@ -41,9 +41,29 @@ test("accepts empty graphs", () => {
currency: "USD",
sankey: { basis: "net_by_category", nodes: [], links: [] },
}),
- { nodes: [], links: [] },
+ { basis: "net_by_category", nodes: [], links: [] },
);
});
+test("accepts a graph grouped by account", () => {
+ const body = payload();
+ body.sankey.basis = "net_by_account";
+ body.sankey.nodes[1] = {
+ id: "account_one",
+ name: "Checking",
+ kind: "account",
+ value: "12.345",
+ percentage: "100.0",
+ color: "#737373",
+ };
+ const graph = cashFlowChartData(body);
+ assert.equal(graph.basis, "net_by_account");
+ assert.equal(graph.nodes[1].kind, "account");
+});
+test("rejects an unknown basis", () => {
+ const body = payload();
+ body.sankey.basis = "net_by_merchant";
+ assert.throws(() => cashFlowChartData(body), /Invalid cash flow graph/);
+});
test("rejects malformed, unsafe, and cyclic graphs", () => {
for (const mutate of [
(p) => (p.sankey.nodes[0].value = "Infinity"),
diff --git a/test/models/income_statement/account_sankey_test.rb b/test/models/income_statement/account_sankey_test.rb
new file mode 100644
index 0000000000..1b1bffba2d
--- /dev/null
+++ b/test/models/income_statement/account_sankey_test.rb
@@ -0,0 +1,102 @@
+require "test_helper"
+
+class IncomeStatement::AccountSankeyTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = families(:empty)
+ @checking = @family.accounts.create!(name: "Checking", currency: "USD", balance: 0, accountable: Depository.new)
+ @card = @family.accounts.create!(name: "Card", currency: "USD", balance: 0, accountable: CreditCard.new)
+ @month = Date.new(2024, 2, 1)
+ @salary = @family.categories.create!(name: "Salary", color: "#00aa00")
+ @shopping = @family.categories.create!(name: "Shopping", color: "#123456")
+ @groceries = @family.categories.create!(name: "Groceries", parent: @shopping)
+ end
+
+ test "flows run from income categories through each account to expense categories" do
+ transaction(@checking, -1000, @salary)
+ transaction(@checking, 300, @shopping)
+ transaction(@card, 200, @groceries)
+ result = graph
+
+ assert_equal "net_by_account", result[:basis]
+ assert_equal "1000.0", result[:income]
+ assert_equal "500.0", result[:spending]
+ assert_equal "500.0", result[:net_savings]
+ assert_nil node(result, "cash_flow_node")
+ assert_equal "account", node(result, "account_#{@checking.id}")[:kind]
+ assert_link result, "income_#{@salary.id}", "account_#{@checking.id}", "1000.0"
+ assert_link result, "account_#{@checking.id}", "expense_#{@shopping.id}", "300.0"
+ assert_link result, "account_#{@card.id}", "expense_#{@shopping.id}", "200.0"
+ assert_equal "500.0", node(result, "expense_#{@shopping.id}")[:value], "one category node across accounts"
+ assert_link result, "expense_#{@shopping.id}", "expense_sub_#{@groceries.id}", "200.0"
+ assert_equal @groceries.filter_value, node(result, "expense_sub_#{@groceries.id}")[:filter_value]
+ assert_balanced result
+ end
+
+ test "an account taking in more than it spends feeds Surplus, one spending more is fed by Deficit" do
+ transaction(@checking, -1000, @salary)
+ transaction(@checking, 100, @shopping)
+ transaction(@card, 250, @shopping)
+ result = graph
+
+ assert_link result, "account_#{@checking.id}", "surplus_node", "900.0"
+ assert_link result, "deficit_node", "account_#{@card.id}", "250.0"
+ assert_equal "900.0", node(result, "surplus_node")[:value]
+ assert_equal "250.0", node(result, "deficit_node")[:value]
+ assert_balanced result
+ end
+
+ test "accounts without income or spending are left out, and an empty period is empty" do
+ transaction(@checking, 50, @shopping)
+ assert_nil node(graph, "account_#{@card.id}")
+ assert_equal({ nodes: [], links: [] }, graph(Date.new(2023, 1, 1)).slice(:nodes, :links))
+ end
+
+ test "a category's per-account netting matches the category view" do
+ transaction(@checking, 120, @shopping)
+ transaction(@checking, -20, @shopping)
+ result = graph
+ by_category = IncomeStatement::Sankey.new(IncomeStatement.new(@family), period: period).as_json
+
+ assert_equal by_category[:spending], result[:spending]
+ assert_equal node(by_category, "expense_#{@shopping.id}")[:value], node(result, "expense_#{@shopping.id}")[:value]
+ end
+
+ private
+ def transaction(account, amount, category)
+ create_transaction(account: account, amount: amount, category: category, date: @month)
+ end
+
+ def period(month = @month)
+ Period.custom(start_date: month, end_date: month.end_of_month)
+ end
+
+ def graph(month = @month)
+ IncomeStatement::AccountSankey.new(IncomeStatement.new(@family), period: period(month)).as_json
+ end
+
+ def node(graph, id)
+ graph[:nodes].find { |node| node[:id] == id }
+ end
+
+ def assert_link(graph, source_id, target_id, value)
+ ids = graph[:nodes].map { |node| node[:id] }
+ link = graph[:links].find { |l| l[:source] == ids.index(source_id) && l[:target] == ids.index(target_id) }
+ assert link, "expected a link #{source_id} -> #{target_id}"
+ assert_equal value, link[:value]
+ end
+
+ # Every account balances, and every node's value is its larger side.
+ def assert_balanced(graph)
+ graph[:nodes].each_with_index do |node, index|
+ incoming, outgoing = %i[target source].map do |end_point|
+ graph[:links].select { |link| link[end_point] == index }.sum { |link| link[:value].to_d }
+ end
+ assert_operator node[:value].to_d, :>, 0
+ assert_operator node[:percentage].to_d, :<=, 100
+ assert_equal incoming, outgoing, "#{node[:id]} must balance" if node[:kind] == "account"
+ assert_equal node[:value].to_d, [ incoming, outgoing ].max, "#{node[:id]} must match its links' capacity"
+ end
+ end
+end
diff --git a/test/system/cash_flow_group_by_test.rb b/test/system/cash_flow_group_by_test.rb
new file mode 100644
index 0000000000..db48831bce
--- /dev/null
+++ b/test/system/cash_flow_group_by_test.rb
@@ -0,0 +1,33 @@
+require "application_system_test_case"
+
+class CashFlowGroupByTest < ApplicationSystemTestCase
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @month = Date.current.beginning_of_month
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ category = @user.family.categories.create!(name: "Group By Shopping", color: "#123456")
+ account = @user.family.accounts.create!(name: "Group By Checking", currency: "USD", balance: 0, accountable: Depository.new)
+ create_transaction(account: account, category: category, amount: 100, date: @month)
+ end
+
+ test "switching the preview Sankey to flows by account redraws it and is remembered" do
+ sign_in @user
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ chart = find("#cashflow-preview [data-preview-sankey-chart-target='chart']", match: :first)
+ assert_selector "#cashflow-preview svg .sankey-link"
+ assert_no_selector "#cashflow-preview svg text", text: "Group By Checking"
+
+ within("#cashflow-preview") { click_button "Account" }
+
+ chart.assert_selector "svg text", text: "Group By Checking"
+ assert_selector "#cashflow-preview button[aria-pressed='true']", text: "Account"
+ assert_nil find("#cashflow-preview")["data-sankey-comparison"].presence, "only the category view is compared with the legacy chart"
+
+ visit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)
+ find("#cashflow-preview [data-preview-sankey-chart-target='chart']", match: :first)
+ .assert_selector "svg text", text: "Group By Checking"
+ assert_equal "account", @user.reload.cashflow_sankey_group_by
+ end
+end