The personal finance app for everyone (by everyone)
Ruby
feat(reports): family setting to stop counting investing as spending (#3952)
scragnog44e5e51911f5
diff --git a/app/controllers/budget_categories_controller.rb b/app/controllers/budget_categories_controller.rbindex 0e83464d1e..9f598d3182 100644--- a/app/controllers/budget_categories_controller.rb+++ b/app/controllers/budget_categories_controller.rb@@ -17,8 +17,10 @@ class BudgetCategoriesController < ApplicationController# correctly tags inflow as funds_movement and outflow per destination# account) shows under the Uncategorized card -- or any retained# category -- even though the aggregate ignores it. See issue #1059.+ # A family that does not count investing as spending also leaves out+ # investment contributions (Family#analytics_excluded_kinds).@recent_transactions = @budget.transactions- .where.not(transactions: { kind: Transaction::BUDGET_EXCLUDED_KINDS })+ .where.not(transactions: { kind: Current.family.analytics_excluded_kinds })if params[:id] == BudgetCategory.uncategorized.id@budget_category = @budget.uncategorized_budget_categorydiff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rbindex 403a50e717..14678bdda5 100644--- a/app/controllers/pages_controller.rb+++ b/app/controllers/pages_controller.rb@@ -281,7 +281,8 @@ class PagesController < ApplicationControllerdashboard_net_totals,dashboard_income_statement.income_totals(period: @period),dashboard_income_statement.expense_totals(period: @period),- Current.family.currency+ Current.family.currency,+ invested_total: dashboard_income_statement.invested_total(period: @period))end@@ -350,7 +351,7 @@ class PagesController < ApplicationControllerProvider::Registry.get_provider(:github)end- def build_cashflow_sankey_data(net_totals, income_totals, expense_totals, currency)+ def build_cashflow_sankey_data(net_totals, income_totals, expense_totals, currency, invested_total: nil)nodes = []links = []node_indices = {}@@ -364,9 +365,12 @@ class PagesController < ApplicationControllertotal_income = net_totals.total_net_income.to_f.round(2)total_expense = net_totals.total_net_expense.to_f.round(2)+ total_invested = invested_total&.amount.to_f.round(2)- # Central Cash Flow node- cash_flow_idx = add_node.call("cash_flow_node", "Cash Flow", total_income, 100.0, "var(--color-success)")+ # Central Cash Flow node, sized to whichever side is larger so a deficit+ # (outflows above income) still balances, as IncomeStatement::Sankey does+ capacity = [ total_income, (total_expense + total_invested).round(2) ].max+ cash_flow_idx = add_node.call("cash_flow_node", "Cash Flow", capacity, 100.0, "var(--color-success)")# Build netted subcategory data from raw totalsnet_subcategories_by_parent = build_net_subcategories(expense_totals, income_totals)@@ -395,12 +399,24 @@ class PagesController < ApplicationControllerflow_direction: :outbound)+ # Money moved into investments, for a family that does not count it as spending+ if total_invested.positive?+ percentage = capacity.zero? ? 0 : (total_invested / capacity * 100).round(1)+ idx = add_node.call("invested_node", t("pages.dashboard.cashflow_preview.node_labels.invested"), total_invested, percentage, IncomeStatement::Sankey::INVESTED_COLOR)+ links << { source: cash_flow_idx, target: idx, value: total_invested, color: IncomeStatement::Sankey::INVESTED_COLOR, percentage: percentage }+ end+# Surplus/Deficit- net = (total_income - total_expense).round(2)+ net = (total_income - total_expense - total_invested).round(2)if net.positive?percentage = total_income.zero? ? 0 : (net / total_income * 100).round(1)idx = add_node.call("surplus_node", "Surplus", net, percentage, "var(--color-success)")links << { source: cash_flow_idx, target: idx, value: net, color: "var(--color-success)", percentage: percentage }+ elsif net.negative?+ deficit = net.abs+ percentage = capacity.zero? ? 0 : (deficit / capacity * 100).round(1)+ idx = add_node.call("deficit_node", t("pages.dashboard.cashflow_preview.node_labels.deficit"), deficit, percentage, "var(--color-destructive)")+ links << { source: idx, target: cash_flow_idx, value: deficit, color: "var(--color-destructive)", percentage: percentage }end{ nodes: nodes, links: links, currency_symbol: Money::Currency.new(currency).symbol }diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rbindex 97079b00f6..9670ced470 100644--- a/app/controllers/reports_controller.rb+++ b/app/controllers/reports_controller.rb@@ -364,7 +364,7 @@ class ReportsController < ApplicationController.where(accounts: { family_id: Current.family.id, status: [ "draft", "active" ] }).merge(Account.included_in_reports).where(entries: { entryable_type: "Transaction", excluded: false, date: @period.date_range })- .where.not(kind: Transaction::BUDGET_EXCLUDED_KINDS)+ .where.not(kind: Current.family.analytics_excluded_kinds).includes(entry: :account, category: :parent)transactions = exclude_tax_advantaged_accounts(transactions)@@ -738,7 +738,7 @@ class ReportsController < ApplicationController.where(accounts: { family_id: Current.family.id, status: [ "draft", "active" ] }).merge(Account.included_in_reports).where(entries: { entryable_type: "Transaction", excluded: false, date: @period.date_range })- .where.not(kind: Transaction::BUDGET_EXCLUDED_KINDS)+ .where.not(kind: Current.family.analytics_excluded_kinds).includes(entry: :account, category: [])transactions = exclude_tax_advantaged_accounts(transactions)@@ -777,7 +777,7 @@ class ReportsController < ApplicationController.where(accounts: { family_id: Current.family.id, status: [ "draft", "active" ] }).merge(Account.included_in_reports).where(entries: { entryable_type: "Transaction", excluded: false, date: @period.date_range })- .where.not(kind: Transaction::BUDGET_EXCLUDED_KINDS)+ .where.not(kind: Current.family.analytics_excluded_kinds).includes(entry: :account, category: [])transactions = exclude_tax_advantaged_accounts(transactions)diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex 63ca194711..bf6eefe334 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -116,7 +116,7 @@ class UsersController < ApplicationControllerdef user_paramsfamily_attrs = [ :name, :currency, :country, :date_format, :timezone, :locale, :month_start_day, :id ]if Current.user.admin?- family_attrs.push(:personal_budgets, :household_budget_enabled) # Needed for updating existing family+ family_attrs.push(:personal_budgets, :household_budget_enabled, :investment_contributions_as_spending) # Needed for updating existing familyfamily_attrs.push(:moniker, :default_account_sharing)family_attrs << { enabled_currencies: [] }end@@ -142,8 +142,10 @@ class UsersController < ApplicationControllerenabled_currencies_changed = family_attrs.key?(:enabled_currencies)personal_budgets_changed = family_attrs.key?(:personal_budgets)household_budget_enabled_changed = family_attrs.key?(:household_budget_enabled)+ investment_contributions_as_spending_changed = family_attrs.key?(:investment_contributions_as_spending)- moniker_changed || sharing_changed || enabled_currencies_changed || personal_budgets_changed || household_budget_enabled_changed+ moniker_changed || sharing_changed || enabled_currencies_changed || personal_budgets_changed || household_budget_enabled_changed ||+ investment_contributions_as_spending_changedenddef ensure_admindiff --git a/app/javascript/utils/cash_flow_chart_data.mjs b/app/javascript/utils/cash_flow_chart_data.mjsindex 4ebb15cac7..2b8cbfcc58 100644--- a/app/javascript/utils/cash_flow_chart_data.mjs+++ b/app/javascript/utils/cash_flow_chart_data.mjs@@ -1,3 +1,11 @@+// Used when the server omits a node's colour. Invested keeps its own colour+// (IncomeStatement::Sankey::INVESTED_COLOR) rather than reading as income.+const FALLBACK_COLORS = {+ expense: "var(--color-destructive)",+ deficit: "var(--color-destructive)",+ invested: "#0d9488",+};+// Decimal strings remain authoritative on the wire. Conversion to Number is// exclusively for D3 geometry and locale formatting, never financial totals.export function cashFlowChartData(body) {@@ -33,6 +41,7 @@ export function cashFlowChartData(body) {"account","surplus","deficit",+ "invested",].includes(node.kind)) {throw new Error("Invalid cash flow node");@@ -40,9 +49,7 @@ export function cashFlowChartData(body) {ids.add(node.id);const color = /^#[0-9a-f]{6}$/i.test(node.color)? node.color- : ["expense", "deficit"].includes(node.kind)- ? "var(--color-destructive)"- : "var(--color-success)";+ : (FALLBACK_COLORS[node.kind] ?? "var(--color-success)");const value = number(node.value),percentage = number(node.percentage);if (value <= 0 || percentage > 100)diff --git a/app/models/assistant/function/get_income_statement.rb b/app/models/assistant/function/get_income_statement.rbindex 2c9b1b80cd..b7fbea240d 100644--- a/app/models/assistant/function/get_income_statement.rb+++ b/app/models/assistant/function/get_income_statement.rb@@ -124,7 +124,7 @@ class Assistant::Function::GetIncomeStatement < Assistant::Functionincome_data = income_statement.income_totals(period: period)expense_data = income_statement.expense_totals(period: period)- {+ result = {currency: family.currency,period: {start_date: period.start_date,@@ -140,6 +140,11 @@ class Assistant::Function::GetIncomeStatement < Assistant::Function},insights: get_insights(income_data, expense_data)}+ # Families that do not count investing as spending: say where that money went.+ unless family.investment_contributions_as_spending?+ result[:invested] = { total: format_money(income_statement.invested_total(period: period).amount) }+ end+ resultend# Category rollups and family stats are family-wide by construction, so a@@ -147,7 +152,7 @@ class Assistant::Function::GetIncomeStatement < Assistant::Functiondef scoped_result(period, account_ids)totals = income_statement.totals_for(period, account_ids: account_ids)- {+ result = {currency: family.currency,period: {start_date: period.start_date,@@ -159,6 +164,11 @@ class Assistant::Function::GetIncomeStatement < Assistant::Functionnet: format_money(totals.income_money.amount - totals.expense_money.amount),breakdown_omitted_reason: "category breakdown is not available with an account filter"}+ # Same as full_result, for the selected accounts only.+ unless family.investment_contributions_as_spending?+ result[:invested] = { total: format_money(totals.invested_money.amount) }+ end+ resultenddef month_buckets(period)diff --git a/app/models/family.rb b/app/models/family.rbindex fa2685ff0d..9d5d8018f9 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -254,6 +254,7 @@ class Family < ApplicationRecordvalidates :default_account_sharing, inclusion: { in: SHARING_DEFAULTS }validates :personal_budgets, inclusion: { in: [ true, false ] }validates :household_budget_enabled, inclusion: { in: [ true, false ] }+ validates :investment_contributions_as_spending, inclusion: { in: [ true, false ] }validates :categories_locked, inclusion: { in: [ true, false ] }validate :timezone_must_be_a_known_zone, if: :timezone_changed?@@ -518,6 +519,15 @@ class Family < ApplicationRecord# Returns the Investment Contributions category for this family, creating it if it doesn't exist.# This is used for auto-categorizing transfers to investment accounts.# Always uses the family's locale to ensure consistent category naming across all users.+ # Transaction kinds left out of spending/income lists. With+ # investment_contributions_as_spending off, money moved into investment+ # accounts is reported as invested rather than spent.+ def analytics_excluded_kinds+ return Transaction::BUDGET_EXCLUDED_KINDS if investment_contributions_as_spending?++ Transaction::BUDGET_EXCLUDED_KINDS + [ "investment_contribution" ]+ end+def investment_contributions_category# Find ALL legacy categories (created under old request-locale behavior)legacy = categories.where(name: Category.all_investment_contributions_names).order(:created_at).to_adiff --git a/app/models/income_statement.rb b/app/models/income_statement.rbindex bdf8120db2..1dec491a68 100644--- a/app/models/income_statement.rb+++ b/app/models/income_statement.rb@@ -26,11 +26,13 @@ class IncomeStatementtotal_income = result.select { |t| t.classification == "income" }.sum(&:total)total_expense = result.select { |t| t.classification == "expense" }.sum(&:total)+ total_invested = result.select { |t| t.classification == "investment" }.sum(&:total)ScopeTotals.new(transactions_count: result.sum(&:transactions_count),income_money: Money.new(total_income, family.currency),- expense_money: Money.new(total_expense, family.currency)+ expense_money: Money.new(total_expense, family.currency),+ invested_money: Money.new(total_invested, family.currency))end@@ -49,6 +51,14 @@ class IncomeStatement@income_totals_by_period[key] = build_period_total(classification: "income", period: period)end+ # Money moved into investment accounts during the period, for a family that+ # does not count it as spending. Zero for everyone else: their+ # contributions are already part of expense_totals.+ def invested_total(period: Period.current_month)+ total = totals_for_period(period).select { |t| t.classification == "investment" }.sum(&:total)+ Money.new(total, family.currency)+ end+def net_category_totals(period: Period.current_month)key = period_cache_key(period)@net_category_totals_by_period ||= {}@@ -184,7 +194,7 @@ class IncomeStatementendprivate- ScopeTotals = Data.define(:transactions_count, :income_money, :expense_money)+ ScopeTotals = Data.define(:transactions_count, :income_money, :expense_money, :invested_money)PeriodTotal = Data.define(:classification, :total, :currency, :category_totals)CategoryTotal = Data.define(:category, :total, :currency, :weight)NetCategoryTotals = Data.define(:net_expense_categories, :net_income_categories, :total_net_expense, :total_net_income, :currency)@@ -330,13 +340,15 @@ class IncomeStatement# An IncomeStatement is a request-scoped reporting snapshot, like its memoized# period totals. Share these aggregate reads across totals and daily series.- # Rates and target currency can change without touching entries or accounts.+ # Rates, target currency and whether investing counts as spending can+ # change without touching entries or accounts.def cache_freshness_key@cache_freshness_key ||= [family.entries_cache_version,family.accounts_status_version,family.currency,- ExchangeRate.maximum(:updated_at)&.to_i+ ExchangeRate.maximum(:updated_at)&.to_i,+ family.investment_contributions_as_spending?]enddiff --git a/app/models/income_statement/account_sankey.rb b/app/models/income_statement/account_sankey.rbindex b76c412573..2a53455630 100644--- a/app/models/income_statement/account_sankey.rb+++ b/app/models/income_statement/account_sankey.rb@@ -20,13 +20,14 @@ class IncomeStatement::AccountSankeyflows = account_flowsincome = flows.sum { |flow| flow[:income] }.to_dspending = flows.sum { |flow| flow[:spending] }.to_d- capacity = [ income, spending ].max+ invested = flows.sum { |flow| flow[:invested] }.to_d+ capacity = [ income, spending + invested ].maxunless 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),+ { basis: "net_by_account", income: decimal(income), spending: decimal(spending), invested: decimal(invested),net_savings: decimal(income - spending), nodes: @nodes.map { |node| serialize(node) }, links: @links }end@@ -39,15 +40,17 @@ class IncomeStatement::AccountSankeygroups = IncomeStatement::CategoryNetting.new(statement, period: @period).groupsincome = groups.sum { |group| side_total(group, :income) }.to_dspending = groups.sum { |group| side_total(group, :expense) }.to_d- next if income.zero? && spending.zero?+ # Zero unless the family stops counting investing as spending (#3952).+ invested = statement.invested_total(period: @period).amount.to_d+ next if income.zero? && spending.zero? && invested.zero?- { account: account, groups: groups, income: income, spending: spending }+ { account: account, groups: groups, income: income, spending: spending, invested: invested }endenddef add_account(flow, income, spending, capacity, subcategory_flows)account = flow[:account]- size = [ flow[:income], flow[:spending] ].max+ size = [ flow[:income], flow[:spending] + flow[:invested] ].maxcenter = node("account_#{account.id}", account.name, :account, color: ACCOUNT_COLOR)center[:value] = sizecenter[:percentage] = percentage(size, capacity)@@ -69,7 +72,14 @@ class IncomeStatement::AccountSankeyendend- net = flow[:income] - flow[:spending]+ if flow[:invested].positive?+ node_invested = node("invested_node", "Invested", :invested, color: IncomeStatement::Sankey::INVESTED_COLOR)+ node_invested[:value] += flow[:invested]+ node_invested[:percentage] = percentage(node_invested[:value], capacity)+ link(center, node_invested, flow[:invested], percentage(flow[:invested], capacity))+ end++ net = flow[:income] - flow[:spending] - flow[:invested]return if net.zero?kind = net.positive? ? :surplus : :deficitdiff --git a/app/models/income_statement/sankey.rb b/app/models/income_statement/sankey.rbindex 2147d892e2..1f63f89b66 100644--- a/app/models/income_statement/sankey.rb+++ b/app/models/income_statement/sankey.rb@@ -1,6 +1,9 @@# Cash-flow Sankey by category: income categories -> Cash Flow -> expense# categories. Netting is IncomeStatement::CategoryNetting's.class IncomeStatement::Sankey+ # The default colour of the Investment Contributions category.+ INVESTED_COLOR = "#0d9488".freeze+def initialize(statement, period:)@statement, @period = statement, periodend@@ -10,14 +13,21 @@ class IncomeStatement::Sankeygroups = IncomeStatement::CategoryNetting.new(@statement, period: @period).groupsincome = groups.sum { |group| side_total(group, :income) }.to_dspending = groups.sum { |group| side_total(group, :expense) }.to_d- capacity = [ income, spending ].max+ # Non-zero only for a family that does not count investing as spending:+ # it leaves the centre as its own outflow, next to spending.+ invested = @statement.invested_total(period: @period).amount.to_d+ capacity = [ income, spending + invested ].maxunless capacity.zero?center = add_node("cash_flow_node", "Cash Flow", :cash_flow, capacity, 100)groups.each do |group|add_group(group, :income, income, center)add_group(group, :expense, spending, center)end- net = income - spending+ unless invested.zero?+ index = add_node("invested_node", "Invested", :invested, invested, percentage(invested, capacity), color: INVESTED_COLOR)+ add_link(center, index, invested, percentage(invested, capacity))+ end+ net = income - spending - investedunless net.zero?kind = net.positive? ? :surplus : :deficitindex = add_node("#{kind}_node", kind.to_s.capitalize, kind, net.abs, percentage(net.abs, capacity))@@ -25,7 +35,7 @@ class IncomeStatement::Sankeyadd_link(source, target, net.abs, percentage(net.abs, capacity))endend- { basis: "net_by_category", income: decimal(income), spending: decimal(spending),+ { basis: "net_by_category", income: decimal(income), spending: decimal(spending), invested: decimal(invested),net_savings: decimal(income - spending), nodes: @nodes, links: @links }end@@ -53,10 +63,10 @@ class IncomeStatement::Sankeyendend- def add_node(id, name, kind, value, percentage, category = nil)+ def add_node(id, name, kind, value, percentage, category = nil, color: category&.color)@nodes << { id: id, name: name, kind: kind.to_s, value: decimal(value), percentage: decimal(percentage),category_id: category&.id, filter_value: category && !category.other_investments? ? category.filter_value : nil,- color: category&.color }+ color: color }@nodes.size - 1enddiff --git a/app/models/income_statement/scoped_transactions_query.rb b/app/models/income_statement/scoped_transactions_query.rbindex 283f916daf..5c95de04df 100644--- a/app/models/income_statement/scoped_transactions_query.rb+++ b/app/models/income_statement/scoped_transactions_query.rb@@ -10,11 +10,14 @@# aliases (`ae`, `a`). The including class must set `@family`.module IncomeStatement::ScopedTransactionsQueryprivate- # Contributions and loan payments are cash outflows recorded as negative- # amounts, so they always classify as expense; other negative amounts- # classify as income.+ # Contributions and loan payments are cash outflows whatever their+ # sign, so they classify as expense; other negative amounts classify as+ # income. A family that does not count investing as spending gets its+ # contributions classified as 'investment' instead, which keeps them out+ # of income and expense totals while still letting callers sum them.def classification_sql(t)- "CASE WHEN #{t}.kind IN ('investment_contribution', 'loan_payment') THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END"+ contribution = @family.investment_contributions_as_spending? ? "expense" : "investment"+ "CASE WHEN #{t}.kind = 'investment_contribution' THEN '#{contribution}' WHEN #{t}.kind = 'loan_payment' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END"end# Entry amount converted to the family currency at the day's exchangediff --git a/app/views/settings/preferences/show.html.erb b/app/views/settings/preferences/show.html.erbindex 5473278ddd..fd997dd44f 100644--- a/app/views/settings/preferences/show.html.erb+++ b/app/views/settings/preferences/show.html.erb@@ -43,6 +43,17 @@<% if @user.family.uses_custom_month_start? %><%= render DS::Alert.new(message: t(".month_start_day_warning"), variant: :warning) %><% end %>+ <% if Current.user.admin? %>+ <div class="flex items-center justify-between gap-4">+ <div class="space-y-1">+ <p class="text-sm" id="investment_contributions_as_spending_label"><%= t(".investment_contributions_as_spending") %></p>+ <p class="text-secondary text-sm"><%= t(".investment_contributions_as_spending_hint") %></p>+ </div>+ <%= family_form.toggle :investment_contributions_as_spending,+ "aria-labelledby": "investment_contributions_as_spending_label",+ data: { auto_submit_form_target: "auto" } %>+ </div>+ <% end %><% if Current.user.admin? && preview_features_enabled? %><div class="flex items-center justify-between"><div class="space-y-1">diff --git a/config/locales/views/pages/en.yml b/config/locales/views/pages/en.ymlindex c3d7f95ef2..581359b20e 100644--- a/config/locales/views/pages/en.yml+++ b/config/locales/views/pages/en.yml@@ -92,6 +92,7 @@ en:cash_flow: "Cash Flow"surplus: "Surplus"deficit: "Deficit"+ invested: "Invested"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."diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex 3c03b34121..f604a86962 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -203,6 +203,8 @@ en:month_start_day: Budget month starts onmonth_start_day_hint: Set when your budget month starts (e.g., payday)month_start_day_warning: Your budgets and MTD calculations will use this custom start day instead of the 1st of each month.+ investment_contributions_as_spending: Count investing as spending+ investment_contributions_as_spending_hint: Money moved into investment accounts counts as spending in budgets, reports and the cash flow chart. Turn off to show it as invested instead.personal_budgets: Personal budgetspersonal_budgets_hint: Enable individual budgets for each family member.household_budget_enabled: Household budgetdiff --git a/db/migrate/20261003120000_add_investment_contributions_as_spending_to_families.rb b/db/migrate/20261003120000_add_investment_contributions_as_spending_to_families.rbnew file mode 100644index 0000000000..88c43472a2--- /dev/null+++ b/db/migrate/20261003120000_add_investment_contributions_as_spending_to_families.rb@@ -0,0 +1,5 @@+class AddInvestmentContributionsAsSpendingToFamilies < ActiveRecord::Migration[8.1]+ def change+ add_column :families, :investment_contributions_as_spending, :boolean, default: true, null: false+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex f6c7ce4892..baafbbe2c1 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -855,6 +855,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_15_090000) dot.boolean "early_access", default: falset.string "enabled_currencies", array: truet.boolean "household_budget_enabled", default: true, null: false+ t.boolean "investment_contributions_as_spending", default: true, null: falset.datetime "last_sync_all_attempted_at"t.datetime "latest_sync_activity_at", default: -> { "CURRENT_TIMESTAMP" }t.datetime "latest_sync_completed_at", default: -> { "CURRENT_TIMESTAMP" }diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex ade0da102b..b461549edf 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -3356,6 +3356,10 @@ components:type: stringnet_savings:type: string+ invested:+ type: string+ description: Money moved into investment accounts, shown as its own node.+ Zero unless the family does not count investing as spendingnodes:type: arrayitems:@@ -3385,6 +3389,7 @@ components:- account- surplus- deficit+ - investedvalue:type: stringdescription: Nonnegative decimal in envelope currencydiff --git a/docs/clients.md b/docs/clients.mdindex e8264236fc..f4fbccbec7 100644--- a/docs/clients.md+++ b/docs/clients.md@@ -115,7 +115,7 @@ Read monthly server-calculated totals and the daily spending comparison usinguse these values instead of rebuilding Sure's reporting rules from transactions.Structural node `name` values are fallback labels; clients should localize-`cash_flow`, `surplus`, and `deficit` by `kind` at the presentation boundary.+`cash_flow`, `surplus`, `deficit`, and `invested` by `kind` at the presentation boundary.`include` and `view` are mutually exclusive; combining them returns `422 invalid_view`.diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rbindex fac23ca0ca..4d41023500 100644--- a/spec/swagger_helper.rb+++ b/spec/swagger_helper.rb@@ -1816,11 +1816,12 @@ RSpec.configure do |config|properties: {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 },+ invested: { type: :string, description: "Money moved into investment accounts, shown as its own node. Zero unless the family does not count investing as spending" },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 account surplus deficit] },+ name: { type: :string }, kind: { type: :string, enum: %w[income expense cash_flow account surplus deficit invested] },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/pages_controller_test.rb b/test/controllers/pages_controller_test.rbindex 2eed82a479..d744d61e86 100644--- a/test/controllers/pages_controller_test.rb+++ b/test/controllers/pages_controller_test.rb@@ -359,6 +359,56 @@ class PagesControllerTest < ActionDispatch::IntegrationTestassert sankey_data.fetch("nodes").any? { |node| node.fetch("id").start_with?("expense_") }end+ test "dashboard sankey shows investment contributions as invested when they are not spending" do+ @family.update!(investment_contributions_as_spending: false)+ category = @family.categories.create!(name: "Shopping", color: "#FF5733")+ income_category = @family.categories.create!(name: "Salary", color: "#33FF57")+ create_transaction(account: @family.accounts.first, name: "Payday", amount: -1000, category: income_category)+ create_transaction(account: @family.accounts.first, name: "Shopping trip", amount: 100, category: category)+ create_transaction(account: @family.accounts.first, name: "To ISA", amount: 400, category: nil, kind: "investment_contribution")++ get root_path+ assert_response :ok++ chart = css_select("[data-controller='sankey-chart']").first+ nodes = JSON.parse(chart["data-sankey-chart-data-value"]).fetch("nodes").index_by { |node| node.fetch("id") }++ assert_equal 400.0, nodes.fetch("invested_node").fetch("value")+ assert_equal I18n.t("pages.dashboard.cashflow_preview.node_labels.invested"), nodes.fetch("invested_node").fetch("name")+ assert nodes.keys.none? { |id| id.start_with?("expense_") && nodes[id].fetch("value") == 400.0 }+ end++ test "dashboard sankey balances a deficit when outflows exceed income" do+ @family.update!(investment_contributions_as_spending: false)+ category = @family.categories.create!(name: "Shopping", color: "#FF5733")+ income_category = @family.categories.create!(name: "Salary", color: "#33FF57")+ create_transaction(account: @family.accounts.first, name: "Payday", amount: -1000, category: income_category)+ create_transaction(account: @family.accounts.first, name: "Shopping trip", amount: 700, category: category)+ create_transaction(account: @family.accounts.first, name: "To ISA", amount: 500, category: nil, kind: "investment_contribution")++ get root_path+ assert_response :ok++ data = JSON.parse(css_select("[data-controller='sankey-chart']").first["data-sankey-chart-data-value"])+ nodes = data.fetch("nodes")+ index = nodes.each_with_index.to_h { |node, i| [ node.fetch("id"), i ] }+ links = data.fetch("links")+ center = index.fetch("cash_flow_node")++ assert_not index.key?("surplus_node")+ deficit = nodes[index.fetch("deficit_node")]+ assert_equal I18n.t("pages.dashboard.cashflow_preview.node_labels.deficit"), deficit.fetch("name")+ inflow = links.select { |link| link.fetch("target") == center }.sum { |link| link.fetch("value") }+ outflow = links.select { |link| link.fetch("source") == center }.sum { |link| link.fetch("value") }+ assert_in_delta outflow, inflow, 0.01, "the Cash Flow node must balance"+ assert links.any? { |link| link.fetch("source") == index.fetch("deficit_node") && link.fetch("target") == center },+ "the deficit flows into Cash Flow"+ assert_operator deficit.fetch("value"), :>=, 200.0, "at least the 200 by which this month's new outflows exceed the payday"+ capacity = nodes[center].fetch("value")+ assert_in_delta (500 / capacity * 100).round(1), nodes[index.fetch("invested_node")].fetch("percentage"), 0.05,+ "invested is a share of the Cash Flow node, which outflows size when they exceed income"+ end+test "dashboard sankey nodes carry a stable filter_value, including opposite-direction subcategories" doparent_category = @family.categories.create!(name: "Shopping", color: "#FF5733")subcategory = @family.categories.create!(name: "Rebate Program", parent: parent_category, color: "#33FF57")diff --git a/test/controllers/settings/preferences_controller_test.rb b/test/controllers/settings/preferences_controller_test.rbindex b083aa1984..66b6f997d9 100644--- a/test/controllers/settings/preferences_controller_test.rb+++ b/test/controllers/settings/preferences_controller_test.rb@@ -11,6 +11,22 @@ class Settings::PreferencesControllerTest < ActionDispatch::IntegrationTestassert_response :successend+ test "admins see the investing-as-spending toggle" do+ get settings_preferences_url++ assert_response :success+ assert_select "input[name='user[family_attributes][investment_contributions_as_spending]']"+ assert_match I18n.t("settings.preferences.show.investment_contributions_as_spending"), response.body+ end++ test "members do not see the investing-as-spending toggle" do+ sign_in users(:family_member)+ get settings_preferences_url++ assert_response :success+ assert_select "input[name='user[family_attributes][investment_contributions_as_spending]']", count: 0+ end+test "group moniker uses group currencies copy and hides legacy currency field" dousers(:family_admin).family.update!(moniker: "Group")diff --git a/test/controllers/users_controller_test.rb b/test/controllers/users_controller_test.rbindex 63c00b478a..f96367445d 100644--- a/test/controllers/users_controller_test.rb+++ b/test/controllers/users_controller_test.rb@@ -66,6 +66,32 @@ class UsersControllerTest < ActionDispatch::IntegrationTestassert_equal original_codes, @member.family.reload.enabled_currency_codesend+ test "admin can stop counting investing as spending" do+ patch user_url(@user), params: {+ user: {+ redirect_to: "preferences",+ family_attributes: { id: @user.family.id, investment_contributions_as_spending: "0" }+ }+ }++ assert_redirected_to settings_preferences_url+ assert_not @user.family.reload.investment_contributions_as_spending?+ end++ test "non-admin cannot change whether investing counts as spending" do+ sign_in @member = users(:family_member)++ patch user_url(@member), params: {+ user: {+ redirect_to: "preferences",+ family_attributes: { id: @member.family.id, investment_contributions_as_spending: "0" }+ }+ }++ assert_redirected_to settings_profile_url+ assert @member.family.reload.investment_contributions_as_spending?+ end+test "admin can reset family data" doaccount = accounts(:investment)category = categories(:income)diff --git a/test/javascript/utils/cash_flow_chart_data_test.mjs b/test/javascript/utils/cash_flow_chart_data_test.mjsindex 838fe5efe9..316b511db8 100644--- a/test/javascript/utils/cash_flow_chart_data_test.mjs+++ b/test/javascript/utils/cash_flow_chart_data_test.mjs@@ -35,6 +35,39 @@ test("maps graph geometry without rounding or changing API payload", () => {assert.equal(body.sankey.nodes[0].value, "12.345");assert.equal(graph.nodes[0].color, "#123456");});+test("accepts an invested node", () => {+ const body = payload();+ body.sankey.nodes.push({+ id: "invested_node",+ name: "Invested",+ kind: "invested",+ value: "5",+ percentage: "40.5",+ color: "#0d9488",+ });+ body.sankey.links.push({+ source: 1,+ target: 2,+ value: "5",+ percentage: "40.5",+ });+ const graph = cashFlowChartData(body);+ assert.equal(graph.nodes[2].kind, "invested");+ assert.equal(graph.nodes[2].color, "#0d9488");+});+test("an invested node without a colour falls back to its own colour", () => {+ const body = payload();+ body.sankey.nodes.push({+ id: "invested_node",+ name: "Invested",+ kind: "invested",+ value: "5",+ percentage: "40.5",+ });+ body.sankey.links.push({ source: 1, target: 2, value: "5", percentage: "40.5" });+ const graph = cashFlowChartData(body);+ assert.equal(graph.nodes[2].color, "#0d9488");+});test("accepts empty graphs", () => {assert.deepEqual(cashFlowChartData({diff --git a/test/models/assistant/function/get_income_statement_test.rb b/test/models/assistant/function/get_income_statement_test.rbindex 468641464c..921f366cb0 100644--- a/test/models/assistant/function/get_income_statement_test.rb+++ b/test/models/assistant/function/get_income_statement_test.rb@@ -85,6 +85,26 @@ class Assistant::Function::GetIncomeStatementTest < ActiveSupport::TestCaseassert result[:net].present?end+ test "account_ids results report the selected accounts' invested total when investing is not spending" do+ @family.update!(investment_contributions_as_spending: false)+ account = @family.accounts.visible.first+ other = @family.accounts.visible.where.not(id: account.id).first+ account.entries.create!(date: Date.current, amount: 250, currency: @family.currency, name: "To ISA",+ entryable: Transaction.new(kind: "investment_contribution"))+ other.entries.create!(date: Date.current, amount: 900, currency: @family.currency, name: "To SIPP",+ entryable: Transaction.new(kind: "investment_contribution"))++ result = @fn.call(@params.merge("account_ids" => [ account.id ]))++ assert_equal @fn.send(:format_money, 250), result.dig(:invested, :total)+ end++ test "account_ids results omit invested while investing counts as spending" do+ result = @fn.call(@params.merge("account_ids" => [ @family.accounts.visible.first.id ]))++ assert_not result.key?(:invested)+ end+test "unknown account ids return a soft failure naming them" dobogus = SecureRandom.uuiddiff --git a/test/models/income_statement/account_sankey_test.rb b/test/models/income_statement/account_sankey_test.rbindex 1b1bffba2d..ae6e95eea8 100644--- a/test/models/income_statement/account_sankey_test.rb+++ b/test/models/income_statement/account_sankey_test.rb@@ -47,6 +47,19 @@ class IncomeStatement::AccountSankeyTest < ActiveSupport::TestCaseassert_balanced resultend+ test "money invested leaves each account for Invested when investing is not spending" do+ @family.update!(investment_contributions_as_spending: false)+ transaction(@checking, -1000, @salary)+ transaction(@checking, 200, @shopping)+ create_transaction(account: @checking, amount: 300, category: nil, date: @month, kind: "investment_contribution")+ result = graph++ assert_equal "300.0", result[:invested]+ assert_link result, "account_#{@checking.id}", "invested_node", "300.0"+ assert_link result, "account_#{@checking.id}", "surplus_node", "500.0"+ assert_balanced result+ end+test "accounts without income or spending are left out, and an empty period is empty" dotransaction(@checking, 50, @shopping)assert_nil node(graph, "account_#{@card.id}")diff --git a/test/models/income_statement/sankey_test.rb b/test/models/income_statement/sankey_test.rbindex 9547706c05..b7e1c557c7 100644--- a/test/models/income_statement/sankey_test.rb+++ b/test/models/income_statement/sankey_test.rb@@ -95,6 +95,33 @@ class IncomeStatement::SankeyTest < ActiveSupport::TestCaseassert_equal graph, graphend+ test "investment contributions get their own invested node when they are not spending" do+ @family.update!(investment_contributions_as_spending: false)+ transaction(-1000, @family.categories.create!(name: "Salary", color: "#33FF57"))+ transaction(300, @parent)+ create_transaction(account: @account, amount: 500, category: nil, date: @month, kind: "investment_contribution")+ result = graph+ assert_equal "1000.0", result[:income]+ assert_equal "300.0", result[:spending]+ assert_equal "500.0", result[:invested]+ assert_equal "700.0", result[:net_savings]+ invested = node(result, "invested_node")+ assert_equal "invested", invested[:kind]+ assert_equal "500.0", invested[:value]+ assert_equal "200.0", node(result, "surplus_node")[:value]+ assert_balanced(result)+ end++ test "investment contributions stay in spending by default" do+ transaction(-1000, @family.categories.create!(name: "Salary", color: "#33FF57"))+ create_transaction(account: @account, amount: 500, category: nil, date: @month, kind: "investment_contribution")+ result = graph+ assert_equal "500.0", result[:spending]+ assert_equal "0.0", result[:invested]+ assert_nil node(result, "invested_node")+ assert_balanced(result)+ end+privatedef transaction(amount, category)create_transaction(account: @account, amount: amount, category: category, date: @month)diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex 42155e1200..40f12848d5 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -540,6 +540,37 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal Money.new(1900, @family.currency), totals.expense_money # 900 + 1000 investmentend+ test "reports investment contributions as invested when the family does not count them as spending" do+ create_transaction(account: @checking_account, amount: 1000, category: nil, kind: "investment_contribution")+ @family.update!(investment_contributions_as_spending: false)++ income_statement = IncomeStatement.new(@family)+ totals = income_statement.totals(date_range: Period.last_30_days.date_range)++ assert_equal Money.new(1000, @family.currency), totals.income_money+ assert_equal Money.new(900, @family.currency), totals.expense_money+ assert_equal 900, income_statement.expense_totals(period: Period.last_30_days).total+ assert_equal Money.new(1000, @family.currency), income_statement.invested_total(period: Period.last_30_days)+ end++ test "invested total is zero while investing counts as spending" do+ create_transaction(account: @checking_account, amount: 1000, category: nil, kind: "investment_contribution")++ income_statement = IncomeStatement.new(@family)++ assert_equal Money.new(0, @family.currency), income_statement.invested_total(period: Period.last_30_days)+ assert_equal 1900, income_statement.expense_totals(period: Period.last_30_days).total+ end++ test "loan payments still count as spending when investing does not" do+ create_transaction(account: @checking_account, amount: 300, category: nil, kind: "loan_payment")+ @family.update!(investment_contributions_as_spending: false)++ totals = IncomeStatement.new(@family).totals(date_range: Period.last_30_days.date_range)++ assert_equal Money.new(1200, @family.currency), totals.expense_money+ end+test "includes provider-imported investment_contribution inflows as expenses" do# Simulates a 401k contribution that was auto-deducted from payroll# Provider imports this as an inflow to the investment account (negative amount)diff --git a/test/system/cash_flow_test.rb b/test/system/cash_flow_test.rbindex ae4b5821ad..0e05196aa6 100644--- a/test/system/cash_flow_test.rb+++ b/test/system/cash_flow_test.rb@@ -12,6 +12,7 @@ class CashFlowTest < ApplicationSystemTestCaseaccount = @user.family.accounts.create!(name: "Sankey checking", currency: "USD", balance: 0, accountable: Depository.new)create_transaction(account: account, category: parent, amount: 100, date: @month)create_transaction(account: account, category: child, amount: 50, date: @month)+ @child, @account = child, accountendtest "loads the dashboard graph, expands, zooms, and preserves transaction date filters" do@@ -321,11 +322,11 @@ class CashFlowTest < ApplicationSystemTestCaseRails.configuration.stubs(:app_mode).returns("managed".inquiry)# A previous lifetime marker must no longer suppress comparisons.@user.update!(preferences: @user.preferences.merge("sankey_comparison_result" => "mismatch"))+ add_refunded_subcategorysign_in @uservisit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)assert_selector "#cashflow-preview svg .sankey-link"install_posthog_fake- # Expense-only input adds an explicit deficit in the new graph.assert_event_count "new_sankey_mismatch", 1page.execute_script("document.dispatchEvent(new Event('posthog:ready'))")find("#cashflow-preview [data-sankey-preview-target='expandButton']").click@@ -352,6 +353,7 @@ class CashFlowTest < ApplicationSystemTestCaseendtest "feedback buttons highlight the current comparison without analytics and reset on loading" do+ add_refunded_subcategorysign_in @uservisit root_path(start_date: @month.iso8601, end_date: Date.current.iso8601)assert_selector "#cashflow-preview[data-sankey-comparison='mismatch']"@@ -432,4 +434,10 @@ class CashFlowTest < ApplicationSystemTestCasepage.evaluate_script("window.sankeyEvents.filter(e => e.event === #{event.to_json}).length") == countendend++ # A subcategory refunded beyond its spending nests under its parent in the+ # new graph but links straight to Cash Flow in the original, so they differ.+ def add_refunded_subcategory+ create_transaction(account: @account, category: @child, amount: -80, date: @month)+ endend