Portfolio hub: preview-gated /portfolio page with consolidated holdings, value chart, allocation and data quality (#120)

Merged
JA
3mo ago
+2683-35

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 through Portfolio::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
    commits 177bfc9b7 and c41fccd5a (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 to main.
  • 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)

DecisionWhere
D1"Portfolio" for nav, title, breadcrumb and URL; the dashboard widget keeps "Investments".locales
D2Corrected 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
D3Consolidated rows expand (native <details>) to per-account positions with the existing holding_path drawer link; no new route.holdings partial
D4Server-side sort `?sort=valueweight
D5Deterministic palette from Category::COLORS (the chart palette the app already uses), indexed by sorted position.PortfoliosHelper
D6Stale = 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
D8Periodable persists the chosen period as the user's default, as the dashboard and accounts do.controller
D9The 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 by config/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 BigDecimal and documented rounding points (weights .round(2);
    all money through Money).
  • 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)

AssertionTest
E-aNon-preview user → redirect to the dashboard with the preview flash; preview user → 200; nav entry in the desktop sidebar and not in the bottom barPortfoliosControllerTest "redirects users without preview access to the dashboard", "the nav shows Portfolio on desktop only, and never without the preview flag"
E-bDuplicate-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-cEach KPI figure equals the statement's own figure for the period"the KPI row prints the statement's own figures"
E-d10 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-eA linked account whose history starts inside the period produces no leading zero pointsInvestmentStatementTest "value_series does not chart leading zeros before a linked account's first supported history"
E-fOrder 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-gA stub section appended to the registry renders last with no view changePortfolio::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.

MutationTests 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_costSurvived — 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):

CommandResult
bin/rails test8833 runs, 36731 assertions, 0 failures, 0 errors, 30 skips (pre-existing skips)
bin/rails portfolio:verify_contract_coverageVerified 40 portfolio contract rows against existing tests (at 1c0d4ae78)
Statement, portfolio, portfolios/reports/pages controller, helper, user and balance tests at 1c0d4ae78360 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 c7f66f951136 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 githubno offenses
bin/brakeman --no-pager0 security warnings
bundle exec erb_lint ./app/**/*.erbone 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 lint123 files, no issues
System testsnot 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, OpenAPInone

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):

CommitsFilesInsertions
jaysbeekay/sure#133 after adoption17222,774
This PR on top11452,510
Whole stack over upstream28615,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:

StateQueries
Before the accounts-grid preload88 (14 attachment, 12 provider and 12 accountable lookups, one per account)
Before the batched cost-basis preload, half the positions basis-less115 (two trades queries per basis-less holding from unrealized_gains_trend)
Final54, 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: only reports/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_preferences and 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 sums holding_day_change
    over one previous_holdings query; the three hub series pass through the normaliser trim, which
    only removes leading points before the common supported-history start.
  • series_cache_key carries holdings_version for 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), in en and de (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
    to main (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 in a69d7b99e). 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_key has 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 /portfolio hub 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.
AuthorLines addedLines removed
jaysbeekay1,586273
Claude30763