Add cash-anchor accounting for manual accounts

Closed
VL
13d ago
+998-74

Superseded by #5671 in the native Bitcoin stack. Further review continues there on the same commit, 5878948f1. This PR preserves the earlier discussion. Feature tracker.

Latest review update. An imported holding survives deletion of its last trade. The regression now creates the holding first, records a split retroactively, then corrects its ratio. Both changes recompute the carried quantity, price and per-share cost on the same holding. Migration 20261122120000_add_cost_basis_inherited_to_holdings adds a boolean defaulting to false. Older explicit cost locks retain their value.

Summary

Part 1 of the split of #3753 agreed in https://github.com/we-promise/sure/pull/3753#issuecomment-6248037835. No Bitcoin code: everything here is tested on plain manual accounts.

A cash_anchor valuation fixes an account's cash on a date, and from then on the account keeps forward accounting. The Bitcoin wallet in part 4 creates one when it starts tracking a manual Crypto account: the account's cash stays as it was, and only the BTC position changes from then on.

What an anchor does:

  • Cash on the anchor's day is the anchor amount, adjusted by any later change to the ledger before that day. The amount is the cash the ledger gives for today, not the cached cash_balance, so a movement not yet synced or dated after today is neither lost nor doubled. cash_entry_total records the ledger total when the anchor was made, so editing, adding or deleting an earlier cash movement applies once through the anchor.
  • Valuations on the same day: a total valuation entered earlier that day is marked superseded_at and yields to the anchor. One entered later, or edited in amount or date, still sets the total. A notes-only edit doesn't change which one wins.
  • Rebuilds start from the given date, or from the first anchor when none is given (trades, transfers, bulk deletes, reconciliations and imports sync without a date), and leave earlier history as recorded. Deleting an entry or a holding passes its date, so the rebuild covers it. Deleting a security's last trade also removes the holdings calculated from it.
  • Holdings without trades are carried forward with their cost basis and locks, valued at the last known quote on days without one (or left at their last value when no FX rate is available). Carried rows are calculated, so they have no provider and keep being repriced. Their quantity and basis follow later stock splits, and a quote carried across a split is unscaled. Days before the window are replayed with their splits, income trades (qty 0) don't count as trades, and investment reports take an anchored account's latest holding in any currency.
  • Syncs of an anchored account run in the family's time zone, like the request that created the anchor. A sync that is already running no longer absorbs a newer request, and a pending sync is only reused by the same parent.
  • Activity: anchors are internal baselines. They are hidden from the account's activity list, valuation lookups by date (reconciliation, the valuations API, the assistant) skip them through Entry.excluding_cash_anchors, and the valuations API neither lists nor opens them.

Accounts without an anchor keep their current behavior; every new branch checks accounting_start_date first. One exception: calculated holdings dated after today are now removed for every account (Holding::Materializer#purge_stale_holdings), so a materialization run in a time zone ahead of the server can't leave stale future rows.

Nothing creates an anchor yet; part 4 does.

Migrations

Two additive, nullable columns on valuations: cash_entry_total and superseded_at. Existing rows are not rewritten. The migration versions match #3753, so databases that already ran it skip them (cash_entry_total also uses if_not_exists).

Validation

  • New test/models/account/cash_anchor_test.rb (29 tests): FX and split handling, same-day valuations and restoring a superseded one, editing the anchor, editing, backdating and deleting earlier movements, unsynced and future-dated movements, syncs without a date, deleting a security's last trade, income trades beside a snapshot, stock splits before the window and after the last quote, carried holdings and their basis, missing FX, a year of history across windows, sync coalescing.
  • sync_job_test.rb: the family time zone applies only to anchored accounts.
  • balance/materializer_test.rb, holding/materializer_test.rb, balance/sync_cache_test.rb: windows for accounts without an anchor, future-dated holdings, running ledger totals.
  • accounts_controller_test.rb: anchors are hidden from activity. api/v1/valuations_controller_test.rb: a valuation created on an anchor's date is returned, not the anchor, and anchors are neither listed nor shown.
  • Rails suite on the rebased head passed with 18,543 tests, 113,714 assertions, 9 skips, zero failures or errors.
  • System tests: not run locally. The only user-facing change is hiding anchors from the activity list, covered by the controller test.
  • RuboCop and Brakeman: no offenses or warnings.

Summary by CodeRabbit

  • New Features

    • Added cash balance reconciliation that preserves account history and incorporates cash movements, trades, and currency conversions into balance calculations.
    • Account holdings and balance history now carry forward and reprice available security snapshots between activity dates.
    • Cash balance reconciliation labels are available in several languages.
  • Bug Fixes

    • Cash reconciliation entries no longer appear in account activity or valuation listings, or interfere with other valuations on the same date.
    • Historical balance and holdings updates better reflect edits and deletions to past account activity.
    • Account syncs use the configured family time zone when available, falling back to the application time zone.