Add family-wide investment value, holdings and gains series
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 forkmain. The instance#normalizeis upstream's (forkmainpredates 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 throughHistoricalAccountScope.active_until_dates, with a new test. Forkmainstill has its private copy, so forkmainshould 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 newaggregate_account_idstest that the fork does not have.HistoricalScope,HistoricalAccountScope,NetWorthSeriesBuilderandhistorical_scope_test.rb: byte-identical to forkmain.
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:
01cc0134dShare the cut-off and supported-history trim helpers49d431a40Add family-wide investment value, holdings and gains series39c1df5a7Refresh the series cache when a provider link is removed (from review: an unlink clearsaccount_provider_idwithout touchingupdated_at, and the supported-history trim reads that column)8401948d2Pin the hand-worked totals in the value series test (from review: the sum comparison builds its expectation with the sameBalance::ChartSeriesBuilderthe statement calls)0c4a00af3Key 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)ac92684d4Test 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 beforedisabled_at, or beforeupdated_atwhendisabled_atis unset. Active and draft accounts are left out. BalanceSheet::NetWorthSeriesBuilderandBalanceSheet::NetWorthBreakdownSeriesBuildereach 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_idsalready 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 inaccount_idshas 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_idsnow calls it. The instance-level#normalizeisn't touched.
InvestmentStatement::HistoricalScope (new)
#accounts:BalanceSheet::HistoricalAccountScope#relationlimited toInvestmentandCrypto. 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 appliesincluded_in_finances_for. It loads once per instance.#account_ids, and#active_until_datesfrom the helper above.
InvestmentStatement#value_series, #holdings_value_series, #gains_series (period: defaults to Period.last_30_days)
- Each builds
Balance::ChartSeriesBuilderoverhistorical_scope.account_ids, withaccount_active_until_dates: historical_scope.active_until_dates, and callsbalance_series,holdings_balance_seriesorgains_series. - The result goes through
trim_to_supported_historyfor the scope's accounts, so a linked broker's zero rows before its first snapshot aren't charted. #historical_scopeis public, so later model code can use the same accounts and cut-off dates.
Caching
Rails.cacheunderfamily.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 latestupdated_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 share version (count and latest
- 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_seriesequals 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 fromHistoricalScope. 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 sharesBalance::ChartSeriesBuilderwith the code under test.- a disabled account counts on its cut-off date and not the day after
- the series is historical where
portfolio_valueis 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_seriesandgains_seriescall 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 withoutdisabled_at), draft accounts having no cut-off, a share withoutinclude_in_finances, and one accounts query per instancetest/models/balance/linked_investment_series_normalizer_test.rb:trim_to_supported_historydrops the leading points, flattens the first trend and leaves an unlinked series untouched.aggregate_account_idsstill trims, andSeries#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:
| Breakage | Caught by |
|---|---|
| Cut-off on the disabled day, not the day before | 5 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 account | 4 tests, incl. net worth and the draft-account test |
| Trim keeps the stale first trend | trim test |
aggregate_account_ids skips the trim | aggregate test |
| Series not trimmed | leading-zeros test |
| Builder gets no cut-off dates | 2 series tests |
| Scope not limited to Investment/Crypto | scope types test |
| Scope reads visible accounts only | 7 tests |
| Scope ignores the user | shared-account test |
| Cache key without the holdings version | 3 cache key tests |
| Cache key without the share version | share-revoked test |
Cache key without family.currency | currency-change test |
| Cache key without the accounts version | account-deletion test |
Accounts version reduced to the latest updated_at (no count) | account-deletion test |
| Accounts version made to vary per request | key-reused test |
| No per-instance memo | memo test |
holdings_value_series / gains_series read the balance series | the matching delegation test |
value_series ignores its period | 2 series tests |
NetWorthSeriesBuilder passes no cut-off | net worth series test already on main |
NetWorthBreakdownSeriesBuilder passes no cut-off | breakdown test |
Balance::ChartSeriesBuilder drops the FX rate from end_balance | the 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 skipsbin/rubocop -f githubon the changed files: no offensesbundle 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 byNetWorthSeriesBuilderwith its historical accounts and byNetWorthBreakdownSeriesBuilderwith 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 onmain, passes unchanged and fails if either builder stops passing the cut-off.Balance::LinkedInvestmentSeriesNormalizer.aggregate_account_ids. Its only caller isAccountableSparklinesController#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, andshared/_sparklinerenders withuse-tooltip-value: false. The figure next to the sparkline isSeries#trend, which compares the first and last values, so it's unchanged too.aggregate_accountsdelegates to it and has no other callers.Balance::LinkedInvestmentSeriesNormalizer#normalize(the per-account chart) isn't touched.Balance::ChartSeriesBuilderisn'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::NetWorthSeriesBuilderandBalanceSheet::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_dataandGoal#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.