The personal finance app for everyone (by everyone)
Ruby
feat(goals): reserves you maintain, not goals you finish (#3167)
buzzromain6d7ca3584c6c
diff --git a/app/components/goals/card_component.rb b/app/components/goals/card_component.rbindex 2a1d23fc2d..b03719e62d 100644--- a/app/components/goals/card_component.rb+++ b/app/components/goals/card_component.rb@@ -14,9 +14,8 @@ class Goals::CardComponent < ApplicationComponent# live in that primitive — see #1899).def ring_tonecase goal.status- when :reached, :on_track then :success- when :behind then :warning- else :neutral+ when :reached, :on_track, :funded then :success+ else goal.needs_attention? ? :warning : :neutralendend@@ -67,6 +66,10 @@ class Goals::CardComponent < ApplicationComponentenddef pace_line+ # A reserve has no deadline, so `pace_money` has nothing to compare+ # against — printing "saving X/mo" next to a floor the user is simply+ # holding reads as progress toward something it is not.+ return nil if goal.maintained?return nil if goal.archived? || goal.paused? || goal.completed? || goal.status == :reachedavg = goal.pace_money.format(precision: 0)@@ -83,6 +86,13 @@ class Goals::CardComponent < ApplicationComponentI18n.t("goals.goal_card.footer_archived")elsif goal.paused?I18n.t("goals.goal_card.footer_paused")+ # A reserve has no deadline and no pace, so none of the one-off lines+ # below apply: what it owes is the shortfall, and that is exactly+ # remaining_amount.+ elsif goal.maintained?+ goal.status == :funded ?+ I18n.t("goals.goal_card.footer_reserve_intact") :+ I18n.t("goals.goal_card.footer_reserve_short", amount: goal.remaining_amount_money.format(precision: 0))elsif goal.completed? || goal.status == :reachedI18n.t("goals.goal_card.footer_reached")elsif goal.status == :behind && goal.monthly_target_amount@@ -102,6 +112,6 @@ class Goals::CardComponent < ApplicationComponentenddef footer_has_money?- goal.status == :behind && goal.monthly_target_amount+ (goal.status == :behind && goal.monthly_target_amount.present?) || goal.status == :depletedendenddiff --git a/app/components/goals/lifecycle_panel_component.html.erb b/app/components/goals/lifecycle_panel_component.html.erbnew file mode 100644index 0000000000..21e17f9967--- /dev/null+++ b/app/components/goals/lifecycle_panel_component.html.erb@@ -0,0 +1,157 @@+<%# Keys are absolute: a relative `t(".x")` here would resolve against this+ component's own path, not the goal page these strings belong to. %>+<% case panel %>+<% when :inactive %>+ <%= render DS::Card.new(class: "items-center justify-center text-center") do %>+ <div class="w-16 h-16 rounded-full bg-surface-inset inline-flex items-center justify-center text-secondary mb-3">+ <%= helpers.icon(inactive_icon, size: "2xl") %>+ </div>+ <h2 class="text-lg font-semibold text-primary">+ <%= t("goals.show.#{inactive_heading_key}") %>+ </h2>+ <p class="text-sm text-secondary mt-1 max-w-md tabular-nums privacy-sensitive">+ <%= t("goals.show.inactive.body", saved: goal.current_balance_money.format(precision: 0), target: goal.target_amount_money.format(precision: 0)) %>+ </p>+ <% end %>++<% when :celebration %>+ <%= render DS::Card.new(class: "items-center justify-center text-center") do %>+ <div class="w-16 h-16 rounded-full bg-success/10 inline-flex items-center justify-center text-success mb-3">+ <%= helpers.icon(celebration_icon, size: "2xl", color: "success") %>+ </div>+ <h2 class="text-lg font-semibold text-primary">+ <%= t("goals.show.#{celebration_heading_key}") %>+ </h2>+ <p class="text-sm text-secondary mt-1 max-w-md privacy-sensitive">+ <%= t("goals.show.#{celebration_body_key}",+ saved: goal.current_balance_money.format(precision: 0),+ target: goal.target_amount_money.format(precision: 0)) %>+ </p>+ <% if show_frozen_note? %>+ <p class="text-xs text-secondary mt-2 tabular-nums privacy-sensitive">+ <%= t("goals.show.celebration.frozen",+ date: l(goal.completed_at.to_date, format: :long),+ amount: goal.current_balance_money.format(precision: 0)) %>+ </p>+ <% end %>+ <% case celebration_action %>+ <% when :close %>+ <div class="mt-4">+ <%# Same confirmation as the menu action: closing releases the goal's+ earmarked money, and a one-click release is not a gesture to make+ reversible-by-apology. %>+ <%= render DS::Button.new(+ text: t("goals.show.celebration.close_cta"),+ href: helpers.complete_goal_path(goal),+ variant: "primary",+ size: "sm",+ method: :patch,+ confirm: helpers.goal_complete_confirm(goal)+ ) %>+ </div>+ <p class="text-xs text-secondary mt-2 max-w-md"><%= t("goals.show.celebration.close_hint") %></p>+ <% when :archive %>+ <div class="mt-4">+ <%= render DS::Button.new(+ text: t("goals.show.celebration.archive_cta"),+ href: helpers.archive_goal_path(goal),+ variant: "outline",+ size: "sm",+ method: :patch+ ) %>+ </div>+ <% end %>+ <% end %>++<% when :reserve_shortfall %>+ <%= render DS::Card.new(class: "items-center justify-center text-center") do %>+ <div class="w-16 h-16 rounded-full bg-warning/10 inline-flex items-center justify-center text-warning mb-3">+ <%= helpers.icon("shield-alert", size: "2xl", color: "warning") %>+ </div>+ <h2 class="text-lg font-semibold text-primary"><%= t("goals.show.reserve_shortfall.heading") %></h2>+ <p class="text-sm text-secondary mt-1 max-w-md tabular-nums privacy-sensitive">+ <%= t("goals.show.reserve_shortfall.body",+ saved: goal.current_balance_money.format(precision: 0),+ target: goal.target_amount_money.format(precision: 0),+ missing: goal.remaining_amount_money.format(precision: 0)) %>+ </p>+ <% end %>++<% when :empty %>+ <%# No movement yet on the linked account: an inline "make your first+ transfer" card instead of a flat-at-zero chart that looks broken. %>+ <%= render DS::Card.new(class: "items-center justify-center text-center") do %>+ <div class="w-16 h-16 rounded-full bg-surface-inset inline-flex items-center justify-center text-secondary mb-3">+ <%= helpers.icon("piggy-bank", size: "2xl") %>+ </div>+ <h2 class="text-lg font-semibold text-primary"><%= t("goals.show.empty.heading") %></h2>+ <p class="text-sm text-secondary mt-1 max-w-md"><%= t("goals.show.empty.body") %></p>+ <div class="mt-4">+ <%= render DS::Link.new(+ text: t("goals.show.record_pledge_cta"),+ variant: "primary",+ size: "sm",+ href: helpers.new_goal_pledge_path(goal),+ icon: "plus",+ frame: :modal+ ) %>+ </div>+ <% end %>++<% else %>+ <%= render DS::Card.new do %>+ <div class="flex flex-col gap-2 mb-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3">+ <div class="min-w-0">+ <h2 class="text-sm font-medium text-primary"><%= t("goals.show.projection.heading") %></h2>+ <p class="text-xs text-secondary mt-0.5"><%= helpers.sanitize goal.projection_summary %></p>+ <% if show_catch_up? %>+ <p class="text-xs text-secondary mt-0.5 tabular-nums privacy-sensitive">+ <%= t("goals.show.catch_up.body", avg: goal.pace_money.format(precision: 0), required: Money.new(goal.monthly_target_amount, goal.currency).format(precision: 0)) %>+ </p>+ <% end %>+ </div>+ <%# Swatches are bordered spans rather than inline SVG. The projection one+ keeps the chart's own colour variables in an inline style rather than+ taking `border-success` / `border-warning`: a legend that does not+ match the line it describes is worse than the markup it saves, and+ the chart hard-codes green-600 / yellow-600. %>+ <div class="flex items-center flex-wrap gap-x-5 gap-y-1 text-xs text-secondary sm:gap-x-3 sm:shrink-0">+ <span class="inline-flex items-center gap-1.5">+ <span class="inline-block w-5 border-t-2 border-current text-primary" aria-hidden="true"></span>+ <%= t("goals.show.projection.legend_saved") %>+ </span>+ <% if show_projection_legend? %>+ <span class="inline-flex items-center gap-1.5">+ <span class="inline-block w-5 border-t-2 border-dashed" style="border-color: <%= projection_color %>" aria-hidden="true"></span>+ <%= t("goals.show.projection.legend_projection") %>+ </span>+ <% if show_required_legend? %>+ <span class="inline-flex items-center gap-1.5">+ <span class="inline-block w-5 border-t-2 border-dotted border-current text-secondary opacity-50" aria-hidden="true"></span>+ <%= t("goals.show.projection.legend_required") %>+ </span>+ <% end %>+ <% end %>+ </div>+ </div>+ <div class="flex-1 min-h-[200px] privacy-sensitive"+ data-controller="goal-projection-chart"+ data-goal-projection-chart-data-value="<%= goal.projection_payload.to_json %>"+ data-goal-projection-chart-aria-label-value="<%= t("goals.show.projection.aria_label", name: goal.name) %>"+ data-goal-projection-chart-aria-description-value="<%= helpers.strip_tags(goal.projection_summary) %>"+ data-goal-projection-chart-today-label-value="<%= t("goals.show.projection.today_marker") %>"+ data-goal-projection-chart-projected-template-value="<%= t("goals.show.projection.tooltip_projected", amount: "{amount}") %>"+ data-goal-projection-chart-saved-template-value="<%= t("goals.show.projection.tooltip_saved", amount: "{amount}") %>"+ data-goal-projection-chart-target-relation-template-value="<%= t("goals.show.projection.tooltip_target_relation", percent: "{percent}", target: "{target}") %>"></div>+ <% if goal.target_date.nil? %>+ <div class="mt-3 flex items-center gap-2 text-xs text-secondary">+ <span class="text-subdued"><%= helpers.icon("calendar-plus", size: "sm") %></span>+ <span class="flex-1"><%= t("goals.show.no_target_date.body") %></span>+ <%= helpers.link_to t("goals.show.no_target_date.cta"),+ helpers.edit_goal_path(goal),+ data: { turbo_frame: :modal },+ class: "font-medium text-primary underline-offset-2 hover:underline" %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/components/goals/lifecycle_panel_component.rb b/app/components/goals/lifecycle_panel_component.rbnew file mode 100644index 0000000000..4c10aed5c4--- /dev/null+++ b/app/components/goals/lifecycle_panel_component.rb@@ -0,0 +1,92 @@+# The panel between the goal header and its funding breakdown. Which panel a+# goal gets is a lifecycle question with five answers, and the template used to+# work it out inline from `completed?`, `maintained?`, `one_off?`, `status` and+# `may_complete?` — five predicates deep in ERB, where the ordering between+# them mattered and nothing said so.+#+# The decision lives here; the template only renders the answer.+class Goals::LifecyclePanelComponent < ApplicationComponent+ attr_reader :goal++ def initialize(goal:)+ @goal = goal+ end++ # Order is load-bearing, so it is stated once, here.+ #+ # `:reserve_shortfall` comes before `:empty`: a brand-new reserve sits at+ # zero balance and zero pace, and the generic "make your first transfer"+ # card would swallow it — where what it needs is the one figure a projection+ # cannot show, how far it is below its floor. Ordering it after also meant+ # asking a reserve for a pace it does not have.+ def panel+ return :inactive if goal.archived? || goal.paused?+ return :celebration if goal.completed? || goal.status == :reached || goal.status == :funded+ return :reserve_shortfall if goal.maintained?+ return :empty if goal.current_balance.to_d.zero? && goal.pace.to_d.zero?++ :projection+ end++ # --- inactive ---++ def inactive_icon = goal.archived? ? "archive" : "pause"++ def inactive_heading_key+ goal.archived? ? "inactive.heading_archived" : "inactive.heading_paused"+ end++ # --- celebration ---++ # 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+ # frozen. A goal merely at 100% is still holding its money and still+ # competing with its siblings on the account.+ def closed? = goal.completed?++ def celebration_icon = goal.maintained? ? "shield-check" : "party-popper"++ def celebration_heading_key+ goal.maintained? ? "celebration.heading_reserve" : "celebration.heading"+ end++ def celebration_body_key+ return "celebration.body_reserve" if goal.maintained?++ closed? ? "celebration.body" : "celebration.body_reached"+ end++ def show_frozen_note? = closed? && goal.completed_at.present?++ # A reserve at its floor is in its normal state, not waiting to be closed:+ # offering to release the money would be offering to undo the thing it+ # exists for. Closing is also what releases the earmark, where archiving is+ # the gesture that does not — so a goal merely at 100% is offered `:close`,+ # not `:archive`.+ def celebration_action+ return :none if goal.maintained?+ return :close if !closed? && goal.one_off? && goal.may_complete?+ return :archive if goal.may_archive?++ :none+ end++ # --- projection ---+++ # The chart draws its projection line with these same two variables+ # (`goal_projection_chart_controller.js`), so the legend swatch has to use+ # them too rather than the semantic border tokens — a legend whose colour+ # does not match its line is worse than the markup it would save.+ def projection_color+ goal.status == :on_track ? "var(--color-green-600)" : "var(--color-yellow-600)"+ end++ def show_catch_up? = goal.status == :behind && goal.monthly_target_amount.present?++ def show_projection_legend? = goal.target_date.present?++ def show_required_legend?+ goal.monthly_target_amount.to_d.positive? && goal.remaining_amount.to_d.positive?+ end+enddiff --git a/app/components/goals/progress_ring_component.rb b/app/components/goals/progress_ring_component.rbindex 67f92525a9..edbfbf1e58 100644--- a/app/components/goals/progress_ring_component.rb+++ b/app/components/goals/progress_ring_component.rb@@ -24,7 +24,9 @@ class Goals::ProgressRingComponent < ApplicationComponentdef percent_text_classcase goal.status- when :reached then "text-success"+ # `funded` is a reserve sitting at its floor — the same "nothing to do+ # here" as a one-off that reached its target, and it should read as such.+ when :reached, :funded then "text-success"else "text-primary"endenddiff --git a/app/components/goals/status_pill_component.rb b/app/components/goals/status_pill_component.rbindex 134500b623..4d2cfcf895 100644--- a/app/components/goals/status_pill_component.rb+++ b/app/components/goals/status_pill_component.rb@@ -10,6 +10,11 @@ class Goals::StatusPillComponent < ApplicationComponentreached: { tone: :green, icon: "star" },completed: { tone: :green, icon: "circle-check-big" },no_target_date: { tone: :gray, icon: "infinity" },+ # A reserve at its floor is steady, not celebratory: green, but a shield+ # rather than the star a one-off gets for finishing. Below its floor it+ # reads like `behind` — something to top back up.+ funded: { tone: :green, icon: "shield-check" },+ depleted: { tone: :amber, icon: "shield-alert" },paused: { tone: :gray, icon: "pause" },archived: { tone: :gray, icon: "archive" }}.freezediff --git a/app/controllers/goals_controller.rb b/app/controllers/goals_controller.rbindex 7e193e4603..d20e46f57c 100644--- a/app/controllers/goals_controller.rb+++ b/app/controllers/goals_controller.rb@@ -176,11 +176,11 @@ class GoalsController < ApplicationControllerenddef goal_params- params.require(:goal).permit(:name, :target_amount, :target_date, :color, :icon, :notes)+ params.require(:goal).permit(:name, :target_amount, :target_date, :color, :icon, :notes, :kind)enddef goal_update_params- params.require(:goal).permit(:name, :target_amount, :target_date, :color, :icon, :notes)+ params.require(:goal).permit(:name, :target_amount, :target_date, :color, :icon, :notes, :kind)enddef lookup_accounts(ids)@@ -283,10 +283,15 @@ class GoalsController < ApplicationController# fund, etc.) has no required monthly pace, so "on track" is# undefined. Counting it would penalise the user for having# open-ended goals — they'd never improve the ratio.+ # - maintained → a reserve has no deadline and no pace benchmark at+ # all. Its statuses are `funded`/`depleted`, which match none of the+ # exclusions above, so without this it would land in the denominator+ # and never in the numerator: a family with one reserve read+ # "0 of 1 on track" for a goal that is working exactly as intended.# When this hits zero the tile swaps to a celebration / empty# state in the view.tracked_total = active_goals.count do |g|- !g.paused? && g.status != :reached && g.status != :no_target_date+ !g.paused? && !g.maintained? && g.status != :reached && g.status != :no_target_dateend{diff --git a/app/helpers/goals_helper.rb b/app/helpers/goals_helper.rbnew file mode 100644index 0000000000..704dfdddb4--- /dev/null+++ b/app/helpers/goals_helper.rb@@ -0,0 +1,22 @@+module GoalsHelper+ # Completing a goal releases the money it was holding, so both places that+ # offer it — the header menu and the celebration panel — ask first, and ask+ # the same question. Built here rather than twice inline: the two wordings+ # drifting apart is how one of them ends up describing the wrong consequence.+ def goal_complete_confirm(goal)+ body = if goal.progress_percent < 100+ t("goals.show.confirm_complete_body_short",+ progress: goal.progress_percent,+ saved: goal.current_balance_money.format(precision: 0),+ target: goal.target_amount_money.format(precision: 0))+ else+ t("goals.show.confirm_complete_body")+ end++ CustomConfirm.new(+ title: t("goals.show.confirm_complete_title"),+ body: body,+ btn_text: t("goals.show.confirm_complete_cta")+ )+ end+enddiff --git a/app/javascript/controllers/goal_kind_controller.js b/app/javascript/controllers/goal_kind_controller.jsnew file mode 100644index 0000000000..95aaec26a9--- /dev/null+++ b/app/javascript/controllers/goal_kind_controller.js@@ -0,0 +1,29 @@+import { Controller } from "@hotwired/stimulus"++// A maintained reserve has no deadline: it is a level to hold, not something+// due on a date. Hiding the target-date field keeps a stale value from being+// submitted and driving a pace the goal does not have.+export default class extends Controller {+ static targets = ["radio", "dateField"]++ connect() {+ this.refresh()+ }++ refresh() {+ const maintained = this.radioTargets.some((radio) => radio.checked && radio.value === "maintained")+ this.dateFieldTargets.forEach((field) => field.classList.toggle("hidden", maintained))+ if (maintained) {+ this.dateFieldTargets.forEach((field) => {+ const input = field.querySelector("input")+ if (!input) return++ input.value = ""+ // Assigning `value` fires nothing, so the pace suggestion bound to+ // this input's action kept showing a monthly figure derived from a+ // deadline the goal no longer has.+ input.dispatchEvent(new Event("input", { bubbles: true }))+ })+ }+ }+}diff --git a/app/models/goal.rb b/app/models/goal.rbindex 63d051bfd4..4070e46f4c 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -41,6 +41,12 @@ class Goal < ApplicationRecordvalidate :linked_accounts_must_belong_to_familyvalidate :currency_locked_once_linkedvalidate :restore_must_not_recreate_whole_account_conflict+ validate :kind_locked_while_released+ # 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+ # cannot see.+ before_validation :clear_target_date_for_maintained# Autosave validates each link separately, so each would otherwise take its# own account lock in association order. Two goals saving links on the same@@ -82,16 +88,23 @@ class Goal < ApplicationRecordRELEASED_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.+ # floor to hold — an emergency fund is not an achievement to file away, it+ # is a level to keep. The two differ in what 100% means, whether `complete`+ # is even allowed, and how they sort.KINDS = %w[one_off maintained].freezevalidates :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+ # Display order for active (non-completed/non-archived) goals: whatever+ # needs money first, then on-track, then open-ended, then the reserves that+ # are already whole. Paused sorts after all of these.+ #+ # `depleted` shares rank 0 with `behind`: a reserve below its floor is the+ # same kind of "this needs attention" as a goal off pace. `active_display_sort`+ # falls back to 4 for anything unranked, so omitting these two would bury a+ # drained emergency fund at the very bottom of the list — the exact opposite+ # of what it means.+ ACTIVE_DISPLAY_STATUS_RANK = { behind: 0, depleted: 0, on_track: 1, no_target_date: 2, funded: 3 }.freezescope :alphabetically, -> { order(Arel.sql("LOWER(name) ASC")) }scope :active_first, lambda {@@ -241,8 +254,17 @@ class Goal < ApplicationRecord# Display order shared by the goals index and the Plan hub: behind first,# then on-track, then open-ended, paused last, name as tie-breaker.+ # Paused sorts last, behind every ranked status and the unranked fallback.+ # It used to share rank 3 with :funded, so a paused goal whose name sorted+ # first jumped ahead of a reserve that was whole — the list claiming the+ # paused one wanted attention more.+ PAUSED_DISPLAY_RANK = 5+def self.active_display_sort(goals)- goals.sort_by { |goal| [ goal.paused? ? 3 : ACTIVE_DISPLAY_STATUS_RANK.fetch(goal.status, 4), goal.name.downcase ] }+ goals.sort_by do |goal|+ rank = goal.paused? ? PAUSED_DISPLAY_RANK : ACTIVE_DISPLAY_STATUS_RANK.fetch(goal.status, 4)+ [ rank, goal.name.downcase ]+ endend# Active goals ready to render outside the goals index (e.g. the Plan hub).@@ -283,8 +305,11 @@ class Goal < ApplicationRecordtransitions from: :paused, to: :activeend+ # Guarded to one_off: completing releases the earmark, and releasing the+ # money is the opposite of what a reserve is for. A maintained goal at+ # 100% is simply whole; there is nothing to close.event :complete do- transitions from: [ :active, :paused ], to: :completed+ transitions from: [ :active, :paused ], to: :completed, guard: :one_off?endevent :archive do@@ -533,6 +558,10 @@ class Goal < ApplicationRecorddef statusreturn @status if defined?(@status)+ # A reserve is never "reached": sitting at its floor is its steady state,+ # not an achievement to file away. It is either whole or short.+ return @status = (remaining_amount.to_d.zero? ? :funded : :depleted) if maintained?+@status = if completed? || remaining_amount.to_d.zero?:reachedelsif target_date.nil?@@ -548,8 +577,13 @@ class Goal < ApplicationRecord# are excluded even when their raw status computes :behind — pausing stops# the pace clock on purpose, so surfacing them as behind (or summing them# into "needs this month") would nag the user about a goal they shelved.+ #+ # Maintained reserves are excluded for a different reason: they have no+ # pace at all. monthly_target_amount and pace both derive from target_date,+ # which a reserve does not have, so "save X/month to catch up" would be+ # advice about a deadline that does not exist.def behind_pace?- !paused? && status == :behind+ !paused? && !maintained? && status == :behindend# Date of the most-recently-matched pledge's underlying entry. Used by the@@ -656,6 +690,11 @@ class Goal < ApplicationRecordendwhen :no_target_dateI18n.t("goals.show.status_callout.no_target_date")+ when :depleted+ # A drained reserve had no callout at all: the one status that most+ # deserves a line of explanation was the one that said nothing.+ I18n.t("goals.show.status_callout.depleted",+ amount: remaining_amount_money.format(precision: 0))endend@@ -693,11 +732,25 @@ class Goal < ApplicationRecord# Single source of truth for the projection-chart subtitle / chart-aria# description. Used to live inline in show.html.erb as a 17-line if/elsif# chain. Returns an `html_safe` string when it picks the `_html` variant.+ # The two statuses that mean "this one wants looking at": a goal off its+ # pace, and a reserve below its floor. Named once because three places were+ # spelling the pair out and one of them had already fallen behind.+ def needs_attention?+ status.in?(%i[behind depleted])+ end+def projection_summaryreturn @projection_summary if defined?(@projection_summary)@projection_summary =- if completed? || progress_percent >= 100+ if maintained?+ # A reserve holds a level; there is no finish line to project toward+ # and no target to have "hit". It never reaches the projection panel+ # today — the shortfall and celebration panels catch it first — but+ # this method reads as the single source of truth for that subtitle,+ # so it should not hand a caller a one-off's wording.+ I18n.t("goals.show.projection.reserve")+ elsif completed? || progress_percent >= 100I18n.t("goals.show.projection.reached")elsif target_date.nil?I18n.t("goals.show.projection.no_target_date")@@ -927,6 +980,27 @@ class Goal < ApplicationRecorderrors.add(:linked_accounts, :must_belong_to_family)end+ # Switching a released goal to `maintained` would leave a reserve sitting in+ # `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.+ def kind_locked_while_released+ return unless persisted? && will_save_change_to_kind?+ # The PERSISTED state, not the one in memory. A single update can set+ # `state: "active"` alongside the new kind, and reading the attribute+ # would see the goal as already reopened and wave it through — while the+ # direct write skipped the `reopen` transition that clears+ # `completed_amount`, leaving an active reserve reporting a frozen+ # snapshot forever. Reopening has to be its own gesture.+ return unless state_in_database.in?(RELEASED_STATES)++ errors.add(:kind, :locked_while_released)+ end++ def clear_target_date_for_maintained+ self.target_date = nil if maintained?+ end+def currency_locked_once_linkedreturn unless persisted? && currency_changed?return unless goal_accounts.where.not(id: nil).exists?diff --git a/app/views/goals/_form.html.erb b/app/views/goals/_form.html.erbindex c87d96a6a3..f4fe92b470 100644--- a/app/views/goals/_form.html.erb+++ b/app/views/goals/_form.html.erb@@ -1,6 +1,10 @@<%# locals: (goal:, linkable_accounts:, currently_linked_account_ids: []) %>-<div data-controller="goal-form"+<%# goal-kind lives on this wrapper, not on the kind selector: its+ dateField target is a sibling of the radios, and a controller only sees+ targets inside its own element. Scoped to the selector, dateFieldTargets+ came back empty and picking "Reserve to maintain" never hid the date. %>+<div data-controller="goal-form goal-kind"data-goal-form-currency-value="<%= Current.family.primary_currency_code %>"data-goal-form-require-account-value="<%= !goal.persisted? %>"data-goal-form-suggested-with-date-value="<%= t("goals.form.suggested_with_date") %>"@@ -14,6 +18,24 @@<%= render "color_picker", form: f, colors: Goal::COLORS, icons: Goal::ICONS %></div>+ <%# Kind first: it changes what the rest of the form means. A reserve has+ no deadline — target_date is hidden rather than disabled so it cannot+ be submitted with a value that would then drive a pace the goal does+ not have. %>+ <div class="grid grid-cols-2 gap-2">+ <% Goal::KINDS.each do |kind| %>+ <label class="flex items-start gap-2 rounded-lg border border-primary p-3 cursor-pointer has-[:checked]:border-secondary has-[:checked]:bg-surface-inset">+ <%= f.radio_button :kind, kind,+ class: "radio mt-0.5 shrink-0",+ data: { goal_kind_target: "radio", action: "change->goal-kind#refresh" } %>+ <span class="min-w-0">+ <span class="block text-sm font-medium text-primary"><%= t("goals.form.kinds.#{kind}.label") %></span>+ <span class="block text-xs text-secondary"><%= t("goals.form.kinds.#{kind}.hint") %></span>+ </span>+ </label>+ <% end %>+ </div>+<div><%= f.text_field :name,placeholder: t("goals.form.fields.name_placeholder"),@@ -33,9 +55,11 @@amount_data: { goal_form_target: "amountInput", action: "input->goal-form#suggestedChanged" } %><p class="<%= "hidden" unless goal.errors[:target_amount].any? %> mt-1.5 text-xs text-destructive" data-goal-form-target="amountError"><%= t("goals.form.errors.amount_required") %></p></div>- <%= f.date_field :target_date,- label: t("goals.form.fields.target_date"),- data: { goal_form_target: "dateInput", action: "input->goal-form#suggestedChanged" } %>+ <div data-goal-kind-target="dateField">+ <%= f.date_field :target_date,+ label: t("goals.form.fields.target_date"),+ data: { goal_form_target: "dateInput", action: "input->goal-form#suggestedChanged" } %>+ </div></div><p class="text-xs text-secondary italic tabular-nums privacy-sensitive hidden" data-goal-form-target="suggested"></p>diff --git a/app/views/goals/show.html.erb b/app/views/goals/show.html.erbindex 4a878dc388..e687975134 100644--- a/app/views/goals/show.html.erb+++ b/app/views/goals/show.html.erb@@ -38,25 +38,13 @@<% menu.with_item(variant: "button", text: t(".resume"), icon: "play", href: resume_goal_path(@goal), method: :patch) %><% end %><% if @goal.may_complete? %>- <% complete_body = if @goal.progress_percent < 100- t(".confirm_complete_body_short",- progress: @goal.progress_percent,- saved: @goal.current_balance_money.format(precision: 0),- target: @goal.target_amount_money.format(precision: 0))- else- t(".confirm_complete_body")- end %><% menu.with_item(variant: "button",text: t(".complete"),icon: "circle-check-big",href: complete_goal_path(@goal),method: :patch,- confirm: CustomConfirm.new(- title: t(".confirm_complete_title"),- body: complete_body,- btn_text: t(".confirm_complete_cta")- )+ confirm: goal_complete_confirm(@goal)) %><% end %><% if @goal.may_archive? %>@@ -141,7 +129,7 @@<% unless @goal.completed? %><p class="text-xs text-subdued tabular-nums mt-0.5 privacy-sensitive"><%= t(".ring.to_go", amount: @goal.remaining_amount_money.format(precision: 0)) %></p><% end %>- <% unless @goal.completed? || @goal.status == :reached || @goal.paused? || @goal.archived? %>+ <% unless @goal.completed? || @goal.status == :reached || @goal.status == :funded || @goal.paused? || @goal.archived? %><%# Single Record pledge entry point on the page. Pre-filled with thecatch-up delta when behind so accepting once funds the gap. %><% prefill_amount = @goal.status == :behind && @goal.catch_up_delta_money.amount.positive? ? @goal.catch_up_delta_money.amount.to_f : nil %>@@ -158,154 +146,19 @@<% end %></div>- <% if @goal.archived? || @goal.paused? %>- <div class="bg-container rounded-xl shadow-border-xs p-5 flex flex-col items-center justify-center text-center">- <div class="w-16 h-16 rounded-full bg-surface-inset inline-flex items-center justify-center text-secondary mb-3">- <%= icon(@goal.archived? ? "archive" : "pause", size: "2xl") %>- </div>- <h2 class="text-lg font-semibold text-primary">- <%= t(@goal.archived? ? ".inactive.heading_archived" : ".inactive.heading_paused") %>- </h2>- <p class="text-sm text-secondary mt-1 max-w-md tabular-nums privacy-sensitive">- <%= t(".inactive.body", saved: @goal.current_balance_money.format(precision: 0), target: @goal.target_amount_money.format(precision: 0)) %>- </p>- </div>- <% elsif @goal.completed? || @goal.status == :reached %>- <div class="bg-container rounded-xl shadow-border-xs p-5 flex flex-col items-center justify-center text-center">- <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(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"),- href: archive_goal_path(@goal),- variant: "outline",- size: "sm",- method: :patch- ) %>- </div>- <% end %>- </div>- <% elsif @goal.current_balance.to_d.zero? && @goal.pace.to_d.zero? %>- <%# No movement yet on the linked account: render an inline "make your first transfer"- CTA card instead of a flat-at-$0 chart that looks broken. %>- <div class="bg-container rounded-xl shadow-border-xs p-5 flex flex-col items-center justify-center text-center">- <div class="w-16 h-16 rounded-full bg-surface-inset inline-flex items-center justify-center text-secondary mb-3">- <%= icon("piggy-bank", size: "2xl") %>- </div>- <h2 class="text-lg font-semibold text-primary"><%= t(".empty.heading") %></h2>- <p class="text-sm text-secondary mt-1 max-w-md"><%= t(".empty.body") %></p>- <div class="mt-4">- <%= render DS::Link.new(- text: t(".record_pledge_cta"),- variant: "primary",- size: "sm",- href: new_goal_pledge_path(@goal),- icon: "plus",- frame: :modal- ) %>- </div>- </div>- <% else %>- <div class="bg-container rounded-xl shadow-border-xs p-5 flex flex-col">- <div class="flex flex-col gap-2 mb-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3">- <div class="min-w-0">- <h2 class="text-sm font-medium text-primary"><%= t(".projection.heading") %></h2>- <p class="text-xs text-secondary mt-0.5"><%= sanitize @goal.projection_summary %></p>- <% if @goal.status == :behind && @goal.monthly_target_amount %>- <p class="text-xs text-secondary mt-0.5 tabular-nums privacy-sensitive">- <%= t("goals.show.catch_up.body", avg: @goal.pace_money.format(precision: 0), required: Money.new(@goal.monthly_target_amount, @goal.currency).format(precision: 0)) %>- </p>- <% end %>- </div>- <% projection_color = @goal.status == :on_track ? "var(--color-green-600)" : "var(--color-yellow-600)" %>- <div class="flex items-center flex-wrap gap-x-5 gap-y-1 text-[11px] text-secondary sm:gap-x-3 sm:shrink-0">- <span class="inline-flex items-center gap-1.5">- <svg width="18" height="6" class="text-primary"><line x1="0" y1="3" x2="18" y2="3" stroke="currentColor" stroke-width="2" /></svg>- <%= t(".projection.legend_saved") %>- </span>- <% unless @goal.target_date.nil? %>- <span class="inline-flex items-center gap-1.5">- <svg width="18" height="6"><line x1="0" y1="3" x2="18" y2="3" stroke="<%= projection_color %>" stroke-width="2" stroke-dasharray="3 3" /></svg>- <%= t(".projection.legend_projection") %>- </span>- <% if @goal.monthly_target_amount.to_d.positive? && @goal.remaining_amount.to_d.positive? %>- <span class="inline-flex items-center gap-1.5">- <svg width="18" height="6" class="text-secondary"><line x1="0" y1="3" x2="18" y2="3" stroke="currentColor" stroke-width="2" stroke-dasharray="2 4" opacity="0.5" /></svg>- <%= t(".projection.legend_required") %>- </span>- <% end %>- <% end %>- </div>- </div>- <div class="flex-1 min-h-[200px] privacy-sensitive"- data-controller="goal-projection-chart"- data-goal-projection-chart-data-value="<%= @goal.projection_payload.to_json %>"- data-goal-projection-chart-aria-label-value="<%= t("goals.show.projection.aria_label", name: @goal.name) %>"- data-goal-projection-chart-aria-description-value="<%= strip_tags(@goal.projection_summary) %>"- data-goal-projection-chart-today-label-value="<%= t("goals.show.projection.today_marker") %>"- data-goal-projection-chart-projected-template-value="<%= t("goals.show.projection.tooltip_projected", amount: "{amount}") %>"- data-goal-projection-chart-saved-template-value="<%= t("goals.show.projection.tooltip_saved", amount: "{amount}") %>"- data-goal-projection-chart-target-relation-template-value="<%= t("goals.show.projection.tooltip_target_relation", percent: "{percent}", target: "{target}") %>"></div>- <% if @goal.target_date.nil? %>- <div class="mt-3 flex items-center gap-2 text-xs text-secondary">- <span class="text-subdued"><%= icon("calendar-plus", size: "sm") %></span>- <span class="flex-1"><%= t(".no_target_date.body") %></span>- <%= link_to t(".no_target_date.cta"),- edit_goal_path(@goal),- data: { turbo_frame: :modal },- class: "font-medium text-primary underline-offset-2 hover:underline" %>- </div>- <% end %>- </div>- <% end %>+ <%= render Goals::LifecyclePanelComponent.new(goal: @goal) %></section><% if @goal.linked_accounts.any? %>- <section class="bg-container rounded-xl shadow-border-xs p-5">+ <%= render DS::Card.new do %><%= render Goals::FundingAccountsBreakdownComponent.new(goal: @goal) %>- </section>+ <% end %><% end %><% if @goal.notes.present? %>- <section class="bg-container rounded-xl shadow-border-xs p-5">+ <%= render DS::Card.new do %><h2 class="text-sm font-medium text-primary mb-2"><%= t(".notes") %></h2><p class="text-sm text-secondary whitespace-pre-line"><%= @goal.notes %></p>- </section>+ <% end %><% end %></div>diff --git a/app/views/plans/_goals_card.html.erb b/app/views/plans/_goals_card.html.erbindex 3b7a533caa..7530d14c5e 100644--- a/app/views/plans/_goals_card.html.erb+++ b/app/views/plans/_goals_card.html.erb@@ -95,7 +95,10 @@</div><% if goal.target_amount.to_d.positive? %><div class="h-1 bg-container-inset rounded-full overflow-hidden">- <div class="h-full <%= goal.status == :behind ? "bg-warning" : "bg-inverse" %> rounded-full"+ <%# A depleted reserve wants attention as much as a goal off its+ pace: the pill beside this bar is already amber for it, and+ the bar was still neutral. %>+ <div class="h-full <%= goal.needs_attention? ? "bg-warning" : "bg-inverse" %> rounded-full"style="inline-size: <%= goal.progress_percent.clamp(0, 100) %>%"></div></div><% elsif goal.months_of_runway.present? %>diff --git a/config/locales/models/goal/en.yml b/config/locales/models/goal/en.ymlindex f4a1a5a552..f6ede4b781 100644--- a/config/locales/models/goal/en.yml+++ b/config/locales/models/goal/en.yml@@ -22,5 +22,7 @@ en:must_be_fundable: All linked accounts must be cash or investment accounts.currency_mismatch: All linked accounts must share the same currency.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.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 0a08fe66a6..eedf95df7e 100644--- a/config/locales/models/goal/fr.yml+++ b/config/locales/models/goal/fr.yml@@ -18,6 +18,8 @@ fr:base:at_least_one_linked_account_required: Sélectionnez au moins un compte pour financer cet objectif.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.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 38946a4a42..871b28fd34 100644--- a/config/locales/views/goals/en.yml+++ b/config/locales/views/goals/en.yml@@ -104,6 +104,9 @@ en:unarchive: Restorereopen: Reopen goaldelete: Delete+ reserve_shortfall:+ heading: Reserve below its level+ body: "You are holding %{saved} of %{target}. Add %{missing} to bring it back to its floor."record_pledge_cta: Record pledgepledge_just_transferred: Log a transfer you madepledge_just_saved: Log money you set aside@@ -117,6 +120,7 @@ en:funding_last_30d: last 30dfunding_last_90d: last 90dstatus_callout:+ depleted: "%{amount} short of its level — top it up to bring the reserve back"behind: "save %{amount}/mo more to catch up"behind_covered: "pending pledges close the gap"on_track: "reaches goal around %{date}"@@ -150,6 +154,7 @@ en:legend_saved: Savedlegend_projection: Projectionlegend_required: Required+ reserve: "A reserve holds a level, so there is no finish line to project."reached: You've hit the target. No projection needed.no_target_date: No target date set. Set one to project a finish line.no_pace: No deposits yet. Add money to a linked account to start a projection.@@ -183,6 +188,8 @@ en:body: Restore it to continue contributing, or leave it as a record.restore_cta: Restore goalcelebration:+ heading_reserve: Reserve intact+ body_reserve: "Your reserve is at its full level, %{saved} of %{target}. Nothing to do — it stays earmarked."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@@ -209,6 +216,8 @@ en:completed: Completedarchived: Archivedstatus:+ funded: Reserve intact+ depleted: Needs topping upon_track: On trackbehind: Behindreached: Reached@@ -241,6 +250,8 @@ en:pace_no_target: "%{avg}/mo avg"footer_paused: Pausedfooter_archived: Archived+ footer_reserve_intact: Reserve intact+ footer_reserve_short: "%{amount} to top up"footer_reached: Goal reachedfooter_catch_up: "Save %{amount}/mo to catch up"footer_no_deadline: Open@@ -254,6 +265,13 @@ en:one: Last pledge matched 1 day agoother: "Last pledge matched %{count} days ago"form:+ kinds:+ one_off:+ hint: Save toward something, then close it when you spend it.+ label: One-off goal+ maintained:+ hint: A level to keep, like an emergency fund. Never closed.+ label: Reserve to maintaincreate: Create goalsave: Save changessuggested_with_date: "Save {monthly}/mo across {accounts} to hit it on time."diff --git a/config/locales/views/goals/fr.yml b/config/locales/views/goals/fr.ymlindex d1ab24092e..3552265b39 100644--- a/config/locales/views/goals/fr.yml+++ b/config/locales/views/goals/fr.yml@@ -30,6 +30,13 @@ fr:errors:not_found: Cet objectif n'a pas pu être trouvé. Il a peut-être été supprimé.form:+ kinds:+ maintained:+ hint: Un niveau à tenir, comme une épargne de précaution. Jamais clôturée.+ label: Réserve à maintenir+ one_off:+ hint: Épargner pour quelque chose, puis clôturer une fois la dépense faite.+ label: Objectif ponctuelcreate: Créer l'objectiferrors:accounts_required: Sélectionnez au moins un compte de financement.@@ -76,6 +83,8 @@ fr:footer_no_deadline: Ouvertfooter_no_pledges: Aucune promesse rapprochéefooter_paused: En pause+ footer_reserve_intact: Réserve constituée+ footer_reserve_short: "%{amount} à recompléter"footer_reached: Objectif atteintleft: restantn_accounts: "%{first} +%{count}"@@ -168,6 +177,8 @@ fr:body: Rythme actuel %{avg}/mois · requis %{required}/mois pour atteindre votre objectif.title: Épargnez %{amount}/mois de plus pour rattraper le retardcelebration:+ body_reserve: "Votre réserve a atteint son niveau cible, %{saved} sur %{target}. Rien à faire — elle reste affectée."+ heading_reserve: Réserve constituéebody_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 objectifclose_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.@@ -242,11 +253,15 @@ fr:no_pace: Aucun dépôt pour le moment. Ajoutez de l'argent sur un compte lié pour démarrer la projection.no_target_date: Aucune date cible définie. Définissez-en une pour projeter la fin.on_track_html: Au rythme actuel, vous atteindrez cet objectif vers le <strong class="text-primary whitespace-nowrap">%{date}</strong>.+ reserve: "Une réserve maintient un niveau : il n'y a pas d'échéance à projeter."reached: Vous avez atteint l'objectif. Aucune projection nécessaire.today_marker: Aujourd'huitooltip_projected: 'Projeté : %{amount}'tooltip_saved: 'Épargné : %{amount}'tooltip_target_relation: "%{percent}% de la cible de %{target}"+ reserve_shortfall:+ heading: Réserve sous son niveau+ body: "Vous détenez %{saved} sur %{target}. Complétez de %{missing} pour la ramener à son niveau."record_pledge_cta: Enregistrer une promessereopen: Réouvrir l'objectifresume: Reprendre@@ -258,6 +273,7 @@ fr:saved: Épargnéto_go: "%{amount} restant(s)"status_callout:+ depleted: "il manque %{amount} — complétez pour ramener la réserve à son niveau"behind: épargnez %{amount}/mois de plus pour rattraper le retardbehind_covered: les promesses en attente comblent le retardno_target_date: définissez une date cible pour projeter une date de fin@@ -269,6 +285,8 @@ fr:completed: Terminépaused: En pausestatus:+ depleted: À recompléter+ funded: Réserve constituéearchived: Archivébehind: En retardcompleted: Terminédiff --git a/test/components/goals/lifecycle_panel_component_test.rb b/test/components/goals/lifecycle_panel_component_test.rbnew file mode 100644index 0000000000..1dcdb2231c--- /dev/null+++ b/test/components/goals/lifecycle_panel_component_test.rb@@ -0,0 +1,74 @@+require "test_helper"++# The panel choice was five predicates deep in ERB where the ordering between+# them mattered and nothing said so. These pin the order, not the markup.+class Goals::LifecyclePanelComponentTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ end++ test "an archived or paused goal gets the inactive panel whatever its progress" do+ goal = funded_goal+ goal.archive!+ assert_equal :inactive, panel_for(goal)++ other = funded_goal(name: "Paused")+ other.pause!+ assert_equal :inactive, panel_for(other)+ end++ test "a reserve at its floor celebrates rather than reporting a shortfall" do+ assert_equal :celebration, panel_for(funded_goal(kind: "maintained"))+ end++ # A brand-new reserve sits at zero balance and zero pace, which is also what+ # the generic "make your first transfer" card tests for. It must not win:+ # what the reserve needs is how far below its floor it is.+ test "an empty reserve reports its shortfall rather than looking untouched" do+ goal = @family.goals.create!(+ name: "Precaution", target_amount: 6_000, currency: @family.currency, kind: "maintained"+ ) { |g| g.goal_accounts.build(account: pot(balance: 0), allocated_amount: 0) }++ assert_equal :reserve_shortfall, panel_for(goal)+ end++ test "a one-off goal with nothing in it yet is asked for its first transfer" do+ goal = @family.goals.create!(+ name: "Trip", target_amount: 5_000, currency: @family.currency+ ) { |g| g.goal_accounts.build(account: pot(balance: 0), allocated_amount: 0) }++ assert_equal :empty, panel_for(goal)+ end++ # A reserve is never offered closing: releasing the money would undo the+ # thing it exists for.+ test "a funded reserve is offered no closing action" do+ assert_equal :none, component_for(funded_goal(kind: "maintained")).celebration_action+ end++ # Closing releases the earmark; archiving does not. A goal merely at 100% is+ # still holding its money, so it gets the gesture that lets go of it.+ test "a goal at its target is offered closing, not archiving" do+ assert_equal :close, component_for(funded_goal).celebration_action+ end++ private+ def pot(balance:, name: "Pot #{SecureRandom.hex(3)}")+ Account.create!(family: @family, accountable: Depository.new, name: name,+ currency: @family.currency, balance: balance)+ end++ def funded_goal(name: "Trip", kind: "one_off")+ @family.goals.create!(+ name: name, target_amount: 1_000, currency: @family.currency, kind: kind+ ) { |g| g.goal_accounts.build(account: pot(balance: 1_000), allocated_amount: 1_000) }+ end++ def component_for(goal)+ Goals::LifecyclePanelComponent.new(goal: goal)+ end++ def panel_for(goal)+ component_for(goal).panel+ end+enddiff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rbindex 9fae6e32b5..4b438e51b7 100644--- a/test/controllers/goals_controller_test.rb+++ b/test/controllers/goals_controller_test.rb@@ -418,6 +418,87 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestassert_no_match(/#{Regexp.escape(I18n.t("goals.show.celebration.close_cta"))}/, response.body)end++ # --- Lot B3a: reserves ---++ test "create accepts the maintained kind" do+ account = unclaimed_account("Reserve Pot")++ assert_difference -> { Goal.count }, 1 do+ post goals_url, params: {+ goal: { name: "Emergency", target_amount: "6000", color: "#4da568", kind: "maintained", account_ids: [ account.id ] }+ }+ end++ assert Goal.order(created_at: :desc).first.maintained?+ end++ # The AASM guard refuses the transition; the controller must report that+ # rather than claim success or blow up.+ test "completing a reserve is refused at the controller too" do+ goal = fully_funded_goal+ goal.update_column(:kind, "maintained")++ patch complete_goal_url(goal)++ assert_redirected_to goal_path(goal)+ assert_match(/./, flash[:alert].to_s)+ assert_equal "active", goal.reload.state+ end++ test "a funded reserve reads as intact, with nothing to do" do+ goal = fully_funded_goal+ goal.update_column(:kind, "maintained")++ get goal_url(goal)++ assert_response :success+ assert_match I18n.t("goals.show.celebration.heading_reserve"), response.body+ assert_no_match(/#{Regexp.escape(I18n.t("goals.show.celebration.close_cta"))}/, response.body)+ assert_no_match(/#{Regexp.escape(I18n.t("goals.show.celebration.archive_cta"))}/, response.body)+ end++ # A reserve has no deadline and no pace benchmark, so it can never land in+ # the on-track numerator. Leaving it in the denominator made a family with+ # one reserve read "0 of 1 on track" for a goal working exactly as intended.+ test "a reserve stays out of the on-track denominator" do+ @user.family.goals.where.not(state: "archived").find_each(&:archive!)+ account = Account.create!(+ family: @user.family, accountable: Depository.new,+ name: "Reserve Pot", currency: @user.family.currency, balance: 1_000+ )+ @user.family.goals.create!(+ name: "Precaution", target_amount: 6_000, currency: @user.family.currency, kind: "maintained"+ ) { |g| g.goal_accounts.build(account: account) }++ get goals_url++ assert_response :success+ # The tile prints "<on track> of <tracked total>". The reserve must not+ # appear in the denominator: before this, the page read "0 of 1".+ assert_no_match(/0 of 1/, response.body)+ assert_match(/0 of 0/, response.body)+ end++ # A brand-new reserve is depleted with a zero balance, which used to match the+ # generic "make your first transfer" branch first. It is still a reserve short+ # of its floor, and the shortfall panel is what says so.+ test "a reserve with nothing in it yet gets the shortfall panel" do+ account = Account.create!(+ family: @user.family, accountable: Depository.new,+ name: "Empty Reserve Pot", currency: @user.family.currency, balance: 0+ )+ goal = @user.family.goals.create!(+ name: "Precaution", target_amount: 6_000, currency: @user.family.currency, kind: "maintained"+ ) { |g| g.goal_accounts.build(account: account) }++ get goal_url(goal)++ assert_response :success+ assert_match I18n.t("goals.show.reserve_shortfall.heading"), response.body+ assert_no_match(/#{Regexp.escape(I18n.t("goals.show.empty.heading"))}/, response.body)+ end+private# An active one_off goal sitting exactly at its target, on an account no# other goal claims.diff --git a/test/controllers/plans_controller_test.rb b/test/controllers/plans_controller_test.rbindex 64b567f602..cfb1bf7fc9 100644--- a/test/controllers/plans_controller_test.rb+++ b/test/controllers/plans_controller_test.rb@@ -8,6 +8,35 @@ class PlansControllerTest < ActionDispatch::IntegrationTestensure_tailwind_buildend++ # The status pill beside this bar was already amber for a depleted reserve+ # while the bar itself stayed neutral: the same goal reported as needing+ # attention and not, an inch apart.+ #+ # Counted rather than matched: a fixture goal is already off its pace, so+ # the markup is on the page either way and a presence check passes without+ # the fix.+ test "the goals card bars a depleted reserve in warning colour" do+ bar = /h-full bg-warning rounded-full/++ get plan_url+ before = response.body.scan(bar).size++ family = @user.family+ account = Account.create!(family: family, accountable: Depository.new,+ name: "Reserve pot", currency: family.currency, balance: 1_000)+ family.goals.create!(name: "Precaution", target_amount: 6_000,+ currency: family.currency, kind: "maintained") do |g|+ g.goal_accounts.build(account: account, allocated_amount: 1_000)+ end++ get plan_url++ assert_response :success+ assert_equal before + 1, response.body.scan(bar).size,+ "the depleted reserve's bar stayed neutral"+ end+test "redirects users without preview access to budgets" do@user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => false))diff --git a/test/models/goal_test.rb b/test/models/goal_test.rbindex 6f5457ece9..212351b6d9 100644--- a/test/models/goal_test.rb+++ b/test/models/goal_test.rb@@ -598,6 +598,85 @@ class GoalTest < ActiveSupport::TestCaseassert_not @goal.valid?end+ # --- Lot B3a: reserves to maintain ---++ test "a reserve is funded at its floor and depleted below it" do+ goal = reserve_goal(balance: 6_000, target: 6_000)+ assert_equal :funded, goal.status++ goal.linked_accounts.first.update!(balance: 4_500)+ assert_equal :depleted, Goal.find(goal.id).status+ end++ # `complete` releases the earmark. For a reserve that is the opposite of the+ # point, so the transition is refused outright rather than hidden in the UI.+ test "a reserve cannot be completed" do+ goal = reserve_goal(balance: 6_000, target: 6_000)++ assert_not goal.may_complete?+ assert_raises(AASM::InvalidTransition) { goal.complete! }+ assert_equal "active", goal.reload.state+ assert_nil goal.completed_amount+ end++ test "a one_off goal at its target can still be completed" do+ goal = reserve_goal(balance: 6_000, target: 6_000)+ goal.update!(kind: "one_off")++ assert goal.may_complete?+ end++ # monthly_target_amount and pace both derive from target_date, which a+ # reserve does not have — "save X/month to catch up" would be advice about+ # a deadline that does not exist.+ test "a depleted reserve is never behind pace" do+ goal = reserve_goal(balance: 1_000, target: 6_000)++ assert_equal :depleted, goal.status+ assert_not goal.behind_pace?+ end++ # ACTIVE_DISPLAY_STATUS_RANK falls back to 4 for anything unranked, so a+ # missing :depleted entry would sort a drained reserve dead last.+ # Named so the alphabetical tie-break works AGAINST the reserve: only the+ # rank can put it first. Unranked, :depleted would fall back to 4 and land+ # behind the open-ended goal's 2.+ test "a depleted reserve sorts ahead of a goal that needs nothing" do+ drained = reserve_goal(balance: 100, target: 6_000, name: "Zzz drained")+ open_ended = @family.goals.create!(+ name: "Aaa open ended", target_amount: 1_000, currency: "USD"+ ) do |g|+ g.goal_accounts.build(account: Account.create!(+ family: @family, accountable: Depository.new,+ name: "Open Ended Pot", currency: "USD", balance: 900+ ))+ end++ sorted = Goal.active_display_sort([ open_ended, drained ])++ assert_equal :depleted, drained.status+ assert_equal :no_target_date, open_ended.status+ assert_equal drained.id, sorted.first.id,+ "a reserve below its floor must not sort below a goal that needs nothing"+ end++ # The reserve keeps reserving: a withdrawal creates a shortfall, it does not+ # release the earmark the way completing a one-off does.+ test "a withdrawal leaves a reserve's earmark in place" do+ goal = reserve_goal(balance: 6_000, target: 6_000, allocated: 6_000)+ account = goal.linked_accounts.first++ assert_equal BigDecimal("6000"), account.goal_earmarked_total++ account.update!(balance: 4_000)+ account.reload++ assert_equal BigDecimal("6000"), account.goal_earmarked_total,+ "a reserve holds its earmark whatever the balance does"+ assert_equal :depleted, Goal.find(goal.id).status+ assert_equal BigDecimal("2000"), Goal.find(goal.id).remaining_amount.to_d+ end+test "account free_to_earmark subtracts non-archived fixed earmarks" doaccount = 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|@@ -862,6 +941,114 @@ class GoalTest < ActiveSupport::TestCaseassert_nil Goal.where(id: goal.id).pick(:completed_amount)end+ # --- Review follow-ups on the reserves lot ---++ test "a released goal cannot be turned into a reserve without reopening" do+ goal = @family.goals.create!(name: "Trip", target_amount: 5_000, currency: "USD") do |g|+ g.goal_accounts.build(account: standoff_account)+ end+ goal.complete!++ goal.reload.kind = "maintained"++ assert_not goal.valid?+ assert_includes goal.errors[:kind], "Reopen this goal before turning it into a reserve."+ end++ test "reopening first lets the conversion through" do+ goal = @family.goals.create!(name: "Trip", target_amount: 5_000, currency: "USD") do |g|+ g.goal_accounts.build(account: standoff_account)+ end+ goal.complete!+ goal.reload.reopen!++ assert goal.reload.update(kind: "maintained"), goal.errors.full_messages.to_sentence+ end++ # The form hides the date for a reserve, so one can only arrive through a+ # conversion or a crafted request. Either way it must not survive: a stored+ # deadline would drive a pace the reserve does not have.+ test "a reserve drops any target date it is given" do+ goal = reserve_goal(balance: 3_000, target: 6_000)++ assert goal.update(target_date: 6.months.from_now.to_date), goal.errors.full_messages.to_sentence+ assert_nil goal.reload.target_date+ end++ test "converting a dated goal into a reserve clears its deadline" do+ goal = @family.goals.create!(+ name: "Trip", target_amount: 5_000, currency: "USD", target_date: 6.months.from_now.to_date+ ) { |g| g.goal_accounts.build(account: standoff_account) }++ goal.update!(kind: "maintained")++ assert_nil goal.reload.target_date+ end++ test "a drained reserve gets a status callout telling it what is missing" do+ goal = reserve_goal(balance: 4_000, target: 6_000)++ assert_equal :depleted, goal.status+ assert_includes goal.status_callout_context.to_s, "2,000"+ end++ test "a reserve at its level has no callout to make" do+ goal = reserve_goal(balance: 6_000, target: 6_000)++ assert_equal :funded, goal.status+ assert_nil goal.status_callout_context+ end++ # Setting state and kind in one write skips the `reopen` transition, so+ # `completed_amount` never thaws. Reading the in-memory state let that+ # through: the goal looked already-reopened while its frozen snapshot+ # survived, and an active reserve reported it forever.+ test "reopening and converting in a single write is refused" do+ goal = @family.goals.create!(name: "Trip", target_amount: 5_000, currency: "USD") do |g|+ g.goal_accounts.build(account: standoff_account)+ end+ goal.complete!+ frozen = goal.reload.completed_amount++ assert_not goal.update(state: "active", kind: "maintained")+ assert_includes goal.errors[:kind], "Reopen this goal before turning it into a reserve."+ assert_equal "completed", goal.reload.state+ assert_equal frozen, goal.reload.completed_amount+ end+++ # A reserve holds a level: there is no finish line to project toward and no+ # target to have "hit". It does not reach the projection panel today, but+ # this method reads as the single source of truth for that subtitle.+ test "a reserve is never told it has hit a target" do+ reserve = @family.goals.create!(+ name: "Precaution", target_amount: 1_000, currency: @family.currency, kind: "maintained"+ ) { |g| g.goal_accounts.build(account: attention_pot(1_000), allocated_amount: 1_000) }++ assert_equal :funded, reserve.status+ assert_equal I18n.t("goals.show.projection.reserve"), reserve.projection_summary+ end++ # `needs_attention?` names the pair once. Three places were spelling it out+ # and the Plan card had already fallen behind, leaving a depleted reserve+ # with an amber pill beside a neutral progress bar.+ test "a depleted reserve wants attention just as a goal off its pace does" do+ reserve = @family.goals.create!(+ name: "Precaution", target_amount: 6_000, currency: @family.currency, kind: "maintained"+ ) { |g| g.goal_accounts.build(account: attention_pot(1_000), allocated_amount: 1_000) }++ assert_equal :depleted, reserve.status+ assert reserve.needs_attention?+ end++ test "a funded reserve wants nothing" do+ reserve = @family.goals.create!(+ name: "Precaution", target_amount: 1_000, currency: @family.currency, kind: "maintained"+ ) { |g| g.goal_accounts.build(account: attention_pot(1_000), allocated_amount: 1_000) }++ assert_not reserve.needs_attention?+ end+private# Its own account, so the shared-pool haircut does not make the frozen@@ -874,6 +1061,12 @@ class GoalTest < ActiveSupport::TestCaseg.goal_accounts.build(account: account, allocated_amount: 4_000)endend++ def attention_pot(balance)+ Account.create!(family: @family, accountable: Depository.new,+ name: "Pot #{SecureRandom.hex(3)}",+ currency: @family.currency, balance: balance)+ 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.@@ -889,4 +1082,34 @@ class GoalTest < ActiveSupport::TestCasegoal.goal_accounts.build(account: account)endend++ def reserve_goal(balance:, target:, allocated: nil, name: "Emergency reserve")+ account = Account.create!(+ family: @family, accountable: Depository.new,+ name: "#{name} Pot", currency: "USD", balance: balance+ )+ @family.goals.create!(name: name, target_amount: target, currency: "USD", kind: "maintained") do |g|+ g.goal_accounts.build(account: account, allocated_amount: allocated)+ end+ end++ # :funded and paused both used to rank 3, so a paused goal whose name sorted+ # first jumped ahead of a reserve that was whole.+ test "a paused goal sorts behind a funded reserve whatever its name" do+ pot = ->(name) {+ Account.create!(family: @family, accountable: Depository.new, name: name,+ currency: @family.currency, balance: 2_000)+ }+ reserve = @family.goals.create!(+ name: "Zeta reserve", target_amount: 1_000, currency: @family.currency, kind: "maintained"+ ) { |g| g.goal_accounts.build(account: pot.call("Zeta pot"), allocated_amount: 1_000) }+ paused = @family.goals.create!(+ name: "Alpha goal", target_amount: 1_000, currency: @family.currency+ ) { |g| g.goal_accounts.build(account: pot.call("Alpha pot"), allocated_amount: 1_000) }+ paused.pause!++ sorted = Goal.active_display_sort([ paused, reserve ])++ assert_equal [ reserve.id, paused.id ], sorted.map(&:id)+ endend