Files
sure/app/models/account/reconciliation_manager.rb
Guillem Arias Fauste c5ca0431c9 feat(goals): investment-backed goals (Phase 2) (#2491)
* feat(goals): earmark a portion of an account toward a goal

Goals currently count each linked account's whole balance, so an account
shared across goals double-counts and one account can't fund several goals
in distinct slices. Add a per-account earmark — the "GoalBacking" the v1
model already foreshadowed (goal.rb).

- goal_accounts.allocated_amount (nullable). NULL = "dedicate the whole
  balance" (the v1 default: no backfill, existing goals unchanged); a set
  amount reserves a fixed slice.
- Goal#current_balance is now the single chokepoint computing each account's
  backing under a family-wide shared pool: fixed earmarks take their slice,
  an unallocated link takes the remainder, and when fixed earmarks exceed the
  balance every slice is scaled down pro-rata so the goals' shares can never
  sum past the account balance (no double-counting).
- Account#free_to_earmark / #goal_earmarked_total (mirror Budget's
  available_to_allocate) back a soft, non-blocking over-allocation hint.
- GoalsController threads a goal[allocations] hash through create/update.

Phase 1 of the goals earmarking work; investment-backed goals follow.

* feat(goals): earmark UI on the goal form + backing-aware funding breakdown

- Goal form: a per-account "earmark amount" input (blank = whole balance)
  next to each funding-account checkbox, prefilled from the saved
  allocation on edit.
- Goal#account_backing exposes a single linked account's share so the
  funding-accounts breakdown shows each account's earmarked contribution
  and percent instead of its whole balance — keeping the show page
  consistent with the (now allocation-aware) progress ring.
- English strings for the earmark controls and the "earmarked of balance"
  breakdown line.

* fix(goals): address review on the earmark shared-pool math

- Overdrawn (<= 0 balance) accounts now back nothing on both the fixed and
  whole-balance paths. The fixed path previously produced negative backing and
  let a goal claim money the account doesn't hold.
- An archived goal reads its OWN earmark from its own goal_accounts instead of
  the shared pool (which excludes archived goals), so it no longer mis-reports
  the whole account balance for itself.
- goals#index injects one family-wide earmark pool into every card
  (Goal.pooled_allocations_for) instead of querying once per goal (N+1), and
  preloads goal_accounts.
- The projection chart scales its whole-account historical series by the
  backing ratio so the saved line meets current_balance at "today" rather than
  dropping off a cliff for earmarked goals.
- Honest comments: free_to_earmark no longer claims a form warning that doesn't
  exist yet; pace documents its deliberate whole-account basis.

* fix(goals): widen the earmark input so the 'Whole balance' placeholder isn't clipped

* fix(goals): address review on #2490

- autosave: true on goal_accounts so earmark edits to already-linked accounts
  persist through goal.save! (Rails only auto-saves newly built children, so
  changing/clearing an existing earmark was silently dropped). + test.
- Reset the balance/progress memos on AASM transitions, not just the status
  memos, so a same-instance render after complete!/archive! isn't stale. + test.
- backing_ratio is 0 (not 1) when the linked-account total is non-positive, so
  the projection saved series ends at 0 to match the forced-zero current_balance.
- Localize the funding-row subtype label via goals.form.subtypes.*.
- Add the earmark strings to zh-CN (the maintained second locale; goals has no
  ca locale, so Catalan keeps falling back to en like the rest of goals).

* feat(goals): investment-backed goals (Phase 2)

Goals can now be funded by investment accounts, not just depository.

- Relax linked_accounts_must_be_depository -> _must_be_fundable
  (depository || investment); the funding picker + counts include investment
  accounts.
- Add goals.progress_basis ('balance' | 'contributions', default 'balance').
  Investment-backed goals default to 'contributions' so a market swing doesn't
  move the goal: current_balance = value - cumulative market gain
  (Sum of balances.net_market_flows); depository accounts have zero
  net_market_flows, so they're unchanged. Goal#market_value_money shows what
  it's worth today next to the contributed figure on the show page.
