The personal finance app for everyone (by everyone)
Ruby
Allow crypto accounts to fund goals (#4432)
Artem Danilov1d0f5328a039
diff --git a/app/models/account.rb b/app/models/account.rbindex 120a9393b1..ac56db95b4 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -641,10 +641,10 @@ class Account < ApplicationRecord# decision in one place so the new-pledge controller / preview helper# can't disagree on what they're going to save.def default_pledge_kind- # Investment accounts never use manual_save: a positive valuation delta on a- # brokerage is usually a market move, not a deposit, and would false-match a- # pledge. They resolve on transfer (cash-inflow) entries only.- manual? && !investment? ? "manual_save" : "transfer"+ # Investment and crypto accounts never use manual_save: a positive valuation+ # delta there is usually a market move, not a deposit, and would false-match+ # a pledge. They resolve on transfer (cash-inflow) entries only.+ manual? && balance_type != :investment ? "manual_save" : "transfer"end# Total fixed earmark this account currently has reserved across every goaldiff --git a/app/models/account/reconciliation_manager.rb b/app/models/account/reconciliation_manager.rbindex 242ab2d0df..9eb9e71ff4 100644--- a/app/models/account/reconciliation_manager.rb+++ b/app/models/account/reconciliation_manager.rb@@ -70,9 +70,9 @@ class Account::ReconciliationManager# first reconciliation's full balance is its contribution.## The delta is only ever consumed by manual_save pledges, which never- # attach to investment accounts: Account#default_pledge_kind forces+ # attach to investment or crypto accounts: Account#default_pledge_kind forces# `transfer` there and GoalPledge#matches? rejects valuation deltas on- # investment accounts (a market move isn't a deposit). So a positive delta+ # them (a market move isn't a deposit). So a positive delta# only feeds depository saves, where balances are positive and a positive# delta really is a deposit — the reconciler's positive-delta guard holds.def valuation_contribution(valuation, prior_valuation_amount, old_balance_components)diff --git a/app/models/goal.rb b/app/models/goal.rbindex 06e886b7de..ceb12fb022 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -36,7 +36,7 @@ class Goal < ApplicationRecordvalidates :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_investment+ before_save :default_progress_basis_for_market_accounts# 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@@ -102,7 +102,7 @@ class Goal < ApplicationRecordmonetize :target_amount# Account types that can back a goal (see linked_accounts_must_be_fundable).- FUNDABLE_ACCOUNT_TYPES = %w[Depository Investment].freeze+ FUNDABLE_ACCOUNT_TYPES = %w[Depository Investment Crypto].freeze# States in which a goal has let go of the money it was holding, and so# drops out of the shared pool. `completed` belongs here: reaching a goal@@ -954,7 +954,7 @@ class Goal < ApplicationRecordend# "I just transferred" when any linked account resolves pledges via a transfer- # (synced accounts AND investment accounts, per default_pledge_kind); "I just+ # (synced accounts AND investment/crypto accounts, per default_pledge_kind); "I just# saved" only for manual cash accounts. Keyed off default_pledge_kind so the# copy matches the kind actually saved — a manual brokerage uses transfer, not# manual_save, so it must not show the "update your manual balance" path.@@ -1367,18 +1367,19 @@ class Goal < ApplicationRecorddef linked_accounts_must_be_fundableoffending = goal_accounts.reject(&:marked_for_destruction?).reject do |sga|- sga.account&.depository? || sga.account&.investment?+ FUNDABLE_ACCOUNT_TYPES.include?(sga.account&.accountable_type)endreturn if offending.empty?errors.add(:linked_accounts, :must_be_fundable)end- # Goals funded by an investment 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_investment- return unless goal_accounts.any? { |ga| ga.account&.investment? }+ # 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"diff --git a/app/models/goal_pledge.rb b/app/models/goal_pledge.rbindex 82160c2fe4..02e432ae25 100644--- a/app/models/goal_pledge.rb+++ b/app/models/goal_pledge.rb@@ -61,9 +61,9 @@ class GoalPledge < ApplicationRecordis_valuation = entry.entryable.is_a?(Valuation)if is_valuation- # Never match a valuation delta on an investment account: it may be a- # market move, not a deposit, and would false-match (investment goals).- return false if account&.investment?+ # Never match a valuation delta on an investment or crypto account: it may+ # be a market move, not a deposit, and would false-match.+ return false if account&.balance_type == :investmentreturn false if valuation_delta.nil? || valuation_delta.to_d <= 0elsif kind_transfer? && !entry.amount.to_d.negative?return falsediff --git a/config/locales/models/goal/ca.yml b/config/locales/models/goal/ca.ymlindex 7445066134..ff7e7e275f 100644--- a/config/locales/models/goal/ca.yml+++ b/config/locales/models/goal/ca.yml@@ -24,7 +24,7 @@ ca:blank: Indica quants mesos de despeses ha de cobrir aquesta reserva.only_with_months_mode: Els mesos de despeses només s'apliquen quan l'objectiu es defineix d'aquesta manera.linked_accounts:- must_be_fundable: Tots els comptes enllaçats han de ser comptes d'efectiu o d'inversió.+ must_be_fundable: Tots els comptes enllaçats han de ser comptes d'efectiu, d'inversió o de criptomonedes.must_belong_to_family: Els comptes enllaçats han de pertànyer a la mateixa família que l'objectiu.kind:locked_while_released: Torna a obrir aquest objectiu abans de convertir-lo en una reserva.diff --git a/config/locales/models/goal/de.yml b/config/locales/models/goal/de.ymlindex 80a37cf4b4..459df6925e 100644--- a/config/locales/models/goal/de.yml+++ b/config/locales/models/goal/de.yml@@ -20,5 +20,5 @@ de:currency:locked_after_linked: Die Währung lässt sich nicht mehr ändern, sobald das Ziel mit Konten verknüpft ist.linked_accounts:- must_be_fundable: Alle verknüpften Konten müssen Bank- oder Investmentkonten sein.+ 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.diff --git a/config/locales/models/goal/en.yml b/config/locales/models/goal/en.ymlindex 3b1797a097..e253915ded 100644--- a/config/locales/models/goal/en.yml+++ b/config/locales/models/goal/en.yml@@ -25,7 +25,7 @@ en:blank: Say how many months of expenses this reserve should cover.only_with_months_mode: Months of expenses only apply when the target is set that way.linked_accounts:- must_be_fundable: All linked accounts must be cash or investment accounts.+ must_be_fundable: All linked accounts must be cash, investment or crypto accounts.must_belong_to_family: Linked accounts must belong to the same family as the goal.kind:locked_while_released: Reopen this goal before turning it into a reserve.diff --git a/config/locales/models/goal/es.yml b/config/locales/models/goal/es.ymlindex 8178cbd24e..58b4e30364 100644--- a/config/locales/models/goal/es.yml+++ b/config/locales/models/goal/es.yml@@ -18,7 +18,7 @@ es:base:at_least_one_linked_account_required: Elige al menos una cuenta para financiar este objetivo.linked_accounts:- must_be_fundable: Todas las cuentas vinculadas deben ser cuentas de efectivo o de inversión.+ must_be_fundable: Todas las cuentas vinculadas deben ser cuentas de efectivo, de inversión o de criptomonedas.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.diff --git a/config/locales/models/goal/fr.yml b/config/locales/models/goal/fr.ymlindex c995f00647..028b92333f 100644--- a/config/locales/models/goal/fr.yml+++ b/config/locales/models/goal/fr.yml@@ -32,5 +32,5 @@ fr:blank: Indiquez combien de mois de dépenses cette réserve doit couvrir.only_with_months_mode: Les mois de dépenses ne s'appliquent que si la cible est exprimée ainsi.linked_accounts:- must_be_fundable: Tous les comptes liés doivent être des comptes de trésorerie ou d'investissement.+ 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.diff --git a/config/locales/models/goal/it.yml b/config/locales/models/goal/it.ymlindex 8a7c144def..78446f53c6 100644--- a/config/locales/models/goal/it.yml+++ b/config/locales/models/goal/it.yml@@ -18,7 +18,7 @@ it:base:at_least_one_linked_account_required: Scegli almeno un conto per finanziare questo obiettivo.linked_accounts:- must_be_fundable: Tutti i conti collegati devono essere conti correnti o conti di investimento.+ must_be_fundable: Tutti i conti collegati devono essere conti correnti, conti di investimento o conti cripto.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.diff --git a/config/locales/models/goal/pl.yml b/config/locales/models/goal/pl.ymlindex b7c064c3ce..c795948008 100644--- a/config/locales/models/goal/pl.yml+++ b/config/locales/models/goal/pl.yml@@ -29,8 +29,8 @@ pl:locked_while_released: Otwórz ponownie ten cel, zanim zmienisz go wrezerwę.linked_accounts:- must_be_fundable: Wszystkie połączone konta muszą być kontami gotówkowymi- lub inwestycyjnymi.+ must_be_fundable: Wszystkie połączone konta muszą być kontami gotówkowymi, inwestycyjnymi+ lub kryptowalutowymi.must_belong_to_family: Połączone konta muszą należeć do tej samej rodzinyco cel.target_amount:diff --git a/config/locales/models/goal/pt-PT.yml b/config/locales/models/goal/pt-PT.ymlindex ea420c8bb1..2c8601a992 100644--- a/config/locales/models/goal/pt-PT.yml+++ b/config/locales/models/goal/pt-PT.yml@@ -24,7 +24,7 @@ pt-PT:blank: Indique quantos meses de despesas esta reserva deve cobrir.only_with_months_mode: Os meses de despesas só se aplicam quando o objetivo é definido dessa forma.linked_accounts:- must_be_fundable: Todas as contas associadas têm de ser contas de dinheiro ou de investimento.+ must_be_fundable: Todas as contas associadas têm de ser contas de dinheiro, de investimento ou de criptomoedas.must_belong_to_family: As contas associadas têm de pertencer à mesma família que o objetivo.kind:locked_while_released: Reabra este objetivo antes de o transformar numa reserva.diff --git a/config/locales/models/goal/ru.yml b/config/locales/models/goal/ru.ymlindex 95035e28fe..fd9ee51e46 100644--- a/config/locales/models/goal/ru.yml+++ b/config/locales/models/goal/ru.yml@@ -22,8 +22,7 @@ ru:currency:locked_after_linked: Нельзя изменить валюту после привязки счетов к цели.linked_accounts:- must_be_fundable: Все связанные счета должны быть денежными или- инвестиционными.+ must_be_fundable: Все связанные счета должны быть денежными, инвестиционными или криптовалютными.must_belong_to_family: Связанные счета должны принадлежать той же семье/группе,что и цель.target_mode:diff --git a/config/locales/models/goal/tr.yml b/config/locales/models/goal/tr.ymlindex 611b6a1226..5026bb0ce8 100644--- a/config/locales/models/goal/tr.yml+++ b/config/locales/models/goal/tr.yml@@ -23,7 +23,7 @@ tr:locked_after_linked: Hedef hesaplara bağlandıktan sonra para birimideğiştirilemez.linked_accounts:- must_be_fundable: Bağlı tüm hesaplar nakit veya yatırım hesabı olmalıdır.+ must_be_fundable: Bağlı tüm hesaplar nakit, yatırım veya kripto hesabı olmalıdır.must_belong_to_family: Bağlı hesaplar, hedefle aynı aileye ait olmalıdır.target_mode:months_requires_maintained: Yalnızca sürdürdüğünüz bir rezervin hedefi aylık gider cinsinden belirlenebilir.diff --git a/config/locales/models/goal/uk.yml b/config/locales/models/goal/uk.ymlindex b09602c7da..75ba46f1d2 100644--- a/config/locales/models/goal/uk.yml+++ b/config/locales/models/goal/uk.yml@@ -19,7 +19,7 @@ uk:at_least_one_linked_account_required: "Виберіть принаймні один рахунок для фінансування цієї цілі."whole_account_conflict_on_restore: 'Неможливо відновити цю ціль: рахунок «%{account_name}» тепер повністю виділено для цілі «%{goal_name}». Спершу вкажіть суму для однієї з них.'linked_accounts:- must_be_fundable: "Всі прив'язані рахунки мають бути грошовими або інвестиційними."+ must_be_fundable: "Всі прив'язані рахунки мають бути грошовими, інвестиційними або криптовалютними."must_belong_to_family: "Прив'язані рахунки повинні належати до тієї ж сім'ї, що й ціль."currency:locked_after_linked: "Неможливо змінити валюту після прив'язки цілі до рахунків."diff --git a/config/locales/models/goal/zh-CN.yml b/config/locales/models/goal/zh-CN.ymlindex 1736ee68d4..a7e82d372f 100644--- a/config/locales/models/goal/zh-CN.yml+++ b/config/locales/models/goal/zh-CN.yml@@ -20,7 +20,7 @@ zh-CN:missing_exchange_rate: 此目标关联的其中一个账户目前没有可用汇率,因此无法完成。whole_account_conflict_on_restore: 无法恢复此目标:“%{account_name}” 目前已全部预留给“%{goal_name}”。请先在其中一个目标中输入具体金额。linked_accounts:- must_be_fundable: 所有关联账户必须是现金或投资账户。+ must_be_fundable: 所有关联账户必须是现金、投资或加密货币账户。must_belong_to_family: 关联账户必须属于与目标相同的家庭。currency:locked_after_linked: 目标关联账户后不能更改货币。diff --git a/config/locales/models/goal/zh-TW.yml b/config/locales/models/goal/zh-TW.ymlindex 2bb6ae550f..bae34d0c16 100644--- a/config/locales/models/goal/zh-TW.yml+++ b/config/locales/models/goal/zh-TW.yml@@ -18,7 +18,7 @@ zh-TW:base:at_least_one_linked_account_required: 請至少選擇一個帳戶來支應這個目標。linked_accounts:- must_be_fundable: 所有已連結的帳戶都必須是現金或投資帳戶。+ must_be_fundable: 所有已連結的帳戶都必須是現金、投資或加密貨幣帳戶。must_belong_to_family: 已連結的帳戶必須和這個目標屬於同一個家庭。currency:locked_after_linked: 目標連結帳戶之後就不能再更改幣別了。diff --git a/docs/llm-guides/goals.md b/docs/llm-guides/goals.mdindex 48ed075e0d..d6f68c6e23 100644--- a/docs/llm-guides/goals.md+++ b/docs/llm-guides/goals.md@@ -92,25 +92,29 @@ Locales:A goal records a name, target amount, optional target date, color, optionalicon, optional notes, currency, and an AASM `state` (`active` / `paused` /-`completed` / `archived`). It links cash and investment accounts via the join-table `goal_accounts`.+`completed` / `archived`). It links cash, investment and crypto accounts via the+join table `goal_accounts`.The goal's *progress* is its allocated share of linked accounts, converted toits currency at request time. `Goal#current_balance` preserves native account-allocations and shared-pool limits before conversion. Investment-backed goals-default to contribution progress, excluding cumulative market gains from their-backing; `market_value_money` separately shows the current market value.+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.A `GoalPledge` is an intent: amount, account, kind, status, expires_at.The status enum is `open` / `matched` / `cancelled` / `expired`. The kind-enum is `transfer` / `manual_save`; kind is decided at create time from-the selected account's connection state.+enum is `transfer` / `manual_save`; kind is decided at create time by+`Account#default_pledge_kind` (see "Connected vs manual accounts").## Currencies and account allocations-A goal can link cash and investment accounts in different currencies. New goals-use the family's display currency, matching the target field; an existing goal's-currency remains locked. Target, progress, consumed amount and pledges use goal+A goal can link cash, investment and crypto accounts in different currencies.+New goals use the family's display currency, matching the target field; an+existing goal's currency remains locked. Target, progress, consumed amount and pledges use goalcurrency. Each `GoalAccount#allocated_amount` remains in its account's currency.Shared-pool allocation and pro-rata scaling happen before conversion, so goalswith different currencies cannot double-count the same account.@@ -212,14 +216,16 @@ would otherwise touch `updated_at` on every matched pledge and reset the`account_providers` association rows, no `plaid_account_id`, and no`simplefin_account_id`. This mirrors the `Account.manual` query scope.-`Goal#any_connected_account?` returns true when *any* linked account is-not manual. It drives the modal-title copy: connected accounts get-"I just transferred…", manual-only goals get "I just saved…"+`Account#default_pledge_kind` is per-account: manual cash accounts get+`manual_save`; connected accounts and every investment or crypto account+(`balance_type == :investment`, manual or not) get `transfer`, because a+positive valuation delta there is usually a market move, not a deposit. A+goal with one manual and one connected linked account works correctly; the+kind reflects the specific account the user picked, not the goal as a whole.-`GoalPledgesController#kind_for_account(account)` is per-account:-manual → `manual_save`, connected → `transfer`. A goal with one manual-and one connected linked account works correctly; the kind reflects the-specific account the user picked, not the goal as a whole.+`Goal#pledge_action_label_key` picks the modal copy from the same method:+"I just transferred…" when any linked account uses `transfer`, "I just+saved…" otherwise.## Color mapdiff --git a/test/models/goal_test.rb b/test/models/goal_test.rbindex 78883e1edc..4e791134d4 100644--- a/test/models/goal_test.rb+++ b/test/models/goal_test.rb@@ -153,12 +153,20 @@ class GoalTest < ActiveSupport::TestCaseassert_equal "contributions", new_goal.progress_basisend+ test "crypto accounts are fundable and default to the contributions basis" do+ new_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_sentence+ new_goal.save!+ assert_equal "contributions", new_goal.progress_basis+ end+test "non-fundable account types are rejected" docredit = accounts(:credit_card)new_goal = @family.goals.new(name: "Test", target_amount: 100, currency: "USD")new_goal.goal_accounts.build(account: credit)assert_not new_goal.valid?- assert_includes new_goal.errors[:linked_accounts], "All linked accounts must be cash or investment accounts."+ assert_includes new_goal.errors[:linked_accounts], "All linked accounts must be cash, investment or crypto accounts."endtest "linked accounts must belong to family" do@@ -886,6 +894,22 @@ class GoalTest < ActiveSupport::TestCaseassert_equal "transfer", accounts(:investment).default_pledge_kindend+ test "manual crypto accounts default to transfer pledge kind, never manual_save" do+ crypto = accounts(:crypto)+ assert crypto.manual?+ assert_equal "transfer", crypto.default_pledge_kind+ end++ test "a valuation delta on a crypto account never matches a pledge" do+ crypto = accounts(:crypto)+ goal = goals(:vacation_italy)+ goal.goal_accounts.create!(account: crypto)+ pledge = goal.goal_pledges.create!(account: crypto, amount: 100, kind: "manual_save")+ entry = crypto.entries.create!(name: "Reconciliation", date: Date.current, amount: 1100, currency: crypto.currency,+ entryable: Valuation.new(kind: "reconciliation"))+ assert_not pledge.matches?(entry, valuation_delta: 100)+ end+test "adding an investment account via update flips a depository goal to contributions" dogoal = goals(:emergency_fund)assert_equal "balance", goal.progress_basis