Add family-wide investment value, holdings and gains series

Merged
JA
2mo ago
+701-18

Part of #119

Upstream pre-flight for drop 0.2 of #119 (row C of the drop 0 table in #118): the family-wide investment series plus InvestmentStatement::HistoricalScope, with the two helpers it needs. Upstream issue: we-promise/sure#4078 (part 1). Upstream PR: we-promise/sure#4087 (draft, opened 2026-10-09). Same branch, same commit.

Base is mirror/upstream-main; the branch is cut from upstream main at 00dd977fb. The mirror carries 20 merged pre-flight commits on top of that, some in the same files (investment_statement.rb, both net worth builders). git merge-tree merges it cleanly, and CI here runs on that merge.

Divergences from fork main, all in this branch's favour or declared for the owner:

  • Balance::LinkedInvestmentSeriesNormalizer: the class methods (aggregate_account_ids, trim_to_supported_history, flatten_first_trend) are byte-identical to fork main. The instance #normalize is upstream's (fork main predates upstream's opening-balance change, we-promise/sure#4009). The fork's separate "normalize flattens the first trend" change and its test are not sent; they are a per-account-chart change and a different idea.
  • BalanceSheet::NetWorthBreakdownSeriesBuilder: routed through HistoricalAccountScope.active_until_dates, with a new test. Fork main still has its private copy, so fork main should take this change to stay single-copy.
  • InvestmentStatement: the ported methods are byte-identical except one comment (a fork drop reference removed). One test comment reworded; a new aggregate_account_ids test that the fork does not have.
  • HistoricalScope, HistoricalAccountScope, NetWorthSeriesBuilder and historical_scope_test.rb: byte-identical to fork main.

The upstream body below already carries the fixes for the Codex review of we-promise/sure#4087 (0c4a00af3, ac92684d4). The same edit to the upstream body is drafted and awaits the owner; until then the upstream body still describes 8401948d2.


Part of #4078

Part of #3494 (drop 0.2 of jaysbeekay/sure#119)

Fork pre-flight PR: jaysbeekay/sure#362 (same branch, same commit)

Summary

This adds a family-wide value series for investments: InvestmentStatement#value_series, #holdings_value_series and #gains_series. Each charts the family's Investment and Crypto accounts together over a period, in the family currency, the same way the net worth series charts every account. Nothing is drawn yet. A later portfolio chart, and return calculations that need a daily value, read these series.

The design choice to know about: the account scope is historical, like net worth's. A disabled broker keeps its history up to the day before it was disabled. So the series' last point can differ from portfolio_value, which only sees visible accounts, when a disabled account still had a balance before its cut-off. Closing an account shouldn't change what the family held last March.

