Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(goals): a reached goal lets go of the money it was holding (#3165)

buzzromain8f9529fbe98d
diff --git a/app/models/account.rb b/app/models/account.rb
index 57771ac2fe..a6035c705b 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -471,14 +471,16 @@ class Account < ApplicationRecord
manual? && !investment? ? "manual_save" : "transfer"
end
- # Total fixed earmark this account currently has reserved across every
- # non-archived goal (unallocated/whole-balance links reserve no fixed
- # slice). Mirrors Budget#allocated_spending.
+ # Total fixed earmark this account currently has reserved across every goal
+ # still holding its money (unallocated/whole-balance links reserve no fixed
+ # slice). Mirrors Budget#allocated_spending. Scoped to Goal::RELEASED_STATES
+ # so this and Goal.pooled_allocations_for never disagree — if they did,
+ # free_to_earmark would contradict the figures the goals themselves show.
def goal_earmarked_total
GoalAccount.joins(:goal)
.where(account_id: id)
.where.not(allocated_amount: nil)
- .where.not(goals: { state: "archived" })
+ .where.not(goals: { state: Goal::RELEASED_STATES })
.sum(:allocated_amount)
.to_d
end
diff --git a/app/models/goal.rb b/app/models/goal.rb
index edee4c41bb..63d051bfd4 100644
--- a/app/models/goal.rb
+++ b/app/models/goal.rb
@@ -49,11 +49,46 @@ class Goal < ApplicationRecord
# is what makes the order the same for everyone.
before_validation :lock_whole_account_claims_in_order
+ # AASM's event `after` hooks run on the non-bang form too, which does not
+ # save. `goal.complete` therefore left the row `active` in the database
+ # while stamping it with a completion snapshot — a goal still being funded,
+ # carrying a frozen amount and a completion date. Everything downstream that
+ # keys off `completed_amount.present?` then read it as closed.
+ #
+ # Hung off the persisted change instead, so the side effects and the state
+ # they belong to are the same fact. Still inside the save transaction, so a
+ # later failure takes both back.
+ after_save :apply_state_change_side_effects, if: :saved_change_to_state?
+
monetize :target_amount
# Account types that can back a goal (see linked_accounts_must_be_fundable).
FUNDABLE_ACCOUNT_TYPES = %w[Depository Investment].freeze
+ # States in which a goal has let go of the money it was holding, and so
+ # drops out of the shared pool. `completed` belongs here: reaching a goal
+ # is the moment its earmark stops competing with its siblings on the same
+ # account — that is what "done" means for money.
+ #
+ # `paused` is deliberately absent. Pausing means "I have stopped feeding
+ # this", not "I have released it"; a paused goal keeps its reservation.
+ #
+ # ⚠️ Four places filter on this and must agree, or free_to_earmark will
+ # contradict the pool: here, Account#goal_earmarked_total,
+ # GoalAccount#whole_account_link_must_be_exclusive (through
+ # 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.
+ RELEASED_STATES = %w[archived completed].freeze
+
+ # A one-off goal is reached once and then closed; a maintained one is a
+ # floor to hold (see Lot B3, which gives this column its behavior). Nothing
+ # branches on it yet beyond these predicates — the column exists now so the
+ # lifecycle written here does not have to be retrofitted later.
+ KINDS = %w[one_off maintained].freeze
+
+ validates :kind, inclusion: { in: KINDS }
+
# Display order for active (non-completed/non-archived) goals: behind
# first, then on-track, then open-ended. Paused sorts after all of these.
ACTIVE_DISPLAY_STATUS_RANK = { behind: 0, on_track: 1, no_target_date: 2 }.freeze
@@ -63,7 +98,7 @@ class Goal < ApplicationRecord
order(Arel.sql("CASE state WHEN 'active' THEN 0 WHEN 'paused' THEN 1 WHEN 'completed' THEN 2 ELSE 3 END"))
}
- # Family-wide map of non-archived goal earmarks, grouped by account_id:
+ # Family-wide map of live goal earmarks, grouped by account_id:
# { account_id => [{ goal_id:, allocated_amount: }, ...] }. The controller
# assigns this to each goal on index (goal.pooled_allocations = ...) so the
# shared-pool backing math runs ONE query for the whole page instead of one
@@ -274,6 +309,13 @@ class Goal < ApplicationRecord
# direct DB writes, account-currency edits outside goal validation, or
# future code that bypasses the validation chain.
def current_balance
+ # A closed goal reports what it reached, not what its accounts hold now.
+ # The guard is `present?`, never `completed?`: `archive` accepts a goal
+ # straight from active or paused, so an archived goal that was never
+ # completed has no frozen amount and keeps the live calculation. Both
+ # shapes coexist in the database.
+ return completed_amount.to_d if completed_amount.present?
+
@current_balance ||= begin
matching = linked_accounts.select { |a| a.currency == currency }
if matching.size != linked_accounts.size
@@ -299,6 +341,14 @@ class Goal < ApplicationRecord
progress_basis == "contributions"
end
+ def one_off?
+ kind == "one_off"
+ end
+
+ def maintained?
+ kind == "maintained"
+ end
+
# Market value of the goal's backing (balance basis), regardless of the
# progress basis — the "what it's worth today" figure shown next to
# contributions on an investment-backed goal.
@@ -418,7 +468,14 @@ class Goal < ApplicationRecord
whole_total = linked_accounts.select { |a| a.currency == currency }.sum { |a| a.balance.to_d }
# 0 when the linked-account total is non-positive: current_balance is forced
# to 0 there, so the saved series must end at 0 too (no stray non-zero tail).
+ #
+ # Capped at 1 because `current_balance` no longer tracks the accounts once a
+ # goal is closed: it returns the amount frozen at completion. Spend those
+ # accounts afterwards and the ratio runs away — a frozen 4,000 over a live
+ # 100 scales every historical point by fifty, drawing a chart that never
+ # happened. The goal's share of its accounts cannot exceed all of them.
backing_ratio = whole_total.positive? ? (current_balance.to_d / whole_total) : 0.to_d
+ backing_ratio = 1.to_d if backing_ratio > 1
saved_series = series_values.map { |v| { date: v.date.to_s, value: (v.value.amount.to_d * backing_ratio).to_f } }
earliest = series_values.first&.date || created_at.to_date
@@ -746,10 +803,38 @@ class Goal < ApplicationRecord
# 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_effects
+ previous_state, next_state = saved_change_to_state
+
+ # The memos were cleared at transition time, but anything that read the
+ # goal between then and the save will have refilled them from the old
+ # state. Cleared again so `current_balance` below is the closing figure.
+ reset_state_dependent_caches!
+
+ if next_state == "completed"
+ # Freeze what the goal actually reached. A completed goal reserves
+ # nothing, but its amount would still be recomputed from the live
+ # balance — so spending the money would walk the finished goal back
+ # down and rewrite its own history.
+ update_columns(completed_amount: current_balance, completed_at: Time.current)
+ elsif previous_state.in?(RELEASED_STATES) && !next_state.in?(RELEASED_STATES)
+ thaw_completed_amount!
+ end
+ end
+
+ def thaw_completed_amount!
+ update_columns(completed_amount: nil, completed_at: nil)
+ end
+
def reset_state_dependent_caches!
- # current_balance now depends on the goal's own archived state (an
- # archived goal is excluded from the shared pool), so the balance-derived
- # memos must be cleared on a transition too, not just the status memos.
+ # 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
+ # reads its frozen amount instead of its accounts — so the
+ # balance-derived memos must be cleared on a transition too, not just
+ # the status memos.
%i[
@display_status @projection_summary
@current_balance @current_balance_money
diff --git a/app/models/goal_account.rb b/app/models/goal_account.rb
index 2c38626353..7a6e3943e0 100644
--- a/app/models/goal_account.rb
+++ b/app/models/goal_account.rb
@@ -29,8 +29,11 @@ class GoalAccount < ApplicationRecord
#
# The conflict lookup itself lives on Goal (`whole_account_conflicts_on`),
# scoped to Goal::RELEASED_STATES — exactly the set
- # Goal.pooled_allocations_for feeds into the backing math. Sharing one
- # method with the restore guard is what keeps this door and that one from
+ # Goal.pooled_allocations_for feeds into the backing math. A completed goal
+ # has released its earmark, so it no longer blocks a new whole-balance
+ # link: refusing one because of a finished goal whose money has already
+ # been handed back would be inexplicable to the user. Sharing one method
+ # with the restore guard is what keeps this door and that one from
# disagreeing about which goals still hold their money.
def whole_account_link_must_be_exclusive
return unless whole_account?
diff --git a/app/views/goals/show.html.erb b/app/views/goals/show.html.erb
index 36c46d99f9..4a878dc388 100644
--- a/app/views/goals/show.html.erb
+++ b/app/views/goals/show.html.erb
@@ -175,9 +175,41 @@
<div class="w-16 h-16 rounded-full bg-success/10 inline-flex items-center justify-center text-success mb-3">
<%= icon("party-popper", size: "2xl", color: "success") %>
</div>
+ <%# Two situations reach this panel and they are not the same thing.
+ A `completed` goal is closed: its earmark has been released and
+ its amount is frozen. A goal merely at 100% is still holding its
+ money and still competing with its siblings on the account — the
+ copy used to tell it "Goal closed at ...", and offered Archive as
+ the only action, which is the gesture that does NOT release
+ anything. Closing is what does. %>
+ <% closed = @goal.completed? %>
<h2 class="text-lg font-semibold text-primary"><%= t(".celebration.heading") %></h2>
- <p class="text-sm text-secondary mt-1 max-w-md privacy-sensitive"><%= t(".celebration.body", saved: @goal.current_balance_money.format(precision: 0), target: @goal.target_amount_money.format(precision: 0)) %></p>
- <% if @goal.may_archive? %>
+ <p class="text-sm text-secondary mt-1 max-w-md privacy-sensitive">
+ <%= t(closed ? ".celebration.body" : ".celebration.body_reached",
+ saved: @goal.current_balance_money.format(precision: 0),
+ target: @goal.target_amount_money.format(precision: 0)) %>
+ </p>
+ <% if closed && @goal.completed_at.present? %>
+ <p class="text-xs text-secondary mt-2 tabular-nums privacy-sensitive">
+ <%= t(".celebration.frozen",
+ date: l(@goal.completed_at.to_date, format: :long),
+ amount: @goal.current_balance_money.format(precision: 0)) %>
+ </p>
+ <% end %>
+ <%# A maintained reserve at 100% is in its normal state, not waiting
+ to be closed — Lot B3 forbids `complete` for them outright. %>
+ <% if !closed && @goal.one_off? && @goal.may_complete? %>
+ <div class="mt-4">
+ <%= render DS::Button.new(
+ text: t(".celebration.close_cta"),
+ href: complete_goal_path(@goal),
+ variant: "primary",
+ size: "sm",
+ method: :patch
+ ) %>
+ </div>
+ <p class="text-xs text-secondary mt-2 max-w-md"><%= t(".celebration.close_hint") %></p>
+ <% elsif @goal.may_archive? %>
<div class="mt-4">
<%= render DS::Button.new(
text: t(".celebration.archive_cta"),
diff --git a/config/locales/views/goals/en.yml b/config/locales/views/goals/en.yml
index e3524b78fe..38946a4a42 100644
--- a/config/locales/views/goals/en.yml
+++ b/config/locales/views/goals/en.yml
@@ -165,11 +165,11 @@ en:
body: "Current pace %{avg}/mo · required %{required}/mo to hit your target."
adjust_target_cta: Adjust target instead
confirm_complete_title: Mark this goal complete?
- confirm_complete_body: It leaves the Ongoing list. You can still archive or restore it later.
+ confirm_complete_body: The money earmarked for it is released for your other goals on the same account. It leaves the Ongoing list, and you can still archive or restore it later.
confirm_complete_body_short: "You're at %{progress}%, %{saved} of %{target}. Marking complete records this as your achievement instead of the original target. Continue, or close this and adjust the target instead?"
confirm_complete_cta: Mark complete
confirm_archive_title: Archive this goal?
- confirm_archive_body: Archived goals disappear from the main list. You can restore them later.
+ confirm_archive_body: Archived goals disappear from the main list. You can restore them later. Archiving does not record what you reached — mark the goal complete first if you want that kept.
confirm_archive_cta: Archive
confirm_delete_title: Delete this goal?
confirm_delete_body: "%{name} and its pledge history are removed for good. Your linked accounts, balances and transactions are not affected. To keep it as a record instead, archive it."
@@ -184,6 +184,10 @@ en:
restore_cta: Restore goal
celebration:
heading: Goal reached. Nice work.
+ body_reached: "You've hit your target at %{saved} of %{target}. It is not closed yet — the money is still earmarked for it."
+ close_cta: Close this goal
+ close_hint: Closing releases the earmarked money for your other goals on the same account. Do this once you have actually spent it.
+ frozen: "Reached on %{date} · %{amount}"
body: "Goal closed at %{saved} of %{target}. Keep it as a record, or archive it now."
archive_cta: Archive goal
inactive:
diff --git a/config/locales/views/goals/fr.yml b/config/locales/views/goals/fr.yml
index e7d44ea6b8..d1ab24092e 100644
--- a/config/locales/views/goals/fr.yml
+++ b/config/locales/views/goals/fr.yml
@@ -168,17 +168,21 @@ fr:
body: Rythme actuel %{avg}/mois · requis %{required}/mois pour atteindre votre objectif.
title: Épargnez %{amount}/mois de plus pour rattraper le retard
celebration:
+ body_reached: "Vous avez atteint votre cible, à %{saved} sur %{target}. Il n'est pas encore clôturé — l'argent lui reste affecté."
+ close_cta: Clôturer cet objectif
+ close_hint: La clôture libère l'argent affecté au profit de vos autres objectifs sur le même compte. À faire une fois la dépense réellement effectuée.
+ frozen: "Atteint le %{date} · %{amount}"
archive_cta: Archiver l'objectif
body: Objectif clôturé à %{saved} sur %{target}. Conservez-le, ou archivez-le dès maintenant.
heading: Objectif atteint. Bon travail !
complete: Marquer comme terminé
- confirm_archive_body: Les objectifs archivés disparaissent de la liste principale. Vous pourrez les restaurer plus tard.
+ confirm_archive_body: Les objectifs archivés disparaissent de la liste principale. Vous pourrez les restaurer plus tard. L'archivage n'enregistre pas le montant atteint — clôturez d'abord l'objectif si vous voulez le conserver.
confirm_archive_cta: Archiver
confirm_archive_title: Archiver cet objectif ?
confirm_delete_title: "Supprimer cet objectif ?"
confirm_delete_body: "%{name} et son historique de versements sont supprimés définitivement. Vos comptes liés, soldes et transactions ne sont pas affectés. Pour en garder une trace, archivez-le plutôt."
confirm_delete_cta: "Supprimer l'objectif"
- confirm_complete_body: Il quittera la liste En cours. Vous pourrez toujours l'archiver ou le restaurer plus tard.
+ confirm_complete_body: L'argent qui lui était affecté sera libéré pour vos autres objectifs sur le même compte. Il quittera la liste En cours, et vous pourrez toujours l'archiver ou le restaurer plus tard.
confirm_complete_body_short: Vous êtes à %{progress}%, %{saved} sur %{target}. Marquer comme terminé enregistrera cela comme votre réussite à la place de l'objectif initial. Continuer, ou fermer ceci et ajuster l'objectif à la place ?
confirm_complete_cta: Marquer comme terminé
confirm_complete_title: Marquer cet objectif comme terminé ?
diff --git a/db/migrate/20260824120000_add_lifecycle_to_goals.rb b/db/migrate/20260824120000_add_lifecycle_to_goals.rb
new file mode 100644
index 0000000000..ad48586ec1
--- /dev/null
+++ b/db/migrate/20260824120000_add_lifecycle_to_goals.rb
@@ -0,0 +1,19 @@
+class AddLifecycleToGoals < ActiveRecord::Migration[7.2]
+ def change
+ # Frozen at the moment `complete` fires, so a reached goal keeps showing
+ # what it actually reached even after the money is spent. Nullable, and
+ # deliberately NOT backfilled: an already-completed goal's past value
+ # cannot be recovered, and guessing it would freeze an already-eroded
+ # number — the wrong one. `Goal#current_balance` falls back to the live
+ # calculation whenever this is nil.
+ add_column :goals, :completed_amount, :decimal, precision: 19, scale: 4
+ add_column :goals, :completed_at, :datetime
+
+ # Introduced here without behavior on purpose. Lots B3 (maintained
+ # reserves) and B4 (partial consumption) both branch on it, and adding
+ # the column with them would mean retrofitting the lifecycle written
+ # here. Everything is `one_off` until B3 gives `maintained` a meaning.
+ add_column :goals, :kind, :string, null: false, default: "one_off"
+ add_check_constraint :goals, "kind IN ('one_off','maintained')", name: "chk_goals_kind_enum"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index f20402a765..7c5871e59f 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_23_000000) do
+ActiveRecord::Schema[7.2].define(version: 2026_08_24_120000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pgcrypto"
enable_extension "plpgsql"
@@ -881,9 +881,13 @@ ActiveRecord::Schema[7.2].define(version: 2026_08_23_000000) do
t.datetime "updated_at", null: false
t.string "icon"
t.string "progress_basis", default: "balance", null: false
+ t.decimal "completed_amount", precision: 19, scale: 4
+ t.datetime "completed_at"
+ t.string "kind", default: "one_off", null: false
t.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 "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"
t.check_constraint "target_amount > 0::numeric", name: "chk_savings_goals_target_amount_positive"
diff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rb
index 30b9a0b4d4..9fae6e32b5 100644
--- a/test/controllers/goals_controller_test.rb
+++ b/test/controllers/goals_controller_test.rb
@@ -357,7 +357,80 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest
assert_select "input[type=checkbox][name='goal[account_ids][]'][value=?][checked]", account.id
end
+ # --- Lot B2: closing a reached goal ---
+
+ # The panel used to say "Goal closed at ..." for a goal that was merely at
+ # 100%, and offer Archive — the gesture that does NOT release the money.
+ test "a one_off goal at 100 percent is offered closing, not archiving" do
+ goal = fully_funded_goal
+
+ get goal_url(goal)
+
+ assert_response :success
+ assert_match I18n.t("goals.show.celebration.close_cta"), response.body
+ assert_match I18n.t("goals.show.celebration.close_hint"), response.body
+ assert_no_match(/#{Regexp.escape(I18n.t("goals.show.celebration.archive_cta"))}/, response.body)
+ end
+
+ test "a goal below 100 percent is offered no closing action" do
+ goal = fully_funded_goal
+ goal.update!(target_amount: 10_000)
+
+ get goal_url(goal)
+
+ assert_response :success
+ assert_no_match(/#{Regexp.escape(I18n.t("goals.show.celebration.close_cta"))}/, response.body)
+ end
+
+ # Reaching the target is the normal state of a reserve, not a prompt to
+ # close it — and B3 forbids `complete` for them outright.
+ test "a maintained goal at 100 percent is never offered closing" do
+ goal = fully_funded_goal
+ goal.update_column(:kind, "maintained")
+
+ get goal_url(goal)
+
+ assert_response :success
+ assert_no_match(/#{Regexp.escape(I18n.t("goals.show.celebration.close_cta"))}/, response.body)
+ end
+
+ test "a completed goal shows the amount and date it froze" do
+ goal = fully_funded_goal
+ goal.complete!
+
+ get goal_url(goal)
+
+ assert_response :success
+ assert_match I18n.t("goals.show.celebration.frozen",
+ date: I18n.l(goal.reload.completed_at.to_date, format: :long),
+ amount: goal.current_balance_money.format(precision: 0)),
+ response.body
+ assert_no_match(/#{Regexp.escape(I18n.t("goals.show.celebration.close_cta"))}/, response.body)
+ end
+
+ test "an archived goal is offered no closing action" do
+ goal = fully_funded_goal
+ goal.archive!
+
+ get goal_url(goal)
+
+ assert_response :success
+ assert_no_match(/#{Regexp.escape(I18n.t("goals.show.celebration.close_cta"))}/, response.body)
+ end
+
private
+ # An active one_off goal sitting exactly at its target, on an account no
+ # other goal claims.
+ def fully_funded_goal
+ account = Account.create!(
+ family: @user.family, accountable: Depository.new,
+ name: "Funded Pot", currency: "USD", balance: 2_000
+ )
+ @user.family.goals.create!(name: "Funded", target_amount: 2_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: account)
+ end
+ end
+
# A fundable account no goal fixture claims. The fixtures link
# @depository and @connected as whole-balance earmarks, and GoalAccount
# refuses a second whole-balance link on an account already claimed in
diff --git a/test/models/goal_account_test.rb b/test/models/goal_account_test.rb
index bb6725afb7..0ae79c4a9b 100644
--- a/test/models/goal_account_test.rb
+++ b/test/models/goal_account_test.rb
@@ -57,9 +57,8 @@ class GoalAccountTest < ActiveSupport::TestCase
assert ga.valid?, ga.errors.full_messages.to_sentence
end
- # The guard tracks Goal.pooled_allocations_for, which excludes archived goals
- # from the backing math. Money held by an archived goal is not claimed, so it
- # must not block a live one.
+ # The guard tracks Goal.pooled_allocations_for through Goal::RELEASED_STATES.
+ # Money an archived goal held is not claimed, so it must not block a live one.
test "an archived goal's whole-account link does not block a new one" do
other = goals(:vacation_italy)
other.goal_accounts.create!(account: @account)
@@ -70,16 +69,18 @@ class GoalAccountTest < ActiveSupport::TestCase
assert ga.valid?, ga.errors.full_messages.to_sentence
end
- # A completed goal still holds its money and still feeds the pool, so unlike
- # an archived one it does claim the balance.
- test "a completed goal's whole-account link still blocks a new one" do
+ # Inverted by Lot B1: a completed goal has released its earmark, so like an
+ # archived one it no longer claims the balance. Refusing a new link because
+ # of a finished goal whose money has already been handed back would be
+ # inexplicable — the account genuinely is free again.
+ test "a completed goal's whole-account link no longer blocks a new one" do
other = goals(:vacation_italy)
other.goal_accounts.create!(account: @account)
other.complete!
ga = GoalAccount.new(goal: @goal, account: @account, allocated_amount: nil)
- assert_not ga.valid?
+ assert ga.valid?, ga.errors.full_messages.to_sentence
end
test "another family's whole-account link on its own account is irrelevant" do
diff --git a/test/models/goal_test.rb b/test/models/goal_test.rb
index f0d5619e18..6f5457ece9 100644
--- a/test/models/goal_test.rb
+++ b/test/models/goal_test.rb
@@ -460,6 +460,144 @@ class GoalTest < ActiveSupport::TestCase
assert_equal BigDecimal("5000"), Goal.find(whole.id).current_balance.to_d
end
+ # --- Lot B1: a reached goal lets go of its money ---
+
+ # The whole scenario from the plan, as one regression test. Before B1 the
+ # last line read 2500 / 50%: the completed goal kept reserving, the
+ # untouched precaution goal was cut in half by the pro-rata haircut, and
+ # archiving froze the wrong figure into the history.
+ test "completing a goal frees its siblings and keeps its own history straight" do
+ livret = Account.create!(family: @family, accountable: Depository.new, name: "Livret B1", currency: "USD", balance: 10_000)
+ precaution = @family.goals.create!(name: "Precaution B1", target_amount: 5_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: livret, allocated_amount: 5_000)
+ end
+ vacances = @family.goals.create!(name: "Vacances B1", target_amount: 5_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: livret, allocated_amount: 5_000)
+ end
+
+ assert_equal BigDecimal("5000"), Goal.find(precaution.id).current_balance.to_d
+ assert_equal BigDecimal("5000"), Goal.find(vacances.id).current_balance.to_d
+
+ vacances.complete!
+ livret.update!(balance: 5_000)
+
+ assert_equal BigDecimal("5000"), Goal.find(precaution.id).current_balance.to_d,
+ "the untouched goal must keep its full earmark once its sibling is done"
+ assert_equal 100, Goal.find(precaution.id).progress_percent.to_i
+ assert_equal BigDecimal("5000"), Goal.find(vacances.id).current_balance.to_d,
+ "a completed goal reports what it reached, not what is left"
+
+ vacances.archive!
+ assert_equal BigDecimal("5000"), Goal.find(vacances.id).current_balance.to_d,
+ "archiving after completion must not rewrite the frozen figure"
+ end
+
+ test "a completed goal releases its earmark from the shared pool" do
+ account = Account.create!(family: @family, accountable: Depository.new, name: "Pool Savings", currency: "USD", balance: 5_000)
+ whole = @family.goals.create!(name: "Whole C", target_amount: 10_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: account)
+ end
+ earmarked = @family.goals.create!(name: "Earmarked C", target_amount: 2_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: account, allocated_amount: 2_000)
+ end
+
+ assert_equal BigDecimal("3000"), Goal.find(whole.id).current_balance.to_d
+ earmarked.complete!
+ assert_equal BigDecimal("5000"), Goal.find(whole.id).current_balance.to_d
+ end
+
+ test "a completed goal keeps its amount when the balance later drops" do
+ account = Account.create!(family: @family, accountable: Depository.new, name: "Spent Savings", currency: "USD", balance: 4_000)
+ goal = @family.goals.create!(name: "Frozen", target_amount: 4_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: account)
+ end
+
+ goal.complete!
+ assert_equal BigDecimal("4000"), goal.completed_amount.to_d
+ assert goal.completed_at.present?
+
+ account.update!(balance: 100)
+ assert_equal BigDecimal("4000"), Goal.find(goal.id).current_balance.to_d
+ end
+
+ # `archive` accepts a goal straight from active or paused, so an archived
+ # goal that was never completed has no frozen amount — the read guard is
+ # `completed_amount.present?`, not `completed?`.
+ test "a goal archived without being completed keeps the live calculation" do
+ account = Account.create!(family: @family, accountable: Depository.new, name: "Direct Archive", currency: "USD", balance: 3_000)
+ goal = @family.goals.create!(name: "Straight to archive", target_amount: 3_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: account)
+ end
+
+ goal.archive!
+ assert_nil goal.completed_amount
+
+ account.update!(balance: 250)
+ assert_equal BigDecimal("250"), Goal.find(goal.id).current_balance.to_d
+ end
+
+ test "reopen and unarchive hand the goal back to the live calculation" do
+ account = Account.create!(family: @family, accountable: Depository.new, name: "Thaw Savings", currency: "USD", balance: 2_000)
+
+ [ :reopen, :unarchive ].each_with_index do |event, i|
+ goal = @family.goals.create!(name: "Thaw #{i}", target_amount: 2_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: account, allocated_amount: 1_000)
+ end
+ goal.complete!
+ assert_equal BigDecimal("1000"), goal.completed_amount.to_d
+
+ goal.archive! if event == :unarchive
+ goal.public_send("#{event}!")
+
+ assert_nil goal.reload.completed_amount, "#{event} must clear the frozen amount"
+ assert_nil goal.completed_at
+ account.update!(balance: 500)
+ assert_equal BigDecimal("500"), Goal.find(goal.id).current_balance.to_d
+ account.update!(balance: 2_000)
+ goal.destroy!
+ end
+ end
+
+ # Pause means "I have stopped feeding this", not "I have released it".
+ test "a paused goal keeps reserving its earmark" do
+ account = Account.create!(family: @family, accountable: Depository.new, name: "Paused Savings", currency: "USD", balance: 5_000)
+ whole = @family.goals.create!(name: "Whole P", target_amount: 10_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: account)
+ end
+ earmarked = @family.goals.create!(name: "Earmarked P", target_amount: 2_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: account, allocated_amount: 2_000)
+ end
+
+ earmarked.pause!
+ assert_equal BigDecimal("3000"), Goal.find(whole.id).current_balance.to_d,
+ "a paused goal must keep its slice out of the pool's reach"
+ end
+
+ # free_to_earmark and the pool read the same set of goals — Goal::RELEASED_STATES.
+ # If they disagreed, the account would advertise headroom the goals deny.
+ test "free_to_earmark and the shared pool agree after a completion" do
+ account = Account.create!(family: @family, accountable: Depository.new, name: "Agreement Savings", currency: "USD", balance: 5_000)
+ goal = @family.goals.create!(name: "Agreeable", target_amount: 1_500, currency: "USD") do |g|
+ g.goal_accounts.build(account: account, allocated_amount: 1_500)
+ end
+
+ assert_equal BigDecimal("1500"), account.goal_earmarked_total
+ goal.complete!
+ account.reload
+
+ assert_equal BigDecimal("0"), account.goal_earmarked_total
+ assert_equal BigDecimal("5000"), account.free_to_earmark
+ assert_empty Goal.pooled_allocations_for(@family)[account.id].to_a
+ end
+
+ test "goals are one_off by default and kind is constrained" do
+ assert @goal.one_off?
+ assert_not @goal.maintained?
+
+ @goal.kind = "nonsense"
+ assert_not @goal.valid?
+ end
+
test "account free_to_earmark subtracts non-archived fixed earmarks" do
account = Account.create!(family: @family, accountable: Depository.new, name: "Headroom Savings", currency: "USD", balance: 5_000)
@family.goals.create!(name: "Earmarker", target_amount: 10_000, currency: "USD") do |g|
@@ -646,7 +784,96 @@ class GoalTest < ActiveSupport::TestCase
assert_equal "active", goal.reload.state
end
+ # Once a goal is closed, `current_balance` returns the frozen amount and stops
+ # tracking its accounts. Spending them afterwards used to send the projection
+ # ratio past 1 — a frozen amount over a live 100 scaled every historical point
+ # by the difference, drawing a chart that never happened.
+ #
+ # The series is stubbed at its collaborator rather than built from Balance
+ # rows: ChartSeriesBuilder returns zeros for a fixture account here, and a
+ # series of zeros multiplies to zero whatever the ratio, so the assertion
+ # would pass without proving anything.
+ test "the projection never scales the saved series past the accounts it came from" do
+ goal = @family.goals.create!(name: "Closed trip", target_amount: 4_000, currency: "USD") do |g|
+ g.goal_accounts.build(account: @depository, allocated_amount: 4_000)
+ end
+ goal.complete!
+ @depository.update!(balance: 100)
+
+ historical = OpenStruct.new(date: Date.current, value: Money.new(5_000, "USD"))
+ Balance::ChartSeriesBuilder.any_instance
+ .stubs(:balance_series)
+ .returns(OpenStruct.new(values: [ historical ]))
+
+ payload = Goal.find(goal.id).projection_payload
+
+ # The series is the WHOLE linked-account history, scaled to this goal's
+ # share of it. A share cannot exceed the whole, so no point may come out
+ # above the historical figure it was scaled from — whatever the frozen
+ # amount says. Unclamped this rendered 5,000 x 33.
+ assert_not_empty payload[:saved_series], "empty series would make this assertion vacuous"
+ assert_operator payload[:saved_series].first[:value].to_d, :<=, 5_000,
+ "a saved point outran the history it was scaled from"
+ end
+
+
+ # AASM runs an event's `after` hook on the non-bang form too, which does not
+ # save. The completion snapshot used to be written there, so `complete` left
+ # the row `active` in the database carrying a frozen amount and a completion
+ # date — a goal still being funded that everything keying off
+ # `completed_amount.present?` read as closed.
+ test "complete without the bang stamps nothing" do
+ goal = completable_goal
+
+ goal.complete
+
+ row = Goal.where(id: goal.id).pick(:state, :completed_amount, :completed_at)
+ assert_equal "active", row[0]
+ assert_nil row[1]
+ assert_nil row[2]
+ end
+
+ test "complete! freezes the amount alongside the state it belongs to" do
+ goal = completable_goal
+
+ goal.complete!
+
+ row = Goal.where(id: goal.id).pick(:state, :completed_amount, :completed_at)
+ assert_equal "completed", row[0]
+ assert_equal 4_000, row[1].to_d
+ assert_not_nil row[2]
+ end
+
+ test "reopening without the bang thaws nothing" do
+ goal = completable_goal
+ goal.complete!
+
+ goal.reopen
+
+ assert_equal 4_000, Goal.where(id: goal.id).pick(:completed_amount).to_d
+ end
+
+ test "reopen! hands the goal back to the live calculation" do
+ goal = completable_goal
+ goal.complete!
+
+ goal.reopen!
+
+ assert_nil Goal.where(id: goal.id).pick(:completed_amount)
+ end
+
private
+
+ # Its own account, so the shared-pool haircut does not make the frozen
+ # figure depend on what the fixtures happen to claim.
+ def completable_goal
+ account = Account.create!(family: @family, accountable: Depository.new,
+ name: "Close pot #{SecureRandom.hex(3)}",
+ currency: @family.currency, balance: 4_000)
+ @family.goals.create!(name: "Trip", target_amount: 4_000, currency: @family.currency) do |g|
+ g.goal_accounts.build(account: account, allocated_amount: 4_000)
+ end
+ end
# A fresh account: the fixtures deliberately carry three goals holding
# whole-account links on `depository`, a legacy overlap the exclusivity
# rule tolerates but which would muddy every assertion here.