The personal finance app for everyone (by everyone)
Ruby
feat(budgets): show what is actually free, beside the plan (#3179)
buzzromain03b783b139f4
diff --git a/app/models/budget.rb b/app/models/budget.rbindex 057c974799..3a477d99ea 100644--- a/app/models/budget.rb+++ b/app/models/budget.rb@@ -19,6 +19,7 @@ class Budget < ApplicationRecordvalidates :start_date, :end_date, presence: truevalidates :start_date, :end_date, uniqueness: { scope: [ :family_id, :user_id ] }+ monetize :available_cash, :earmarked_for_goals, :free_cashmonetize :budgeted_spending, :expected_income, :allocated_spending,:actual_spending, :available_to_spend, :available_to_allocate,:estimated_spending, :estimated_income, :actual_income, :remaining_expected_income,@@ -177,6 +178,72 @@ class Budget < ApplicationRecordscopeend+ # --- Cash on hand, next to the plan ---+ #+ # DELIBERATELY OUTSIDE the allocation arithmetic. `budgeted_spending`,+ # `allocated_spending` and `available_to_allocate` keep their exact meaning:+ # they answer "what did I plan to spend, and how much of it have I+ # distributed". These three answer a different question — "what do I actually+ # have" — and mixing the two is how a budget stops being readable. A page+ # showing "expected income 3,000" beside "really free 1,600" leaves the user+ # unsure which number drives the split.+ #+ # This is the whole of the compromise: the plan stays a forecast, and the+ # cash is shown beside it rather than folded into it.++ # Liquidity only. Cash held inside investment accounts (Account#cash_balance)+ # is deliberately out: it is not money available to this month's budget.+ #+ # Scoped like #transactions — a personal budget sees only its owner's+ # accounts, the household one what the viewer can see — because a figure+ # labelled "available" must mean available to the person reading it.+ def cash_accounts+ scope = family.accounts.visible.included_in_reports.where(accountable_type: "Depository")++ if user_id.present?+ scope.where(owner_id: user_id)+ elsif current_user+ scope.accessible_by(current_user)+ else+ scope+ end+ end++ def available_cash+ @available_cash ||= cash_accounts.sum { |account| convert_to_budget_currency(account.balance, account.currency) }+ end++ # What goals have already spoken for, out of THE SAME accounts. Restricting+ # to `cash_accounts` is the point: Goal::FUNDABLE_ACCOUNT_TYPES also includes+ # Investment, and subtracting an earmark held on a brokerage account from a+ # cash figure that never counted it would show a "really free" amount that is+ # too low — or negative — with nothing on the page to explain why.+ #+ # Built from the shared pool rather than summing allocated_amount, because a+ # whole-account link reserves no fixed slice and would otherwise count as+ # zero while actually claiming the remainder.+ def earmarked_for_goals+ @earmarked_for_goals ||= begin+ ids = cash_accounts.map(&:id)++ if ids.empty?+ 0.to_d+ else+ # Converted per goal. `available_cash` converts each account balance+ # into the budget currency, so summing backings in their own would+ # subtract euros from dollars: a fully earmarked EUR 1,000 account in+ # a USD budget would read 1,200 available, 1,000 earmarked and 200+ # free, when none of it is free.+ Goal.prepared_for(family, scope: family.goals.where.not(state: Goal::RELEASED_STATES))+ .sum { |goal| convert_to_budget_currency(goal.backing_within(ids), goal.currency) }+ end+ end+ end++ def free_cash+ [ available_cash - earmarked_for_goals, 0 ].max+ end+def nameif family.uses_custom_month_start?I18n.t(@@ -431,6 +498,18 @@ class Budget < ApplicationRecordendprivate+ # `find_or_fetch_rate`, not `find_rate` — the latter does not exist, and+ # every multi-currency family opening this page hit a NoMethodError.+ #+ # No rate for the day leaves the amount as it stands. A cash panel that+ # renders with one figure unconverted is wrong by the spread; one that+ # raises takes the whole budget page down with it.+ def convert_to_budget_currency(amount, from_currency)+ return amount.to_d if from_currency == currency++ rate = ExchangeRate.find_or_fetch_rate(from: from_currency, to: currency, date: Date.current)&.rate+ rate ? amount.to_d * rate : amount.to_d+ enddef income_statement@income_statement ||= family.income_statement(user: current_user, accounts: income_statement_accounts)enddiff --git a/app/models/goal.rb b/app/models/goal.rbindex 56afe9b0b5..0343a45b22 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -372,6 +372,20 @@ class Goal < ApplicationRecord# This goal's backing from a single linked account — the earmarked slice, or# the whole-balance remainder when the link is unallocated — as Money. Used# by the funding breakdown so the per-account rows reconcile with the ring.+ # This goal's backing drawn from a specific set of accounts, in its own+ # currency. Used by the budget to ask "how much of THESE accounts is already+ # spoken for" without counting a link held on an account outside the set.+ #+ # Goes through the same `backing_share_for` as everything else, so a+ # whole-account link is counted for the remainder it actually claims rather+ # than the zero its nil allocation would suggest.+ def backing_within(account_ids)+ ids = Array(account_ids).to_set+ linked_accounts+ .select { |account| account.currency == currency && ids.include?(account.id) }+ .sum { |account| account_amount_for(account) }+ end+def account_backing(account)Money.new(account_amount_for(account), currency)enddiff --git a/app/views/budgets/_available_cash.html.erb b/app/views/budgets/_available_cash.html.erbnew file mode 100644index 0000000000..7a47dff607--- /dev/null+++ b/app/views/budgets/_available_cash.html.erb@@ -0,0 +1,43 @@+<%# locals: (budget:) %>++<%# Beside the plan, never inside it. The figures above answer "what did I plan+ to spend"; these answer "what do I actually have". Folding one into the+ other leaves the reader unsure which number drives the split, so the panel+ keeps its own frame and its own heading. %>+<div class="w-full bg-container rounded-xl shadow-border-xs p-4">+ <div class="flex items-start justify-between gap-3 mb-3">+ <div class="min-w-0">+ <h2 class="text-sm font-medium text-primary"><%= t(".heading") %></h2>+ <p class="text-xs text-secondary mt-0.5"><%= t(".subtitle") %></p>+ </div>+ <%= render DS::Link.new(+ text: t(".goals_link"),+ href: goals_path,+ variant: "outline",+ size: "sm"+ ) %>+ </div>++ <dl class="space-y-2">+ <div class="flex items-baseline justify-between gap-3">+ <dt class="text-sm text-secondary"><%= t(".available") %></dt>+ <dd class="text-lg font-medium text-primary tabular-nums privacy-sensitive">+ <%= format_money budget.available_cash_money %>+ </dd>+ </div>++ <div class="flex items-baseline justify-between gap-3">+ <dt class="text-sm text-secondary"><%= t(".earmarked") %></dt>+ <dd class="text-sm text-secondary tabular-nums privacy-sensitive">+ −<%= format_money budget.earmarked_for_goals_money %>+ </dd>+ </div>++ <div class="flex items-baseline justify-between gap-3 border-t border-subdued pt-2">+ <dt class="text-sm font-medium text-primary"><%= t(".free") %></dt>+ <dd class="text-lg font-medium text-primary tabular-nums privacy-sensitive">+ <%= format_money budget.free_cash_money %>+ </dd>+ </div>+ </dl>+</div>diff --git a/app/views/budgets/show.html.erb b/app/views/budgets/show.html.erbindex c88fce4daf..e921b76214 100644--- a/app/views/budgets/show.html.erb+++ b/app/views/budgets/show.html.erb@@ -46,6 +46,13 @@<% end %></div>+ <%# Goals live behind the preview flag, so a panel that subtracts what they+ claim — and links to them — must too, or it points at a page the reader+ cannot reach and explains a subtraction they have no way to inspect. %>+ <% if preview_features_enabled? %>+ <%= render "budgets/available_cash", budget: @budget %>+ <% end %>+<%# Bottom Section: Categories full width %><% has_over_budget = budget_has_over_budget?(@budget) %><%= content_tag :div,diff --git a/config/locales/views/budgets/en.yml b/config/locales/views/budgets/en.ymlindex 63d1a05898..aaeb331b43 100644--- a/config/locales/views/budgets/en.yml+++ b/config/locales/views/budgets/en.yml@@ -38,6 +38,13 @@ en:name:custom_range: "%{start} - %{end_date}"month_year: "%{month}"+ available_cash:+ heading: Cash on hand+ subtitle: Beside the plan above, not part of it.+ available: Available in cash+ earmarked: Already earmarked for goals+ free: Really free+ goals_link: View goalsshow:categories:amount: Amountdiff --git a/config/locales/views/budgets/fr.yml b/config/locales/views/budgets/fr.ymlindex 594e7782b5..23f0cbf59b 100644--- a/config/locales/views/budgets/fr.yml+++ b/config/locales/views/budgets/fr.yml@@ -57,6 +57,13 @@ fr:status: Statutview_all_transactions: Voir toutes les transactions de catégoriebudgets:+ available_cash:+ heading: Trésorerie disponible+ subtitle: À côté du plan ci-dessus, pas dedans.+ available: Disponible en cash+ earmarked: Déjà fléché vers des objectifs+ free: Réellement libre+ goals_link: Voir les objectifsswitcher:aria_label: "Changer de budget"household: "Commun"diff --git a/test/controllers/budgets_controller_test.rb b/test/controllers/budgets_controller_test.rbindex 0e5e43c0c7..c81469d278 100644--- a/test/controllers/budgets_controller_test.rb+++ b/test/controllers/budgets_controller_test.rb@@ -35,6 +35,26 @@ class BudgetsControllerTest < ActionDispatch::IntegrationTestassert_select "a[href=?]", plan_path, count: 0assert_select "a[href=?]", budgets_path, minimum: 1end+ # --- Lot A3: cash on hand ---++ test "the cash panel is hidden without preview access" do+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => false))++ get budget_url(Budget.date_to_param(Date.current.beginning_of_month))++ assert_response :success+ assert_no_match I18n.t("budgets.available_cash.heading"), response.body+ end++ test "the cash panel shows what goals have already claimed" do+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))++ get budget_url(Budget.date_to_param(Date.current.beginning_of_month))++ assert_response :success+ assert_match I18n.t("budgets.available_cash.heading"), response.body+ assert_match I18n.t("budgets.available_cash.free"), response.body+ endendclass BudgetsControllerSharingTest < ActionDispatch::IntegrationTestdiff --git a/test/models/budget_available_cash_test.rb b/test/models/budget_available_cash_test.rbnew file mode 100644index 0000000000..a37a2e8cb2--- /dev/null+++ b/test/models/budget_available_cash_test.rb@@ -0,0 +1,154 @@+require "test_helper"++# Lot A3: cash on hand shown beside the plan, never folded into it.+class BudgetAvailableCashTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ @budget = Budget.find_or_bootstrap(@family, start_date: Date.current, user: nil)+ @budget.update!(budgeted_spending: 3_000, expected_income: 5_000)+ end++ test "counts only liquidity" do+ cash = depository(2_000)+ investment(9_000)++ assert_equal cash.balance.to_d, @budget.available_cash+ end++ test "leaves out accounts excluded from reports" do+ depository(2_000)+ depository(500).update!(exclude_from_reports: true)++ assert_equal 2_000, @budget.available_cash+ end++ test "subtracts what a goal has earmarked on those accounts" do+ account = depository(6_000)+ goal_on(account, earmark: 2_000)++ assert_equal 6_000, @budget.available_cash+ assert_equal 2_000, @budget.earmarked_for_goals+ assert_equal 4_000, @budget.free_cash+ end++ # A whole-account link reserves no fixed slice, so summing `allocated_amount`+ # would read it as zero while it actually claims the remainder.+ test "a whole-account link counts for what it really claims" do+ account = depository(6_000)+ goal_on(account, earmark: nil)++ assert_equal 6_000, @budget.earmarked_for_goals+ assert_equal 0, @budget.free_cash+ end++ # Goal::FUNDABLE_ACCOUNT_TYPES includes Investment. Subtracting an earmark+ # held on a brokerage account from a cash figure that never counted it would+ # show a "really free" amount too low, with nothing on the page to explain it.+ test "ignores an earmark held on an account the cash figure never counted" do+ depository(4_000)+ goal_on(investment(9_000), earmark: 5_000)++ assert_equal 4_000, @budget.available_cash+ assert_equal 0, @budget.earmarked_for_goals+ assert_equal 4_000, @budget.free_cash+ end++ test "a released goal has handed its money back" do+ account = depository(6_000)+ goal = goal_on(account, earmark: 2_000)++ goal.archive!++ assert_equal 0, Budget.find(@budget.id).earmarked_for_goals+ end++ test "free cash never reads as negative" do+ account = depository(1_000)+ goal_on(account, earmark: nil)+ goal_on(depository(500), earmark: nil)++ assert_operator Budget.find(@budget.id).free_cash, :>=, 0+ end++ # The whole point of the compromise: the plan is a forecast and stays one.+ test "none of this touches the allocation arithmetic" do+ before_allocated = @budget.allocated_spending+ before_available = @budget.available_to_allocate+ goal_on(depository(6_000), earmark: 2_000)++ reloaded = Budget.find(@budget.id)++ assert_equal before_allocated, reloaded.allocated_spending+ assert_equal before_available, reloaded.available_to_allocate+ assert_equal 3_000, reloaded.budgeted_spending+ end+++ # --- Review follow-ups (#3179) ---++ # `available_cash` converts each balance into the budget currency, so an+ # earmark summed in the goal's own would be subtracted from a figure it does+ # not match: a fully earmarked EUR account reading as partly free.+ test "a foreign-currency earmark is converted before it is subtracted" do+ account = Account.create!(+ family: @family, accountable: Depository.new,+ name: "EUR pot", currency: "EUR", balance: 1_000+ )+ @family.goals.create!(+ name: "Trip", target_amount: 1_000, currency: "EUR"+ ) { |g| g.goal_accounts.build(account: account, allocated_amount: 1_000) }++ ExchangeRate.stubs(:find_or_fetch_rate).returns(OpenStruct.new(rate: 1.2))++ assert_equal 1_200, @budget.available_cash+ assert_equal 1_200, @budget.earmarked_for_goals+ assert_equal 0, @budget.free_cash, "none of a fully earmarked account is free"+ end++ # `ExchangeRate.find_rate` does not exist; every multi-currency family+ # opening the budget page hit a NoMethodError before the cash panel rendered.+ test "a foreign-currency account does not take the page down" do+ Account.create!(+ family: @family, accountable: Depository.new,+ name: "EUR pot", currency: "EUR", balance: 1_000+ )++ ExchangeRate.stubs(:find_or_fetch_rate).returns(OpenStruct.new(rate: 1.2))++ assert_equal 1_200, @budget.available_cash+ end++ # A missing rate leaves the amount as it stands rather than raising: a panel+ # wrong by the spread beats the whole budget page failing to render.+ test "a missing rate leaves the figure standing rather than raising" do+ Account.create!(+ family: @family, accountable: Depository.new,+ name: "EUR pot", currency: "EUR", balance: 1_000+ )++ ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)++ assert_equal 1_000, @budget.available_cash+ end++ private+ def depository(balance)+ Account.create!(+ family: @family, accountable: Depository.new,+ name: "Cash #{SecureRandom.hex(4)}", currency: @family.currency, balance: balance+ )+ end++ def investment(balance)+ Account.create!(+ family: @family, accountable: Investment.new,+ name: "Brokerage #{SecureRandom.hex(4)}", currency: @family.currency, balance: balance+ )+ end++ def goal_on(account, earmark:)+ @family.goals.create!(+ name: "Goal #{SecureRandom.hex(4)}", target_amount: 10_000, currency: @family.currency+ ) { |g| g.goal_accounts.build(account: account, allocated_amount: earmark) }+ end+end