Two helpers that the series shares with the net worth charts come first, as a separate commit:

  • 01cc0134d Share the cut-off and supported-history trim helpers
  • 49d431a40 Add family-wide investment value, holdings and gains series
  • 39c1df5a7 Refresh the series cache when a provider link is removed (from review: an unlink clears account_provider_id without touching updated_at, and the supported-history trim reads that column)
  • 8401948d2 Pin the hand-worked totals in the value series test (from review: the sum comparison builds its expectation with the same Balance::ChartSeriesBuilder the statement calls)
  • 0c4a00af3 Key portfolio series on family currency and accounts (from review: a currency change, or deleting an account with no holdings that isn't the newest, moved nothing in the key)
  • ac92684d4 Test that portfolio series keys are reused when nothing changes

What changed

BalanceSheet::HistoricalAccountScope.active_until_dates(accounts) (new class method)

  • Returns { account_id => date } for each disabled account: the day before disabled_at, or before updated_at when disabled_at is unset. Active and draft accounts are left out.
  • BalanceSheet::NetWorthSeriesBuilder and BalanceSheet::NetWorthBreakdownSeriesBuilder each had a private copy of this rule. Both now call this method, with the same body, so the three charts drop a closed account on the same day.

Balance::LinkedInvestmentSeriesNormalizer.trim_to_supported_history(series, account_ids:) (new class method)

  • The trim aggregate_account_ids already applied to its own balance series, pulled out so a caller that builds its own series can use it. It drops the points before the date every linked account in account_ids has real history for. An unlinked account has no such date, so the series is returned untouched.
  • After a trim, the new first point gets a flat trend (flatten_first_trend, public on the class). Its old trend compared it with a point the chart no longer draws.
  • aggregate_account_ids now calls it. The instance-level #normalize isn't touched.

InvestmentStatement::HistoricalScope (new)

  • #accounts: BalanceSheet::HistoricalAccountScope#relation limited to Investment and Crypto. That's the same relation net worth uses, so it includes disabled and draft accounts, excludes accounts excluded from reports or pending deletion, and with a user applies included_in_finances_for. It loads once per instance.
  • #account_ids, and #active_until_dates from the helper above.

InvestmentStatement#value_series, #holdings_value_series, #gains_series (period: defaults to Period.last_30_days)

  • Each builds Balance::ChartSeriesBuilder over historical_scope.account_ids, with account_active_until_dates: historical_scope.active_until_dates, and calls balance_series, holdings_balance_series or gains_series.
  • The result goes through trim_to_supported_history for the scope's accounts, so a linked broker's zero rows before its first snapshot aren't charted.
  • #historical_scope is public, so later model code can use the same accounts and cut-off dates.

Caching

  • Rails.cache under family.build_cache_key(..., invalidate_on_data_updates: true), as the net worth series does. The key also carries:
    • a share version (count and latest updated_at), because revoking a share deletes a row, which moves neither timestamp in the family key.
    • a holdings version, because the gains series reads holdings.cost_basis, which a manual edit rewrites in place, and the trim reads provider holdings.
    • family.currency, because every series is converted to it, and a profile currency change neither syncs nor writes an account.
    • Family#accounts_status_version (account count and latest updated_at, as the transactions index caches use), because deleting an account with no holdings that isn't the most recently updated one moves neither timestamp in the family key nor the holdings version.
  • A per-instance memo per kind and period, so a render that asks for the same series twice runs one query.

Demo data

No demo data change. There is no UI to show it on yet.

Screenshots

None. No UI.

Migration notes

No migration.

Verification

The tests were written to fail first. With the app files reset to main (00dd977fb), the 19 new series and scope tests error, because the methods and the scope class don't exist there. Two other new tests pass on main on purpose. They pin behaviour this PR must not change: aggregate_account_ids still trims, and the breakdown builder still cuts a disabled account off. The breakages below show both are live.

New tests:

  • test/models/investment_statement_test.rb:
    • value_series equals the sum of the per-account series on every date. Three accounts (USD, EUR at a stored rate, and one disabled). The expected cut-off is worked out in the test, separately from HistoricalScope. The totals are also pinned by hand (1900 on the three days up to the disabled account's cut-off, 1800 on the three after), because the sum comparison shares Balance::ChartSeriesBuilder with the code under test.
    • a disabled account counts on its cut-off date and not the day after
    • the series is historical where portfolio_value is live, so they differ for a closed account
    • an empty family gets a zero series
    • a linked account's zero rows before its first provider activity aren't charted
    • holdings_value_series and gains_series call the matching builder method
    • the builder is built once per period per instance
    • the cache key changes when a share is revoked, when a cost basis is edited by hand, and when a holding is deleted (for every series kind)
    • every series cache key changes when the family currency changes, and when an account without holdings is deleted; both failed before the fix, on 6075b20f1, with identical keys
    • every series cache key is reused while nothing it reads changes (the negative case: a key that moved on every request would pass the tests above)
  • test/models/investment_statement/historical_scope_test.rb: the types and statuses in scope, cut-off dates (with and without disabled_at), draft accounts having no cut-off, a share without include_in_finances, and one accounts query per instance
  • test/models/balance/linked_investment_series_normalizer_test.rb: trim_to_supported_history drops the leading points, flattens the first trend and leaves an unlinked series untouched. aggregate_account_ids still trims, and Series#trend, which the sparkline renders, is taken from the trimmed points.
  • test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb: a disabled account counts in the month before its cut-off and not after

I also broke each part on purpose and reran the affected test files. A test failed for every break, with no errors:

BreakageCaught by
Cut-off on the disabled day, not the day before5 tests, incl. the net worth series test already on main
disabled_at ignored (always updated_at)4 tests, incl. the breakdown test
Cut-off given to every account4 tests, incl. net worth and the draft-account test
Trim keeps the stale first trendtrim test
aggregate_account_ids skips the trimaggregate test
Series not trimmedleading-zeros test
Builder gets no cut-off dates2 series tests
Scope not limited to Investment/Cryptoscope types test
Scope reads visible accounts only7 tests
Scope ignores the usershared-account test
Cache key without the holdings version3 cache key tests
Cache key without the share versionshare-revoked test
Cache key without family.currencycurrency-change test
Cache key without the accounts versionaccount-deletion test
Accounts version reduced to the latest updated_at (no count)account-deletion test
Accounts version made to vary per requestkey-reused test
No per-instance memomemo test
holdings_value_series / gains_series read the balance seriesthe matching delegation test
value_series ignores its period2 series tests
NetWorthSeriesBuilder passes no cut-offnet worth series test already on main
NetWorthBreakdownSeriesBuilder passes no cut-offbreakdown test
Balance::ChartSeriesBuilder drops the FX rate from end_balancethe hand-worked totals in the value_series sum test (the sum comparison alone still passes, since both sides move)

Commands, on ac92684d4:

  • bin/rails test: 11,846 runs, 54,632 assertions, 0 failures, 0 errors, 34 skips
  • bin/rubocop -f github on the changed files: no offenses
  • bundle exec erb_lint: not applicable (no ERB)
  • npm run lint: not applicable (no JS)
  • bin/brakeman --no-pager -q: no warnings

Size: 209 added and 18 removed in app/, 492 added in test/.

Blast radius

Who else hits these lines, and what do they pass?

  • BalanceSheet::HistoricalAccountScope.active_until_dates. Called by NetWorthSeriesBuilder with its historical accounts and by NetWorthBreakdownSeriesBuilder with each group's accounts, the same lists they passed to their private copies. The body is the one both copies had, so net worth output is unchanged. test/models/balance_sheet_test.rb's "net worth series preserves disabled history" test, already on main, passes unchanged and fails if either builder stops passing the cut-off.
  • Balance::LinkedInvestmentSeriesNormalizer.aggregate_account_ids. Its only caller is AccountableSparklinesController#aggregate_normalized_series, for linked Investment/Crypto sparklines. The points it keeps and their values are unchanged. The only difference is the first kept point's own trend after a trim, now flat. A per-point trend is read only by the chart tooltip, and shared/_sparkline renders with use-tooltip-value: false. The figure next to the sparkline is Series#trend, which compares the first and last values, so it's unchanged too. aggregate_accounts delegates to it and has no other callers.
  • Balance::LinkedInvestmentSeriesNormalizer#normalize (the per-account chart) isn't touched.
  • Balance::ChartSeriesBuilder isn't touched. The new series pass it the same arguments the net worth builder does.

What else reads what I changed the reading of? git grep -n "disabled_at ||\|ChartSeriesBuilder.new" over app/:

  • BalanceSheet::NetWorthSeriesBuilder and BalanceSheet::NetWorthBreakdownSeriesBuilder: the two copies of the cut-off rule. Both now use the helper.
  • Account::Chartable: a single account, already trimmed by #normalize. Unchanged.
  • Assistant::Function::GetBalanceSheet#historical_data and Goal#balance_series_values: they read visible accounts only, so there's no disabled account to cut off. Unchanged.
  • AccountableSparklinesController#build_series: unlinked sparklines, visible accounts, no trim. Unchanged.