Draw net contributions beside total value on the account chart
Summary
Closes #326 (upstream issue we-promise/sure#4008).
Before: the chart on an investment account page plots one line per view. Nothing on it shows how much the owner has put into the account, so whether the account has actually grown has to be worked out by hand.
After: on an account that holds trades (Investment, and Crypto of the exchange subtype), the Total value view draws a second, dashed line: Net contributions. The tooltip adds that figure and the signed difference from total value, with the difference as a percentage of net contributions. A one-line legend under the chart names both lines. When a flow could not be valued, a note under the legend says the line is understated. The Holdings, Cash and Gains views, and accounts that do not hold trades, are unchanged.
For the issue's example (opened with $10,000, $5,000 deposited, a $150 dividend, $2,000 withdrawn), the line reads $10,000, then $15,000 from the deposit, unchanged through the dividend, then $13,000 from the withdrawal. The dividend moves the value line only.
How:
Balance::ChartSeriesBuilder#net_contributions_seriesis inception-anchored. It starts from the opening value of the account's first balance row and adds every external flow up to each date, sampled on the value line's own dates. It reads the flows throughPortfolio::DailyReturns, soPortfolio::FlowClassifierdecides what is external, with the account itself as the scope. Each flow is valued the way the returns engine values it: a deposit at its cash amount, a security journalled in at the position's value (R18), and a foreign-currency flow at the previous day's rate (R11).Account#balance_seriesacceptsview: :net_contributions. For a linked investment account whose value line is trimmed to supported history, the line opens on the trim date at that day's closing value and adds only later flows, so both lines start at the same point (QA review 5999950093, decision 2). The normalizer does not run on this series. On the trim date itself the line takes the value line's own point, so when a coarse interval makes the normalizer prepend a synthetic opening point, both lines still open at the same figure.- When a flow the line counts could not be valued (
rate_missing, or asuppressedday with a positive denominator, which is an unpriced journal),#net_contributions_understated?is true and the chart says so under the legend: "Some money moved in or out could not be valued, so net contributions are understated from that date." UI::Account::Chartpasses the series as a new optionalcomparisonvalue totime_series_chart_controller. That value draws a dashedtext-secondaryline on the same scales and adds two rows to the tooltip, built as DOM nodes with d3's.text(). Without the value, the controller takes exactly the path it took before.
Deviation from the plan, stated. The plan described one new SQL query built on FlowClassifier#sql_case. I reused Portfolio::DailyReturns instead, because its flow valuation already handles security journals and FX, and a second copy of that SQL would be a second definition to keep in step. The cost is one daily query from the account's first balance to the period end on each Total value render (see Risks).
Scope and dependencies
- Issue: #326 (upstream we-promise/sure#4008)
- Parent PR/branch, if stacked: none; base is fork
main(branched at4d08917;mainhas since gained only a workflow change, and the branch merges cleanly) - Intentionally out of scope: a family-wide line on
/portfolio; the Holdings, Cash and Gains views; accounts that do not hold trades; the Gains query (#323); the goal basis (#299); a toggle (the line is on by default, which the issue named as a default the owner can overrule).
Evidence checklist
- Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
- Contract rows touched by this change name existing tests. Not applicable: no returns-contract row changes;
DailyReturnsis read, not changed. - Any gate test has an observed failing mutation transcript attached (below).
- Fixtures used as evidence assert internal consistency. The new tests build their own accounts with
lay_balance, which refuses a day whose components do not add up. - Financial calculations use
BigDecimal: the cumulation runs onDailyReturnsrows, which are BigDecimal. Rounding happens only at display, throughMoney#for_display, as the value line's points do. - De-identification: the screenshots use a test account named "Brokerage" with generated figures.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Validation
Tests, written first. Each one failed before its change: on main, the builder tests with NoMethodError for net_contributions_series, the Chartable tests with ArgumentError: Invalid view type, and the component tests with NoMethodError for show_net_contributions?. The tests added in d4c29fb each fail with their change reverted (the last four rows of the break-it table).
test/models/balance/chart_series_builder_test.rb:net contributions open at the opening value and step up by a deposit on its date. It also checks the line is sampled on the value line's dates, and that dates before the first balance read 0.a withdrawal lowers net contributions by its amount on its datea dividend moves the value line and leaves net contributions unchanged(a before/after delta on the dividend date)a fee, a buy and a sell leave net contributions unchangeda transfer in from another account in the family counts as a contributiona period that starts after the deposits still opens at the cumulative figurea foreign-currency deposit converts at its ratea security journalled in counts at its valuean anchor date opens at that day's closing value and adds only later flowsnet contributions carry a trend against the previous pointnet contributions say when a flow could not be valued(a EUR deposit with no rate; it also asserts the deposit counts as nothing)an unpriced journal makes net contributions understated
test/models/account/chartable_test.rb:balance_series accepts the net contributions view on the value line's dates(an unknown view still raises)a linked account's net contributions open where its trimmed value line doeson a coarse interval a linked account's net contributions start from the value line's own opening point(weekly;[0, 1,600, 1,900])
test/components/UI/account/chart_test.rb:the total value view of an investment account carries net contributions and a legend. It checks the serialized difference: $400, +2.7% of $15,000.net contributions are not drawn on the holdings, cash or gains viewsnet contributions are drawn only for accounts that hold trades(an exchange Crypto account yes; a wallet Crypto account and a Depository account no)the chart says when net contributions are understated
Break-it. Each change was reverted in turn, and a test caught every one:
| Breakage | Result |
|---|---|
| External flows dropped from the cumulation | 8 builder failures |
| Income added to the cumulation | 4 failures, including the dividend test |
| Cumulation windowed to the period start | the period-start test fails |
anchor_date ignored in the builder | the anchor test and the linked Chartable test fail |
| Chartable passes no anchor | the linked Chartable test fails |
Component drops the balance view check | the views test fails |
Component drops the supports_trades? check | the account-type test fails |
| Difference computed the wrong way round | the component test fails |
| Anchor date keeps its own figure, not the value line's point | the coarse-interval test fails |
rate_missing dropped from the understated check | the EUR test fails |
Positive-denominator suppressed dropped from the check | the journal test fails |
| Understated note removed from the view | the component note test fails |
Commands, on d4c29fb:
- Full suite,
bin/rails test: 11,890 runs, 4 failures, 1 error, 33 skips. All five fail the same way onmainin this environment and none touches charts:Provider::OpenaiTest(Ruby-style hash inspect),Provider::RegistryTest(Anthropic env), andSettings::HostingsControllerTest×3 (Anthropic base URL). - System tests (
account_chart_drag_select,dashboard_chart_drag_select,accounts,trades): 15 runs, 0 failures. - The three changed test files: 58 runs, 0 failures. Neighbours on
cd9bf1d(test/models/portfolio,investment_statement_test,i18n_test, plus those files): 368 runs, 0 failures. bin/rubocopon the changed Ruby: no offences.erb_linton the changed view: no errors.npm run lintandbiome checkon the controller: clean.bin/brakeman: no warnings.- Checked against
AGENTS.md: logic in models, a thin component, Minitest with fixtures, no new dependency, no migration, strings throught(), functional tokens only (text-secondary,border-current), and no raw SVG added.
Screenshots
Light and dark, 90D, hovering a date after the first deposit: Net contributions $25,000.00, Difference +$1,769.52 (+7.1%). They were taken with a throwaway system test against a generated account and are not committed. They are in the project files at pr-assets/326/, and can go on an assets/pr-337-screenshots branch like the earlier PRs once the owner agrees.
Risks, blockers, and follow-up
- Siblings that use the same words for something else. The figures differ by design. Both readers are left unchanged and are recorded here, as the plan required.
InvestmentStatement#net_contributions(the/portfolioKPI) is buys minus sells.InvestmentStatement::Totalsfeeds contributions and withdrawals from trades only (P29,app/models/investment_statement/totals.rb) and leaves deposits out to avoid counting a deposit and the buy it funded twice. So for a one-account family, the chart line's change over a period does not equal that KPI: a $5,000 deposit followed by a $3,000 buy moves this line by $5,000 and the KPI by $3,000. This is inferred from the code, not run as a test. The plan's consistency assertion was therefore not added, because it would fail by design. Whether the KPI should be renamed or redefined is an owner call for its own issue.Goal#net_contributed_forcounts income as contributions (balance minusnet_market_flows). #299 owns the goal basis.
- Query cost. Each Total value render of an investment account now runs one daily
DailyReturnsquery from the account's first balance to the period end, plus the existing balance query. That is about 3,650 daily rows for a ten-year account, each an index lookup onbalancesandexchange_rates. It is not cached and has not been profiled on a large account. - A flow that could not be valued (no rate, or an unpriced journal) still counts as nothing, as it does in returns, so the line is understated from that day. The chart now says so (light review 6017675456). The coarse-interval anchoring cubic found is fixed in
d4c29fb. Both answers are in comment 6018054582. - Liability accounts never reach the series: it is drawn only where
supports_trades?, which is asset-only. The method is documented as asset-only (cubic'ssign_multiplierfinding, declined in the same comment). - Upstream (corrected 2026-10-07). Only
Portfolio::FlowClassifiergoes upstream through we-promise/sure#3557.Portfolio::DailyReturns, which this PR reads for valuation, is fork-only and is not proposed upstream. Owner decision (option b): the upstream version of #4008 is reworked rather than waiting onDailyReturns.- It classifies entries with
FlowClassifier.sql_caseand sums external inflows and outflows per day, converted at the entry date's rate. - It differs from this PR in two places: a security journalled in counts at its trade value, not the position's value that day; and a foreign-currency flow converts at the entry date's rate, not the previous day's. A missing rate still marks the line as understated.
- It goes as two upstream PRs: the model (builder query and
Account::Chartable), then the chart UI (component, JS controller, locale), because this PR's non-test code is 376 lines. - Both are cut after #3557 lands (CLAUDE.md rule 8), with the two-way links added then. This fork PR keeps the
DailyReturnsversion.
- It classifies entries with
- Next unblocked: the owner's call on marking this ready, which starts the full Gatekeeper review.
Summary by CodeRabbit
- New Features
- Balance charts for eligible investment accounts now include a net-contributions line alongside total value, with a legend and dated value and difference details in chart tooltips.
- Net-contributions history reflects deposits, withdrawals, transfers, and valued security journals while excluding dividends, fees, and trades.
- Charts display a notice when some contributions or withdrawals could not be valued.