The personal finance app for everyone (by everyone)
Ruby
Measure goal pace on valuation-tracked accounts (#4316)
jaysbeekayc59a21054685
diff --git a/app/components/goals/card_component.rb b/app/components/goals/card_component.rbindex b03719e62d..a724f77031 100644--- a/app/components/goals/card_component.rb+++ b/app/components/goals/card_component.rb@@ -72,8 +72,13 @@ class Goals::CardComponent < ApplicationComponentreturn nil if goal.maintained?return nil if goal.archived? || goal.paused? || goal.completed? || goal.status == :reached- avg = goal.pace_money.format(precision: 0)target = goal.monthly_target_amount ? Money.new(goal.monthly_target_amount, goal.currency).format(precision: 0) : nil+ # An unmeasured pace is not a pace of zero, so it is not printed as one.+ unless goal.pace_measurable?+ return target ? I18n.t("goals.goal_card.pace_unknown_with_target", target: target) : I18n.t("goals.goal_card.pace_unknown")+ end++ avg = goal.pace_money.format(precision: 0)if targetI18n.t("goals.goal_card.pace_with_target", avg: avg, target: target)elsediff --git a/app/components/goals/lifecycle_panel_component.html.erb b/app/components/goals/lifecycle_panel_component.html.erbindex 6aff8c28c5..b8a174b9af 100644--- a/app/components/goals/lifecycle_panel_component.html.erb+++ b/app/components/goals/lifecycle_panel_component.html.erb@@ -141,12 +141,12 @@<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 %>+ <% 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 %></div></div>diff --git a/app/components/goals/lifecycle_panel_component.rb b/app/components/goals/lifecycle_panel_component.rbindex a276f576ab..8d6c637d1d 100644--- a/app/components/goals/lifecycle_panel_component.rb+++ b/app/components/goals/lifecycle_panel_component.rb@@ -100,9 +100,12 @@ class Goals::LifecyclePanelComponent < ApplicationComponentdef show_catch_up? = goal.status == :behind && goal.monthly_target_amount.present?- def show_projection_legend? = goal.target_date.present?+ # No swatch for a projection line the chart does not draw.+ def show_projection_legend? = goal.target_date.present? && goal.pace_measurable?+ # The chart draws the required line from the target alone, so this swatch+ # does not depend on a measurable pace.def show_required_legend?- goal.monthly_target_amount.to_d.positive? && goal.remaining_amount.to_d.positive?+ goal.target_date.present? && goal.monthly_target_amount.to_d.positive? && goal.remaining_amount.to_d.positive?endenddiff --git a/app/components/goals/status_pill_component.rb b/app/components/goals/status_pill_component.rbindex 4d2cfcf895..7b06379619 100644--- a/app/components/goals/status_pill_component.rb+++ b/app/components/goals/status_pill_component.rb@@ -10,6 +10,9 @@ class Goals::StatusPillComponent < ApplicationComponentreached: { tone: :green, icon: "star" },completed: { tone: :green, icon: "circle-check-big" },no_target_date: { tone: :gray, icon: "infinity" },+ # No measurable pace: neither on track nor behind, so neutral, with a+ # question mark rather than the open-ended goal's infinity.+ pace_unknown: { tone: :gray, icon: "circle-help" },# 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.diff --git a/app/controllers/goals_controller.rb b/app/controllers/goals_controller.rbindex f897b37a3f..40f9ea8730 100644--- a/app/controllers/goals_controller.rb+++ b/app/controllers/goals_controller.rb@@ -303,6 +303,7 @@ class GoalsController < ApplicationControllerreached = active_goals.count { |g| g.status == :reached }no_date = active_goals.count { |g| g.status == :no_target_date }paused = active_goals.count(&:paused?)+ pace_unknown = active_goals.count { |g| !g.paused? && g.status == :pace_unknown }# Denominator of the "Goals on track" tile. A goal only belongs in# the fraction if there is a benchmark to compare against:@@ -317,10 +318,13 @@ class GoalsController < ApplicationController# 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.+ # - pace_unknown → its accounts give no measurable pace, so there is+ # nothing to compare the required pace against. Like no_target_date,+ # it can be neither on track nor behind.# 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.maintained? && g.status != :reached && g.status != :no_target_date+ !g.paused? && !g.maintained? && !g.status.in?(%i[reached no_target_date pace_unknown])end{@@ -336,6 +340,7 @@ class GoalsController < ApplicationControllerbehind_count: behind,no_date_count: no_date,paused_count: paused,+ pace_unknown_count: pace_unknown,tracked_total: tracked_total,active_total: active_goals.size}diff --git a/app/javascript/controllers/goal_projection_chart_controller.js b/app/javascript/controllers/goal_projection_chart_controller.jsindex ed4ee109c5..b32ff9e841 100644--- a/app/javascript/controllers/goal_projection_chart_controller.js+++ b/app/javascript/controllers/goal_projection_chart_controller.js@@ -121,6 +121,9 @@ export default class extends Controller {const targetAmount = data.target_amount || 0;const currentAmount = data.current_amount || 0;const avgMonthly = data.avg_monthly || 0;+ // null when the goal's accounts give no measurable pace: draw no+ // projection rather than a flat line that claims the goal will fall short.+ const paceKnown = data.avg_monthly != null;// Past-due goals: pin endDate at today so the "today" marker stays inside// the x-domain instead of clipping right at the edge.@@ -153,7 +156,7 @@ export default class extends Controller {const projectionEnd = target? Math.max(currentAmount, currentAmount + avgMonthly * Math.max(0, this._monthsBetween(today, target))): currentAmount;- const projectionSeries = target+ const projectionSeries = target && paceKnown? [{ date: today, value: currentAmount },{ date: target, value: projectionEnd },diff --git a/app/models/goal.rb b/app/models/goal.rbindex ceb12fb022..e07e61d813 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -159,7 +159,10 @@ class Goal < ApplicationRecord# 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 }.freeze+ #+ # `pace_unknown` shares rank 2 with `no_target_date`: neither has a pace to+ # compare against, so neither is ahead of or behind anything.+ ACTIVE_DISPLAY_STATUS_RANK = { behind: 0, depleted: 0, on_track: 1, no_target_date: 2, pace_unknown: 2, funded: 3 }.freezescope :alphabetically, -> { order(Arel.sql("LOWER(name) ASC")) }scope :active_first, lambda {@@ -247,12 +250,18 @@ class Goal < ApplicationRecordattr_writer :pooled_allocations+ # Every account linked to one of the family's goals: the list the family-wide+ # readers below start from. inject_backing_math! reads it once and hands it to+ # each of them.+ def self.linked_account_ids_for(family)+ GoalAccount.joins(:goal).where(goals: { family_id: family.id }).distinct.pluck(:account_id)+ end+# Family-wide map of cumulative market gain/loss per account_id (sum of# balances.net_market_flows). Injected on index alongside pooled_allocations# so contributions-basis goals don't fire one Balance aggregate per account# per goal (N+1).- def self.market_flows_for(family)- account_ids = GoalAccount.joins(:goal).where(goals: { family_id: family.id }).distinct.pluck(:account_id)+ def self.market_flows_for(family, account_ids: linked_account_ids_for(family))return {} if account_ids.empty?Balance.where(account_id: account_ids).group(:account_id).sum(:net_market_flows)@@ -267,8 +276,7 @@ class Goal < ApplicationRecord# (active_display_sort calls goal.status, which reaches #pace for any goal# with a target_date) fires one grouped query instead of one Entry.sum per# goal.- def self.pace_for(family)- account_ids = GoalAccount.joins(:goal).where(goals: { family_id: family.id }).distinct.pluck(:account_id)+ def self.pace_for(family, account_ids: linked_account_ids_for(family))return {} if account_ids.empty?Entry@@ -285,6 +293,102 @@ class Goal < ApplicationRecordattr_writer :pooled_pace+ BALANCE_PACE_DAYS = 365+ BALANCE_PACE_VALUATION_KINDS = %w[reconciliation current_anchor].freeze++ # Accounts are tracked by transactions or by balance updates. An account with+ # no counted transaction in the pace window (see pace_for) is measured from+ # its balance instead, provided someone has actually recorded a value for it+ # in the last year:+ #+ # { balance: { account_id => { start: year-old end_balance, market_flows: window sum,+ # excluded_flows: window sum of excluded entry amounts } },+ # dormant: [account_id, ...] }+ #+ # `balance` holds accounts with a reconciliation or current-anchor valuation+ # in the trailing year AND a balance row a year back to measure from. History+ # shorter than a year is not measured: there is no year-old row, and reading+ # its absence as zero would call the whole balance growth. Stored balances+ # include excluded entries, which pace_for leaves out, so their sum over the+ # window is carried too and taken back out of the change. `dormant` holds+ # accounts with counted transactions, just none lately: their pace is a+ # measured zero. Excluded and pending ones do not count there either, as+ # they do not in pace_for.+ # Any linked account in neither map (an opening balance and nothing since, a+ # recent valuation on under a year of history, or updates all older than a+ # year) has no measurable pace.+ #+ # A fixed number of family-wide queries, none per goal, for the same N+1 reason as+ # pace_for. `transaction_pace` is pace_for's result, so accounts it already+ # covers are not read again.+ def self.balance_pace_for(family, transaction_pace = pace_for(family), account_ids: linked_account_ids_for(family))+ account_ids -= transaction_pace.keys+ return { balance: {}, dormant: [] } if account_ids.empty?++ cutoff = Date.current - BALANCE_PACE_DAYS++ valued_ids = Entry+ .joins("INNER JOIN valuations ON valuations.id = entries.entryable_id AND entries.entryable_type = 'Valuation'")+ .where(account_id: account_ids, date: cutoff..Date.current)+ .where(valuations: { kind: BALANCE_PACE_VALUATION_KINDS })+ .distinct+ .pluck(:account_id)++ balance = {}+ if valued_ids.any?+ in_account_currency = Balance.joins(:account).where(account_id: valued_ids).where("balances.currency = accounts.currency")++ starts = in_account_currency+ .where("balances.date <= ?", cutoff)+ .select("DISTINCT ON (balances.account_id) balances.account_id, balances.end_balance")+ .order("balances.account_id, balances.date DESC")+ .to_h { |row| [ row.account_id, row.end_balance ] }++ flows = in_account_currency+ .where("balances.date > ?", cutoff)+ .group(:account_id)+ .sum(:net_market_flows)++ # Read the way Balance::SyncCache builds the balance: split parents left+ # out (their children count instead), each amount converted to the+ # account's currency, and an entry with no rate skipped, as it was there.+ excluded_flows = Hash.new(0.to_d)+ Entry+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")+ .where(account_id: starts.keys, date: (cutoff + 1)..Date.current, excluded: true)+ .merge(Transaction.excluding_pending)+ .excluding_split_parents+ .includes(:account, :entryable)+ .each do |entry|+ excluded_flows[entry.account_id] += entry.amount_money.exchange_to(+ entry.account.currency, date: entry.date, custom_rate: entry.entryable.exchange_rate+ ).amount.to_d+ rescue Money::ConversionError+ next+ end++ starts.each do |account_id, start|+ balance[account_id] = {+ start: start.to_d,+ market_flows: (flows[account_id] || 0).to_d,+ excluded_flows: excluded_flows[account_id]+ }+ end+ end++ dormant = Entry+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")+ .where(account_id: account_ids - valued_ids)+ .where("entries.excluded IS NOT TRUE")+ .merge(Transaction.excluding_pending)+ .distinct+ .pluck(:account_id)++ { balance: balance, dormant: dormant }+ end++ attr_writer :pooled_balance_pace+# Goals loaded ready to render: association preloads for the card/row# partials plus the family-wide pooled-allocations + market-flows injection# so the per-goal backing math doesn't fire a query per row (N+1). Pass a@@ -302,14 +406,17 @@ class Goal < ApplicationRecord# pace_for).def self.inject_backing_math!(goals, family)pooled = pooled_allocations_for(family)- flows = market_flows_for(family)- pace_map = pace_for(family)+ account_ids = linked_account_ids_for(family)+ flows = market_flows_for(family, account_ids: account_ids)+ pace_map = pace_for(family, account_ids: account_ids)+ balance_pace_map = balance_pace_for(family, pace_map, account_ids: account_ids)converter = CurrencyConverter.newgoals.each do |goal|goal.currency_converter = convertergoal.pooled_allocations = pooledgoal.market_flows = flowsgoal.pooled_pace = pace_map+ goal.pooled_balance_pace = balance_pace_mapendend@@ -761,6 +868,13 @@ class Goal < ApplicationRecord# goes up, status flips off "behind". Excludes user-flagged-excluded# entries. Entry amount sign convention in Sure: inflow is negative.#+ # An account with no counted transaction in that window is measured from its+ # balance instead: the change over the last year, divided by twelve (see+ # Goal.balance_pace_for). Excluded transactions in that year are taken back+ # out, as they are here. On the contributions basis the year's market movement is+ # taken out, so pace measures the same thing progress does. An account with+ # no evidence either way contributes 0 here, and makes pace_measurable? false.+ ## NOTE: pace is whole-account inflow by design in this phase, even for an# earmarked goal whose current_balance is only a slice — so runway/status# mix a whole-account numerator with an earmark-scoped balance. Earmark-aware@@ -779,7 +893,27 @@ class Goal < ApplicationRecordconvert_money(Money.new(amount, entry_currency.presence || account.currency)).amountendend- (-net.to_d / 3).round(2)+ # Balance-measured pace is in the account's currency; convert it the+ # same way, at today's rate.+ from_balances = linked_accounts.sum do |account|+ native = account_balance_pace(account)+ native.nil? ? 0.to_d : convert_money(Money.new(native, account.currency)).amount+ end+ (-net.to_d / 3 + from_balances).round(2)+ end+ end++ # False when any linked account has no evidence of how its balance moves: no+ # recent transactions, no transactions ever, and no balance updates over a+ # year of history to measure from. All or nothing, because a goal with part+ # of its money unmeasured cannot honestly be called on track or behind.+ def pace_measurable?+ return @pace_measurable if defined?(@pace_measurable)++ @pace_measurable = linked_accounts.all? do |account|+ pooled_pace.key?(account.id) ||+ pooled_balance_pace[:balance].key?(account.id) ||+ pooled_balance_pace[:dormant].include?(account.id)endend@@ -787,9 +921,11 @@ class Goal < ApplicationRecord@pace_money ||= Money.new(pace, currency)end- # Months of cash on hand at current pace (open-ended goals).+ # Months of cash on hand at current pace (open-ended goals). None while part+ # of the money is unmeasured: the pace would cover only the measured part.def months_of_runwayreturn nil if target_date.present?+ return nil unless pace_measurable?return nil if pace.zero? || pace.negative?(current_balance.to_d / pace.to_d).round(1)@@ -854,13 +990,15 @@ class Goal < ApplicationRecordtarget_amount_short_label: short_money(target_amt, currency),currency_symbol: Money.new(0, currency).currency.symbol,current_amount: current_balance.to_f,- avg_monthly: pace.to_f,+ # nil, not 0, when there is no pace to measure: the chart then draws no+ # projection line rather than a flat one.+ avg_monthly: (pace.to_f if pace_measurable?),required_monthly: monthly_target_amount&.to_f,currency: currency,status: status.to_s,projection_end_value: proj_end.to_f,projection_end_label: Money.new(proj_end, currency).format(precision: 0),- projection_shortfall_label: (target_amt > proj_end ? Money.new(target_amt - proj_end, currency).format(precision: 0) : nil)+ projection_shortfall_label: (pace_measurable? && target_amt > proj_end ? Money.new(target_amt - proj_end, currency).format(precision: 0) : nil)}end@@ -868,7 +1006,7 @@ class Goal < ApplicationRecord# the JS calculation so the server can pre-format the chart annotation# without re-rendering after each Stimulus draw.def projection_end_amount- return current_balance.to_d if target_date.nil?+ return current_balance.to_d if target_date.nil? || !pace_measurable?months = ((target_date - Date.current).to_f / 30.44).clamp(0.0, Float::INFINITY)projected = current_balance.to_d + (pace.to_d * months)[ current_balance.to_d, projected ].max@@ -892,6 +1030,7 @@ class Goal < ApplicationRecord# :on_track → has target_date and pace >= required monthly# :behind → has target_date and pace < required monthly# :no_target_date → open-ended+ # :pace_unknown → has target_date, but no measurable pace to comparedef statusreturn @status if defined?(@status)@@ -903,6 +1042,8 @@ class Goal < ApplicationRecord:reachedelsif target_date.nil?:no_target_date+ elsif !pace_measurable?+ :pace_unknownelsif monthly_target_amount.to_d <= pace.to_d:on_trackelse@@ -1022,6 +1163,8 @@ class Goal < ApplicationRecordendwhen :no_target_dateI18n.t("goals.show.status_callout.no_target_date")+ when :pace_unknown+ I18n.t("goals.show.status_callout.pace_unknown")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.@@ -1086,6 +1229,9 @@ class Goal < ApplicationRecordI18n.t("goals.show.projection.reached")elsif target_date.nil?I18n.t("goals.show.projection.no_target_date")+ elsif !pace_measurable?+ # Ahead of `behind`: an unmeasured pace is not a pace of zero.+ I18n.t("goals.show.projection.pace_unknown")elsif monthly_target_amount && pace.to_d < monthly_target_amount.to_dI18n.t("goals.show.projection.behind")elsif pace.positive?@@ -1188,6 +1334,23 @@ class Goal < ApplicationRecord@pooled_pace ||= self.class.pace_for(family)end+ def pooled_balance_pace+ @pooled_balance_pace ||= self.class.balance_pace_for(family, pooled_pace)+ end++ # Monthly pace of one account measured from its balance, in the account's+ # currency, or nil when the account is not on the balance path.+ def account_balance_pace(account)+ evidence = pooled_balance_pace[:balance][account.id]+ return nil if evidence.nil?++ # An entry's amount is negative for an inflow, so adding the excluded sum+ # takes those flows back out of the change.+ change = account.balance.to_d - evidence[:start] + evidence[:excluded_flows]+ change -= evidence[:market_flows] if contributions_basis?+ change / 12+ end+def prepare_completion_conversionlinked_accounts.each { |account| convert_money!(account_native_backing(account)) }rescue Money::ConversionError@@ -1315,7 +1478,7 @@ class Goal < ApplicationRecord@remaining_amount @remaining_amount_money@progress_percent @monthly_target_amount@progress_amount_money @consumed_amount_money- @pace @pace_money @status @pooled_allocations @missing_exchange_rate_currencies+ @pace @pace_money @pace_measurable @status @pooled_allocations @missing_exchange_rate_currencies].each do |ivar|remove_instance_variable(ivar) if instance_variable_defined?(ivar)enddiff --git a/app/views/goals/index.html.erb b/app/views/goals/index.html.erbindex 48c6c5ead3..2ff1c0bdd0 100644--- a/app/views/goals/index.html.erb+++ b/app/views/goals/index.html.erb@@ -59,8 +59,13 @@<p class="text-3xl font-medium text-primary mt-2"><%= t(".kpi.on_track_all_caught_up") %></p>+ <%# A goal whose pace cannot be measured is outside the fraction too,+ but "All caught up" must not read as covering it. %><p class="text-xs text-secondary mt-1">- <%= t(".kpi.on_track_sub_parts.reached", count: @kpi[:reached_count]) %>+ <%= [+ t(".kpi.on_track_sub_parts.reached", count: @kpi[:reached_count]),+ (t(".kpi.on_track_sub_parts.pace_unknown", count: @kpi[:pace_unknown_count]) if @kpi[:pace_unknown_count].positive?)+ ].compact.join(" · ") %></p><% else %><p class="text-3xl font-medium text-primary tabular-nums mt-2">@@ -77,6 +82,7 @@parts << t(".kpi.on_track_sub_parts.behind", count: @kpi[:behind_count]) if @kpi[:behind_count].positive?parts << t(".kpi.on_track_sub_parts.no_date", count: @kpi[:no_date_count]) if @kpi[:no_date_count].positive?parts << t(".kpi.on_track_sub_parts.paused", count: @kpi[:paused_count]) if @kpi[:paused_count].positive?+ parts << t(".kpi.on_track_sub_parts.pace_unknown", count: @kpi[:pace_unknown_count]) if @kpi[:pace_unknown_count].positive?%><% if parts.any? %><%= parts.join(" · ") %>diff --git a/config/locales/views/goals/en.yml b/config/locales/views/goals/en.ymlindex 8ac2e6a55e..a9fd82f032 100644--- a/config/locales/views/goals/en.yml+++ b/config/locales/views/goals/en.yml@@ -45,6 +45,9 @@ en:paused:one: 1 pausedother: "%{count} paused"+ pace_unknown:+ one: 1 with pace unknown+ other: "%{count} with pace unknown"on_track_sub_all_good: All active goals on paceon_track_all_caught_up: All caught upgoals_section:@@ -161,6 +164,7 @@ en:behind_covered: "pending pledges close the gap"on_track: "reaches goal around %{date}"no_target_date: "set a target date to project a finish line"+ pace_unknown: "can't measure a pace from these accounts yet; that needs a balance update in the last year and a year of balance history"pending_pledge:title:zero: "Pending: %{amount} into %{account} · expires today"@@ -196,6 +200,7 @@ en: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.+ pace_unknown: Not enough history on these accounts to measure a pace yet, so there is no projection.behind: Falling short at current pace.on_track_html: At your current pace, you'll reach this goal around <strong class="text-primary whitespace-nowrap">%{date}</strong>.aria_label: "Projection chart for %{name}"@@ -261,6 +266,7 @@ en:reached: Reachedcompleted: Completedno_target_date: Open+ pace_unknown: Pace unknownpaused: Pausedarchived: Archivedempty_state:@@ -288,6 +294,8 @@ en:other: "%{count} days left"pace_with_target: "%{avg}/mo · target %{target}/mo"pace_no_target: "%{avg}/mo avg"+ pace_unknown_with_target: "Pace unknown · target %{target}/mo"+ pace_unknown: Pace unknownfooter_paused: Pausedfooter_archived: Archivedfooter_reserve_intact: Reserve intactdiff --git a/docs/llm-guides/goals.md b/docs/llm-guides/goals.mdindex d6f68c6e23..6d21b2d168 100644--- a/docs/llm-guides/goals.md+++ b/docs/llm-guides/goals.md@@ -142,6 +142,12 @@ balances and transactions are unchanged; no migration is required.- `:reached` when `progress_percent >= 100`.- `:no_target_date` when `target_date.nil?`.+- `:pace_unknown` when the goal has a deadline but `pace_measurable?` is+ false: at least one linked account gives no evidence of how its balance+ moves (see below). It is neither on track nor behind, so it stays out of+ the "behind" count and the on-track tile's denominator (whose subline+ counts it instead), sorts beside `:no_target_date`, and has no index chip+ of its own.- `:on_track` when the goal has a deadline and `monthly_target_amount <= pace`.- `:behind` otherwise.@@ -167,6 +173,40 @@ pending provider transactions via `Transaction.excluding_pending`. Thislast filter matters: a pending Plaid deposit that later reverses wouldotherwise quietly reshape pace.+That reads cash transactions only, so an account maintained by balance+updates (a manually tracked pension or superannuation fund) would always+show 0. Each linked account therefore takes exactly one of four paths, in+this order:++1. **Transactions.** At least one counted transaction in the 90-day+ window: the net inflow above, divided by three. Unchanged.+2. **Balance.** Otherwise, a `reconciliation` or `current_anchor` valuation+ in the trailing 365 days: the account's balance today minus the+ `end_balance` of its latest balance row on or before a year ago,+ divided by twelve. On the contributions basis the window's+ `net_market_flows` are subtracted, so pace measures what progress does.+ Stored balances include excluded entries, so excluded transactions in+ the window are taken back out, as path 1 leaves them out. They are read+ as `Balance::SyncCache` counts them: split parents skipped, amounts+ converted to the account's currency, unconvertible entries skipped.+ With no balance row a year back, the account is unmeasured; a missing+ row is never read as a zero opening balance.+3. **Dormant.** Otherwise, any transaction that is neither excluded nor+ pending, at any date: a measured zero.+ A savings account nobody has paid into lately is honestly behind.+4. **Unmeasured.** Anything else (an opening balance and nothing since,+ or valuations all older than a year).++`Goal#pace_measurable?` is true only when every linked account is on path+1, 2 or 3. `Goal#pace` stays numeric (an unmeasured account adds 0). When+pace is unmeasurable, `projection_payload` sends `avg_monthly: nil` and no+shortfall label, and the chart draws no projection line. The evidence is+read by `Goal.pace_for` and `Goal.balance_pace_for`, both family-wide and+injected by `Goal.inject_backing_math!`, so a page of goals costs no+query per goal. That method reads the linked account ids once+(`Goal.linked_account_ids_for`) and passes them to both, and to+`Goal.market_flows_for`.+`Goal#monthly_target_amount` is `(remaining_amount / months_remaining).ceil(2)`.`months_remaining` uses day precision: `(target_date - Date.current) / 30.0`,clamped at zero. Calendar-month math is wrong here — it produces a cliff@@ -270,11 +310,14 @@ state means touching:3. `Goals::StatusPillComponent::VARIANTS` to add the chip styling(classes + icon).4. `Goals::CardComponent#footer_line` if the footer copy depends.-5. `GoalsController#kpi_payload` if the KPI strip counts it.-6. `config/locales/views/goals/en.yml` under `goals.status.*` for the+5. `GoalsController#kpi_payload` if the KPI strip counts it, and+ `tracked_total` if it has no pace benchmark.+6. `Goal::ACTIVE_DISPLAY_STATUS_RANK`, or it sorts below funded reserves.+7. `config/locales/views/goals/en.yml` under `goals.status.*` for thepill label, plus chip and subtitle keys if the new status filterson the index.-7. `Goals::StatusPillComponent#status_key` and the goal-filter Stimulus+8. `Goal#status_callout_context` if the show page should explain it.+9. `Goals::StatusPillComponent#status_key` and the goal-filter Stimuluscontroller (`data-status="..."` on chips) if the new status filters.### Adding a new pledge kinddiff --git a/test/components/goals/card_component_test.rb b/test/components/goals/card_component_test.rbnew file mode 100644index 0000000000..2dccb2c54d--- /dev/null+++ b/test/components/goals/card_component_test.rb@@ -0,0 +1,37 @@+require "test_helper"++class Goals::CardComponentTest < ViewComponent::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:dylan_family)+ end++ # The card used to print the unmeasured pace as a measured zero:+ # "$0/mo · target $900/mo".+ test "a goal whose pace cannot be measured says so rather than showing a zero" do+ component = Goals::CardComponent.new(goal: unmeasurable_goal)+ target = Money.new(900, "USD").format(precision: 0)++ assert_equal I18n.t("goals.goal_card.pace_unknown_with_target", target: target), component.pace_line+ assert_not_includes component.pace_line, Money.new(0, "USD").format(precision: 0)+ end++ test "the card's accessible name names the unmeasured status" do+ label = Goals::CardComponent.new(goal: unmeasurable_goal).aria_label++ assert_includes label, I18n.t("goals.status.pace_unknown")+ assert_not_includes label, "translation missing"+ end++ private+ # 9,000 to find over 10 months: 900/mo required. The only account carries+ # an opening balance and nothing since, so there is no pace to measure.+ def unmeasurable_goal+ account = Account.create!(family: @family, accountable: Depository.new,+ name: "Anchored #{SecureRandom.hex(3)}", currency: "USD", balance: 1_000)+ create_valuation(account: account, amount: 1_000, date: 30.days.ago.to_date, kind: "opening_anchor")+ @family.goals.create!(name: "Trip", target_amount: 10_000, target_date: 300.days.from_now.to_date,+ currency: "USD") { |g| g.goal_accounts.build(account: account) }+ end+enddiff --git a/test/components/goals/lifecycle_panel_component_test.rb b/test/components/goals/lifecycle_panel_component_test.rbindex de3cae565f..74fd17dce8 100644--- a/test/components/goals/lifecycle_panel_component_test.rb+++ b/test/components/goals/lifecycle_panel_component_test.rb@@ -3,6 +3,8 @@ 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 < ViewComponent::TestCase+ include EntriesTestHelper+setup do@family = families(:dylan_family)# The panel scopes what it offers to the reader's accessible accounts, so@@ -128,12 +130,47 @@ class Goals::LifecyclePanelComponentTest < ViewComponent::TestCaseassert_no_selector "#goal-celebration-actions"end+ # The chart draws no projection line when pace cannot be measured, so the+ # legend must not offer a swatch for one.+ test "the projection legend is shown only for a pace that can be measured" do+ anchored = pot(balance: 1_000)+ create_valuation(account: anchored, amount: 1_000, date: 30.days.ago.to_date, kind: "opening_anchor")+ unmeasurable = dated_goal(anchored)++ paid = pot(balance: 1_000)+ create_transaction(account: paid, amount: -300, date: 10.days.ago.to_date)+ measured = dated_goal(paid)++ assert_not component_for(unmeasurable).show_projection_legend?+ assert component_for(measured).show_projection_legend?+ end++ # The chart draws the required line from the target alone, measured pace or+ # not, so its swatch must not disappear with the projection's.+ test "an unmeasurable goal keeps its required swatch and loses only the projection's" do+ anchored = pot(balance: 1_000)+ create_valuation(account: anchored, amount: 1_000, date: 30.days.ago.to_date, kind: "opening_anchor")+ goal = dated_goal(anchored)+ assert goal.monthly_target_amount.to_d.positive?++ render_inline(component_for(goal))++ assert_selector "span", exact_text: I18n.t("goals.show.projection.legend_required"), normalize_ws: true+ assert_no_selector "span", exact_text: I18n.t("goals.show.projection.legend_projection"), normalize_ws: true+ end+privatedef pot(balance:, name: "Pot #{SecureRandom.hex(3)}")Account.create!(family: @family, accountable: Depository.new, name: name,currency: @family.currency, balance: balance)end+ def dated_goal(account)+ @family.goals.create!(+ name: "Dated", target_amount: 10_000, target_date: 300.days.from_now.to_date, currency: @family.currency+ ) { |g| g.goal_accounts.build(account: account) }+ end+def funded_goal(name: "Trip", kind: "one_off")@family.goals.create!(name: name, target_amount: 1_000, currency: @family.currency, kind: kinddiff --git a/test/components/goals/status_pill_component_test.rb b/test/components/goals/status_pill_component_test.rbnew file mode 100644index 0000000000..652e20bccc--- /dev/null+++ b/test/components/goals/status_pill_component_test.rb@@ -0,0 +1,14 @@+require "test_helper"++class Goals::StatusPillComponentTest < ViewComponent::TestCase+ # Without its own variant an unmeasurable goal fell back to the "Open"+ # styling, the infinity glyph of an open-ended goal it is not.+ test "a goal whose pace cannot be measured gets a gray question-mark pill" do+ component = Goals::StatusPillComponent.new(goal: OpenStruct.new(display_status: :pace_unknown))++ assert_equal({ tone: :gray, icon: "circle-help" }, component.variant)++ render_inline(component)+ assert_text I18n.t("goals.status.pace_unknown")+ end+enddiff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rbindex c6450a536f..9a873063fe 100644--- a/test/controllers/goals_controller_test.rb+++ b/test/controllers/goals_controller_test.rb@@ -452,7 +452,11 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest# One trackable goal (has target_date) + one open-ended (no target_date).# The trackable one should be the only thing in the denominator;# open-ended goals can't be off pace because they have no required pace.- build_goal(family, "House", target_amount: 1_000_000, target_date: 1.year.from_now)+ house = build_goal(family, "House", target_amount: 1_000_000, target_date: 1.year.from_now)+ # An account with no history at all has no measurable pace, and a goal+ # without one leaves the fraction too. A deposit long ago gives it a+ # measured pace of zero, which keeps it trackable (and behind).+ create_transaction(account: house.linked_accounts.first, amount: -100, date: 200.days.ago.to_date)build_goal(family, "Emergency", target_amount: 1_000_000, target_date: nil)get goals_url@@ -974,6 +978,70 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest"a spend was still offered against money the reader cannot see"end+ # A goal whose pace cannot be measured has no benchmark to be on track or+ # behind against, so it belongs in neither the fraction nor the behind count+ # -- the same treatment an open-ended goal gets.+ test "an unmeasurable goal is not counted against the on-track tile" do+ @goal.pause! # the fixture goal links an account with no history at all++ paid = unclaimed_account("Paid Pot")+ create_transaction(account: paid, amount: -3_000, date: 10.days.ago.to_date) # 1,000/mo+ @user.family.goals.create!(+ name: "On track", target_amount: 1_500, target_date: 300.days.from_now.to_date, currency: "USD"+ ) { |g| g.goal_accounts.build(account: paid) }++ anchored = unclaimed_account("Anchored Pot")+ create_valuation(account: anchored, amount: 1_000, date: 30.days.ago.to_date, kind: "opening_anchor")+ unknown = @user.family.goals.create!(+ name: "Unknown", target_amount: 5_000, target_date: 300.days.from_now.to_date, currency: "USD"+ ) { |g| g.goal_accounts.build(account: anchored) }++ get goals_url++ assert_response :success+ assert_select "p", text: I18n.t("goals.index.kpi.on_track_value", on_track: 1, total: 1)+ assert_select "p", text: I18n.t("goals.index.kpi.needs_this_month_zero_sub")+ assert_no_match I18n.t("goals.index.kpi.on_track_sub_parts.behind", count: 1), response.body+ assert_equal :pace_unknown, unknown.status+ # Left out of the fraction, but not hidden: the tile must not call every+ # goal on pace while one of them cannot be measured.+ assert_select "p", text: /#{Regexp.escape(I18n.t("goals.index.kpi.on_track_sub_parts.pace_unknown", count: 1))}/+ assert_no_match I18n.t("goals.index.kpi.on_track_sub_all_good"), response.body+ end++ test "a family whose only dated goal is unmeasurable is not told every goal is on pace" do+ # Destroyed rather than paused: a paused goal at its target still counts as+ # reached, which takes the tile to its "All caught up" branch instead.+ @goal.destroy!+ anchored = unclaimed_account("Anchored Pot")+ create_valuation(account: anchored, amount: 1_000, date: 30.days.ago.to_date, kind: "opening_anchor")+ @user.family.goals.create!(+ name: "Unknown", target_amount: 5_000, target_date: 300.days.from_now.to_date, currency: "USD"+ ) { |g| g.goal_accounts.build(account: anchored) }++ get goals_url++ assert_response :success+ assert_select "p", text: /#{Regexp.escape(I18n.t("goals.index.kpi.on_track_sub_parts.pace_unknown", count: 1))}/+ assert_no_match I18n.t("goals.index.kpi.on_track_sub_all_good"), response.body+ end++ test "a family with every tracked goal reached still hears about an unmeasurable one" do+ @user.family.goals.where.not(id: @goal.id).destroy_all+ @goal.update!(target_amount: 1) # reached against the depository balance+ anchored = unclaimed_account("Anchored Pot")+ create_valuation(account: anchored, amount: 1_000, date: 30.days.ago.to_date, kind: "opening_anchor")+ @user.family.goals.create!(+ name: "Unknown", target_amount: 5_000, target_date: 300.days.from_now.to_date, currency: "USD"+ ) { |g| g.goal_accounts.build(account: anchored) }++ get goals_url++ assert_response :success+ assert_select "p", text: I18n.t("goals.index.kpi.on_track_all_caught_up")+ assert_select "p", text: /#{Regexp.escape(I18n.t("goals.index.kpi.on_track_sub_parts.pace_unknown", count: 1))}/+ end+privatedef spent_goal_for_displaydiff --git a/test/models/goal_test.rb b/test/models/goal_test.rbindex 4e791134d4..5fdec7ba15 100644--- a/test/models/goal_test.rb+++ b/test/models/goal_test.rb@@ -1317,7 +1317,358 @@ class GoalTest < ActiveSupport::TestCaseassert_equal Goals::AvatarComponent.new(goal: goal).color, saved[:color]end+ # --- pace on accounts whose value moves through valuations ---+ #+ # Pace used to read only transaction entries, so an account maintained by+ # balance updates (a manually tracked superannuation fund) always reported 0+ # and every dated goal on it read "behind". Balance rows are created by hand+ # with known dates and values rather than by running a sync, so each+ # precondition is set rather than assumed.++ test "pace on a valuation-tracked account is its balance change over the last year" do+ account = valuation_tracked_account(balance: 112_000, year_ago: 100_000)+ goal = goal_on(account, target_amount: 200_000)++ assert goal.pace_measurable?+ assert_equal 1000, goal.pace.to_d++ # The delta: without a recent balance update there is nothing to measure.+ account.entries.where(entryable_type: "Valuation").destroy_all+ assert_not Goal.find(goal.id).pace_measurable?+ end++ # A goal can now link an account in another currency. The balance path+ # measures in the account's currency, so its pace is converted to the goal's+ # at today's rate, as the transaction path is.+ test "a valuation-tracked pace in another currency is converted to the goal's" do+ ExchangeRate.stubs(:provider).returns(nil)+ account = valuation_tracked_account(balance: 112_000, year_ago: 100_000, currency: "EUR")+ goal = goal_on(account, target_amount: 300_000)++ # No rate: the 1,000 EUR/mo is left out and reported, never read as dollars.+ assert goal.pace_measurable?+ assert_equal 0, goal.pace.to_d+ assert goal.currency_conversion_incomplete?++ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", rate: 1.5, date: Date.current)+ goal = Goal.find(goal.id)+ assert_equal 1500, goal.pace.to_d+ assert_not goal.currency_conversion_incomplete?+ end++ test "a valuation-tracked goal whose required pace is below its balance pace is on track" do+ account = valuation_tracked_account(balance: 112_000, year_ago: 100_000)+ # 9,600 to find over 12 months: 800/mo required against a 1,000/mo pace.+ goal = goal_on(account, target_amount: 121_600, target_date: 360.days.from_now.to_date)++ assert_equal 800, goal.monthly_target_amount.to_d+ assert_equal :on_track, goal.status+ end++ test "on the contributions basis a valuation-tracked pace leaves out market movement" do+ account = valuation_tracked_account(balance: 112_000, year_ago: 100_000)+ account.balances.create!(date: 100.days.ago.to_date, balance: 105_000, currency: "USD", net_market_flows: 2_400)++ # Fixed slices, so the two goals can share the account. Pace is whole-account+ # by design, so the slice does not change it.+ balance_goal = goal_on(account, target_amount: 200_000, basis: "balance", name: "Balance basis", allocated: 1_000)+ contributions_goal = goal_on(account, target_amount: 200_000, basis: "contributions",+ name: "Contributions basis", allocated: 1_000)++ assert_equal 1000, balance_goal.pace.to_d+ # (12,000 change − 2,400 market gain) / 12.+ assert_equal 800, contributions_goal.pace.to_d+ end++ test "a shrinking valuation-tracked account is measured and behind" do+ account = valuation_tracked_account(balance: 88_000, year_ago: 100_000)+ goal = goal_on(account, target_amount: 120_000, target_date: 360.days.from_now.to_date)++ assert goal.pace_measurable?+ assert_equal(-1000, goal.pace.to_d)+ assert_equal :behind, goal.status+ end++ test "an account with only an opening anchor has no measurable pace" do+ account = Account.create!(family: @family, accountable: Investment.new, name: "Second super",+ currency: "USD", balance: 94_000)+ create_valuation(account: account, amount: 94_000, date: 30.days.ago.to_date, kind: "opening_anchor")+ # A year of balance history, so only the anchor's kind decides: an opening+ # balance is where tracking started, not a recorded update.+ account.balances.create!(date: 400.days.ago.to_date, balance: 80_000, start_cash_balance: 80_000, currency: "USD")+ goal = goal_on(account, target_amount: 200_000, target_date: 2.years.from_now.to_date)++ assert_not goal.pace_measurable?+ assert_equal :pace_unknown, goal.status+ assert_not goal.behind_pace?+ assert_equal I18n.t("goals.show.projection.pace_unknown"), goal.projection_summary+ assert_equal I18n.t("goals.show.status_callout.pace_unknown"), goal.status_callout_context++ payload = goal.projection_payload+ assert_nil payload[:avg_monthly]+ assert_nil payload[:projection_shortfall_label]+ assert_equal goal.current_balance.to_d, goal.projection_end_amount+ end++ test "under a year of balance history is not read as growth from zero" do+ account = valuation_tracked_account(balance: 112_000, year_ago: 100_000, history_from: 200.days.ago.to_date)+ goal = goal_on(account, target_amount: 121_600, target_date: 360.days.from_now.to_date)++ assert_equal :pace_unknown, goal.status+ assert_equal 0, goal.pace.to_d+ end++ # A recent valuation shows the balance moves outside transactions, so an old+ # transaction must not make the account a measured zero (dormant).+ test "a recent valuation on under a year of history stays unmeasured despite an older transaction" do+ account = valuation_tracked_account(balance: 112_000, year_ago: 100_000, history_from: 200.days.ago.to_date)+ create_transaction(account: account, amount: -1_000, date: 150.days.ago.to_date)+ goal = goal_on(account, target_amount: 121_600, target_date: 360.days.from_now.to_date)++ assert_not goal.pace_measurable?+ assert_equal :pace_unknown, goal.status+ end++ test "a balance update exactly a year old still counts, one a day older does not" do+ on_edge = valuation_tracked_account(balance: 112_000, year_ago: 100_000, valuation_on: Date.current - 365)+ past_edge = valuation_tracked_account(balance: 112_000, year_ago: 100_000, valuation_on: Date.current - 366)++ assert goal_on(on_edge, target_amount: 200_000, name: "Edge").pace_measurable?+ assert_not goal_on(past_edge, target_amount: 200_000, name: "Past edge").pace_measurable?+ end++ test "a counted transaction in the window keeps the account on transaction pace" do+ account = valuation_tracked_account(balance: 112_000, year_ago: 100_000)+ create_transaction(account: account, amount: -300, date: 10.days.ago.to_date)+ goal = goal_on(account, target_amount: 200_000)++ # 300 inflow / 3, the 12,000 balance change ignored.+ assert_equal 100, goal.pace.to_d++ account.entries.where(entryable_type: "Transaction").destroy_all+ assert_equal 1000, Goal.find(goal.id).pace.to_d+ end++ # The transaction path leaves excluded entries out of pace; the balance path+ # reads stored balances, which include them. Without taking them back out, an+ # excluded deposit that pushed the account off the transaction path would be+ # counted after all, through the balance change.+ test "an excluded deposit does not count towards a valuation-tracked pace" do+ account = valuation_tracked_account(balance: 124_000, year_ago: 100_000)+ goal = goal_on(account, target_amount: 200_000)+ # 24,000 change / 12 before anything is excluded.+ assert_equal 2000, goal.pace.to_d++ create_transaction(account: account, amount: -12_000, date: 10.days.ago.to_date, excluded: true)++ # Still on the balance path (an excluded entry is no counted transaction),+ # and the excluded 12,000 leaves (24,000 − 12,000) / 12.+ assert_equal 1000, Goal.find(goal.id).pace.to_d+ end++ # The stored balance converts each entry to the account's currency, so the+ # excluded sum taken back out of it has to be in that currency too.+ test "an excluded deposit in another currency comes out at its converted amount" do+ account = valuation_tracked_account(balance: 124_000, year_ago: 100_000)+ ExchangeRate.create!(date: 10.days.ago.to_date, from_currency: "EUR", to_currency: "USD", rate: 2)+ create_transaction(account: account, amount: -6_000, currency: "EUR", date: 10.days.ago.to_date, excluded: true)++ # (24,000 − 12,000) / 12; read raw, the 6,000 would leave 1,500.+ assert_equal 1000, goal_on(account, target_amount: 200_000).pace.to_d+ end++ # The balance leaves out an entry it cannot convert, so there is nothing of+ # it in the change to take back out.+ test "an excluded entry with no exchange rate is left alone, as the balance leaves it" do+ account = valuation_tracked_account(balance: 124_000, year_ago: 100_000)+ create_transaction(account: account, amount: -6_000, currency: "EUR", date: 10.days.ago.to_date, excluded: true)++ assert_equal 2000, goal_on(account, target_amount: 200_000).pace.to_d+ end++ # A split parent is always excluded, but the balance counts its children+ # instead of it. Taking the parent out as well would remove the money twice.+ test "a split parent is not taken out of a valuation-tracked pace on top of its children" do+ account = valuation_tracked_account(balance: 124_000, year_ago: 100_000)+ parent = create_transaction(account: account, amount: -12_000, date: 10.days.ago.to_date)+ parent.split!([+ { name: "Gift", amount: -8_000, excluded: "1" },+ { name: "Refund", amount: -4_000, excluded: "1" }+ ])+ assert parent.reload.excluded?++ # The children's 12,000 out once: (24,000 − 12,000) / 12.+ assert_equal 1000, goal_on(account, target_amount: 200_000).pace.to_d+ end++ test "an excluded entry older than the pace year does not move the balance pace" do+ account = valuation_tracked_account(balance: 124_000, year_ago: 100_000)+ create_transaction(account: account, amount: -12_000, date: 380.days.ago.to_date, excluded: true)++ # Already inside the year-old balance it is measured from.+ assert_equal 2000, goal_on(account, target_amount: 200_000).pace.to_d+ end++ # An account whose only transactions are excluded has no counted history, so+ # it is not a measured zero.+ test "an account whose only transactions are excluded is not dormant" do+ account = Account.create!(family: @family, accountable: Depository.new, name: "Excluded only",+ currency: "USD", balance: 1_000)+ create_transaction(account: account, amount: -1_000, date: 200.days.ago.to_date, excluded: true)+ goal = goal_on(account, target_amount: 5_000, target_date: 360.days.from_now.to_date)++ assert_not goal.pace_measurable?+ assert_equal :pace_unknown, goal.status++ account.entries.update_all(excluded: false)+ assert Goal.find(goal.id).pace_measurable?+ end++ # A pending transaction can still be reversed, so it is no evidence that the+ # account has a history of being paid into. pace_for leaves it out too.+ test "an account whose only transaction is pending is not dormant" do+ account = Account.create!(family: @family, accountable: Depository.new, name: "Pending only",+ currency: "USD", balance: 1_000)+ entry = create_transaction(account: account, amount: -1_000, date: 200.days.ago.to_date)+ entry.transaction.update!(extra: { "plaid" => { "pending" => true } })+ goal = goal_on(account, target_amount: 5_000, target_date: 360.days.from_now.to_date)++ assert_not goal.pace_measurable?+ assert_equal :pace_unknown, goal.status++ entry.transaction.update!(extra: {})+ assert Goal.find(goal.id).pace_measurable?+ end++ test "a cash account nobody has paid into lately is still measured and behind" do+ account = Account.create!(family: @family, accountable: Depository.new, name: "Dormant savings",+ currency: "USD", balance: 1_000)+ create_transaction(account: account, amount: -1_000, date: 200.days.ago.to_date)+ goal = goal_on(account, target_amount: 5_000, target_date: 360.days.from_now.to_date)++ assert goal.pace_measurable?+ assert_equal 0, goal.pace.to_d+ assert_equal :behind, goal.status+ end++ test "one unmeasurable account makes the goal unmeasurable, two measured accounts sum" do+ cash = Account.create!(family: @family, accountable: Depository.new, name: "Paid savings",+ currency: "USD", balance: 900)+ create_transaction(account: cash, amount: -900, date: 10.days.ago.to_date)+ anchored = Account.create!(family: @family, accountable: Depository.new, name: "Anchored savings",+ currency: "USD", balance: 500)+ create_valuation(account: anchored, amount: 500, date: 30.days.ago.to_date, kind: "opening_anchor")+ valued = valuation_tracked_account(balance: 112_000, year_ago: 100_000, accountable: Depository.new)++ mixed = goal_on([ cash, anchored ], target_amount: 50_000, target_date: 360.days.from_now.to_date, name: "Mixed")+ assert_equal :pace_unknown, mixed.status+ # The measured half has a pace of its own (300/mo); the projection still+ # claims nothing beyond today's balance.+ assert_equal 300, mixed.pace.to_d+ assert_equal mixed.current_balance.to_d, mixed.projection_end_amount++ # Fixed slices: `cash` is already claimed in full by the goal above.+ measured = goal_on([ cash, valued ], target_amount: 500_000, name: "Measured", allocated: 100)+ assert measured.pace_measurable?+ assert_equal 1300, measured.pace.to_d+ end++ test "an open-ended goal with an unmeasurable account claims no runway" do+ cash = Account.create!(family: @family, accountable: Depository.new, name: "Paid savings",+ currency: "USD", balance: 900)+ create_transaction(account: cash, amount: -900, date: 10.days.ago.to_date)+ anchored = Account.create!(family: @family, accountable: Depository.new, name: "Anchored savings",+ currency: "USD", balance: 500)+ create_valuation(account: anchored, amount: 500, date: 30.days.ago.to_date, kind: "opening_anchor")++ measured = goal_on(cash, target_amount: 50_000, name: "Measured", allocated: 450)+ assert_equal BigDecimal("1.5"), measured.months_of_runway++ # The measured half still has a pace of 300/mo of its own.+ mixed = goal_on([ cash, anchored ], target_amount: 50_000, name: "Mixed", allocated: 450)+ assert_equal 300, mixed.pace.to_d+ assert_nil mixed.months_of_runway+ end++ test "a goal whose pace cannot be measured sorts beside open-ended goals" do+ on_track = goal_on(valuation_tracked_account(balance: 112_000, year_ago: 100_000),+ target_amount: 121_600, target_date: 360.days.from_now.to_date, name: "Zeta on track")+ anchored = Account.create!(family: @family, accountable: Depository.new, name: "Anchored pot",+ currency: "USD", balance: 500)+ create_valuation(account: anchored, amount: 500, date: 30.days.ago.to_date, kind: "opening_anchor")+ unknown = goal_on(anchored, target_amount: 5_000, target_date: 360.days.from_now.to_date, name: "Middle unknown")+ reserve = reserve_goal(balance: 2_000, target: 1_000, allocated: 1_000, name: "Alpha reserve")++ assert_equal :on_track, on_track.status+ assert_equal :pace_unknown, unknown.status+ assert_equal :funded, reserve.status+ assert_equal [ on_track.id, unknown.id, reserve.id ], Goal.active_display_sort([ reserve, unknown, on_track ]).map(&:id)+ end++ test "an open-ended valuation-tracked goal gets a runway from its balance pace" do+ goal = goal_on(valuation_tracked_account(balance: 112_000, year_ago: 100_000), target_amount: 500_000)++ assert_equal :no_target_date, goal.status+ assert_equal BigDecimal("112.0"), goal.months_of_runway+ end++ test "the evidence behind pace is read once for the family, not once per goal" do+ goal_on(valuation_tracked_account(balance: 112_000, year_ago: 100_000), target_amount: 500_000, name: "Super A")+ goal_on(valuation_tracked_account(balance: 50_000, year_ago: 40_000), target_amount: 500_000, name: "Super B")++ goals = Goal.prepared_for(@family)+ assert_operator goals.size, :>=, 5++ # Uncached: the query cache would otherwise answer a per-goal fallback+ # read, and assert_no_queries does not count cached queries.+ ActiveRecord::Base.uncached do+ assert_no_queries do+ goals.each do |goal|+ goal.pace+ goal.pace_measurable?+ end+ end+ end+ end++ # pace_for, balance_pace_for and market_flows_for all start from the same+ # family-wide list of linked accounts.+ test "preparing the goals reads the family's linked accounts once" do+ goal_on(valuation_tracked_account(balance: 112_000, year_ago: 100_000), target_amount: 500_000)++ plucks = 0+ sub = ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload|+ plucks += 1 if payload[:sql].to_s.include?('SELECT DISTINCT "goal_accounts"."account_id"')+ end+ ActiveRecord::Base.uncached { Goal.prepared_for(@family) }++ assert_equal 1, plucks+ ensure+ ActiveSupport::Notifications.unsubscribe(sub) if sub+ end+private+ # A manual account whose value moves only through balance updates: a+ # balance row at `history_from`, a reconciliation valuation on+ # `valuation_on`, today's value on the account itself, no transactions.+ def valuation_tracked_account(balance:, year_ago:, history_from: 400.days.ago.to_date,+ valuation_on: 30.days.ago.to_date, accountable: Investment.new, currency: "USD")+ account = Account.create!(family: @family, accountable: accountable,+ name: "Super #{SecureRandom.hex(3)}", currency: currency, balance: balance)+ account.balances.create!(date: history_from, balance: year_ago, start_cash_balance: year_ago, currency: currency)+ create_valuation(account: account, amount: balance, date: valuation_on, currency: currency)+ account+ end++ # Reloaded, so every figure is read fresh rather than from a memo.+ def goal_on(accounts, target_amount:, target_date: nil, basis: "balance", name: "Pace goal #{SecureRandom.hex(3)}", allocated: nil)+ goal = @family.goals.create!(name: name, target_amount: target_amount, target_date: target_date, currency: "USD") do |g|+ Array(accounts).each { |account| g.goal_accounts.build(account: account, allocated_amount: allocated) }+ end+ goal.update_column(:progress_basis, basis)+ Goal.find(goal.id)+ end+# A goal with something saved and something left, so both segments exist.def ring_goal(color:)account = Account.create!(family: @family, accountable: Depository.new, name: "Ring savings", currency: "USD", balance: 2_000)