The personal finance app for everyone (by everyone)
Ruby
feat(goals): let a goal be spent without looking like it fell behind (#3176)
buzzromain613964529ae7
diff --git a/app/controllers/goals_controller.rb b/app/controllers/goals_controller.rbindex d20e46f57c..aeadeef081 100644--- a/app/controllers/goals_controller.rb+++ b/app/controllers/goals_controller.rb@@ -1,6 +1,6 @@class GoalsController < ApplicationControllerbefore_action :require_preview_features!- before_action :set_goal, only: %i[show edit update destroy pause resume complete archive unarchive reopen]+ before_action :set_goal, only: %i[show edit update destroy pause resume complete archive unarchive reopen consume record_consumption]FUNDABLE_TYPES = Goal::FUNDABLE_ACCOUNT_TYPESrescue_from ActiveRecord::RecordNotFound, with: :goal_not_found@@ -160,6 +160,22 @@ class GoalsController < ApplicationControllerperform_transition!(:unarchive)end+ # Renders the dialog. The write lives in its own action below.+ def consume+ @consumption_accounts = eligible_consumption_accounts+ end++ def record_consumption+ amount = params[:amount].to_d+ @goal.consume!(amount, account: consumption_account)+ redirect_to goal_path(@goal),+ notice: t("goals.consume.success", amount: Money.new(amount, @goal.currency).format)+ rescue Goal::ConsumptionRefused => e+ redirect_to goal_path(@goal), alert: t("goals.consume.errors.#{e.reason}")+ rescue ActiveRecord::RecordInvalid => e+ redirect_to goal_path(@goal), alert: e.record.errors.full_messages.to_sentence+ end+def reopenperform_transition!(:reopen)end@@ -312,6 +328,40 @@ class GoalsController < ApplicationController}end+ # A blank id means "the goal has one link, use it" and the model decides+ # whether that is true. An id that resolves to nothing is refused here+ # 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.+ # 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+ # 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.+ def eligible_consumption_accounts+ @eligible_consumption_accounts ||= begin+ linked = @goal.linked_accounts+ visible_ids = Current.user.accessible_accounts.where(id: linked.map(&:id)).pluck(:id).to_set+ linked.select { |account| visible_ids.include?(account.id) }+ end+ end++ def consumption_account+ eligible = eligible_consumption_accounts+ raise 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 } ||+ raise(Goal::ConsumptionRefused.new(:account_not_linked))+ end++ # Named explicitly even when the goal has several links, because the one+ # the viewer can reach is not necessarily the one the model would pick on+ # its own. With more than one eligible link it stays nil, and the model+ # refuses rather than guessing.+ eligible.size == 1 ? eligible.first : nil+ end+def perform_transition!(event)unless @goal.aasm.may_fire_event?(event)redirect_to goal_path(@goal), alert: t(".invalid_transition")diff --git a/app/models/goal.rb b/app/models/goal.rbindex 4070e46f4c..a68baec35e 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -42,6 +42,8 @@ class Goal < ApplicationRecordvalidate :currency_locked_once_linkedvalidate :restore_must_not_recreate_whole_account_conflictvalidate :kind_locked_while_released+ validate :kind_locked_once_consumed+ validate :target_must_cover_what_was_consumed# A reserve has no deadline. Normalising here rather than rejecting: the form# hides the field for a reserve, so a date can only arrive from a conversion# or a crafted request — refusing would show an error about a field the user@@ -85,6 +87,18 @@ class Goal < ApplicationRecord# Goal#whole_account_conflicts_on), and the restore guard# #restore_must_not_recreate_whole_account_conflict, which reads the same# method. Adding a state here makes all of them release together.+ # Raised by #consume!. Carries a reason so the controller can say WHICH rule+ # refused rather than "something went wrong" — every one of them is+ # actionable by the user.+ class ConsumptionRefused < StandardError+ attr_reader :reason++ def initialize(reason)+ @reason = reason+ super("goal consumption refused: #{reason}")+ end+ end+RELEASED_STATES = %w[archived completed].freeze# A one-off goal is reached once and then closed; a maintained one is a@@ -382,8 +396,70 @@ class Goal < ApplicationRecordMoney.new(amount, currency)end+ # What is still to be found. Money already SPENT on the thing the goal was+ # for counts as found: it did its job. Without that term, coming home from+ # the holiday a goal paid for dropped it from 100% to 20%, and the only way+ # back was to edit the target — falsifying what the user had set out to save.def remaining_amount- @remaining_amount ||= [ target_amount - current_balance, 0 ].max+ @remaining_amount ||= [ target_amount - current_balance - consumed_amount.to_d, 0 ].max+ end++ # Records that `amount` was spent on the thing this goal was for.+ #+ # Two things happen, and the second is the one that is easy to miss: the+ # earmark on the account shrinks by the same amount. Without that, money the+ # user has already spent stays reserved, and keeps its share of the account+ # away from every sibling goal — the very double-counting the exclusivity+ # rules exist to prevent, arriving through the back door.+ #+ # `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)+ amount = amount.to_d+ raise ConsumptionRefused.new(:non_positive) unless amount.positive?+ # A reserve is not consumed, it is drawn down and refilled. Spending from+ # one leaves a shortfall to close, which `remaining_amount` already reports+ # on its own; recording it as consumption would erase exactly the signal+ # the reserve exists to give.+ raise ConsumptionRefused.new(:maintained) if maintained?++ link = consumption_link_for(account)++ # The GOAL is locked, not just the link. `consumed_amount` lives here, and+ # two concurrent requests locking only their own links would both read the+ # same old value, both pass the target check, and both add to it — the+ # goal ending up consumed past its target with neither request at fault.+ # The checks below therefore run under the lock, on freshly read values.+ with_lock do+ raise ConsumptionRefused.new(:not_active) unless active?+ raise ConsumptionRefused.new(:exceeds_target) if consumed_amount.to_d + amount > target_amount.to_d++ link.lock!++ # A whole-account link reserves no fixed slice, so there is nothing to+ # shrink — it already takes only what the account has left.+ if link.allocated_amount.present?+ # Refused rather than clamped. Clamping released only what the link+ # held while `consumed_amount` took the full figure, so the two sides+ # silently disagreed: money counted as spent that was never released,+ # and still reserved against every sibling goal on the account.+ if amount > link.allocated_amount.to_d+ raise ConsumptionRefused.new(:exceeds_earmark)+ end++ link.update!(allocated_amount: link.allocated_amount.to_d - amount)+ end++ update!(consumed_amount: consumed_amount.to_d + amount)+ end++ # `reload` refreshes the columns and leaves the memos standing. Consuming+ # moves the same balance-derived figures a transition does — and shrinks a+ # link's allocation, so the pooled-allocation memo goes with them.+ reload+ reset_state_dependent_caches!+ selfenddef remaining_amount_money@@ -400,7 +476,7 @@ class Goal < ApplicationRecordelsif remaining_amount.to_d.zero?100else- ((current_balance.to_d / target_amount.to_d) * 100).floor.clamp(0, 99)+ (((current_balance.to_d + consumed_amount.to_d) / target_amount.to_d) * 100).floor.clamp(0, 99)endend@@ -852,13 +928,6 @@ class Goal < ApplicationRecord@pooled_pace ||= self.class.pace_for(family)end- # Cleared after every AASM transition. The state column drives the- # display_status / projection_summary memos; without this the same- # instance keeps returning the pre-transition value if a controller- # calls archive! / pause! and then renders without reload.- # Reopening or unarchiving hands the goal back to the live calculation:- # it is being funded again, so a figure frozen at an earlier close would- # misreport it from here on.def apply_state_change_side_effectsprevious_state, next_state = saved_change_to_state@@ -878,10 +947,33 @@ class Goal < ApplicationRecordendend+ def consumption_link_for(account)+ links = goal_accounts.to_a+ raise ConsumptionRefused.new(:no_linked_account) if links.empty?++ if account.nil?+ raise ConsumptionRefused.new(:account_required) if links.size > 1+ return links.first+ end++ links.find { |link| link.account_id == account.id } ||+ raise(ConsumptionRefused.new(:account_not_linked))+ end++ # Reopening or unarchiving hands the goal back to the live calculation: it+ # is being funded again, so a figure frozen at an earlier close would+ # misreport it from here on. Reopening restarts the goal, so what was spent+ # under its previous life goes with the frozen figure — leaving it would+ # 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)+ update_columns(completed_amount: nil, completed_at: nil, consumed_amount: 0)end+ # Cleared after every AASM transition. The state column drives the+ # display_status / projection_summary memos; without this the same instance+ # keeps returning the pre-transition value if a controller calls archive! /+ # pause! and then renders without reload.def reset_state_dependent_caches!# current_balance depends on the goal's own state — a goal in any of# RELEASED_STATES is excluded from the shared pool, and a completed one@@ -984,6 +1076,28 @@ class Goal < ApplicationRecord# `completed` — a state that has HANDED BACK its earmark — while the show# page promises its money stays reserved. The conversion has to go through# an active state, where `complete` is already refused for a reserve.+ # A reserve refuses consumption, so letting a goal that has already recorded+ # some become one leaves that figure stranded: it still counts toward+ # progress, on an object whose whole model says spending is a shortfall to+ # refill rather than a job done. The two readings cannot both be true.+ def kind_locked_once_consumed+ return unless will_save_change_to_kind?+ return unless maintained?+ return unless consumed_amount.to_d.positive?++ errors.add(:kind, :locked_once_consumed)+ end++ # The consumed total is checked while consuming, which left the ordinary+ # edit form free to lower the target underneath it — a goal reporting more+ # spent than it ever set out to save.+ def target_must_cover_what_was_consumed+ return unless target_amount.present? && consumed_amount.to_d.positive?+ return if target_amount.to_d >= consumed_amount.to_d++ errors.add(:target_amount, :below_consumed)+ end+def kind_locked_while_releasedreturn unless persisted? && will_save_change_to_kind?# The PERSISTED state, not the one in memory. A single update can setdiff --git a/app/views/goals/consume.html.erb b/app/views/goals/consume.html.erbnew file mode 100644index 0000000000..eddb3f5dbc--- /dev/null+++ b/app/views/goals/consume.html.erb@@ -0,0 +1,52 @@+<%# Rendered into the modal frame by the "I used some of this" action on the+ goal page. DS::Dialog rather than a hand-rolled one — the component carries+ focus trapping, Escape, click-outside and focus restore. %>+<%= render DS::Dialog.new(width: "sm") do |dialog| %>+ <% dialog.with_header(title: t(".title"), subtitle: t(".subtitle", goal: @goal.name)) %>++ <% dialog.with_body do %>+ <%= styled_form_with url: consume_goal_path(@goal), method: :post, class: "space-y-4" do |f| %>+ <div class="space-y-1">+ <%= label_tag :amount, t(".amount_label"), class: "text-sm text-secondary" %>+ <%= number_field_tag :amount, nil,+ step: Money::Currency.new(@goal.currency).step,+ min: Money::Currency.new(@goal.currency).step,+ max: (@goal.target_amount.to_d - @goal.consumed_amount.to_d).to_f,+ required: true,+ autocomplete: "off",+ autofocus: true,+ class: "form-field__input w-full text-right tabular-nums privacy-sensitive" %>+ <p class="text-xs text-secondary">+ <%= t(".amount_hint", saved: @goal.current_balance_money.format(precision: 0)) %>+ </p>+ </div>++ <%# Only asked when there is a choice to make. With one link the model+ takes it on its own, and a select of one is a question with no answer. %>+ <%# The viewer's eligible links, not the goal's. Listing all of them+ would name private accounts the reader may not know exist, and offer+ options the controller then refuses. %>+ <% if @consumption_accounts.size > 1 %>+ <%# DS::Select, not a bare select_tag: the design system already has the+ primitive and hand-rolling an input shape is how a page stops+ matching the rest of the app. %>+ <%= render DS::Select.new(+ form: f,+ method: :account_id,+ items: @consumption_accounts.map { |account| { label: account.name, value: account.id } },+ label: t(".account_label")+ ) %>+ <% end %>++ <p class="text-xs text-secondary"><%= t(".earmark_note") %></p>++ <div class="flex justify-end gap-2 pt-1">+ <%= render DS::Button.new(text: t(".cancel"),+ variant: "secondary",+ type: "button",+ data: { action: "DS--dialog#close" }) %>+ <%= render DS::Button.new(text: t(".submit"), type: "submit") %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/goals/show.html.erb b/app/views/goals/show.html.erbindex e687975134..f39f582e14 100644--- a/app/views/goals/show.html.erb+++ b/app/views/goals/show.html.erb@@ -37,6 +37,13 @@<% if @goal.may_resume? %><% menu.with_item(variant: "button", text: t(".resume"), icon: "play", href: resume_goal_path(@goal), method: :patch) %><% end %>+ <%# Partial spend: only offered on a one-off goal that is still running+ and has something to spend. A reserve is drawn down and refilled,+ not consumed — the model refuses it outright. %>+ <% if @goal.one_off? && @goal.active? && @goal.current_balance.to_d.positive? %>+ <% menu.with_item(variant: "link", text: t(".consume"), icon: "hand-coins",+ href: consume_goal_path(@goal), data: { turbo_frame: :modal }) %>+ <% end %><% if @goal.may_complete? %><% menu.with_item(variant: "button",diff --git a/config/locales/models/goal/en.yml b/config/locales/models/goal/en.ymlindex f6ede4b781..cf1272f5de 100644--- a/config/locales/models/goal/en.yml+++ b/config/locales/models/goal/en.yml@@ -24,5 +24,8 @@ en:must_belong_to_family: Linked accounts must belong to the same family as the goal.kind:locked_while_released: Reopen this goal before turning it into a reserve.+ locked_once_consumed: This goal has already recorded money as spent, so it cannot become a reserve.+ target_amount:+ below_consumed: Can't set a target below what this goal has already recorded as spent.currency:locked_after_linked: Can't change the currency after the goal is linked to accounts.diff --git a/config/locales/models/goal/fr.yml b/config/locales/models/goal/fr.ymlindex eedf95df7e..2040ae58b6 100644--- a/config/locales/models/goal/fr.yml+++ b/config/locales/models/goal/fr.yml@@ -20,6 +20,9 @@ fr:whole_account_conflict_on_restore: "Impossible de restaurer cet objectif : « %{account_name} » est désormais entièrement affecté à « %{goal_name} ». Indiquez d'abord un montant sur l'un des deux."kind:locked_while_released: Rouvrez cet objectif avant d'en faire une réserve.+ locked_once_consumed: Cet objectif a déjà enregistré des dépenses, il ne peut pas devenir une réserve.+ target_amount:+ below_consumed: Impossible de fixer une cible inférieure à ce que cet objectif a déjà enregistré comme dépensé.currency:locked_after_linked: Impossible de modifier la devise après que l'objectif a été lié à des comptes.linked_accounts:diff --git a/config/locales/views/goals/en.yml b/config/locales/views/goals/en.ymlindex 871b28fd34..c35a51da19 100644--- a/config/locales/views/goals/en.yml+++ b/config/locales/views/goals/en.yml@@ -95,8 +95,28 @@ en:reopen:success: Goal reopened.invalid_transition: Goal can't be reopened from its current state.+ consume:+ title: Record a spend+ subtitle: "%{goal}"+ amount_label: How much did you use?+ amount_hint: "%{saved} is currently backing this goal."+ account_label: From which account?+ earmark_note: The amount you record stops being reserved for this goal, so your other goals on that account get their share back.+ cancel: Cancel+ submit: Record it+ success: "%{amount} recorded as used."+ errors:+ non_positive: Enter an amount greater than zero.+ maintained: A reserve is drawn down and refilled, not spent — its shortfall already shows on the goal.+ exceeds_target: That is more than this goal ever set out to save.+ account_required: This goal is funded by several accounts — say which one the money came out of.+ 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.+ no_linked_account: This goal has no funding account left.show:edit: Edit+ consume: I used some of this moneypause: Pauseresume: Resumecomplete: Mark completediff --git a/config/locales/views/goals/fr.yml b/config/locales/views/goals/fr.ymlindex 3552265b39..03642562ef 100644--- a/config/locales/views/goals/fr.yml+++ b/config/locales/views/goals/fr.yml@@ -166,6 +166,25 @@ fr:resume:invalid_transition: L'objectif ne peut pas être repris dans son état actuel.success: Objectif repris.+ consume:+ title: Enregistrer une dépense+ subtitle: "%{goal}"+ amount_label: Combien avez-vous utilisé ?+ amount_hint: "%{saved} soutiennent actuellement cet objectif."+ account_label: Depuis quel compte ?+ earmark_note: "Le montant enregistré cesse d'être réservé à cet objectif : vos autres objectifs sur ce compte récupèrent leur part."+ cancel: Annuler+ submit: Enregistrer+ success: "%{amount} enregistrés comme utilisés."+ errors:+ non_positive: Indiquez un montant supérieur à zéro.+ maintained: Une réserve se ponctionne et se recomplète, elle ne se dépense pas — son manque apparaît déjà sur l'objectif.+ exceeds_target: C'est plus que ce que cet objectif visait à épargner.+ account_required: Cet objectif est financé par plusieurs comptes — indiquez celui d'où vient l'argent.+ 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.+ no_linked_account: Cet objectif n'a plus de compte de financement.show:archive: Archiverarchived_banner:@@ -199,6 +218,7 @@ fr:confirm_complete_title: Marquer cet objectif comme terminé ?delete: Supprimeredit: Modifier+ consume: J'ai utilisé une partie de cet argentempty:body: Effectuez un virement sur votre compte lié. Sure le détectera lors de la prochaine synchronisation. Ou mettez à jour manuellement le solde du compte.heading: Aucun dépôt pour l'instantdiff --git a/config/routes.rb b/config/routes.rbindex 44352608ba..51edee89cc 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -428,6 +428,12 @@ Rails.application.routes.draw dopatch :archivepatch :unarchivepatch :reopen+ # Two actions on one path rather than one action branching on the verb:+ # HEAD routes like GET but `request.get?` is false for it, so a branch+ # would send a HEAD request down the write path. A goal can be partly+ # spent more than once, so the write is a POST, not a PATCH on the goal.+ get :consume+ post :consume, action: :record_consumption, as: nilendresources :pledges, only: %i[new create destroy], controller: "goal_pledges" dodiff --git a/db/migrate/20260825120000_add_consumed_amount_to_goals.rb b/db/migrate/20260825120000_add_consumed_amount_to_goals.rbnew file mode 100644index 0000000000..cf100ec8e3--- /dev/null+++ b/db/migrate/20260825120000_add_consumed_amount_to_goals.rb@@ -0,0 +1,20 @@+class AddConsumedAmountToGoals < ActiveRecord::Migration[7.2]+ def change+ # What has been spent OUT of this goal, on the thing it was for.+ #+ # Progress reads `(backing + consumed) / target`, so spending the money a+ # goal was saved for stops looking like falling behind. Without it, coming+ # home from the holiday the goal paid for dropped it from 100% to 20%, and+ # the only way back was to edit the target — which falsified what the user+ # had actually set out to save.+ #+ # Kept separate from `completed_amount` rather than folded into it: that+ # one freezes the BACKING at closure, and adding consumption to it would+ # count the same money twice on a goal that was partly spent and then+ # closed.+ add_column :goals, :consumed_amount, :decimal, precision: 19, scale: 4, null: false, default: 0++ add_check_constraint :goals, "consumed_amount >= 0",+ name: "chk_goals_consumed_amount_non_negative"+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 7c5871e59f..9e539914d3 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[7.2].define(version: 2026_08_24_120000) do+ActiveRecord::Schema[7.2].define(version: 2026_08_25_120000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pgcrypto"enable_extension "plpgsql"@@ -882,11 +882,13 @@ ActiveRecord::Schema[7.2].define(version: 2026_08_24_120000) dot.string "icon"t.string "progress_basis", default: "balance", null: falset.decimal "completed_amount", precision: 19, scale: 4+ t.decimal "consumed_amount", precision: 19, scale: 4, default: "0.0", null: falset.datetime "completed_at"t.string "kind", default: "one_off", null: falset.index ["family_id", "state"], name: "index_goals_on_family_id_and_state"t.index ["family_id"], name: "index_goals_on_family_id"t.check_constraint "char_length(name::text) <= 255", name: "chk_savings_goals_name_length"+ t.check_constraint "consumed_amount >= 0::numeric", name: "chk_goals_consumed_amount_non_negative"t.check_constraint "kind::text = ANY (ARRAY['one_off'::character varying, 'maintained'::character varying]::text[])", name: "chk_goals_kind_enum"t.check_constraint "progress_basis::text = ANY (ARRAY['balance'::character varying, 'contributions'::character varying]::text[])", name: "chk_goals_progress_basis_enum"t.check_constraint "state::text = ANY (ARRAY['active'::character varying, 'paused'::character varying, 'completed'::character varying, 'archived'::character varying]::text[])", name: "chk_savings_goals_state_enum"diff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rbindex 4b438e51b7..f95ed0c40d 100644--- a/test/controllers/goals_controller_test.rb+++ b/test/controllers/goals_controller_test.rb@@ -117,6 +117,30 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestassert_no_match(/goal_account_ids_#{private_account.id}/, response.body)end+ # A goal can be backed by an account the viewer is not allowed to see. Both+ # halves of that leak matter: the dialog naming it, and a direct POST moving+ # its earmark — the figures afterwards saying how much was in it.+ test "the consumption dialog does not name a linked account the viewer cannot see" do+ private_account = private_linked_account++ get consume_goal_url(@goal)++ assert_response :success+ assert_no_match(/Member Private Checking/, response.body)+ assert_no_match(/#{private_account.id}/, response.body)+ end++ test "consumption is refused against a linked account the viewer cannot see" do+ private_account = private_linked_account+ link = @goal.goal_accounts.find_by(account_id: private_account.id)++ post consume_goal_url(@goal), params: { amount: "100", account_id: private_account.id }++ assert_redirected_to goal_path(@goal)+ assert_equal 0, @goal.reload.consumed_amount+ assert_equal 500, link.reload.allocated_amount+ end+test "create rejects a same-family account not shared with the current user" doprivate_account = Account.create!(family: @user.family,@@ -499,7 +523,73 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestassert_no_match(/#{Regexp.escape(I18n.t("goals.show.empty.heading"))}/, response.body)end+ # --- Lot B4: recording a partial spend ---++ test "recording a spend keeps the goal at full progress and frees the earmark" do+ account = Account.create!(+ family: @user.family, accountable: Depository.new,+ name: "Trip Pot", currency: @user.family.currency, balance: 5_000+ )+ goal = @user.family.goals.create!(name: "Trip", target_amount: 5_000, currency: @user.family.currency) do |g|+ g.goal_accounts.build(account: account, allocated_amount: 5_000)+ end++ post consume_goal_url(goal), params: { amount: 2_000 }++ assert_redirected_to goal_url(goal)+ assert_equal 2_000, goal.reload.consumed_amount+ assert_equal 3_000, goal.goal_accounts.first.reload.allocated_amount+ end++ test "a refused spend says which rule refused it" do+ account = Account.create!(+ family: @user.family, accountable: Depository.new,+ name: "Reserve Pot", currency: @user.family.currency, balance: 4_000+ )+ reserve = @user.family.goals.create!(+ name: "Precaution", target_amount: 6_000, currency: @user.family.currency, kind: "maintained"+ ) { |g| g.goal_accounts.build(account: account) }++ post consume_goal_url(reserve), params: { amount: 1_000 }++ assert_redirected_to goal_url(reserve)+ assert_equal I18n.t("goals.consume.errors.maintained"), flash[:alert]+ assert_equal 0, reserve.reload.consumed_amount+ end++ # A blank account id means "this goal has one link". An id resolving to+ # nothing must not fall back to that, or a single-link goal would record a+ # spend against an account the user never named.+ test "an unknown account id is refused rather than falling through" do+ account = Account.create!(+ family: @user.family, accountable: Depository.new,+ name: "Trip Pot", currency: @user.family.currency, balance: 5_000+ )+ goal = @user.family.goals.create!(name: "Trip", target_amount: 5_000, currency: @user.family.currency) do |g|+ g.goal_accounts.build(account: account, allocated_amount: 5_000)+ end++ post consume_goal_url(goal), params: { amount: 1_000, account_id: SecureRandom.uuid }++ assert_equal I18n.t("goals.consume.errors.account_not_linked"), flash[:alert]+ assert_equal 0, goal.reload.consumed_amount+ end+private++ # A private account of another member, linked to the goal under test.+ def private_linked_account+ account = Account.create!(+ family: @user.family,+ owner: users(:family_member),+ accountable: Depository.new,+ name: "Member Private Checking",+ currency: @goal.currency,+ balance: 1_000+ )+ @goal.goal_accounts.create!(account: account, allocated_amount: 500)+ account+ 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_consumption_test.rb b/test/models/goal_consumption_test.rbnew file mode 100644index 0000000000..dda28732a3--- /dev/null+++ b/test/models/goal_consumption_test.rb@@ -0,0 +1,224 @@+require "test_helper"++# Lot B4: recording that a goal's money was spent on what it was for.+class GoalConsumptionTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ end++ test "spending a goal's money does not look like falling behind" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)+ assert_equal 100, goal.progress_percent++ goal.consume!(3_000)++ assert_equal 3_000, goal.consumed_amount+ assert_equal 100, goal.progress_percent, "spent money still counts toward the target"+ assert_equal 0, goal.remaining_amount+ end++ # The part that is easy to miss: money already spent must stop being+ # reserved, or it keeps its share of the account away from sibling goals.+ test "consuming shrinks the earmark by the same amount" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)++ goal.consume!(2_000)++ assert_equal 3_000, goal.goal_accounts.first.reload.allocated_amount+ end++ # Deliberately over-earmarked, which is the normal state of a shared account+ # mid-saving: 10,000 claimed on 6,000 held, so the pro-rata haircut is in+ # play and both goals read 3,000. Releasing spent money relieves the haircut+ # and the sibling's share grows — where two plain fixed earmarks inside the+ # balance would each just take their own amount and nothing would move.+ test "the freed share relieves the haircut on a sibling goal" do+ account = fresh_account(6_000)+ mine = goal_on(account, earmark: 5_000, target: 5_000, name: "Trip")+ sibling = goal_on(account, earmark: 5_000, target: 5_000, name: "Sibling")++ before = Goal.find(sibling.id).current_balance.to_d+ assert_equal 3_000, before, "the fixture should start out haircut"++ mine.consume!(2_000)++ assert_equal 3_750, Goal.find(sibling.id).current_balance.to_d+ end++ # A whole-account link reserves no fixed slice, so there is nothing to shrink.+ test "a whole-account link records the consumption and keeps its shape" do+ account = fresh_account(5_000)+ goal = @family.goals.create!(name: "Whole", target_amount: 5_000, currency: "USD") do |g|+ g.goal_accounts.build(account: account)+ end++ goal.consume!(1_000)++ assert_equal 1_000, goal.consumed_amount+ assert_nil goal.goal_accounts.first.reload.allocated_amount+ end++ test "with several linked accounts the caller has to say which one" do+ goal = goal_with(earmark: 3_000, balance: 3_000, target: 6_000)+ goal.goal_accounts.create!(account: fresh_account(3_000), allocated_amount: 3_000)++ error = assert_raises(Goal::ConsumptionRefused) { goal.consume!(1_000) }+ assert_equal :account_required, error.reason+ end++ test "naming one of the linked accounts is enough" do+ goal = goal_with(earmark: 3_000, balance: 3_000, target: 6_000)+ second = fresh_account(3_000)+ goal.goal_accounts.create!(account: second, allocated_amount: 3_000)++ goal.consume!(1_000, account: second)++ assert_equal 2_000, goal.goal_accounts.find_by(account_id: second.id).reload.allocated_amount+ end++ test "an account the goal is not linked to is refused" do+ goal = goal_with(earmark: 3_000, balance: 3_000, target: 5_000)++ error = assert_raises(Goal::ConsumptionRefused) { goal.consume!(500, account: fresh_account(100)) }+ assert_equal :account_not_linked, error.reason+ end++ test "consuming more than the goal ever set out to save is refused" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)++ error = assert_raises(Goal::ConsumptionRefused) { goal.consume!(5_001) }+ assert_equal :exceeds_target, error.reason+ assert_equal 0, goal.reload.consumed_amount+ end++ test "a non-positive amount is refused" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)++ assert_equal :non_positive, assert_raises(Goal::ConsumptionRefused) { goal.consume!(0) }.reason+ end++ # A reserve is drawn down and refilled, not consumed. Recording a withdrawal+ # as consumption would erase the shortfall the reserve exists to report.+ test "a reserve refuses consumption outright" do+ account = fresh_account(4_000)+ reserve = @family.goals.create!(+ name: "Precaution", target_amount: 6_000, currency: "USD", kind: "maintained"+ ) { |g| g.goal_accounts.build(account: account) }++ error = assert_raises(Goal::ConsumptionRefused) { reserve.consume!(1_000) }+ assert_equal :maintained, error.reason+ end++ test "reopening a goal clears what was spent under its previous life" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)+ goal.consume!(2_000)+ goal.complete!++ goal.reload.reopen!++ assert_equal 0, goal.reload.consumed_amount+ end++ # `completed_amount` freezes the BACKING; consumption is counted separately.+ # Folding one into the other would count the same money twice on a goal that+ # was partly spent and then closed.+ test "closing after a partial spend counts each side once" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)+ goal.consume!(2_000)++ goal.complete!++ reloaded = Goal.find(goal.id)+ assert_equal 3_000, reloaded.completed_amount, "the frozen figure is the backing alone"+ assert_equal 2_000, reloaded.consumed_amount+ assert_equal 0, reloaded.remaining_amount+ end++ # --- Review follow-ups ---++ # Clamping released only what the link held while `consumed_amount` took the+ # full figure, so the two sides silently disagreed: money counted as spent+ # that was never released, and still reserved against every sibling.+ test "consuming more than the chosen link holds is refused, not clamped" do+ goal = goal_with(earmark: 3_000, balance: 6_000, target: 9_000)+ second = fresh_account(6_000)+ goal.goal_accounts.create!(account: second, allocated_amount: 1_000)++ error = assert_raises(Goal::ConsumptionRefused) { goal.consume!(2_000, account: second) }++ assert_equal :exceeds_earmark, error.reason+ assert_equal 0, goal.reload.consumed_amount+ assert_equal 1_000, goal.goal_accounts.find_by(account_id: second.id).reload.allocated_amount+ end++ # A dialog left open in another tab, or a client posting directly.+ test "a goal that is no longer active records nothing" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)+ goal.complete!++ error = assert_raises(Goal::ConsumptionRefused) { goal.reload.consume!(1_000) }++ assert_equal :not_active, error.reason+ assert_equal 0, goal.reload.consumed_amount+ end++ # A reserve refuses consumption, so a converted goal would carry a figure+ # counting toward progress on an object whose model says spending is a+ # shortfall to refill. The two readings cannot both be true.+ test "a goal that has recorded a spend cannot become a reserve" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)+ goal.consume!(1_000)++ goal.kind = "maintained"++ assert_not goal.valid?+ assert_includes goal.errors[:kind],+ "This goal has already recorded money as spent, so it cannot become a reserve."+ end++ # The consumed total was only checked while consuming, leaving the ordinary+ # edit form free to lower the target underneath it.+ test "the target cannot be lowered below what was already spent" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 5_000)+ goal.consume!(3_000)++ assert_not goal.update(target_amount: 2_000)+ assert_equal 5_000, goal.reload.target_amount+ end++ # `reload` refreshes columns and leaves memos standing, so an instance that+ # had already read its backing kept reporting the figure from before the+ # spend — while progress, which nets the two, looked unchanged and hid it.+ #+ # Progress holding at 50% is not the bug, it is the feature: the earmark+ # shrinks by exactly what consumption grows by, so spending the money does+ # not move the bar. The backing underneath it does move, and must say so.+ test "the figures an instance already read are refreshed by consuming" do+ goal = goal_with(earmark: 5_000, balance: 5_000, target: 10_000)+ assert_equal 5_000, goal.current_balance.to_d+ assert_equal 50, goal.progress_percent++ goal.consume!(2_000)++ assert_equal 3_000, goal.current_balance.to_d, "the memo survived the spend"+ assert_equal 50, goal.progress_percent, "and progress is preserved, which is the point"+ end++ private+ def fresh_account(balance)+ Account.create!(+ family: @family, accountable: Depository.new,+ name: "Pot #{SecureRandom.hex(4)}", currency: "USD", balance: balance+ )+ end++ def goal_on(account, earmark:, target:, name:)+ @family.goals.create!(name: name, target_amount: target, currency: "USD") do |g|+ g.goal_accounts.build(account: account, allocated_amount: earmark)+ end+ end++ def goal_with(earmark:, balance:, target:)+ goal_on(fresh_account(balance), earmark: earmark, target: target, name: "Trip #{SecureRandom.hex(4)}")+ end+end