The personal finance app for everyone (by everyone)
Ruby
feat(goals): surface money that left a goal's accounts unexplained (#3177)
buzzromainf0333c026e0d
diff --git a/app/controllers/goals_controller.rb b/app/controllers/goals_controller.rbindex ae291283bf..5d2b67f6bd 100644--- a/app/controllers/goals_controller.rb+++ b/app/controllers/goals_controller.rb@@ -34,6 +34,7 @@ class GoalsController < ApplicationControllerdef show@open_pledges = @goal.open_pledges.reverse_chronological.to_a+ @unattributed_outflows = withdrawal_detector.unattributed_outflows.to_a@breadcrumbs = plan_breadcrumb_prefix + [[ t("goals.index.title"), goals_path ],[ @goal.name, nil ]@@ -171,8 +172,10 @@ class GoalsController < ApplicationControllerenddef record_consumption- amount = params[:amount].to_d- @goal.consume!(amount, account: consumption_account)+ txn = consumption_transaction+ amount = txn ? txn.entry.amount.to_d : params[:amount].to_d++ @goal.consume!(amount, account: consumption_account(txn), transaction: txn)redirect_to goal_path(@goal),notice: t("goals.consume.success", amount: Money.new(amount, @goal.currency).format)rescue Goal::ConsumptionRefused => e@@ -338,11 +341,22 @@ class GoalsController < ApplicationController# rather than falling back to nil: on a single-link goal, nil would consume# from that link and the user would see a spend recorded against an account# they did not name.+ # Attributing a detected outflow: the transaction says both how much and+ # from where, so neither is taken from the form.+ def consumption_transaction+ return nil if params[:transaction_id].blank?++ withdrawal_detector.unattributed_outflows(limit: 50)+ .find_by(entryable_id: params[:transaction_id])+ &.entryable ||+ raise(Goal::ConsumptionRefused.new(:transaction_not_found))+ end+# The goal's links narrowed to what the VIEWER may see. A goal can be- # backed by a private account, and both halves of that leak matter: the+ # backed by a private account, and every half of that leak matters: the# dialog would name an account the reader is not allowed to know exists,- # and a direct POST would reduce its earmark — the figures moving- # afterwards saying how much was in it.+ # the outflow panel would list its transactions, and a POST would reduce+ # its earmark — the figures moving afterwards saying how much was in it.def eligible_consumption_accounts@eligible_consumption_accounts ||= beginlinked = @goal.linked_accounts@@ -351,12 +365,20 @@ class GoalsController < ApplicationControllerendend- def consumption_account+ def withdrawal_detector+ Goal::WithdrawalDetector.new(@goal, accounts: eligible_consumption_accounts)+ end++ def consumption_account(txn = nil)eligible = eligible_consumption_accountsraise Goal::ConsumptionRefused.new(:account_not_linked) if eligible.empty?- if params[:account_id].present?- return eligible.find { |account| account.id.to_s == params[:account_id].to_s } ||+ # An attributed outflow names its own account; a typed spend names one+ # only when the goal has a choice to offer.+ account_id = txn ? txn.entry.account_id : params[:account_id]++ if account_id.present?+ return eligible.find { |account| account.id.to_s == account_id.to_s } ||raise(Goal::ConsumptionRefused.new(:account_not_linked))enddiff --git a/app/models/goal.rb b/app/models/goal.rbindex a68baec35e..56afe9b0b5 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -415,7 +415,12 @@ class Goal < ApplicationRecord# `account:` may be omitted only when the goal has one link. With several,# guessing would silently pick a side; the caller has to say which pot the# money came out of.- def consume!(amount, account: nil)+ # `transaction:` anchors the record on the outflow it came from. Without one+ # this is a bare declaration and nothing stops it being made twice; with one,+ # the transaction is stamped and a second attempt on the same outflow is+ # refused. Same `extra["goal"]` namespace the pledges already write into, so+ # the two halves of a goal's money — in and out — are stamped alike.+ def consume!(amount, account: nil, transaction: nil)amount = amount.to_draise ConsumptionRefused.new(:non_positive) unless amount.positive?# A reserve is not consumed, it is drawn down and refilled. Spending from@@ -436,6 +441,7 @@ class Goal < ApplicationRecordraise ConsumptionRefused.new(:exceeds_target) if consumed_amount.to_d + amount > target_amount.to_dlink.lock!+ stamp_consumption!(transaction) if transaction# A whole-account link reserves no fixed slice, so there is nothing to# shrink — it already takes only what the account has left.@@ -947,6 +953,23 @@ class Goal < ApplicationRecordendend+ # Claims the outflow for this goal, refusing one already claimed. Inside+ # the caller's transaction, so a refusal here rolls the consumption back+ # rather than leaving the goal credited for a spend it did not record.+ def stamp_consumption!(txn)+ txn.with_lock do+ claimed_by = txn.extra&.dig("goal", "consumed_goal_id")+ if claimed_by.present? && claimed_by != id+ raise ConsumptionRefused.new(:transaction_already_claimed)+ end+ raise ConsumptionRefused.new(:transaction_already_claimed) if claimed_by == id++ extra = txn.extra || {}+ extra["goal"] = (extra["goal"] || {}).merge("consumed_goal_id" => id)+ txn.update!(extra: extra)+ end+ end+def consumption_link_for(account)links = goal_accounts.to_araise ConsumptionRefused.new(:no_linked_account) if links.empty?@@ -967,7 +990,16 @@ class Goal < ApplicationRecord# have the reopened goal claim credit for money spent on something it has# already been closed for.def thaw_completed_amount!- update_columns(completed_amount: nil, completed_at: nil, consumed_amount: 0)+ attrs = { completed_amount: nil, completed_at: nil }++ # Only a goal that actually closed a lifecycle starts over. A goal+ # archived straight from active never froze a figure, so unarchiving it+ # is picking the same goal back up rather than restarting it — wiping+ # what it had recorded as spent would delete history nothing replaced,+ # and drop its progress for no reason the user can see.+ attrs[:consumed_amount] = 0 if completed_amount.present?++ update_columns(**attrs)end# Cleared after every AASM transition. The state column drives thediff --git a/app/models/goal/withdrawal_detector.rb b/app/models/goal/withdrawal_detector.rbnew file mode 100644index 0000000000..2e5d35b01a--- /dev/null+++ b/app/models/goal/withdrawal_detector.rb@@ -0,0 +1,79 @@+# Finds money that has left a goal's accounts without anyone saying where it+# went.+#+# Goals never read transactions — `current_balance` is a stock, summed from+# account balances — so an outflow reaches them only as a smaller number, with+# no idea which goal it belonged to. `consume!` closes that gap but only if the+# user thinks to declare it, which is the same problem the goal page had before+# the reserve insight: the app knows and does not say.+#+# This is the *pull* half of what `GoalPledge` does for money coming in. The+# pledge asks first and matches later; here there is nothing to promise, so the+# outflow is surfaced after the fact and the user attributes it — or does not.+class Goal::WithdrawalDetector+ # Below this an attribution is more friction than it is worth: a goal-backed+ # savings account sees card-sized outflows that nobody wants to file.+ #+ # Same known limitation as `IdleCashGenerator::MIN_BALANCE`: a flat figure in+ # family-currency units, tuned for dollar/euro-scale currencies.+ MIN_AMOUNT = 100++ # A window, not all history. An outflow nobody attributed in three months is+ # one nobody is going to, and asking forever turns the panel into a chore.+ LOOKBACK_DAYS = 90++ # `accounts:` narrows the search to what the caller may see. A goal can be+ # backed by an account private to another family member, and its outflows are+ # that member's business — surfacing them here would name the account, its+ # spending and roughly its size to someone with no access to it. Defaults to+ # every linked account for callers with no viewer to speak for (jobs, tests).+ def initialize(goal, accounts: nil)+ @goal = goal+ @accounts = accounts+ end++ # Outflows on this goal's accounts that nothing has claimed yet, newest+ # first. Empty for a goal that cannot consume — a reserve is drawn down and+ # refilled rather than spent, and its shortfall already says so on its own.+ def unattributed_outflows(limit: 3)+ return Entry.none unless goal.one_off?+ # A released goal has handed its accounts back, so an outflow on one of+ # them is no longer evidence about this goal — offering it would invite the+ # user to write spending into a history that is closed. `consume!` refuses+ # these too; the panel simply should not ask in the first place.+ return Entry.none unless goal.active?+ return Entry.none if accounts.empty?++ candidates.limit(limit)+ end++ private+ attr_reader :goal++ def accounts+ @accounts ||= goal.linked_accounts+ end++ def candidates+ Entry+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")+ .where(account_id: accounts.map(&:id))+ .where(excluded: false)+ .where(date: LOOKBACK_DAYS.days.ago.to_date..Date.current)+ # In Sure an inflow carries a NEGATIVE amount, so an outflow is the+ # positive side. Reading this the other way round would offer to+ # attribute the user's deposits as spending.+ .where("entries.amount >= ?", MIN_AMOUNT)+ .where("transactions.extra -> 'goal' ->> 'consumed_goal_id' IS NULL")+ # A provisional charge can still be reversed or replaced by its posted+ # form. Attributing one leaves the goal consumed for a transaction that+ # no longer exists, while the posted twin arrives unstamped and gets+ # offered all over again.+ #+ # `pending_providers_sql` is built to be appended to an existing WHERE,+ # so it leads with AND; the rest of its clauses chain correctly once+ # that first one is dropped.+ .where(Transaction.pending_providers_sql("transactions").sub(/\AAND /, ""))+ .order(date: :desc, id: :desc)+ end+enddiff --git a/app/views/goals/_unattributed_outflows.html.erb b/app/views/goals/_unattributed_outflows.html.erbnew file mode 100644index 0000000000..41760abccf--- /dev/null+++ b/app/views/goals/_unattributed_outflows.html.erb@@ -0,0 +1,48 @@+<%# locals: (goal:, outflows:) %>++<%# Money has left this goal's accounts and nothing says where it went. Goals+ never read transactions — `current_balance` is a stock — so an outflow+ reaches them only as a smaller number. This is the app saying what it+ already knows instead of waiting to be asked. %>+<div class="bg-container rounded-xl shadow-border-xs p-4 space-y-3">+ <div class="flex items-start gap-3">+ <div class="w-8 h-8 rounded-full bg-surface-inset inline-flex items-center justify-center text-secondary shrink-0">+ <%= icon("arrow-down-left", size: "sm") %>+ </div>+ <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(".body", goal: goal.name) %></p>+ </div>+ </div>++ <ul class="space-y-2">+ <% outflows.each do |entry| %>+ <li class="flex items-center justify-between gap-3 rounded-lg bg-surface-inset px-3 py-2">+ <div class="min-w-0">+ <p class="text-sm text-primary truncate"><%= entry.name %></p>+ <p class="text-xs text-secondary tabular-nums privacy-sensitive">+ <%= l(entry.date, format: :long) %>+ <span aria-hidden="true"><%= t("shared.dot_separator") %></span>+ <%= entry.account.name %>+ </p>+ </div>+ <div class="flex items-center gap-2 shrink-0">+ <span class="text-sm text-primary tabular-nums privacy-sensitive">+ <%= Money.new(entry.amount, entry.currency).format(precision: 0) %>+ </span>+ <%# DS::Button, not a bare button_to with raw btn classes: the same+ primitive the consumption dialog uses, so the two ways of+ recording a spend do not look like two different features. %>+ <%= render DS::Button.new(+ text: t(".attribute"),+ href: consume_goal_path(goal),+ method: :post,+ params: { transaction_id: entry.entryable_id },+ variant: :secondary,+ size: :sm+ ) %>+ </div>+ </li>+ <% end %>+ </ul>+</div>diff --git a/app/views/goals/show.html.erb b/app/views/goals/show.html.erbindex f39f582e14..ff77c2423a 100644--- a/app/views/goals/show.html.erb+++ b/app/views/goals/show.html.erb@@ -95,6 +95,10 @@<%= render "pending_pledge_banner", pledge: pledge %><% end %>+ <% if @unattributed_outflows.any? %>+ <%= render "unattributed_outflows", goal: @goal, outflows: @unattributed_outflows %>+ <% end %>+<% if @goal.paused? %><%= render DS::Alert.new(variant: "info", title: t("goals.show.paused_banner.title")) do %><p class="text-secondary"><%= t("goals.show.paused_banner.body") %></p>diff --git a/config/locales/views/goals/en.yml b/config/locales/views/goals/en.ymlindex 2f3dba0a26..017d828bda 100644--- a/config/locales/views/goals/en.yml+++ b/config/locales/views/goals/en.yml@@ -113,7 +113,13 @@ en:account_not_linked: That account does not fund this goal.not_active: This goal is no longer active, so nothing can be recorded against it.exceeds_earmark: That is more than this account has earmarked for the goal.+ transaction_already_claimed: That outflow has already been attributed.+ transaction_not_found: That outflow is no longer available to attribute.no_linked_account: This goal has no funding account left.+ unattributed_outflows:+ heading: Money left these accounts+ body: If any of this was spent on %{goal}, say so and it stops counting against the target.+ attribute: This was itshow:edit: Editconsume: I used some of this moneydiff --git a/config/locales/views/goals/fr.yml b/config/locales/views/goals/fr.ymlindex 63988dabaf..4695869a24 100644--- a/config/locales/views/goals/fr.yml+++ b/config/locales/views/goals/fr.yml@@ -188,7 +188,13 @@ fr:account_not_linked: Ce compte ne finance pas cet objectif.not_active: Cet objectif n'est plus actif, rien ne peut y être enregistré.exceeds_earmark: C'est plus que ce que ce compte a affecté à l'objectif.+ transaction_already_claimed: Cette sortie a déjà été attribuée.+ transaction_not_found: Cette sortie n'est plus disponible.no_linked_account: Cet objectif n'a plus de compte de financement.+ unattributed_outflows:+ heading: De l'argent est sorti de ces comptes+ body: Si une partie a servi à %{goal}, dites-le et elle cessera de compter comme un retard.+ attribute: C'était çashow:archive: Archiverarchived_banner:diff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rbindex b850afe745..650bc946c3 100644--- a/test/controllers/goals_controller_test.rb+++ b/test/controllers/goals_controller_test.rb@@ -141,6 +141,22 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestassert_equal 500, link.reload.allocated_amountend+ # The outflow panel is the third door onto a private backing account: it+ # would list its transactions, naming the account, its spending and roughly+ # its size to someone with no access to it.+ test "the outflow panel does not surface a spend on an account the viewer cannot see" do+ private_account = private_linked_account+ private_account.entries.create!(+ name: "Private Spend", date: Date.current, amount: 400,+ currency: private_account.currency, entryable: Transaction.new+ )++ get goal_url(@goal)++ assert_response :success+ assert_no_match(/Private Spend/, response.body)+ end+test "create rejects a same-family account not shared with the current user" doprivate_account = Account.create!(family: @user.family,@@ -626,6 +642,43 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestassert_equal 0, goal.reload.consumed_amountend+ # --- Lot B5: attributing an outflow the app spotted ---++ test "the goal page offers an outflow nothing has claimed" do+ goal, entry = goal_with_outflow++ get goal_url(goal)++ assert_response :success+ assert_match I18n.t("goals.unattributed_outflows.heading"), response.body+ assert_match entry.name, response.body+ end++ test "attributing an outflow takes its amount and stops offering it" do+ goal, entry = goal_with_outflow++ post consume_goal_url(goal), params: { transaction_id: entry.entryable_id }++ assert_redirected_to goal_url(goal)+ assert_equal entry.amount.to_d, goal.reload.consumed_amount++ get goal_url(goal)+ assert_no_match I18n.t("goals.unattributed_outflows.heading"), response.body+ end++ # The stamp is what makes this idempotent: replaying the same attribution+ # must not credit the goal twice for one spend.+ test "the same outflow cannot be attributed twice" do+ goal, entry = goal_with_outflow+ post consume_goal_url(goal), params: { transaction_id: entry.entryable_id }+ recorded = goal.reload.consumed_amount++ post consume_goal_url(goal), params: { transaction_id: entry.entryable_id }++ assert_equal recorded, goal.reload.consumed_amount+ assert_equal I18n.t("goals.consume.errors.transaction_not_found"), flash[:alert]+ end+private# SQL the pooled-allocation read issues, and nothing else: goal_accounts# joined to goals.@@ -656,6 +709,21 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest@goal.goal_accounts.create!(account: account, allocated_amount: 500)accountend++ def goal_with_outflow+ account = Account.create!(+ family: @user.family, accountable: Depository.new,+ name: "Trip Pot #{SecureRandom.hex(4)}", currency: @user.family.currency, balance: 5_000+ )+ goal = @user.family.goals.create!(+ name: "Trip", target_amount: 5_000, currency: @user.family.currency+ ) { |g| g.goal_accounts.build(account: account, allocated_amount: 5_000) }+ entry = account.entries.create!(+ name: "Flights", date: Date.current, amount: 1_200,+ currency: account.currency, entryable: Transaction.new+ )+ [ goal, entry ]+ end# An active one_off goal sitting exactly at its target, on an account no# other goal claims.def fully_funded_goaldiff --git a/test/models/goal/withdrawal_detector_test.rb b/test/models/goal/withdrawal_detector_test.rbnew file mode 100644index 0000000000..68e5b07199--- /dev/null+++ b/test/models/goal/withdrawal_detector_test.rb@@ -0,0 +1,147 @@+require "test_helper"++class Goal::WithdrawalDetectorTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @account = Account.create!(+ family: @family, accountable: Depository.new,+ name: "Trip Pot #{SecureRandom.hex(4)}", currency: "USD", balance: 5_000+ )+ @goal = @family.goals.create!(name: "Trip", target_amount: 5_000, currency: "USD") do |g|+ g.goal_accounts.build(account: @account, allocated_amount: 5_000)+ end+ end++ test "surfaces an outflow nothing has claimed" do+ entry = outflow(1_200)++ assert_equal [ entry.id ], detect.map(&:id)+ end++ # In Sure an inflow carries a NEGATIVE amount. Reading the sign the other way+ # round would offer to attribute the user's own deposits as spending.+ test "never surfaces an inflow" do+ outflow(-1_200)++ assert_empty detect+ end++ test "ignores an outflow below the threshold" do+ outflow(Goal::WithdrawalDetector::MIN_AMOUNT - 1)++ assert_empty detect+ end++ test "ignores an outflow the user excluded" do+ outflow(1_200).update!(excluded: true)++ assert_empty detect+ end++ test "ignores an outflow older than the window" do+ outflow(1_200, date: (Goal::WithdrawalDetector::LOOKBACK_DAYS + 1).days.ago.to_date)++ assert_empty detect+ end++ test "stops offering an outflow once it has been attributed" do+ entry = outflow(1_200)+ assert_equal [ entry.id ], detect.map(&:id)++ @goal.consume!(1_200, transaction: entry.entryable)++ assert_empty detect+ end++ # A reserve is drawn down and refilled, not spent. Asking the user to+ # attribute a withdrawal from one would invite them to erase the shortfall+ # the reserve exists to report.+ test "says nothing for a reserve" do+ reserve_account = Account.create!(+ family: @family, accountable: Depository.new,+ name: "Reserve Pot", currency: "USD", balance: 4_000+ )+ reserve = @family.goals.create!(+ name: "Precaution", target_amount: 6_000, currency: "USD", kind: "maintained"+ ) { |g| g.goal_accounts.build(account: reserve_account) }+ create_outflow(reserve_account, 1_200, Date.current)++ assert_empty Goal::WithdrawalDetector.new(reserve).unattributed_outflows+ end++ test "an outflow on an account this goal does not fund is not its business" do+ other = Account.create!(+ family: @family, accountable: Depository.new,+ name: "Other Pot", currency: "USD", balance: 5_000+ )+ create_outflow(other, 1_200, Date.current)++ assert_empty detect+ end++ test "newest first, capped" do+ older = outflow(1_000, date: 10.days.ago.to_date)+ newest = outflow(2_000, date: 1.day.ago.to_date)+ middle = outflow(3_000, date: 5.days.ago.to_date)++ assert_equal [ newest.id, middle.id ], detect(limit: 2).map(&:id)+ assert_includes detect(limit: 3).map(&:id), older.id+ end++ # --- Review follow-ups ---++ # A released goal has handed its accounts back, so a later outflow on one of+ # them is not evidence about this goal. Offering it invites the user to write+ # spending into a history that is already closed.+ test "says nothing once the goal has been released" do+ entry = outflow(1_200)+ assert_equal [ entry.id ], detect.map(&:id)++ @goal.complete!++ assert_empty detect+ end++ test "says nothing for an archived goal" do+ outflow(1_200)+ @goal.archive!++ assert_empty detect+ end++ # A provisional charge can still be reversed, or replaced by its posted form.+ # Attributing one leaves the goal consumed for a transaction that no longer+ # exists, while the posted twin arrives unstamped and is offered all over.+ test "ignores an outflow the provider has not posted yet" do+ entry = outflow(1_200)+ entry.entryable.update!(extra: { "simplefin" => { "pending" => true } })++ assert_empty detect+ end++ test "still surfaces an outflow the provider has posted" do+ entry = outflow(1_200)+ entry.entryable.update!(extra: { "simplefin" => { "pending" => false } })++ assert_equal [ entry.id ], detect.map(&:id)+ end++ private+ def detect(limit: 3)+ Goal::WithdrawalDetector.new(@goal).unattributed_outflows(limit: limit)+ end++ def outflow(amount, date: Date.current)+ create_outflow(@account, amount, date)+ end++ def create_outflow(account, amount, date)+ account.entries.create!(+ name: "Spend #{SecureRandom.hex(3)}",+ date: date,+ amount: amount,+ currency: account.currency,+ entryable: Transaction.new+ )+ end+enddiff --git a/test/models/goal_consumption_test.rb b/test/models/goal_consumption_test.rbindex dda28732a3..517e619e93 100644--- a/test/models/goal_consumption_test.rb+++ b/test/models/goal_consumption_test.rb@@ -204,6 +204,29 @@ class GoalConsumptionTest < ActiveSupport::TestCaseassert_equal 50, goal.progress_percent, "and progress is preserved, which is the point"end+ # Restarting a goal drops what it spent under its previous life, along with+ # the frozen figure. A goal archived straight from active never froze one —+ # unarchiving it is picking the same goal back up, not restarting it.+ test "unarchiving a goal that never completed keeps what it spent" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)+ goal.consume!(1_000)+ goal.archive!++ goal.unarchive!++ assert_equal 1_000, goal.reload.consumed_amount+ end++ test "reopening a completed goal starts it over" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)+ goal.consume!(1_000)+ goal.complete!++ goal.reopen!++ assert_equal 0, goal.reload.consumed_amount+ end+privatedef fresh_account(balance)Account.create!(