- Pledge false-match guard: investment accounts never use manual_save /
  valuation-delta matching (a market move isn't a deposit) - they resolve on
  transfer (cash-inflow) entries only. Guarded in both
  Account#default_pledge_kind and GoalPledge#matches?.
- Add a `reopen` AASM event (completed -> active) + route/action/menu item so a
  manually-completed goal whose value later dips can be reopened.

Stacked on the earmarking branch (#2490). Full suite green; +6 goal tests.

* fix(goals): address Phase 2 review — allocation-aware contributions, N+1, basis-on-update

- Contributions basis now goes through the same earmark/shared-pool logic as
  the balance basis: backing_balance_for -> backing_share_for(account, base),
  where base is the live balance (balance basis) or net contributions
  (contributions basis). Earmarks are respected and shared accounts no longer
  double-count on contributions goals; market_value_money stays consistent.
- Batch the per-account net_market_flows sum (Goal.market_flows_for) and inject
  it on index like pooled_allocations, killing the N+1 for contributions goals.
- Default the basis on update too (not just create), so adding an investment
  account to an existing depository goal flips it to contributions instead of
  silently tracking market value.
- Fix the stale reconciliation_manager comment (renamed validation) and the
  orphaned zh-CN must_be_depository key.

* fix(goals): address review on #2491

- before_save (not before_validation) for the progress_basis default, so a goal
  can be inspected via valid? without its basis flipping as a side effect (jjmata).
- Pledge copy keys off default_pledge_kind, not manual?, so a manual investment
  account — which pledges via transfer — shows the transfer prompt instead of the
  "update your manual balance" flow (codex). pledge_action_label_key and the
  pledge modal's per-account helper flag both use it.
- Add the Phase 2 strings (reopen success/invalid_transition, show.reopen,
  ring.market_value) to zh-CN.

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-06-30 07:26:23 +02:00

129 lines
5.9 KiB
Ruby

class Account::ReconciliationManager
attr_reader :account
def initialize(account)
@account = account
end
# Reconciles balance by creating a Valuation entry. If existing valuation is provided, it will be updated instead of creating a new one.
def reconcile_balance(balance:, date: Date.current, dry_run: false, existing_valuation_entry: nil)
old_balance_components = old_balance_components(reconciliation_date: date, existing_valuation_entry: existing_valuation_entry)
prepared_valuation = prepare_reconciliation(balance, date, existing_valuation_entry)
# Captured before save!: the amount this valuation already had on disk
# (nil when this reconciliation creates it). See valuation_contribution.
prior_valuation_amount = prepared_valuation.amount_in_database
unless dry_run
prepared_valuation.save!
contribution = valuation_contribution(prepared_valuation, prior_valuation_amount, old_balance_components)
GoalPledge::Reconciler.new(prepared_valuation, valuation_delta: contribution).run
end
ReconciliationResult.new(
success?: true,
old_cash_balance: old_balance_components[:cash_balance],
old_balance: old_balance_components[:balance],
new_cash_balance: derived_cash_balance(date: date, total_balance: prepared_valuation.amount),
new_balance: prepared_valuation.amount,
error_message: nil
)
rescue => e
ReconciliationResult.new(
success?: false,
error_message: e.message
)
end
private
# Returns before -> after OR error message
ReconciliationResult = Struct.new(
:success?,
:old_cash_balance,
:old_balance,
:new_cash_balance,
:new_balance,
:error_message,
keyword_init: true
)
# Contribution recorded by this reconciliation: how much the balance moved
# vs. the prior balance. This (not the full new balance) is what a
# manual_save GoalPledge matches against.
#
# The prior balance is resolved in freshness order:
# 1. The valuation's own pre-save amount, when this reconciliation
# updates an existing valuation. The balances table recomputes
# asynchronously (sync_later fires after this manager returns), so a
# same-date re-reconcile racing that sync would otherwise read the
# pre-first-reconcile row and over- or under-state the delta — an
# overstated delta could wrongly close a larger pledge, which never
# self-heals. The valuation's own prior amount is immune to that
# race, and once the sync lands the two sources are identical (the
# valuation anchors that date's end_balance).
# 2. The balances-table row for the date (first reconcile on a date).
# This can still be stale in one residual window: a reconcile on a
# NEW date racing the previous date's pending sync reads a
# carried-forward row. A missed match self-heals on the next re-save
# — the pledge stays open and retryable until `expires_at`, and the
# date/amount tolerance in GoalPledge#matches? accepts the retry.
# 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 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
end
def prepare_reconciliation(balance, date, existing_valuation)
valuation_record = existing_valuation ||
account.entries.valuations.find_by(date: date) || # In case of conflict, where existing valuation is not passed as arg, but one exists
account.entries.build(
name: Valuation.build_reconciliation_name(account.accountable_type),
entryable: Valuation.new(kind: "reconciliation")
)
valuation_record.assign_attributes(
date: date,
amount: balance,
currency: account.currency
)
valuation_record
end
def derived_cash_balance(date:, total_balance:)
balance_components_for_reconciliation_date = get_balance_components_for_date(date)
return nil unless balance_components_for_reconciliation_date[:balance] && balance_components_for_reconciliation_date[:cash_balance]
# We calculate the existing non-cash balance, which for investments would represents "holdings" for the date of reconciliation
# Since the user is setting "total balance", we have to subtract the existing non-cash balance from the total balance to get the new cash balance
existing_non_cash_balance = balance_components_for_reconciliation_date[:balance] - balance_components_for_reconciliation_date[:cash_balance]
total_balance - existing_non_cash_balance
end
def old_balance_components(reconciliation_date:, existing_valuation_entry: nil)
if existing_valuation_entry
get_balance_components_for_date(existing_valuation_entry.date)
else
get_balance_components_for_date(reconciliation_date)
end
end
def get_balance_components_for_date(date)
balance_record = account.balances.find_by(date: date, currency: account.currency)
{
cash_balance: balance_record&.end_cash_balance,
balance: balance_record&.end_balance
}
end
end