The personal finance app for everyone (by everyone)
Ruby
Let a goal choose market value or contributions as its basis (#4026)
jaysbeekay478babcdf98a
diff --git a/app/controllers/goals_controller.rb b/app/controllers/goals_controller.rbindex 40f9ea8730..2918035fe8 100644--- a/app/controllers/goals_controller.rb+++ b/app/controllers/goals_controller.rb@@ -205,11 +205,11 @@ class GoalsController < ApplicationControllerenddef goal_params- params.require(:goal).permit(:name, :target_amount, :target_date, :color, :icon, :notes, :kind, :target_mode, :target_months)+ params.require(:goal).permit(:name, :target_amount, :target_date, :color, :icon, :notes, :kind, :target_mode, :target_months, :progress_basis)enddef goal_update_params- params.require(:goal).permit(:name, :target_amount, :target_date, :color, :icon, :notes, :kind, :target_mode, :target_months)+ params.require(:goal).permit(:name, :target_amount, :target_date, :color, :icon, :notes, :kind, :target_mode, :target_months, :progress_basis)enddef lookup_accounts(ids)diff --git a/app/models/goal.rb b/app/models/goal.rbindex e07e61d813..0f7d1eb7ac 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -34,9 +34,12 @@ class Goal < ApplicationRecordvalidates :name, presence: true, length: { maximum: 255 }validates :target_amount, presence: true, numericality: { greater_than: 0 }validates :currency, presence: true- # before_save (not before_validation) so it only mutates on persistence, not- # on every valid? call — a goal can be inspected without its basis flipping.- before_save :default_progress_basis_for_market_accounts+ # What progress counts: "balance" is what the linked accounts are worth+ # today, "contributions" only what was put in (market gains and losses+ # taken out). The user chooses; nothing re-bases a goal behind their back+ # (#3964).+ PROGRESS_BASES = %w[balance contributions].freeze+ validates :progress_basis, inclusion: { in: PROGRESS_BASES }# A reserve measured in months is derived, not typed: computing it only in# the monthly job would leave a brand-new one wrong until the 1st, so the# feature's first impression would be its least convincing moment. Fired on@@ -68,6 +71,7 @@ class Goal < ApplicationRecordvalidate :currency_locked_once_linkedvalidate :restore_must_not_recreate_whole_account_conflictvalidate :kind_locked_while_released+ validate :progress_basis_locked_once_completedvalidate :kind_locked_once_consumedvalidate :target_must_cover_what_was_consumed# A reserve has no deadline. Normalising here rather than rejecting: the form@@ -98,6 +102,11 @@ class Goal < ApplicationRecord# they belong to are the same fact. Still inside the save transaction, so a# later failure takes both back.after_save :apply_state_change_side_effects, if: :saved_change_to_state?+ # The basis decides what current_balance counts, so the balance-derived memos+ # filled before the save describe the old basis. Cleared the way a state+ # transition clears them, or the instance the controller renders keeps+ # reporting the figure the user just switched away from.+ after_save :reset_state_dependent_caches!, if: :saved_change_to_progress_basis?monetize :target_amount@@ -588,6 +597,13 @@ class Goal < ApplicationRecordprogress_basis == "contributions"end+ # Whether the basis is frozen with a completion snapshot (see+ # progress_basis_locked_once_completed). The form reads it to stop offering+ # a choice the model would refuse.+ def progress_basis_locked?+ persisted? && !completed_amount_in_database.nil?+ end+def one_off?kind == "one_off"end@@ -1537,17 +1553,6 @@ class Goal < ApplicationRecorderrors.add(:linked_accounts, :must_be_fundable)end- # Goals funded by an investment or crypto account default to the- # contributions basis (so a market swing doesn't move them); depository-only- # goals stay on the balance basis. Only auto-set when the basis is still the- # default.- def default_progress_basis_for_market_accounts- return unless goal_accounts.any? { |ga| ga.account&.balance_type == :investment }- return unless progress_basis.blank? || progress_basis == "balance"-- self.progress_basis = "contributions"- end-def linked_accounts_must_belong_to_familyreturn if family.nil?@@ -1598,6 +1603,19 @@ class Goal < ApplicationRecorderrors.add(:kind, :locked_while_released)end+ # A completed goal reports `completed_amount`, frozen on the basis it had+ # when it closed. Switching basis afterwards would label that figure with+ # the other basis, so the switch waits for a reopen or restore; both thaw+ # the snapshot. The persisted snapshot, for the reason kind_locked_while_released+ # reads the persisted state: a write that also sets `state: "active"` skips+ # the transition that clears it. An archived goal that never completed has+ # no snapshot and reports the live figure, so its basis stays editable.+ def progress_basis_locked_once_completed+ return unless progress_basis_locked? && will_save_change_to_progress_basis?++ errors.add(:progress_basis, :locked_once_completed)+ end+def clear_target_date_for_maintainedself.target_date = nil if maintained?enddiff --git a/app/views/goals/_form.html.erb b/app/views/goals/_form.html.erbindex e202601419..47764d21d3 100644--- a/app/views/goals/_form.html.erb+++ b/app/views/goals/_form.html.erb@@ -27,15 +27,10 @@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>+ <%= render "goals/radio_card", form: f, attribute: :kind, value: kind,+ label: t("goals.form.kinds.#{kind}.label"),+ hint: t("goals.form.kinds.#{kind}.hint"),+ radio_options: { data: { goal_kind_target: "radio", action: "change->goal-kind#refresh" } } %><% end %></div>@@ -201,6 +196,35 @@<% end %></div>+ <%# What progress counts. Only differs for an account that moves with the+ market, but a plain-cash goal reads the same either way, so the choice+ is always offered rather than revealed by the accounts ticked above.+ A completed goal's basis is frozen with its snapshot, so there the+ choice is shown disabled; disabled radios are not submitted, so an+ ordinary edit still saves. Checked against the stored basis, so a+ refused switch re-renders showing the basis that was kept; an unknown+ basis falls back to it too, rather than leaving both radios blank. %>+ <% basis_locked = goal.progress_basis_locked? %>+ <% shown_basis = (basis_locked || Goal::PROGRESS_BASES.exclude?(goal.progress_basis)) ? goal.progress_basis_in_database : goal.progress_basis %>+ <fieldset>+ <legend class="block text-sm font-medium text-primary"><%= t("goals.form.fields.progress_basis") %></legend>+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 mt-1.5">+ <% Goal::PROGRESS_BASES.each do |basis| %>+ <%= render "goals/radio_card", form: f, attribute: :progress_basis, value: basis,+ label: t("goals.form.progress_bases.#{basis}.label"),+ hint: t("goals.form.progress_bases.#{basis}.hint"),+ radio_options: { checked: basis == shown_basis },+ disabled: basis_locked %>+ <% end %>+ </div>+ <% if basis_locked %>+ <p class="mt-1.5 text-xs text-secondary"><%= t("goals.form.progress_basis_locked") %></p>+ <% end %>+ <% goal.errors.messages_for(:progress_basis).each do |message| %>+ <p class="mt-1.5 text-xs text-destructive"><%= message %></p>+ <% end %>+ </fieldset>+<%= f.text_area :notes,label: t("goals.form.fields.notes"),rows: 2,diff --git a/app/views/goals/_radio_card.html.erb b/app/views/goals/_radio_card.html.erbnew file mode 100644index 0000000000..9dd546c25a--- /dev/null+++ b/app/views/goals/_radio_card.html.erb@@ -0,0 +1,12 @@+<%# locals: (form:, attribute:, value:, label:, hint:, radio_options: {}, disabled: false) %>+<%# One option of a radio-card picker: the kind picker and the progress+ basis picker share this shape. radio_options goes straight to+ radio_button, so a caller that needs `checked:` passes it there and one+ that doesn't leaves Rails to check the radio from the attribute. %>+<label class="flex items-start gap-2 rounded-lg border border-primary p-3 <%= disabled ? "cursor-not-allowed opacity-60" : "cursor-pointer" %> has-[:checked]:border-secondary has-[:checked]:bg-surface-inset">+ <%= form.radio_button attribute, value, radio_options.merge(disabled: disabled, class: "radio mt-0.5 shrink-0") %>+ <span class="min-w-0">+ <span class="block text-sm font-medium text-primary"><%= label %></span>+ <span class="block text-xs text-secondary"><%= hint %></span>+ </span>+</label>diff --git a/app/views/goals/show.html.erb b/app/views/goals/show.html.erbindex 100080c66d..2aa9f1f6c5 100644--- a/app/views/goals/show.html.erb+++ b/app/views/goals/show.html.erb@@ -147,6 +147,10 @@<%= t(".ring.including_used", amount: @goal.consumed_amount_money.format(precision: 0)) %></p><% end %>+ <%# Same guard as Goal#current_balance: a snapshot means the figure above+ is what the goal reached, not what the accounts hold today. %>+ <% basis_caption = @goal.completed_amount.present? ? "basis_at_completion" : "basis" %>+ <p class="text-xs text-subdued mt-0.5"><%= t(".ring.#{basis_caption}.#{@goal.contributions_basis? ? "contributions" : "balance"}") %></p><% if @goal.contributions_basis? %><p class="text-xs text-secondary tabular-nums mt-0.5 privacy-sensitive"><%= t(".ring.market_value", amount: @goal.market_value_money.format(precision: 0)) %></p><% end %>diff --git a/config/locales/models/goal/ca.yml b/config/locales/models/goal/ca.ymlindex ff7e7e275f..8642fa8d0e 100644--- a/config/locales/models/goal/ca.yml+++ b/config/locales/models/goal/ca.yml@@ -33,3 +33,5 @@ ca:below_consumed: No pots definir un objectiu inferior al que aquest objectiu ja ha registrat com a gastat.currency:locked_after_linked: No pots canviar la moneda un cop l'objectiu està enllaçat a comptes.+ progress_basis:+ locked_once_completed: Reobre o restaura aquest objectiu abans de canviar què hi compta.diff --git a/config/locales/models/goal/de.yml b/config/locales/models/goal/de.ymlindex 459df6925e..bf3beb1bd4 100644--- a/config/locales/models/goal/de.yml+++ b/config/locales/models/goal/de.yml@@ -22,3 +22,5 @@ de:linked_accounts:must_be_fundable: Alle verknüpften Konten müssen Bank-, Investment- oder Kryptokonten sein.must_belong_to_family: Verknüpfte Konten müssen zur selben Familie gehören wie das Ziel.+ progress_basis:+ locked_once_completed: Öffne dieses Ziel wieder oder stelle es wieder her, bevor du änderst, was dafür zählt.diff --git a/config/locales/models/goal/en.yml b/config/locales/models/goal/en.ymlindex e253915ded..a97edd0c2c 100644--- a/config/locales/models/goal/en.yml+++ b/config/locales/models/goal/en.yml@@ -30,6 +30,8 @@ en:kind:locked_while_released: Reopen this goal before turning it into a reserve.locked_once_consumed: This goal has already recorded money as spent, so it cannot become a reserve.+ progress_basis:+ locked_once_completed: Reopen or restore this goal before changing what counts toward it.target_amount:below_consumed: Can't set a target below what this goal has already recorded as spent.currency:diff --git a/config/locales/models/goal/es.yml b/config/locales/models/goal/es.ymlindex 58b4e30364..c6650fb7cd 100644--- a/config/locales/models/goal/es.yml+++ b/config/locales/models/goal/es.yml@@ -22,3 +22,5 @@ es:must_belong_to_family: Las cuentas vinculadas deben pertenecer a la misma familia que el objetivo.currency:locked_after_linked: No se puede cambiar la moneda cuando el objetivo ya está vinculado a cuentas.+ progress_basis:+ locked_once_completed: Reabre o restaura este objetivo antes de cambiar lo que se tiene en cuenta.diff --git a/config/locales/models/goal/fr.yml b/config/locales/models/goal/fr.ymlindex 028b92333f..c9ddc330bf 100644--- a/config/locales/models/goal/fr.yml+++ b/config/locales/models/goal/fr.yml@@ -34,3 +34,5 @@ fr:linked_accounts:must_be_fundable: Tous les comptes liés doivent être des comptes de trésorerie, d'investissement ou de cryptomonnaies.must_belong_to_family: Les comptes liés doivent appartenir au même foyer que l'objectif.+ progress_basis:+ locked_once_completed: Rouvrez ou restaurez cet objectif avant de changer ce qui est pris en compte.diff --git a/config/locales/models/goal/it.yml b/config/locales/models/goal/it.ymlindex 78446f53c6..fc72abf4b8 100644--- a/config/locales/models/goal/it.yml+++ b/config/locales/models/goal/it.yml@@ -22,3 +22,5 @@ it:must_belong_to_family: I conti collegati devono appartenere alla stessa famiglia dell'obiettivo.currency:locked_after_linked: Impossibile cambiare la valuta dopo che l'obiettivo è stato collegato ai conti.+ progress_basis:+ locked_once_completed: Riapri o ripristina questo obiettivo prima di cambiare cosa conta.diff --git a/config/locales/models/goal/pl.yml b/config/locales/models/goal/pl.ymlindex c795948008..b6abe18002 100644--- a/config/locales/models/goal/pl.yml+++ b/config/locales/models/goal/pl.yml@@ -43,3 +43,5 @@ pl:blank: Podaj, ile miesięcy wydatków ma pokrywać ta rezerwa.only_with_months_mode: Miesiące wydatków mają zastosowanie tylko wtedy,gdy cel jest tak ustawiony.+ progress_basis:+ locked_once_completed: Otwórz ponownie lub przywróć ten cel, zanim zmienisz, co się do niego liczy.diff --git a/config/locales/models/goal/pt-PT.yml b/config/locales/models/goal/pt-PT.ymlindex 2c8601a992..bf21f7b565 100644--- a/config/locales/models/goal/pt-PT.yml+++ b/config/locales/models/goal/pt-PT.yml@@ -33,3 +33,5 @@ pt-PT:below_consumed: Não é possível definir um objetivo abaixo do que este objetivo já registou como gasto.currency:locked_after_linked: Não é possível alterar a moeda depois de o objetivo estar associado a contas.+ progress_basis:+ locked_once_completed: Reabra ou restaure este objetivo antes de alterar o que conta para ele.diff --git a/config/locales/models/goal/ru.yml b/config/locales/models/goal/ru.ymlindex fd9ee51e46..4f9e723fa0 100644--- a/config/locales/models/goal/ru.yml+++ b/config/locales/models/goal/ru.yml@@ -34,4 +34,6 @@ ru:locked_while_released: Чтобы превратить эту цель в резерв, сначала откройте её снова.locked_once_consumed: По этой цели уже учтены потраченные средства, поэтому её нельзя превратить в резерв.target_amount:- below_consumed: Целевая сумма не может быть меньше уже потраченной по этой цели.\ No newline at end of file+ below_consumed: Целевая сумма не может быть меньше уже потраченной по этой цели.+ progress_basis:+ locked_once_completed: Чтобы изменить, что засчитывается в эту цель, сначала откройте её снова или восстановите.\ No newline at end of filediff --git a/config/locales/models/goal/tr.yml b/config/locales/models/goal/tr.ymlindex 5026bb0ce8..0bffa805a5 100644--- a/config/locales/models/goal/tr.yml+++ b/config/locales/models/goal/tr.yml@@ -35,3 +35,5 @@ tr:locked_once_consumed: Bu hedefte zaten harcanmış olarak kaydedilen para var, bu yüzden rezerve dönüştürülemez.target_amount:below_consumed: Hedef, bu hedefte harcanmış olarak kaydedilen tutarın altına ayarlanamaz.+ progress_basis:+ locked_once_completed: Nelerin sayılacağını değiştirmeden önce bu hedefi yeniden açın veya geri yükleyin.diff --git a/config/locales/models/goal/uk.yml b/config/locales/models/goal/uk.ymlindex 75ba46f1d2..5bf6f2908e 100644--- a/config/locales/models/goal/uk.yml+++ b/config/locales/models/goal/uk.yml@@ -33,3 +33,5 @@ uk:locked_once_consumed: Для цієї цілі вже зафіксовано витрачені кошти, тому її не можна перетворити на резерв.target_amount:below_consumed: Цільова сума не може бути меншою, ніж уже зафіксовано як витрачене для цієї цілі.+ progress_basis:+ locked_once_completed: Спершу знову відкрийте цю ціль або поверніть її з архіву, а потім змініть, що до неї зараховується.diff --git a/config/locales/models/goal/zh-CN.yml b/config/locales/models/goal/zh-CN.ymlindex a7e82d372f..7b0d2d07b3 100644--- a/config/locales/models/goal/zh-CN.yml+++ b/config/locales/models/goal/zh-CN.yml@@ -24,6 +24,8 @@ zh-CN:must_belong_to_family: 关联账户必须属于与目标相同的家庭。currency:locked_after_linked: 目标关联账户后不能更改货币。+ progress_basis:+ locked_once_completed: 请先重新打开或恢复此目标,再更改计入方式。target_mode:months_requires_maintained: 只有您持续维护的储备金才能将目标设定为支出月数。target_months:diff --git a/config/locales/models/goal/zh-TW.yml b/config/locales/models/goal/zh-TW.ymlindex bae34d0c16..b6526910c3 100644--- a/config/locales/models/goal/zh-TW.yml+++ b/config/locales/models/goal/zh-TW.yml@@ -22,3 +22,5 @@ zh-TW:must_belong_to_family: 已連結的帳戶必須和這個目標屬於同一個家庭。currency:locked_after_linked: 目標連結帳戶之後就不能再更改幣別了。+ progress_basis:+ locked_once_completed: 請先重新開啟或還原此目標,再變更計入方式。diff --git a/config/locales/views/goals/ca.yml b/config/locales/views/goals/ca.ymlindex 8a7b1ff4a1..1e2d37a5af 100644--- a/config/locales/views/goals/ca.yml+++ b/config/locales/views/goals/ca.yml@@ -177,6 +177,12 @@ ca:market_value: 'Valor de mercat: %{amount}'aria_label: Objectiu completat al %{percent}%. %{amount} estalviats de %{target}.aria_label_with_used: Objectiu completat al %{percent}%. %{amount} de %{target}, incloent-hi %{used} ja utilitzats.+ basis:+ balance: Compta el que valen avui els comptes+ contributions: Compta només el que hi has aportat+ basis_at_completion:+ balance: Comptava el que valien els comptes quan es va completar l'objectiu+ contributions: Comptava només el que hi havies aportat quan es va completar l'objectiuprojection:heading: Projecciólegend_saved: Estalviat@@ -336,6 +342,7 @@ ca:whole_balance: "Buit: tot el saldo"earmark_for: Import reservat de %{account}earmark_hint: Deixa un import en blanc per destinar-hi tot el saldo d'aquell compte.+ progress_basis: Què compta per a aquest objectiusubtypes:checking: Compte correntsavings: Estalvis@@ -343,3 +350,11 @@ ca:cd: Dipòsit a terminimoney_market: Mercat monetariother: Altres+ progress_basis_locked: El progrés d'aquest objectiu es va congelar quan es va completar. Reobre'l o restaura'l per canviar què hi compta.+ progress_bases:+ balance:+ label: El que valen avui els comptes+ hint: Valor de mercat. Els guanys i les pèrdues de les inversions compten per a l'objectiu.+ contributions:+ label: Només el que hi he aportat+ hint: Aportacions netes. Els guanys i les pèrdues del mercat no hi compten.diff --git a/config/locales/views/goals/de.yml b/config/locales/views/goals/de.ymlindex ae33d11c20..790a8b0f98 100644--- a/config/locales/views/goals/de.yml+++ b/config/locales/views/goals/de.yml@@ -48,6 +48,7 @@ de:target_amount: Zielbetragtarget_date: Zieldatumwhole_balance: "Leer: ganzer Saldo"+ progress_basis: Was für dieses Ziel zähltsave: Änderungen speichernsubtypes:cd: Festgeld@@ -58,6 +59,14 @@ de:savings: Sparkontosuggested_no_date: Setz eine Frist, um ein Zieldatum hochzurechnen.suggested_with_date: Spar {monthly}/Monat über {accounts}, um es rechtzeitig zu schaffen.+ progress_basis_locked: Der Fortschritt dieses Ziels wurde beim Abschluss eingefroren. Öffne es wieder oder stelle es wieder her, um zu ändern, was dafür zählt.+ progress_bases:+ balance:+ label: Was die Konten heute wert sind+ hint: Marktwert. Gewinne und Verluste aus Investments zählen für das Ziel.+ contributions:+ label: Nur was ich eingezahlt habe+ hint: Nettoeinlagen. Marktgewinne und -verluste bleiben außen vor.goal_card:accounts:one: 1 Konto@@ -258,6 +267,12 @@ de:of_target: vom Zielsaved: Gespartto_go: "%{amount} fehlen"+ basis:+ balance: Zählt, was die Konten heute wert sind+ contributions: Zählt nur, was du eingezahlt hast+ basis_at_completion:+ balance: Zählte, was die Konten beim Abschluss des Ziels wert waren+ contributions: Zählte nur, was du bis zum Abschluss des Ziels eingezahlt hatteststatus_callout:behind: spar %{amount}/Monat mehr, um aufzuholenbehind_covered: offene Zusagen schließen die Lückediff --git a/config/locales/views/goals/en.yml b/config/locales/views/goals/en.ymlindex a9fd82f032..13c7c7c311 100644--- a/config/locales/views/goals/en.yml+++ b/config/locales/views/goals/en.yml@@ -189,6 +189,12 @@ en:to_go: "%{amount} to go"of_target: of targetmarket_value: "Market value %{amount}"+ basis:+ balance: Counts what the accounts are worth today+ contributions: Counts only what you have put in+ basis_at_completion:+ balance: Counted what the accounts were worth when the goal was completed+ contributions: Counted only what you had put in when the goal was completedaria_label: "Goal %{percent}% complete. %{amount} of %{target} saved."aria_label_with_used: "Goal %{percent}% complete. %{amount} of %{target}, including %{used} already used."projection:@@ -316,6 +322,14 @@ en:target_modes:fixed: A fixed amountmonths_of_expenses: A number of months of expenses+ progress_basis_locked: This goal's progress was frozen when it was completed. Reopen or restore it to change what counts toward it.+ progress_bases:+ balance:+ label: What the accounts are worth today+ hint: Market value. Investment gains and losses count toward the goal.+ contributions:+ label: Only what I have put in+ hint: Net contributions. Market gains and losses are left out.kinds:one_off:hint: Save toward something, then close it when you spend it.@@ -352,6 +366,7 @@ en:notes: Notes (optional)notes_placeholder: A reminder for future you…funding_accounts: Funding accounts+ progress_basis: What counts toward this goalfunding_accounts_hint: This goal's balance is the balance (or earmarked portion) of these accounts.whole_balance: "Blank: whole balance"earmark_for: Earmark amount for %{account}diff --git a/config/locales/views/goals/es.yml b/config/locales/views/goals/es.ymlindex 64ea1881f8..43a84f61a2 100644--- a/config/locales/views/goals/es.yml+++ b/config/locales/views/goals/es.yml@@ -148,6 +148,12 @@ es:of_target: de la metamarket_value: Valor de mercado %{amount}aria_label: Objetivo completado al %{percent}%. %{amount} de %{target} ahorrados.+ basis:+ balance: Tiene en cuenta lo que valen hoy las cuentas+ contributions: Tiene en cuenta solo lo que has aportado+ basis_at_completion:+ balance: Tuvo en cuenta lo que valían las cuentas al completar el objetivo+ contributions: Tuvo en cuenta solo lo que habías aportado al completar el objetivoprojection:heading: Proyecciónlegend_saved: Ahorrado@@ -271,6 +277,7 @@ es:whole_balance: "Vacío: todo el saldo"earmark_for: Importe reservado para %{account}earmark_hint: Deja un importe en blanco para dedicar todo el saldo de esa cuenta.+ progress_basis: Qué se tiene en cuenta para este objetivosubtypes:checking: Corrientesavings: Ahorro@@ -278,3 +285,11 @@ es:cd: Depósito a plazomoney_market: Mercado monetarioother: Otra+ progress_basis_locked: El progreso de este objetivo se congeló al completarse. Reábrelo o restáuralo para cambiar lo que se tiene en cuenta.+ progress_bases:+ balance:+ label: Lo que valen hoy las cuentas+ hint: Valor de mercado. Las ganancias y pérdidas de las inversiones cuentan para el objetivo.+ contributions:+ label: Solo lo que he aportado+ hint: Aportaciones netas. Las ganancias y pérdidas del mercado quedan fuera.diff --git a/config/locales/views/goals/fr.yml b/config/locales/views/goals/fr.ymlindex 061b9e69df..65d04c23db 100644--- a/config/locales/views/goals/fr.yml+++ b/config/locales/views/goals/fr.yml@@ -70,6 +70,7 @@ fr:target_balance_hint: "D'après vos dépenses mensuelles médianes sur le nombre de mois ci-dessus. Recalculé chaque mois."target_date: Date ciblewhole_balance: "Vide : tout le solde"+ progress_basis: Ce qui compte pour cet objectifcurrency_conversion_hint: Les comptes peuvent utiliser des devises différentes. Les totaux sont convertis en %{currency} ; les affectations restent dans la devise de chaque compte.save: Enregistrer les modificationssubtypes:@@ -81,6 +82,14 @@ fr:savings: Épargnesuggested_no_date: Définissez une date cible pour projeter la fin.suggested_with_date: Épargnez {monthly}/mois sur {accounts} pour l'atteindre à temps.+ progress_basis_locked: La progression de cet objectif a été figée lorsqu'il a été terminé. Rouvrez-le ou restaurez-le pour changer ce qui est pris en compte.+ progress_bases:+ balance:+ label: La valeur actuelle des comptes+ hint: Valeur de marché. Les gains et pertes des investissements comptent pour l'objectif.+ contributions:+ label: Uniquement ce que j'ai versé+ hint: Apports nets. Les gains et pertes de marché sont exclus.goal_card:including_used: "Dont %{amount} déjà utilisés"accounts:@@ -323,6 +332,12 @@ fr:of_target: de l'objectifsaved: Épargnéto_go: "%{amount} restant(s)"+ basis:+ balance: Prend en compte la valeur actuelle des comptes+ contributions: Prend en compte uniquement ce que vous avez versé+ basis_at_completion:+ balance: A pris en compte la valeur des comptes au moment où l'objectif a été terminé+ contributions: A pris en compte uniquement ce que vous aviez versé au moment où l'objectif a été terminéstatus_callout:depleted: "il manque %{amount} — complétez pour ramener la réserve à son solde cible"behind: épargnez %{amount}/mois de plus pour rattraper le retarddiff --git a/config/locales/views/goals/it.yml b/config/locales/views/goals/it.ymlindex 021c3ebcd2..e201704707 100644--- a/config/locales/views/goals/it.yml+++ b/config/locales/views/goals/it.yml@@ -144,6 +144,12 @@ it:of_target: dell'obiettivomarket_value: "Valore di mercato %{amount}"aria_label: "Obiettivo %{percent}%% completato. %{amount} di %{target} risparmiati."+ basis:+ balance: Conta ciò che valgono oggi i conti+ contributions: Conta solo ciò che hai versato+ basis_at_completion:+ balance: Ha contato ciò che valevano i conti al completamento dell'obiettivo+ contributions: Ha contato solo ciò che avevi versato al completamento dell'obiettivoprojection:heading: Proiezionelegend_saved: Risparmiato@@ -270,6 +276,7 @@ it:whole_balance: "Vuoto: tutto il saldo"earmark_for: Accantona un importo per %{account}earmark_hint: Lascia vuoto un importo per dedicare l'intero saldo di quel conto.+ progress_basis: Cosa conta per questo obiettivosubtypes:checking: Conto correntesavings: Risparmio@@ -277,3 +284,11 @@ it:cd: CDmoney_market: Mercato monetarioother: Altro+ progress_basis_locked: I progressi di questo obiettivo sono stati congelati al completamento. Riaprilo o ripristinalo per cambiare cosa conta.+ progress_bases:+ balance:+ label: Ciò che valgono oggi i conti+ hint: Valore di mercato. Guadagni e perdite degli investimenti contano per l'obiettivo.+ contributions:+ label: Solo ciò che ho versato+ hint: Contributi netti. Guadagni e perdite di mercato restano esclusi.diff --git a/config/locales/views/goals/pl.yml b/config/locales/views/goals/pl.ymlindex 477d677164..3f45b7ba6d 100644--- a/config/locales/views/goals/pl.yml+++ b/config/locales/views/goals/pl.yml@@ -88,6 +88,7 @@ pl:target_months_hint: Przeliczane 1. dnia każdego miesiąca na podstawie medianyTwoich miesięcznych wydatków.whole_balance: "Puste: całe saldo"+ progress_basis: Co liczy się do tego celukinds:maintained:hint: Saldo do utrzymania, jak fundusz awaryjny. Nigdy nie jest zamykane.@@ -109,6 +110,14 @@ pl:target_modes:fixed: Stała kwotamonths_of_expenses: Liczba miesięcy wydatków+ progress_basis_locked: Postęp tego celu został zamrożony w chwili jego zakończenia. Otwórz go ponownie lub przywróć, aby zmienić, co się do niego liczy.+ progress_bases:+ balance:+ label: Ile konta są dziś warte+ hint: Wartość rynkowa. Zyski i straty z inwestycji liczą się do celu.+ contributions:+ label: Tylko wpłacone środki+ hint: Wpłaty netto. Zyski i straty rynkowe są pomijane.goal_card:accounts:few: "%{count} konta"@@ -359,6 +368,12 @@ pl:of_target: z celusaved: Zaoszczędzonoto_go: Pozostało %{amount}+ basis:+ balance: Liczy, ile konta są dziś warte+ contributions: Liczy tylko wpłacone środki+ basis_at_completion:+ balance: Liczył, ile konta były warte w chwili zakończenia celu+ contributions: Liczył tylko środki wpłacone do chwili zakończenia celustatus_callout:behind: oszczędzaj %{amount}/mies. więcej, aby nadrobićbehind_covered: oczekujące zobowiązania wypełniają lukędiff --git a/config/locales/views/goals/pt-PT.yml b/config/locales/views/goals/pt-PT.ymlindex d69120a14b..c87c20169d 100644--- a/config/locales/views/goals/pt-PT.yml+++ b/config/locales/views/goals/pt-PT.yml@@ -177,6 +177,12 @@ pt-PT:market_value: "Valor de mercado %{amount}"aria_label: "Objetivo %{percent}% concluído. %{amount} de %{target} reservados."aria_label_with_used: "Objetivo %{percent}% concluído. %{amount} de %{target}, incluindo %{used} já utilizados."+ basis:+ balance: Considera o que as contas valem hoje+ contributions: Considera apenas o que depositou+ basis_at_completion:+ balance: Considerou o que as contas valiam quando o objetivo foi concluído+ contributions: Considerou apenas o que tinha depositado quando o objetivo foi concluídoprojection:heading: Projeçãolegend_saved: Reservado@@ -336,6 +342,7 @@ pt-PT:whole_balance: "Vazio: saldo total"earmark_for: Reservar o montante de %{account}earmark_hint: Deixe um montante em branco para dedicar o saldo total dessa conta.+ progress_basis: O que conta para este objetivosubtypes:checking: Conta à ordemsavings: Poupança@@ -343,3 +350,11 @@ pt-PT:cd: CDmoney_market: Mercado monetárioother: Outro+ progress_basis_locked: O progresso deste objetivo foi congelado quando foi concluído. Reabra-o ou restaure-o para alterar o que conta para ele.+ progress_bases:+ balance:+ label: O que as contas valem hoje+ hint: Valor de mercado. Os ganhos e perdas dos investimentos contam para o objetivo.+ contributions:+ label: Apenas o que depositei+ hint: Contribuições líquidas. Os ganhos e perdas de mercado ficam de fora.diff --git a/config/locales/views/goals/ru.yml b/config/locales/views/goals/ru.ymlindex 55fd70efd0..6d6d9b1714 100644--- a/config/locales/views/goals/ru.yml+++ b/config/locales/views/goals/ru.yml@@ -54,6 +54,7 @@ ru:target_balance: Целевой балансtarget_balance_pending: Рассчитается при сохраненииtarget_balance_hint: По медиане ваших ежемесячных расходов за указанное выше число месяцев. Обновляется каждый месяц.+ progress_basis: Что засчитывается в эту цельsave: Сохранить измененияsubtypes:cd: Срочный вклад@@ -79,6 +80,14 @@ ru:prorata: Ваши цели на этом счёте в сумме составляют {total} при балансе {balance} — они будут продвигаться пропорционально.whole_balance: Этот счёт будет пополнять цель всем остатком после других резервирований.whole_balance_alone: Эта цель будет использовать весь баланс этого счёта.+ progress_basis_locked: Прогресс этой цели был зафиксирован при её выполнении. Чтобы изменить, что в неё засчитывается, сначала откройте её снова или восстановите.+ progress_bases:+ balance:+ label: Текущая стоимость счетов+ hint: Рыночная стоимость. Инвестиционные прибыли и убытки засчитываются в цель.+ contributions:+ label: Только мои взносы+ hint: Чистые пополнения. Рыночные прибыли и убытки не учитываются.goal_card:accounts:one: "%{count} счёт"@@ -274,6 +283,12 @@ ru:to_go: Осталось %{amount}including_used: Включая уже потраченные %{amount}aria_label_with_used: Выполнено %{percent}%. %{amount} из %{target}, включая уже потраченные %{used}.+ basis:+ balance: Учитывается текущая стоимость счетов+ contributions: Учитываются только ваши взносы+ basis_at_completion:+ balance: Учитывалась стоимость счетов на момент выполнения цели+ contributions: Учитывались только ваши взносы на момент выполнения целиstatus_callout:behind: откладывайте %{amount}/мес. большеbehind_covered: ожидаемые пополнения покроют разницуdiff --git a/config/locales/views/goals/tr.yml b/config/locales/views/goals/tr.ymlindex 6f768734ad..8881562cb6 100644--- a/config/locales/views/goals/tr.yml+++ b/config/locales/views/goals/tr.yml@@ -57,6 +57,7 @@ tr:target_balance: Hedef bakiyetarget_balance_pending: Kaydettiğinizde hesaplanırtarget_balance_hint: Yukarıdaki ay sayısı ve medyan aylık harcamanızdan hesaplanır. Her ay güncellenir.+ progress_basis: Bu hedefe neler sayılırsave: Değişiklikleri kaydetsubtypes:cd: Vadeli mevduat@@ -83,6 +84,14 @@ tr:prorata: Bu hesaptaki hedefleriniz {balance} bakiyeye karşılık toplam {total} tutarında — orantılı olarak ilerleyecekler.whole_balance: Bu hesap, diğer ayrılan tutarlardan sonra kalan bakiyenin tamamıyla bu hedefi finanse edecek.whole_balance_alone: Bu hedef, bu hesabın tüm bakiyesini kullanacak.+ progress_basis_locked: Bu hedefin ilerlemesi tamamlandığında donduruldu. Nelerin sayılacağını değiştirmek için hedefi yeniden açın veya geri yükleyin.+ progress_bases:+ balance:+ label: Hesapların bugünkü değeri+ hint: Piyasa değeri. Yatırım kazançları ve kayıpları hedefe sayılır.+ contributions:+ label: Yalnızca yatırdığım tutar+ hint: Net katkılar. Piyasa kazançları ve kayıpları hariç tutulur.goal_card:accounts:one: "%{count} hesap"@@ -305,6 +314,12 @@ tr:to_go: "%{amount} kaldı"including_used: Kullanılan %{amount} dahilaria_label_with_used: Hedef %{percent}% tamamlandı. Kullanılan %{used} dahil, %{target} hedefinin %{amount} kadarı.+ basis:+ balance: Hesapların bugünkü değerini sayar+ contributions: Yalnızca yatırdığınız tutarı sayar+ basis_at_completion:+ balance: Hedef tamamlandığında hesapların değerini saydı+ contributions: Hedef tamamlandığında yalnızca yatırdığınız tutarı saydıstatus_callout:behind: yakalamak için ayda %{amount} daha fazla biriktirinbehind_covered: bekleyen taahhütler farkı kapatıyordiff --git a/config/locales/views/goals/uk.yml b/config/locales/views/goals/uk.ymlindex 760f1a5048..c7291a237c 100644--- a/config/locales/views/goals/uk.yml+++ b/config/locales/views/goals/uk.yml@@ -189,6 +189,12 @@ uk:market_value: Ринкова вартість %{amount}aria_label: Ціль виконано на %{percent}%. Накопичено %{amount} з %{target}.aria_label_with_used: Ціль виконано на %{percent}%. %{amount} з %{target}, включно з уже використаними %{used}.+ basis:+ balance: Враховується поточна вартість рахунків+ contributions: Враховуються лише ваші внески+ basis_at_completion:+ balance: Враховувалася вартість рахунків на момент завершення цілі+ contributions: Враховувалися лише ваші внески на момент завершення ціліprojection:heading: Прогнозlegend_saved: Накопичено@@ -356,6 +362,7 @@ uk:whole_balance: "Порожньо: весь баланс"earmark_for: Сума, яку відкласти з %{account}earmark_hint: Залиште суму порожньою, щоб використати весь баланс рахунку.+ progress_basis: Що зараховується до цієї ціліsubtypes:checking: Поточніsavings: Ощадні@@ -363,3 +370,11 @@ uk:cd: Строкові депозитиmoney_market: Грошовий ринокother: Інші+ progress_basis_locked: Прогрес цієї цілі було зафіксовано, коли її завершили. Щоб змінити, що до неї зараховується, спершу знову відкрийте її або поверніть з архіву.+ progress_bases:+ balance:+ label: Поточна вартість рахунків+ hint: Ринкова вартість. Інвестиційні прибутки й збитки зараховуються до цілі.+ contributions:+ label: Лише мої внески+ hint: Чисті внески. Ринкові прибутки й збитки не враховуються.diff --git a/config/locales/views/goals/zh-CN.yml b/config/locales/views/goals/zh-CN.ymlindex 761a7d3375..03e22173c2 100644--- a/config/locales/views/goals/zh-CN.yml+++ b/config/locales/views/goals/zh-CN.yml@@ -186,6 +186,12 @@ zh-CN:of_target: 目标进度market_value: 市值 %{amount}aria_label: 目标已完成 %{percent}%。已存 %{target} 中的 %{amount}。+ basis:+ balance: 计入账户当前的价值+ contributions: 仅计入你投入的资金+ basis_at_completion:+ balance: 按目标完成时账户的价值计入+ contributions: 仅计入目标完成时你已投入的资金aria_label_with_used: "目标已完成 %{percent}%。%{target} 中的 %{amount},包括已使用的 %{used}。"projection:heading: 预测@@ -348,6 +354,7 @@ zh-CN:whole_balance: "留空即全部余额"earmark_for: 为「%{account}」预留的金额earmark_hint: 留空则使用该账户的全部余额。+ progress_basis: 此目标计入什么currency_conversion_hint: "账户可以使用不同货币。总额将转换为 %{currency};账户预留仍以各账户的原货币保留。"subtypes:checking: 支票账户@@ -356,3 +363,11 @@ zh-CN:cd: 定期存单money_market: 货币市场other: 其他+ progress_basis_locked: 此目标的进度已在完成时冻结。重新打开或恢复后才能更改计入方式。+ progress_bases:+ balance:+ label: 账户当前的价值+ hint: 市值。投资收益和亏损计入目标。+ contributions:+ label: 仅我投入的资金+ hint: 净投入。不计市场收益和亏损。diff --git a/config/locales/views/goals/zh-TW.yml b/config/locales/views/goals/zh-TW.ymlindex e510fcb107..d9d7e971d6 100644--- a/config/locales/views/goals/zh-TW.yml+++ b/config/locales/views/goals/zh-TW.yml@@ -144,6 +144,12 @@ zh-TW:of_target: 佔目標比例market_value: 市值 %{amount}aria_label: 目標已完成 %{percent}%。目標 %{target} 中已存 %{amount}。+ basis:+ balance: 計入帳戶目前的價值+ contributions: 僅計入您投入的資金+ basis_at_completion:+ balance: 依目標完成時帳戶的價值計入+ contributions: 僅計入目標完成時您已投入的資金projection:heading: 預測legend_saved: 已存@@ -270,6 +276,7 @@ zh-TW:whole_balance: "留空即全部餘額"earmark_for: 為 %{account} 指定金額earmark_hint: 把金額留白,就會把該帳戶的全部餘額都投入這個目標。+ progress_basis: 此目標計入什麼subtypes:checking: 支票帳戶 (Checking)savings: 儲蓄帳戶 (Savings)@@ -277,3 +284,11 @@ zh-TW:cd: 定期存款 (CD)money_market: 貨幣市場帳戶other: 其他+ progress_basis_locked: 此目標的進度已在完成時凍結。重新開啟或還原後才能變更計入方式。+ progress_bases:+ balance:+ label: 帳戶目前的價值+ hint: 市值。投資收益與虧損計入目標。+ contributions:+ label: 僅我投入的資金+ hint: 淨投入。不計市場收益與虧損。diff --git a/docs/llm-guides/goals.md b/docs/llm-guides/goals.mdindex ca2d593628..1c1858bcff 100644--- a/docs/llm-guides/goals.md+++ b/docs/llm-guides/goals.md@@ -102,15 +102,34 @@ icon, optional notes, currency, and an AASM `state` (`active` / `paused` /`completed` / `archived`). It links cash, investment and crypto accounts via thejoin table `goal_accounts`.-The goal's *progress* is its allocated share of linked accounts, converted to-its currency at request time. `Goal#current_balance` preserves native account-allocations and shared-pool limits before conversion. Investment- and-crypto-backed goals default to contribution progress, excluding cumulative-market gains from their backing; `market_value_money` separately shows the-current market value. Market gains come from `balances.net_market_flows`,-which is derived from holdings, so an account synced as a bare balance with-no holdings (common for crypto wallets) has none: its contribution progress-equals its balance and price moves still show up.+The goal's *progress* is computed live from its linked accounts. There is+no ledger of contributions. `Goal#current_balance` sums, over the linked+accounts, this goal's share of each one: its earmark+(`goal_accounts.allocated_amount`, scaled down pro rata when the earmarks+on an account exceed its figure), or for an unallocated link the remainder+after other goals' earmarks (`Goal#backing_share_for`). The share is taken+in the account's native currency, preserving shared-pool limits, and then+converted to the goal's currency at request time.++`progress_basis` says what each account's figure counts before that share+is taken, and the user chooses it on the form: `balance` (the default) is+the account's balance, what it is worth today; `contributions` is the+balance minus the account's cumulative market gain or loss (the sum of+its signed `balances.net_market_flows`, so a loss adds back), floored at+zero. Nothing re-bases a goal on save or when an account is linked, so an+explicit choice is kept (#3964).+`market_value_money` separately shows the backing's current market value,+whatever the basis.++A goal that has completed reports `completed_amount`, frozen on the basis+it had when it closed, instead of the live figure; its basis is locked+until it is reopened or restored. An archived goal that never completed has no+snapshot and keeps the live calculation.++Market gains come from `balances.net_market_flows`, which is derived from+holdings, so an account synced as a bare balance with no holdings (common for+crypto wallets) has none: its contribution progress equals its balance and+price moves still show up.A `GoalPledge` is an intent: amount, account, kind, status, expires_at.The status enum is `open` / `matched` / `cancelled` / `expired`. The kinddiff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rbindex 9a873063fe..a5d3736c1b 100644--- a/test/controllers/goals_controller_test.rb+++ b/test/controllers/goals_controller_test.rb@@ -264,6 +264,214 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestassert_includes linked, @depository.idend+ # The user chooses what progress counts.+ test "create saves the progress basis the user chose" do+ account = unclaimed_account("Basis Pot")++ post goals_url, params: {+ goal: { name: "Discipline goal", target_amount: "1000", progress_basis: "contributions", account_ids: [ account.id ] }+ }++ goal = @user.family.goals.find_by!(name: "Discipline goal")+ assert_redirected_to goal_path(goal)+ assert_equal "contributions", goal.progress_basis+ end++ test "create without a basis counts market value" do+ account = unclaimed_account("Default Basis Pot")++ post goals_url, params: { goal: { name: "Plain goal", target_amount: "1000", account_ids: [ account.id ] } }++ goal = @user.family.goals.find_by!(name: "Plain goal")+ assert_redirected_to goal_path(goal)+ assert_equal "balance", goal.progress_basis+ end++ test "update changes the progress basis" do+ assert_equal "balance", @goal.progress_basis++ patch goal_url(@goal), params: { goal: { progress_basis: "contributions" } }++ assert_redirected_to goal_path(@goal)+ assert_equal "contributions", @goal.reload.progress_basis+ end++ test "update refuses an unknown progress basis" do+ patch goal_url(@goal), params: { goal: { progress_basis: "speculative" } }++ assert_response :unprocessable_entity+ assert_equal "balance", @goal.reload.progress_basis+ # The re-rendered form still shows the stored basis, not two blank radios.+ assert_select "input[type=radio][name='goal[progress_basis]'][value=balance][checked]", 1+ assert_select "input[type=radio][name='goal[progress_basis]'][checked]", 1+ end++ test "an unknown basis re-renders the stored basis after a valid one was saved" do+ @goal.update!(progress_basis: "contributions")++ patch goal_url(@goal), params: { goal: { progress_basis: "speculative" } }++ assert_response :unprocessable_entity+ assert_select "input[type=radio][name='goal[progress_basis]'][value=contributions][checked]", 1+ assert_select "input[type=radio][name='goal[progress_basis]'][checked]", 1+ end++ test "create with an unknown basis re-renders with the default basis selected" do+ account = unclaimed_account("Unknown Basis Pot")++ assert_no_difference "Goal.count" do+ post goals_url, params: {+ goal: { name: "Unknown basis", target_amount: "1000", progress_basis: "speculative", account_ids: [ account.id ] }+ }+ end++ assert_response :unprocessable_entity+ assert_select "input[type=radio][name='goal[progress_basis]'][value=balance][checked]", 1+ assert_select "input[type=radio][name='goal[progress_basis]'][checked]", 1+ end++ test "update refuses a basis change on a completed goal" do+ @goal.complete!+ snapshot = @goal.reload.completed_amount++ patch goal_url(@goal), params: { goal: { progress_basis: "contributions" } }++ assert_response :unprocessable_entity+ assert_equal "balance", @goal.reload.progress_basis+ assert_equal snapshot, @goal.completed_amount+ # The refusal has to reach the user: the re-rendered form names it, and+ # the locked radios show the basis that was kept, not the one refused.+ assert_select "p.text-destructive", text: I18n.t("activerecord.errors.models.goal.attributes.progress_basis.locked_once_completed")+ assert_select "input[type=radio][name='goal[progress_basis]'][value=balance][checked]", 1+ assert_select "input[type=radio][name='goal[progress_basis]'][value=contributions][checked]", 0+ end++ # A completed goal's basis is frozen with its snapshot, so the form must not+ # offer a choice the model will refuse. Disabled radios are not submitted.+ test "the form locks the basis on a completed goal and says how to unlock it" do+ @goal.complete!++ get edit_goal_url(@goal)++ assert_response :success+ assert_select "input[type=radio][name='goal[progress_basis]'][disabled]", 2+ assert_select "p.text-secondary", text: "This goal's progress was frozen when it was completed. Reopen or restore it to change what counts toward it."+ end++ # Archiving a completed goal keeps its snapshot, so the basis stays locked,+ # but the page offers Restore rather than Reopen. The note has to name a+ # way out that the page actually shows.+ test "the form locks the basis on an archived completed goal and names restore" do+ @goal.complete!+ @goal.archive!++ get edit_goal_url(@goal)++ assert_response :success+ assert_select "input[type=radio][name='goal[progress_basis]'][disabled]", 2+ assert_select "p.text-secondary", text: "This goal's progress was frozen when it was completed. Reopen or restore it to change what counts toward it."+ end++ test "update refuses a basis change on an archived completed goal and names restore" do+ @goal.complete!+ @goal.archive!++ patch goal_url(@goal), params: { goal: { progress_basis: "contributions" } }++ assert_response :unprocessable_entity+ assert_equal "balance", @goal.reload.progress_basis+ assert_select "p.text-destructive", text: "Reopen or restore this goal before changing what counts toward it."+ end++ test "the form leaves the basis editable on an active goal" do+ get edit_goal_url(@goal)++ assert_response :success+ assert_select "input[type=radio][name='goal[progress_basis]']", 2+ assert_select "input[type=radio][name='goal[progress_basis]'][disabled]", 0+ assert_not_includes response.body, I18n.t("goals.form.progress_basis_locked")+ end++ # What the locked form actually submits: everything but the basis.+ test "an ordinary edit of a completed goal still saves" do+ @goal.complete!++ patch goal_url(@goal), params: { goal: { name: "Italy, done" } }++ assert_redirected_to goal_path(@goal)+ assert_equal "Italy, done", @goal.reload.name+ assert_equal "balance", @goal.progress_basis+ end++ test "the basis of another family's goal cannot be changed" do+ other_family = families(:empty)+ account = Account.create!(family: other_family, accountable: Depository.new, name: "Theirs", currency: "USD", balance: 500)+ theirs = other_family.goals.create!(name: "Theirs", target_amount: 1_000, currency: "USD") { |g| g.goal_accounts.build(account: account) }++ patch goal_url(theirs), params: { goal: { progress_basis: "contributions" } }++ assert_redirected_to goals_path+ assert_equal "balance", theirs.reload.progress_basis+ end++ test "the form offers both progress bases with the current one selected" do+ @goal.update_columns(progress_basis: "contributions")++ get edit_goal_url(@goal)++ assert_response :success+ assert_select "input[type=radio][name='goal[progress_basis]']", 2+ assert_select "input[type=radio][name='goal[progress_basis]'][value=contributions][checked]", 1+ assert_includes response.body, I18n.t("goals.form.progress_bases.balance.label")+ assert_includes response.body, I18n.t("goals.form.progress_bases.contributions.label")+ end++ test "the goal page says which basis its progress counts" do+ get goal_url(@goal)+ assert_includes response.body, I18n.t("goals.show.ring.basis.balance")+ assert_not_includes response.body, I18n.t("goals.show.ring.basis.contributions")++ @goal.update_columns(progress_basis: "contributions")+ get goal_url(@goal)+ assert_includes response.body, I18n.t("goals.show.ring.basis.contributions")+ assert_not_includes response.body, I18n.t("goals.show.ring.basis.balance")+ end++ # A completed goal shows its frozen snapshot, so its caption must not say+ # the figure is what the accounts are worth today.+ test "a completed goal's basis caption describes the completion snapshot" do+ get goal_url(@goal)+ assert_includes response.body, I18n.t("goals.show.ring.basis.balance")+ assert_not_includes response.body, I18n.t("goals.show.ring.basis_at_completion.balance")++ @goal.complete!+ assert @goal.reload.completed_amount.present?+ get goal_url(@goal)+ assert_includes response.body, I18n.t("goals.show.ring.basis_at_completion.balance")+ assert_not_includes response.body, I18n.t("goals.show.ring.basis.balance")++ # The basis can't change on a completed goal, so reach a contributions+ # snapshot the way a user would: reopen, switch, complete again.+ @goal.reopen!+ @goal.update!(progress_basis: "contributions")+ @goal.complete!+ assert @goal.reload.completed_amount.present?+ get goal_url(@goal)+ assert_includes response.body, I18n.t("goals.show.ring.basis_at_completion.contributions")+ assert_not_includes response.body, I18n.t("goals.show.ring.basis.contributions")+ end++ # `archive` accepts an active goal, which then has no snapshot and keeps the+ # live figure, so it keeps the live wording too.+ test "an archived goal that never completed keeps the live basis caption" do+ @goal.archive!+ assert_nil @goal.reload.completed_amount++ get goal_url(@goal)+ assert_includes response.body, I18n.t("goals.show.ring.basis.balance")+ assert_not_includes response.body, I18n.t("goals.show.ring.basis_at_completion.balance")+ end+test "update with empty account_ids re-renders with error" dopatch goal_url(@goal), params: { goal: { account_ids: [ "" ] } }assert_response :unprocessable_entitydiff --git a/test/models/goal/currency_conversion_test.rb b/test/models/goal/currency_conversion_test.rbindex e2366654e5..ebd92ffff0 100644--- a/test/models/goal/currency_conversion_test.rb+++ b/test/models/goal/currency_conversion_test.rb@@ -101,8 +101,11 @@ class Goal::CurrencyConversionTest < ActiveSupport::TestCasegoal = goal_on("USD", [ [ eur, nil ] ])goal.market_flows = { eur.id => 200 }rate("EUR", "USD", 1.2)+ assert_equal 1_200, goal.current_balance++ # The basis is the user's choice, never inferred from the account type.+ goal.update!(progress_basis: "contributions")- assert goal.contributions_basis?assert_equal 960, goal.current_balanceassert_equal 1_200, goal.market_value_money.amountenddiff --git a/test/models/goal_test.rb b/test/models/goal_test.rbindex 5fdec7ba15..b8f8ffbfd0 100644--- a/test/models/goal_test.rb+++ b/test/models/goal_test.rb@@ -144,21 +144,37 @@ class GoalTest < ActiveSupport::TestCaseassert_match(/at least one/i, new_goal.errors[:base].join)end- test "investment accounts are fundable and default to the contributions basis" do+ # A new goal counts what its accounts are worth today unless the user+ # chose otherwise, whatever kind of account backs it.+ test "investment accounts are fundable and a new goal defaults to the market value basis" doinvestment = accounts(:investment)new_goal = @family.goals.new(name: "Inv", target_amount: 100, currency: "USD")new_goal.goal_accounts.build(account: investment)assert new_goal.valid?, new_goal.errors.full_messages.to_sentence- new_goal.save! # basis is set on save (before_save), not on valid?- assert_equal "contributions", new_goal.progress_basis+ new_goal.save!+ assert_equal "balance", new_goal.reload.progress_basis+ end++ test "a new investment-backed goal keeps the contributions basis it was given" do+ new_goal = @family.goals.create!(name: "Inv", target_amount: 100, currency: "USD", progress_basis: "contributions") do |g|+ g.goal_accounts.build(account: accounts(:investment))+ end+ assert_equal "contributions", new_goal.reload.progress_basis+ end++ test "an unknown progress basis is rejected" do+ goal = goals(:emergency_fund)+ goal.progress_basis = "speculative"+ assert_not goal.valid?+ assert goal.errors[:progress_basis].any?end- test "crypto accounts are fundable and default to the contributions basis" do+ test "crypto accounts are fundable and stay on the basis the goal was given" donew_goal = @family.goals.new(name: "BTC", target_amount: 100, currency: "USD")new_goal.goal_accounts.build(account: accounts(:crypto))assert new_goal.valid?, new_goal.errors.full_messages.to_sentencenew_goal.save!- assert_equal "contributions", new_goal.progress_basis+ assert_equal "balance", new_goal.reload.progress_basisendtest "non-fundable account types are rejected" do@@ -612,6 +628,22 @@ class GoalTest < ActiveSupport::TestCaseassert_equal :depleted, Goal.find(goal.id).statusend+ # The floor sits between the account's value (6,000) and what was put in+ # (4,000), so the basis alone decides whether the reserve is whole.+ test "a reserve on an investment account on the balance basis counts market gains" do+ goal = investment_reserve(progress_basis: "balance")++ assert_equal :funded, goal.status+ assert_equal BigDecimal("6000"), goal.current_balance.to_d+ end++ test "a reserve on an investment account on the contributions basis leaves market gains out" do+ goal = investment_reserve(progress_basis: "contributions")++ assert_equal :depleted, goal.status+ assert_equal BigDecimal("4000"), goal.current_balance.to_d+ 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@@ -873,7 +905,7 @@ class GoalTest < ActiveSupport::TestCasetest "contributions basis excludes market gains" doaccount = Account.create!(family: @family, accountable: Investment.new, name: "Brokerage", currency: "USD", balance: 10_000)account.balances.create!(date: 10.days.ago.to_date, balance: 10_000, currency: "USD", net_market_flows: 3_000)- goal = @family.goals.create!(name: "Invest goal", target_amount: 20_000, currency: "USD") do |g|+ goal = @family.goals.create!(name: "Invest goal", target_amount: 20_000, currency: "USD", progress_basis: "contributions") do |g|g.goal_accounts.build(account: account)endassert_equal "contributions", goal.progress_basis@@ -910,18 +942,146 @@ class GoalTest < ActiveSupport::TestCaseassert_not pledge.matches?(entry, valuation_delta: 100)end- test "adding an investment account via update flips a depository goal to contributions" do+ # Linking an account never re-bases a goal. Before, this flipped a+ # balance goal to contributions, so an explicit choice of market value could+ # not survive the next save.+ test "adding an investment account via update keeps a balance goal on balance" dogoal = goals(:emergency_fund)assert_equal "balance", goal.progress_basisgoal.goal_accounts.build(account: accounts(:investment))goal.save!+ assert_equal "balance", goal.reload.progress_basis+ end++ test "an explicit market value choice survives saving and linking another account" do+ account = Account.create!(family: @family, accountable: Investment.new, name: "Brokerage M", currency: "USD", balance: 10_000)+ goal = @family.goals.create!(name: "Deposit", target_amount: 20_000, currency: "USD", progress_basis: "balance") do |g|+ g.goal_accounts.build(account: account)+ end+ goal.update!(name: "House deposit")+ assert_equal "balance", goal.reload.progress_basis++ goal.goal_accounts.build(account: accounts(:investment))+ goal.save!+ assert_equal "balance", goal.reload.progress_basis+ end++ test "a save does not re-base an existing contributions goal" do+ goal = goals(:emergency_fund)+ goal.update_columns(progress_basis: "contributions")+ goal.update!(name: "Renamed fund")+ assert_equal "contributions", goal.reload.progress_basis+ end++ # Delta, not presence: the same goal read on each basis differs by exactly the+ # account's recorded market gain, so a basis that silently stopped mattering+ # (or a reader that ignored it) would show no difference.+ test "switching basis moves the goal by exactly the market gain" do+ account = Account.create!(family: @family, accountable: Investment.new, name: "Brokerage S", currency: "USD", balance: 10_000)+ account.balances.create!(date: 10.days.ago.to_date, balance: 10_000, currency: "USD", net_market_flows: 3_000)+ goal = @family.goals.create!(name: "Switch goal", target_amount: 20_000, currency: "USD") do |g|+ g.goal_accounts.build(account: account)+ end+ # Each figure is read off a fresh record, so this measures the basis on its+ # own. Reading through the instance that was saved is the next test's job.+ on_market_value = Goal.find(goal.id).current_balance.to_d++ goal.update!(progress_basis: "contributions")+ on_contributions = Goal.find(goal.id).current_balance.to_d++ goal.update!(progress_basis: "balance")+ back_on_market_value = Goal.find(goal.id).current_balance.to_d++ assert_equal BigDecimal("10000"), on_market_value+ assert_equal BigDecimal("3000"), on_market_value - on_contributions+ assert_equal on_market_value, back_on_market_value+ end++ # The instance that took the save is the one a controller renders, so its+ # memos must follow the new basis. Read before and after on the SAME object:+ # a memo left standing would return the old figure and show no difference.+ test "changing basis refreshes the figures on the saved instance" do+ account = Account.create!(family: @family, accountable: Investment.new, name: "Brokerage R", currency: "USD", balance: 10_000)+ account.balances.create!(date: 10.days.ago.to_date, balance: 10_000, currency: "USD", net_market_flows: 3_000)+ goal = @family.goals.create!(name: "Refresh goal", target_amount: 20_000, currency: "USD") do |g|+ g.goal_accounts.build(account: account)+ end+ before_balance = goal.current_balance.to_d+ before_money = goal.current_balance_money+ before_percent = goal.progress_percent+ before_remaining = goal.remaining_amount.to_d++ goal.update!(progress_basis: "contributions")++ assert_equal BigDecimal("3000"), before_balance - goal.current_balance.to_d+ assert_equal Money.new(3_000, "USD"), before_money - goal.current_balance_money+ assert_equal BigDecimal("3000"), goal.remaining_amount.to_d - before_remaining+ assert_equal 50, before_percent+ assert_equal 35, goal.progress_percent+ end++ # A completed goal reports the amount frozen when it closed, measured on the+ # basis it had then. Switching basis afterwards would put the new label on+ # the old figure, so the switch is refused until the goal is reopened.+ test "a completed goal refuses a basis change and keeps its snapshot" do+ account = Account.create!(family: @family, accountable: Investment.new, name: "Brokerage C", currency: "USD", balance: 10_000)+ account.balances.create!(date: 10.days.ago.to_date, balance: 10_000, currency: "USD", net_market_flows: 3_000)+ goal = @family.goals.create!(name: "Closed invest", target_amount: 20_000, currency: "USD", progress_basis: "contributions") do |g|+ g.goal_accounts.build(account: account)+ end+ goal.complete!+ snapshot = goal.reload.completed_amount+ assert_equal BigDecimal("7000"), snapshot.to_d++ assert_not goal.update(progress_basis: "balance")+ assert goal.errors.of_kind?(:progress_basis, :locked_once_completed)+ assert_equal "contributions", goal.reload.progress_basis+ assert_equal snapshot, goal.completed_amount+ end++ # Reopening in the same write must not slip the change through: the persisted+ # snapshot is what the lock reads, as kind_locked_while_released does.+ test "a completed goal refuses a basis change written alongside state active" do+ goal = goals(:emergency_fund)+ goal.complete!++ assert_not goal.update(state: "active", progress_basis: "contributions")+ assert goal.errors.of_kind?(:progress_basis, :locked_once_completed)+ assert_equal "balance", goal.reload.progress_basis+ end++ # The edit form resubmits the basis the goal already has, so an ordinary edit+ # of a completed goal must not trip the lock.+ test "a completed goal still saves an edit that resubmits its own basis" do+ goal = goals(:emergency_fund)+ goal.complete!++ assert goal.update(name: "Fund, done", progress_basis: "balance")+ assert_equal "Fund, done", goal.reload.name+ end++ test "an archived goal that never completed can still change basis" do+ goal = goals(:emergency_fund)+ goal.archive!+ assert_nil goal.reload.completed_amount++ assert goal.update(progress_basis: "contributions")+ assert_equal "contributions", goal.reload.progress_basis+ end++ test "reopening a completed goal frees its basis again" do+ goal = goals(:emergency_fund)+ goal.complete!+ goal.reopen!++ assert goal.update(progress_basis: "contributions")assert_equal "contributions", goal.reload.progress_basisendtest "earmark is respected on a contributions-basis goal" doaccount = Account.create!(family: @family, accountable: Investment.new, name: "Brokerage2", currency: "USD", balance: 10_000)account.balances.create!(date: 5.days.ago.to_date, balance: 10_000, currency: "USD", net_market_flows: 2_000)- goal = @family.goals.create!(name: "Earmarked invest", target_amount: 20_000, currency: "USD") do |g|+ goal = @family.goals.create!(name: "Earmarked invest", target_amount: 20_000, currency: "USD", progress_basis: "contributions") do |g|g.goal_accounts.build(account: account, allocated_amount: 1_000)endassert_equal "contributions", goal.progress_basis@@ -1733,6 +1893,14 @@ class GoalTest < ActiveSupport::TestCaseendend+ def investment_reserve(progress_basis:)+ account = Account.create!(family: @family, accountable: Investment.new, name: "Reserve brokerage", currency: "USD", balance: 6_000)+ account.balances.create!(date: 10.days.ago.to_date, balance: 6_000, currency: "USD", net_market_flows: 2_000)+ @family.goals.create!(name: "Invested reserve", target_amount: 5_000, currency: "USD", kind: "maintained", progress_basis: progress_basis) do |g|+ g.goal_accounts.build(account: account)+ end+ end+def reserve_goal(balance:, target:, allocated: nil, name: "Emergency reserve")account = Account.create!(family: @family, accountable: Depository.new,