Portfolio hub: preview-gated /portfolio page with consolidated holdings, value chart, allocation and data quality (#120)
Summary
Delivers jaysbeekay/sure#120 (IP1 — portfolio hub): a preview-gated, family-wide /portfolio page
built on the Reports section framework, showing only figures that exist after
jaysbeekay/sure#119. Stacked on jaysbeekay/sure#133 (feat/portfolio-foundations), which this PR
targets so the diff shows the hub alone.
Upstream readiness. This PR cannot be rebased onto current we-promise/sure main alone. At
01361205605578fc4973119fa07909120f599705, source search found none of these portfolio symbols:
holdings_table_rows, HOLDINGS_SORT_KEYS, ALLOCATION_GROUPINGS, AllocationSegment,
DataQualityIssue, holdings_with_avg_costs, and latest_price_dates. The foundation work in
jaysbeekay/sure#133 supplies this code and depends on we-promise/sure#2927 and #3350; both upstream
PRs are still open. Treat those deliveries and the #133 port as prerequisites. After they land,
rebuild/rebase this branch on the resulting upstream tree and verify conflicts, behavior, and tests
there; conflict count and byte-identical equivalence are not established yet.
Sections (drag to reorder, collapse, persisted per user): KPI row (value, day change, unrealised
P&L, period return, net contributions, income), portfolio value chart with the dashboard's period
picker in a Turbo frame, consolidated holdings table (one row per security, server-side sort,
expandable per-account positions with the existing drawer), accounts grid, allocation donut by
security / account / currency / kind, and a data-quality list (missing cost basis, stale price,
provider issues) that hides itself when there is nothing to fix.
Scope and dependencies
- Issue: jaysbeekay/sure#120 (part of jaysbeekay/sure#118). Grows with jaysbeekay/sure#121, #122,
#123, #124, #125, #128 throughPortfolio::SectionRegistry#extra_sections. - Upstream: sits on top of jaysbeekay/sure#133, which builds on we-promise/sure#2927 and
we-promise/sure#3350. Nothing in this PR touches their code directly. - Parent PR/branch and prerequisites: jaysbeekay/sure#133 (
feat/portfolio-foundations) is
this PR's current base. The current base-to-head graph contains 15 commits, including merge
commits177bfc9b7andc41fccd5a(13 non-merge commits). #133 depends on the code being adopted
from we-promise/sure#2927 and #3350; both are still open. Rebuild/rebase this stack against the
resulting upstream tree after those dependencies land, then resolve and test the actual conflicts
before retargeting this PR tomain. - Intentionally out of scope: a security page (D3 keeps the holding drawer), print output, OpenAPI
(no endpoint change — the API check is not needed), the generic sections controller (A3), a
mobile bottom-bar entry (D2, see below).
Decisions adopted (D1–D9 from the readiness review)
| Decision | Where | |
|---|---|---|
| D1 | "Portfolio" for nav, title, breadcrumb and URL; the dashboard widget keeps "Investments". | locales |
| D2 | Corrected by a fact: the review proposed "sidebar and mobile drawer, not the bottom bar", but layouts/application.html.erb renders no nav list in the mobile drawer (the drawer holds the account tabs). The entry is desktop-sidebar-only (desktop_only flag beside the existing mobile_only); phones reach the page through the dashboard and Reports links. | P37 |
| D3 | Consolidated rows expand (native <details>) to per-account positions with the existing holding_path drawer link; no new route. | holdings partial |
| D4 | Server-side sort `?sort=value | weight |
| D5 | Deterministic palette from Category::COLORS (the chart palette the app already uses), indexed by sorted position. | PortfoliosHelper |
| D6 | Stale = latest price older than 5 days before as_of, or no price; plus provider_status != :ok; cash never. | P34 |
| D7 | #119's 0.4 is on the base branch, so the Income card renders from day one (six cards). | KPI row |
| D8 | Periodable persists the chosen period as the user's default, as the dashboard and accounts do. | controller |
| D9 | The two Reports Stimulus controllers are parameterised (url, preferenceKey) with defaults equal to today's literals; no third copy. | F.1 |
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 —
docs/portfolio/methodology.md
P30–P40 added (renumbered from P29–P39 when #133 took P29), bound byconfig/portfolio_contract_tests.yml, verified by
portfolio:verify_contract_coverage. - Any gate test has an observed failing mutation transcript attached (below).
- Fixtures used as evidence assert internal consistency (the roll-up tests assert the two underlying
positions before rendering; the query-ceiling test records the measured count). - Financial calculations use
BigDecimaland documented rounding points (weights.round(2);
all money throughMoney). - De-identification uses token-shape allowlists; no personal data is included.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Exit criteria (the assertions that fail without the change)
| Assertion | Test | |
|---|---|---|
| E-a | Non-preview user → redirect to the dashboard with the preview flash; preview user → 200; nav entry in the desktop sidebar and not in the bottom bar | PortfoliosControllerTest "redirects users without preview access to the dashboard", "the nav shows Portfolio on desktop only, and never without the preview flag" |
| E-b | Duplicate-security fixture → one AAPL row whose value equals the statement's roll-up, expanding to two per-account rows with drawer links | "holdings table renders one row per security with its per-account positions" |
| E-c | Each KPI figure equals the statement's own figure for the period | "the KPI row prints the statement's own figures" |
| E-d | 10 accounts / 60 holdings within the recorded ceiling (measured 54, ceiling 60); 20 more holdings do not change the count | "the page's query count is bounded and does not grow with holdings" |
| E-e | A linked account whose history starts inside the period produces no leading zero points | InvestmentStatementTest "value_series does not chart leading zeros before a linked account's first supported history" |
| E-f | Order and collapse persist under portfolio_*, Reports keys untouched; Reports still posts to its own endpoint | "saves the section order and collapsed set under the portfolio namespace only", "drops preference keys that are not the portfolio's own"; ReportsControllerTest "reports sections rely on the Stimulus defaults and still post to their own endpoint" |
| E-g | A stub section appended to the registry renders last with no view change | Portfolio::SectionRegistryTest "appends extra sections after the built-ins" |
Mutation transcripts
Each mutation was applied to production code, the named tests run, and the file restored.
| Mutation | Tests that went red |
|---|---|
Series trim removed from fetch_series | "value_series does not chart leading zeros before a linked account's first supported history" |
previous_holdings returns nothing | "previous_holdings loads the prior snapshot of every holding in one query" |
before_action :require_preview_features! removed | "redirects users without preview access to the dashboard" |
| Registry ignores the user's saved order | "renders sections in the saved order, collapsed where the user left them" + two registry unit tests |
Bottom bar stops filtering desktop_only | "the nav shows Portfolio on desktop only…" (found 1 in the bottom bar) |
Header sort links drop sort= | "holdings table sorts through whitelisted links that keep the period and grouping" |
Grouping links drop by= | "allocation donut carries the grouping's segments and switches grouping through links" |
| Accounts grid lists every family account | "accounts grid links every countable investment account to its holdings tab and skips excluded shares" |
Per-account row renders holding.avg_cost | Survived — and rightly: after the batched preload (P40) that call is answered from memory, so it is no longer a per-holding query. The ceiling test still fails on a real per-holding query (observed at 115 queries before the preload landed). |
Validation
Commands and results (local, before push):
| Command | Result |
|---|---|
bin/rails test | 8833 runs, 36731 assertions, 0 failures, 0 errors, 30 skips (pre-existing skips) |
bin/rails portfolio:verify_contract_coverage | Verified 40 portfolio contract rows against existing tests (at 1c0d4ae78) |
Statement, portfolio, portfolios/reports/pages controller, helper, user and balance tests at 1c0d4ae78 | 360 runs, 4179 assertions, 0 failures, 0 errors |
bin/rails test at c7f66f951 (CodeRabbit round: series keys, cost-basis hints) | 8860 runs, 36934 assertions, 0 failures, 1 error (environmental: RecurringTransaction::PipelineTest opens its own PG.connect, which fails password auth on this machine on every branch), 30 skips |
Statement, portfolios controller and helper, portfolio models and task, I18nTest at c7f66f951 | 136 runs, 862 assertions, 0 failures, 4 skips |
bin/rails test at 1c0d4ae78 (after merging #133's c11907173) | 8859 runs, 36927 assertions, 0 failures, 1 error (environmental: RecurringTransaction::PipelineTest opens its own PG.connect, which fails password auth on this machine on every branch), 30 skips |
bin/rubocop -f github | no offenses |
bin/brakeman --no-pager | 0 security warnings |
bundle exec erb_lint ./app/**/*.erb | one pre-existing Style/StringLiterals hit in app/views/trading212_items/setup_accounts.html.erb:139, a file this branch does not touch; every portfolio view is clean |
npm run lint | 123 files, no issues |
| System tests | not run locally; CI's test_system job runs them. No browser-only behaviour was added beyond the Reports Stimulus controllers already exercised on Reports. |
| Migrations, OpenAPI | none |
Measured shape of the whole stack once we-promise/sure#2927 and we-promise/sure#3350 are adopted
upstream (jaysbeekay/sure#133 with its five adopted commits dropped, plus this PR):
| Commits | Files | Insertions | |
|---|---|---|---|
| jaysbeekay/sure#133 after adoption | 17 | 22 | 2,774 |
| This PR on top | 11 | 45 | 2,510 |
| Whole stack over upstream | 28 | 61 | 5,281 |
Split by kind: 1,927 lines of application code, 2,462 of tests, 892 of docs, config and CI.
Query evidence (S3): an integration probe counting SQL statements for GET /portfolio with 10 investment
accounts and 60 holdings (half without a stored cost basis), layout included:
| State | Queries |
|---|---|
| Before the accounts-grid preload | 88 (14 attachment, 12 provider and 12 accountable lookups, one per account) |
| Before the batched cost-basis preload, half the positions basis-less | 115 (two trades queries per basis-less holding from unrealized_gains_trend) |
| Final | 54, and unchanged by 20 more holdings; the ceiling test pins 60 |
The dashboard runs the same unrealized_gains_trend, so the batched preload also removes that
per-holding pair of queries from PagesController#dashboard for families whose broker stores no cost
bases.
Blast radius
reports_sortable_controller.js/reports_section_controller.js: onlyreports/index.html.erb
mounts them and passes no values; defaults equal the old literals; a Reports controller test asserts
the page carries no override attributes and the endpoint still stores the original keys.User#update_reports_preferencesand the two Reports readers delegate to the namespaced methods;
existing user and Reports tests unchanged and green.InvestmentStatement#day_change(no in-app reader before this PR) now sumsholding_day_change
over oneprevious_holdingsquery; the three hub series pass through the normaliser trim, which
only removes leading points before the common supported-history start.series_cache_keycarriesholdings_versionfor every series kind, not only gains (P30,be7a5b229): a
holding write, including a manual cost-basis edit, now moves the value and holdings-value keys too, and
building the key costs one memoized holdings count/max per statement.- The holdings table's cost-basis tooltips are two keys,
missing_cost_basis_hint(row badge) and
position_missing_cost_basis_hint(a position's dash), inenandde(c7f66f951). - Dashboard widget and Reports section: one preview-gated link each.
- No migration, no API change, no new Stimulus controller.
Risks, blockers, and follow-up
- Owner decisions D1–D9 are adopted as the review's recommended assumptions; each is a small
change if amended, and the contract rows name the test to update. - Stacked on #133: CI on this PR runs against the foundations branch; after #133 merges, retarget
tomain(GitHub keeps the commits), re-merge, and rerun the suite. - Contract row numbers are shared with #133. Both PRs append to
docs/portfolio/methodology.md, so a
row #133 adds takes the next number and this PR's rows move up (as ina69d7b99e). The gate fails on
a gap or a duplicate, so a collision cannot merge silently. - Reports chrome still hard-codes two English strings (
aria-label="Reports sections"and the
keyboard hint); the hub's equivalents are i18n keys. Worth a small follow-up on Reports. BalanceSheet::NetWorthSeriesBuilder#cache_keyhas the same share-revocation gap #133 fixed
for the statement; out of scope here.- Next unblocked issues: #121 (returns), #122 (classification), #123 (income), #124, #125, #128 —
each adds a section through the registry.
- Adds a preview-gated
/portfoliohub for family-wide investment data. - Adds KPI cards, value charts, holdings, accounts, allocation, and data-quality sections.
- Supports sorting, grouping, drag-and-drop ordering, collapsing, and portfolio-specific preferences.
- Adds batched holdings and average-cost loading to prevent per-holding queries.
- Adds preview-only navigation and dashboard/report links.
- Expands portfolio contract coverage and adds contract tests.
- Updates chart metadata, CI configuration, security classification support, and investment statement behavior.
| Author | Lines added | Lines removed |
|---|---|---|
| jaysbeekay | 1,586 | 273 |
| Claude | 307 | 63 |