Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(goals): investment-backed goals (Phase 2) (#2491)

Guillem Arias Faustec5ca0431c9a5
diff --git a/app/controllers/goals_controller.rb b/app/controllers/goals_controller.rb
index e77db03671..ae0ccb8b27 100644
--- a/app/controllers/goals_controller.rb
+++ b/app/controllers/goals_controller.rb
@@ -1,6 +1,8 @@
class GoalsController < ApplicationController
before_action :require_preview_features!
- before_action :set_goal, only: %i[show edit update destroy pause resume complete archive unarchive]
+ before_action :set_goal, only: %i[show edit update destroy pause resume complete archive unarchive reopen]
+
+ FUNDABLE_TYPES = %w[Depository Investment].freeze
rescue_from ActiveRecord::RecordNotFound, with: :goal_not_found
STATE_FILTERS = %w[all active paused completed archived].freeze
@@ -26,12 +28,16 @@ class GoalsController < ApplicationController
# entirely (rendered with filterable: false).
@grid_goals = @active_goals + @completed_goals
- # One family-wide earmark-pool query injected into every rendered goal so
- # the shared-pool backing math doesn't fire a query per card (N+1).
+ # One family-wide earmark-pool + market-flows query injected into every
+ # rendered goal so the backing math doesn't fire a query per card (N+1).
pooled = Goal.pooled_allocations_for(Current.family)
- (@grid_goals + @archived_goals).each { |goal| goal.pooled_allocations = pooled }
+ flows = Goal.market_flows_for(Current.family)
+ (@grid_goals + @archived_goals).each do |goal|
+ goal.pooled_allocations = pooled
+ goal.market_flows = flows
+ end
- @linkable_account_count = Current.user.accessible_accounts.where(accountable_type: "Depository").visible.count
+ @linkable_account_count = Current.user.accessible_accounts.where(accountable_type: FUNDABLE_TYPES).visible.count
@kpi = kpi_payload(@active_goals)
@any_pending_pledge = @active_goals.any? { |g| g.open_pledges.any? }
@show_search = @grid_goals.size > 6
@@ -152,6 +158,10 @@ class GoalsController < ApplicationController
perform_transition!(:unarchive)
end
+ def reopen
+ perform_transition!(:reopen)
+ end
+
private
def set_goal
@goal = Current.family.goals
@@ -175,11 +185,11 @@ class GoalsController < ApplicationController
return [] if ids.blank?
ids = Array(ids).reject(&:blank?)
- Current.user.accessible_accounts.where(accountable_type: "Depository").visible.where(id: ids).to_a
+ Current.user.accessible_accounts.where(accountable_type: FUNDABLE_TYPES).visible.where(id: ids).to_a
end
def linkable_accounts_for_new
- Current.user.accessible_accounts.where(accountable_type: "Depository").visible.alphabetically.to_a
+ Current.user.accessible_accounts.where(accountable_type: FUNDABLE_TYPES).visible.alphabetically.to_a
end
def sync_linked_accounts!(goal, accounts, allocations = {})
diff --git a/app/models/account.rb b/app/models/account.rb
index d137831d81..ebedd279fd 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -407,7 +407,30 @@ 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
- manual? ? "manual_save" : "transfer"
+ # 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"
+ end
+
+ # Total fixed earmark this account currently has reserved across every
+ # non-archived goal (unallocated/whole-balance links reserve no fixed
+ # slice). Mirrors Budget#allocated_spending.
+ def goal_earmarked_total
+ GoalAccount.joins(:goal)
+ .where(account_id: id)
+ .where.not(allocated_amount: nil)
+ .where.not(goals: { state: "archived" })
+ .sum(:allocated_amount)
+ .to_d
+ end
+
+ # Headroom left to earmark toward goals before fixed allocations exceed the
+ # balance. Negative means the account is over-earmarked. Intended to back a
+ # non-blocking over-allocation warning (UI is a follow-up). Mirrors
+ # Budget#available_to_allocate.
+ def free_to_earmark
+ balance.to_d - goal_earmarked_total
end
# Total fixed earmark this account currently has reserved across every
diff --git a/app/models/account/reconciliation_manager.rb b/app/models/account/reconciliation_manager.rb
index 8d2a3331ee..dd6915f34c 100644
--- a/app/models/account/reconciliation_manager.rb
+++ b/app/models/account/reconciliation_manager.rb
@@ -69,12 +69,12 @@ class Account::ReconciliationManager
# 3. 0, for a brand-new account with no balance record yet, so the
# first reconciliation's full balance is its contribution.
#
- # The delta is only ever consumed for goal-linked accounts, which Goal
- # validates to be Depository assets (Goal#linked_accounts_must_be_depository).
- # Balances there are positive, so a save (deposit) is a positive delta and
- # the reconciler's positive-delta guard is correct. There is no liability
- # sign concern: a credit-card/loan paydown can't reach pledge matching
- # because no manual_save pledge can be attached to a non-depository account.
+ # The delta is only ever consumed by manual_save pledges, which never
+ # attach to investment 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
+ # 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)
prior_balance = prior_valuation_amount || old_balance_components[:balance] || 0
valuation.amount.to_d - prior_balance.to_d
diff --git a/app/models/goal.rb b/app/models/goal.rb
index 3dbc78ac11..51935a86e5 100644
--- a/app/models/goal.rb
+++ b/app/models/goal.rb
@@ -21,8 +21,12 @@ class Goal < ApplicationRecord
validates :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_investment
+
validate :must_have_at_least_one_linked_account
- validate :linked_accounts_must_be_depository
+ validate :linked_accounts_must_be_fundable
validate :linked_accounts_must_match_goal_currency
validate :linked_accounts_must_belong_to_family
validate :currency_locked_once_linked
@@ -56,6 +60,19 @@ class Goal < ApplicationRecord
attr_writer :pooled_allocations
+ # 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)
+ return {} if account_ids.empty?
+
+ Balance.where(account_id: account_ids).group(:account_id).sum(:net_market_flows)
+ end
+
+ attr_writer :market_flows
+
aasm column: :state do
after_all_transitions :reset_state_dependent_caches!
@@ -83,6 +100,10 @@ class Goal < ApplicationRecord
event :unarchive do
transitions from: :archived, to: :active
end
+
+ event :reopen do
+ transitions from: :completed, to: :active
+ end
end
# Balance is this goal's backing across its linked depository accounts that
@@ -100,7 +121,7 @@ class Goal < ApplicationRecord
Rails.logger.warn("Goal##{id} linked-account currency drift: #{linked_accounts.size - matching.size} of #{linked_accounts.size} mismatched (expected #{currency})")
Sentry.capture_message("Goal linked-account currency drift", level: :warning, extra: { goal_id: id, expected_currency: currency }) if defined?(Sentry)
end
- matching.sum { |account| backing_balance_for(account) }
+ matching.sum { |account| account_amount_for(account) }
end
end
@@ -112,7 +133,19 @@ class Goal < ApplicationRecord
# the whole-balance remainder when the link is unallocated — as Money. Used
# by the funding breakdown so the per-account rows reconcile with the ring.
def account_backing(account)
- Money.new(backing_balance_for(account), currency)
+ Money.new(account_amount_for(account), currency)
+ end
+
+ def contributions_basis?
+ progress_basis == "contributions"
+ end
+
+ # Market value of the goal's backing (balance basis), regardless of the
+ # progress basis — the "what it's worth today" figure shown next to
+ # contributions on an investment-backed goal.
+ def market_value_money
+ amount = linked_accounts.select { |a| a.currency == currency }.sum { |a| backing_share_for(a, a.balance.to_d) }
+ Money.new(amount, currency)
end
def remaining_amount
@@ -331,9 +364,17 @@ class Goal < ApplicationRecord
linked_accounts.any? { |a| !a.manual? }
end
- # "I just transferred" for bank-connected accounts, "I just saved" for manual-only.
+ # "I just transferred" when any linked account resolves pledges via a transfer
+ # (synced accounts AND investment 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.
def pledge_action_label_key
- any_connected_account? ? "goals.show.pledge_just_transferred" : "goals.show.pledge_just_saved"
+ pledges_use_transfer? ? "goals.show.pledge_just_transferred" : "goals.show.pledge_just_saved"
+ end
+
+ def pledges_use_transfer?
+ linked_accounts.any? { |a| a.default_pledge_kind == "transfer" }
end
# { account_id => palette_hex } for this goal's linked accounts. Stable
@@ -445,20 +486,36 @@ class Goal < ApplicationRecord
end
private
- # This goal's share of `account`'s live balance under the family-wide
- # shared pool. The goal's OWN earmark is read from its own goal_accounts
- # (reliable even for an archived goal, which is excluded from the pool);
- # OTHER non-archived goals' fixed earmarks come from the shared pool. A
- # fixed earmark takes its slice; an unallocated link takes the balance left
- # after others' fixed earmarks (so it keeps the v1 whole-balance behaviour
- # when nothing else earmarks the account). When the fixed earmarks on an
- # account exceed its balance every fixed slice is scaled down pro-rata (to
- # within sub-cent rounding) so the goals' shares effectively never sum past
- # the account's balance — no double-counting. An overdrawn (<= 0) account
- # backs nothing.
- def backing_balance_for(account)
- balance = account.balance.to_d
- return 0.to_d if balance <= 0
+ # This goal's amount from one linked account under the active progress
+ # basis: net contributions (market-gain-excluded, floored at 0) on the
+ # contributions basis, or the allocation-aware backing balance otherwise.
+ def account_amount_for(account)
+ base = contributions_basis? ? net_contributed_for(account) : account.balance.to_d
+ backing_share_for(account, base)
+ end
+
+ # Net contributions into `account` to date = current value minus cumulative
+ # market gain/loss (sum of balances.net_market_flows), floored at 0.
+ # Depository accounts have zero net_market_flows, so this equals their
+ # balance. The per-account base on the contributions basis.
+ def net_contributed_for(account)
+ market_gain = (market_flows[account.id] || 0).to_d
+ [ account.balance.to_d - market_gain, 0.to_d ].max
+ end
+
+ # This goal's share of one linked account given a per-account `base` amount
+ # (the live balance on the balance basis, net contributions on the
+ # contributions basis). Shared-pool semantics are the same either way: the
+ # goal's OWN earmark is read from its own goal_accounts (reliable even for
+ # an archived goal, which is excluded from the pool); OTHER non-archived
+ # goals' fixed earmarks come from the shared pool. A fixed earmark takes its
+ # slice; an unallocated link takes the remainder after others' fixed
+ # earmarks. When fixed earmarks exceed the base they're scaled down pro-rata
+ # (to within sub-cent rounding) so shares never sum past it — no
+ # double-counting. A non-positive base backs nothing.
+ def backing_share_for(account, base)
+ base = base.to_d
+ return 0.to_d if base <= 0
mine = own_allocation_for(account)
others_fixed = (pooled_allocations[account.id] || [])
@@ -467,13 +524,13 @@ class Goal < ApplicationRecord
if mine
total_fixed = others_fixed + mine
- if total_fixed > balance && total_fixed.positive?
- (mine * (balance / total_fixed)).round(4) # pro-rata haircut
+ if total_fixed > base && total_fixed.positive?
+ (mine * (base / total_fixed)).round(4) # pro-rata haircut
else
mine
end
else
- [ balance - others_fixed, 0 ].max # unallocated link: the remainder
+ [ base - others_fixed, 0 ].max # unallocated link: the remainder
end
end
@@ -491,6 +548,10 @@ class Goal < ApplicationRecord
@pooled_allocations ||= self.class.pooled_allocations_for(family)
end
+ def market_flows
+ @market_flows ||= self.class.market_flows_for(family)
+ end
+
# Cleared after every AASM transition. The state column drives the
# display_status / projection_summary memos; without this the same
# instance keeps returning the pre-transition value if a controller
@@ -550,13 +611,23 @@ class Goal < ApplicationRecord
errors.add(:base, :at_least_one_linked_account_required)
end
- def linked_accounts_must_be_depository
+ def linked_accounts_must_be_fundable
offending = goal_accounts.reject(&:marked_for_destruction?).reject do |sga|
- sga.account&.depository?
+ sga.account&.depository? || sga.account&.investment?
end
return if offending.empty?
- errors.add(:linked_accounts, :must_be_depository)
+ 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? }
+ return unless progress_basis.blank? || progress_basis == "balance"
+
+ self.progress_basis = "contributions"
end
def linked_accounts_must_match_goal_currency
diff --git a/app/models/goal_pledge.rb b/app/models/goal_pledge.rb
index a204933cf2..052e6c9d19 100644
--- a/app/models/goal_pledge.rb
+++ b/app/models/goal_pledge.rb
@@ -61,6 +61,9 @@ class GoalPledge < ApplicationRecord
is_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?
return false if valuation_delta.nil? || valuation_delta.to_d <= 0
elsif kind_transfer? && !entry.amount.to_d.negative?
return false
diff --git a/app/views/goal_pledges/new.html.erb b/app/views/goal_pledges/new.html.erb
index ac5767c95e..a7143a777d 100644
--- a/app/views/goal_pledges/new.html.erb
+++ b/app/views/goal_pledges/new.html.erb
@@ -7,7 +7,11 @@
<%
account_options = @goal.linked_accounts.map do |a|
- [ a.name, a.id, { data: { manual: a.manual?.to_s } } ]
+ # `manual` drives the "update your manual balance" helper copy. Key it
+ # off the pledge kind actually saved (default_pledge_kind), so a manual
+ # investment account — which pledges via transfer — shows the transfer
+ # helper, not the manual one.
+ [ a.name, a.id, { data: { manual: (a.default_pledge_kind == "manual_save").to_s } } ]
end
%>
diff --git a/app/views/goals/show.html.erb b/app/views/goals/show.html.erb
index bffcfdf84f..7fef996100 100644
--- a/app/views/goals/show.html.erb
+++ b/app/views/goals/show.html.erb
@@ -65,6 +65,9 @@
<% if @goal.may_unarchive? %>
<% menu.with_item(variant: "button", text: t(".unarchive"), icon: "archive-restore", href: unarchive_goal_path(@goal), method: :patch) %>
<% end %>
+ <% if @goal.may_reopen? %>
+ <% menu.with_item(variant: "button", text: t(".reopen"), icon: "rotate-ccw", href: reopen_goal_path(@goal), method: :patch) %>
+ <% end %>
<% if @goal.archived? %>
<% menu.with_item(
variant: "button",
@@ -121,6 +124,9 @@
<div class="rounded-xl p-5 flex flex-col items-center justify-center text-center">
<%= render Goals::ProgressRingComponent.new(goal: @goal, size: 180) %>
<p class="text-xl font-medium text-primary tabular-nums privacy-sensitive mt-4"><%= @goal.current_balance_money.format(precision: 0) %></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 %>
<% unless @goal.completed? %>
<p class="text-xs text-subdued tabular-nums mt-0.5 privacy-sensitive"><%= t(".ring.to_go", amount: @goal.remaining_amount_money.format(precision: 0)) %></p>
<% end %>
diff --git a/config/locales/models/goal/en.yml b/config/locales/models/goal/en.yml
index 1df9236578..cbe2b28a94 100644
--- a/config/locales/models/goal/en.yml
+++ b/config/locales/models/goal/en.yml
@@ -16,9 +16,9 @@ en:
goal:
attributes:
base:
- at_least_one_linked_account_required: Pick at least one depository account to fund this goal.
+ at_least_one_linked_account_required: Pick at least one account to fund this goal.
linked_accounts:
- must_be_depository: All linked accounts must be depository (checking, savings, HSA, CD, money-market).
+ must_be_fundable: All linked accounts must be cash or investment accounts.
currency_mismatch: All linked accounts must share the same currency.
must_belong_to_family: Linked accounts must belong to the same family as the goal.
currency:
diff --git a/config/locales/models/goal/zh-CN.yml b/config/locales/models/goal/zh-CN.yml
index 3ce9dff54a..a49e8fddec 100644
--- a/config/locales/models/goal/zh-CN.yml
+++ b/config/locales/models/goal/zh-CN.yml
@@ -16,9 +16,9 @@ zh-CN:
goal:
attributes:
base:
- at_least_one_linked_account_required: 请至少选择一个存款账户为此目标提供资金。
+ at_least_one_linked_account_required: 请至少选择一个账户为此目标提供资金。
linked_accounts:
- must_be_depository: 所有关联账户都必须是存款账户(支票、储蓄、HSA、CD、货币市场账户)。
+ must_be_fundable: 所有关联账户必须是现金或投资账户。
currency_mismatch: 所有关联账户必须使用同一货币。
must_belong_to_family: 关联账户必须属于与目标相同的家庭。
currency:
diff --git a/config/locales/views/goals/en.yml b/config/locales/views/goals/en.yml
index 11e4a65f36..15469ef823 100644
--- a/config/locales/views/goals/en.yml
+++ b/config/locales/views/goals/en.yml
@@ -92,6 +92,9 @@ en:
unarchive:
success: Goal restored.
invalid_transition: Goal can't be restored from its current state.
+ reopen:
+ success: Goal reopened.
+ invalid_transition: Goal can't be reopened from its current state.
show:
edit: Edit
pause: Pause
@@ -99,6 +102,7 @@ en:
complete: Mark complete
archive: Archive
unarchive: Restore
+ reopen: Reopen goal
delete: Delete permanently
record_pledge_cta: Record pledge
pledge_just_transferred: Log a transfer you made
@@ -139,6 +143,7 @@ en:
of: "of %{target}"
to_go: "%{amount} to go"
of_target: of target
+ market_value: "Market value %{amount}"
aria_label: "Goal %{percent}% complete. %{amount} of %{target} saved."
projection:
heading: Projection
diff --git a/config/locales/views/goals/zh-CN.yml b/config/locales/views/goals/zh-CN.yml
index 9f7f365567..6727a0f71e 100644
--- a/config/locales/views/goals/zh-CN.yml
+++ b/config/locales/views/goals/zh-CN.yml
@@ -92,6 +92,9 @@ zh-CN:
unarchive:
success: 目标已恢复。
invalid_transition: 目标当前状态不能恢复。
+ reopen:
+ success: 目标已重新开启。
+ invalid_transition: 目标当前状态无法重新开启。
show:
edit: 编辑
pause: 暂停
@@ -99,6 +102,7 @@ zh-CN:
complete: 标记完成
archive: 归档
unarchive: 恢复
+ reopen: 重新开启目标
delete: 永久删除
record_pledge_cta: 记录承诺
pledge_just_transferred: 记录你完成的转账
@@ -139,6 +143,7 @@ zh-CN:
of: 共 %{target}
to_go: 还差 %{amount}
of_target: 目标进度
+ market_value: 市值 %{amount}
aria_label: 目标已完成 %{percent}%。已存 %{target} 中的 %{amount}。
projection:
heading: 预测
diff --git a/config/routes.rb b/config/routes.rb
index ec7c058e1d..213f312346 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -326,6 +326,7 @@ Rails.application.routes.draw do
patch :complete
patch :archive
patch :unarchive
+ patch :reopen
end
resources :pledges, only: %i[new create destroy], controller: "goal_pledges" do
diff --git a/db/migrate/20260625130000_add_progress_basis_to_goals.rb b/db/migrate/20260625130000_add_progress_basis_to_goals.rb
new file mode 100644
index 0000000000..f084b76a9c
--- /dev/null
+++ b/db/migrate/20260625130000_add_progress_basis_to_goals.rb
@@ -0,0 +1,16 @@
+class AddProgressBasisToGoals < ActiveRecord::Migration[7.2]
+ def change
+ # How a goal measures progress:
+ # - "balance" : live account balance (market value for investment
+ # accounts) — the v1 behaviour, the default.
+ # - "contributions" : net money put in, excluding market gains/losses
+ # (balances.net_market_flows) — the default for goals
+ # funded by investment accounts so a market swing
+ # doesn't move the goal.
+ add_column :goals, :progress_basis, :string, null: false, default: "balance"
+
+ add_check_constraint :goals,
+ "progress_basis IN ('balance','contributions')",
+ name: "chk_goals_progress_basis_enum"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 145b7c728e..9bda13ecda 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -851,9 +851,11 @@ ActiveRecord::Schema[7.2].define(version: 2026_06_25_230639) do
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "icon"
+ t.string "progress_basis", default: "balance", null: false
t.index ["family_id", "state"], name: "index_goals_on_family_id_and_state"
t.index ["family_id"], name: "index_goals_on_family_id"
t.check_constraint "char_length(name::text) <= 255", name: "chk_savings_goals_name_length"
+ t.check_constraint "progress_basis::text = ANY (ARRAY['balance'::character varying, 'contributions'::character varying]::text[])", name: "chk_goals_progress_basis_enum"
t.check_constraint "state::text = ANY (ARRAY['active'::character varying, 'paused'::character varying, 'completed'::character varying, 'archived'::character varying]::text[])", name: "chk_savings_goals_state_enum"
t.check_constraint "target_amount > 0::numeric", name: "chk_savings_goals_target_amount_positive"
end
diff --git a/test/models/goal_test.rb b/test/models/goal_test.rb
index 0333b680e8..1b1bd30eee 100644
--- a/test/models/goal_test.rb
+++ b/test/models/goal_test.rb
@@ -49,12 +49,21 @@ class GoalTest < ActiveSupport::TestCase
assert_match(/at least one/i, new_goal.errors[:base].join)
end
- test "linked accounts must be depository" do
+ test "investment accounts are fundable and default to the contributions basis" do
investment = accounts(:investment)
- new_goal = @family.goals.new(name: "Test", target_amount: 100, currency: "USD")
+ 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
+ end
+
+ test "non-fundable account types are rejected" do
+ credit = 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 depository (checking, savings, HSA, CD, money-market)."
+ assert_includes new_goal.errors[:linked_accounts], "All linked accounts must be cash or investment accounts."
end
test "linked accounts must belong to family" do
@@ -402,4 +411,47 @@ class GoalTest < ActiveSupport::TestCase
goal.complete!
assert_equal 100, goal.progress_percent, "stale memo would still report the pre-complete percent"
end
+
+ test "contributions basis excludes market gains" do
+ account = 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|
+ g.goal_accounts.build(account: account)
+ end
+ assert_equal "contributions", goal.progress_basis
+ # 10,000 value − 3,000 market gain = 7,000 contributed.
+ assert_equal BigDecimal("7000"), goal.current_balance.to_d
+ assert_equal BigDecimal("10000"), goal.market_value_money.amount
+ end
+
+ test "reopen transitions a completed goal back to active" do
+ fresh = goals(:emergency_fund)
+ fresh.complete!
+ assert fresh.completed?
+ fresh.reopen!
+ assert fresh.active?
+ end
+
+ test "investment accounts default to transfer pledge kind, never manual_save" do
+ assert_equal "transfer", accounts(:investment).default_pledge_kind
+ end
+
+ test "adding an investment account via update flips a depository goal to contributions" do
+ goal = goals(:emergency_fund)
+ assert_equal "balance", goal.progress_basis
+ goal.goal_accounts.build(account: accounts(:investment))
+ goal.save!
+ assert_equal "contributions", goal.reload.progress_basis
+ end
+
+ test "earmark is respected on a contributions-basis goal" do
+ account = 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|
+ g.goal_accounts.build(account: account, allocated_amount: 1_000)
+ end
+ assert_equal "contributions", goal.progress_basis
+ # net contributed = 10,000 − 2,000 = 8,000; earmark 1,000 ≤ 8,000 → 1,000.
+ assert_equal BigDecimal("1000"), goal.current_balance.to_d
+ end
end