Draw every loan line on the account chart

Draft
JA
2mo ago
+2569-1264

Summary

Closes #390. Part of #100: on the fork only, this reverses decision 10 (the descoped extra-payment line), as the issue records.

A loan page drew three charts: the plain balance chart at the top, a schedule/projection chart under the Schedule tab's table, and an extra-repayment chart under the Extra repayments form. Now there is one loan chart, in the account chart card at the top, carrying every line. The tabs draw no chart.

  • actual: recorded balances, solid, never past as_of.
  • scheduled: the contract, re-amortised at each recorded rate change, dashed.
  • projected: from today's balance on the schedule's repayment, dashed.
  • extra: the same projection plus the modelled monthly extra, dotted in --color-info. It is drawn only when a valid amount is in the request, and the legend names the amount ("With $250.00 extra each month").

The Extra repayments tab keeps its form and three cards. Submitting it (or Clear) reloads the whole page (_top) with tab and period, so the top chart and the tab redraw together. The Schedule tab keeps its cards and tables. A loan that can't be drawn, and every non-loan account, keeps today's balance chart unchanged.

5732ec466, 2026-10-12: the projection reads its offsets once, not once per period (nightly review MEDIUM, "page-load cost"; owner's instruction: "Fix the #403 sibling too", after the same fix in #405).

  • The defect. The chart builds a payoff projection on every loan page, and the projection asks one Loan::OffsetResolver once per period. Each future period re-ran the offsets' existence check and today's total. The query cache answered them, but building each query cost about 1.6 ms.

  • The fix. Within one projection the linked accounts and today's total are fixed, so the resolver now checks the accounts it already loads and keeps the total. Historical ranges still read their balances per call.

  • Measured on a 360-month variable loan with two offset accounts and ten years of daily balances, one fresh request each, median of three:

    mainbeforeafter
    Overview0.48 s1.18 s0.63 s
    Schedule tab1.99 s2.20 s1.04 s
  • Test: "resolving many future periods reads the offsets and today's total once", over 60 periods.

    • It failed first with 121 queries.
    • Re-querying the total (61 queries) or re-checking existence (62) each fail it.
    • The other resolver tests build a fresh resolver after each balance change, and are unchanged.
  • Validation: full bin/rails test on 5732ec466 gave 12,397 runs and 1 failure, the known Provider::OpenaiTest string. bin/brakeman reports 0 warnings, and bin/rubocop no offenses.

  • Callers: PayoffProjection#offset_resolver builds one resolver per simulation. #405 makes the same change on its engine (51a2d260b), where the page went from 1.74 s to 0.56 s.

Ported from upstream (origin/mirror/upstream-main, we-promise/sure#3474, which 604fdb698 took back out):

  • Loan::PayoffChart: domain, windows, visible?, the actual series clipped to as_of and origination, locale, currency precision, labels and aria text.
  • UI::PeriodPicker's options:.
  • The chart component's loan branch and conditional legend.
  • loan_payoff_chart_controller.js: token colours, x-domain from the payload, locale formatting, keyboard stepping, and the principal/interest tooltip split from #21.
  • chart_card_requested?, with its rescue to nil and Sentry report.
  • The upstream tests. Two were missed in the first commit and are added in a2c4685f9 (see Review findings).

Adapted to the fork's engine.

  • Origination is loan.start_date || loan.account_opening_anchor_date.
  • Scheduled points come from AmortizationSchedule#display_rows, so stale persisted rows are never plotted next to live figures.
  • Amount borrowed is loan.original_balance; the projection is Loan::PayoffProjection.new(loan, as_of:).
  • The fork has no balloon_amount: a balance that never clears says "no payoff" in the aria text and has no projected line.
  • New extra series with extra_payoff_date, its legend label and an aria sentence.
  • Legend swatches use token classes (border-success / border-destructive / border-info) rather than inline var().
  • Tooltip stops include the forecasts' payment dates, so a projection past the contract can be read to its end.
  • The fork's turbo:render redraw hook is kept.
  • The payload's locale reaches Intl through intlLocale(), which falls back to the browser's locale for a tag Intl rejects (a2c4685f9).

Not ported, deliberately:

  • upstream's projected-payoff and interest-saved cards beside the chart, because the Schedule tab already has them;
  • the "Remaining balance" title switch, because the fork's key already reads "Remaining loan balance".

Scope and dependencies

  • Issue: #390.
  • Parent PR/branch, if stacked: none. Base main.
  • Intentionally out of scope: Period, Balance::ChartSeriesBuilder, time_series_chart_controller.js, PayoffProjection's maths, Loan#current_minimum_payment, saved scenarios, moving the form off its tab, and anything upstream.

Wiring and reference dates. AccountsController#show sets @as_of = Date.current once and builds one Loan::ExtraRepaymentComparison on it. The chart, the Schedule tab and the Extra repayments tab all read that comparison. The period picker carries extra_payment[amount] and tab=extra_repayments, but only for a loan chart with an amount.

One addition beyond the plan's explicit list: any page that draws the loan chart now queues the stale-schedule rebuild job the tabs already queued. That is how I read the triage plan's "moves under a loan check". It has its own test, which failed first. Owner to confirm.

Blast radius.

  • UI::Account::Chart renders for every account type. I rendered the chart card on main and on this branch for a depository, a no-rate loan, an investment account and a credit card. The markup is identical apart from whitespace and DS::Menu's random ids.
  • time_series_chart_controller.js is not touched.
  • UI::PeriodPicker's other callers pass their own extra_params and are unaffected. A test passes an amount on a non-loan chart and checks nothing leaks.

Siblings (grep -n "loan-payoff-chart\|payoff_chart_payload\|chart_payload" over app/ and test/):

  • _schedule.html.erb, _extra_repayments.html.erb: chart and legend removed.
  • Loan#payoff_chart_payload and its private extra_payment_label, and ExtraRepaymentComparison#chart_payload: deleted.
  • accounts_controller_test (old 1181, 1233, 1348–1390 and the 1815 helper): moved to the top chart.
  • loan_test.rb: 19 payload tests removed. Their substance (stale rows, composition, front-loading, variable rate, payment anchor, extra series) is re-asserted in payoff_chart_test.rb.
  • amortizations_read_guard_test.rb named the method only in a comment; there was no allowlist entry. Comment updated.
  • loans.tabs.schedule.chart.* removed from en, ru, tr and uk, the only locales carrying it. No extra-repayments legend keys existed.
  • Left alone, because neither shows the chart: the Overview tab still reads its own Date.current, and Api::V1::LoansController still uses Loan#payoff_projection.

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.
  • Any gate test has an observed failing mutation transcript attached.
  • Fixtures used as evidence assert internal consistency.
  • Financial calculations use BigDecimal and documented rounding points.
  • De-identification uses token-shape allowlists; no personal data is included.
  • Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.

The issue's tests 1–9, each seen failing first:

#TestFirst failure
1component, positiveArgumentError: unknown keyword :loan_chart
2non-loan and non-amortizable loan unchangedpinning; passes on main by design, plus the markup comparison above
3exactly one chart, in the card, on every tabexpected 1 in the card, got 0
4extra series as a delta against the no-amount payload, ending on the "Payoff with extra" card's datethe card did not mount the loan chart
5"", 0, -5, abc, NaN, Infinity, 1e400, non-hash: no extra series, no errorsame
6period links carry amount and tab (controller and component)?period=last_day, amount nil
7payload: actual never passes as_of; scheduled opens at origination on the original balance; projected and extra endpoints match the projections for the same as_ofNameError: uninitialized constant Loan::PayoffChart
8browser (test/system/loan_payoff_chart_test.rb): 3 painted paths without an amount, 4 with; a form submit redraws the top chart; light/dark; keyboard; localerun locally on a2c4685f9 in headless Chromium: 11 runs, 97 assertions, 0 failures; CI runs it too
+form/Clear go to _top with tab and period; stale-rebuild queued from the chartboth failed first

Mutations (file copied out and back each time):

MutationCaught by
delete the extra seriestest 4, and the existing extra-line/cards controller test
drop the period-picker paramtest 6, controller and component
restore a Schedule-tab mount / an Extra-tab mounttest 3
actual series allowed past as_of3 tests
scheduled opening point removed6 tests
aria composition sentence removed1 test
form without _top; period hidden field removedtheir tests
loan branch in the component disabled4 tests
picker options removedits test
loan picker params applied to non-loan chartstest 2, once it passed an amount
a database query per scheduled rowthe query-count test
un-memoise origination / domain_startsurvives: the loan and account already memoise the anchor, so it costs nothing
a2c4685f9: the chart rescue narrowed to NotImplementedError"a chart payload that raises degrades..." (ArgumentError: boom)
a2c4685f9: chart_card_requested? always true"a frame request outside the chart card..." (unexpected invocation ... payload())
a2c4685f9: the axis's locale read reverted to data.locale"a locale Intl rejects still paints the chart" (no painted series)
a2c4685f9: the tooltip's locale read revertedthe same test (the tooltip never opens)
5732ec466: the resolver re-queries today's total / re-checks existence per period"resolving many future periods reads the offsets and today's total once" (61 / 62 queries)

Screenshots.

  • How they were taken: from a static harness, because the repository's instructions forbid running rails server here. The harness is the rendered chart-card component with the real Stimulus controller, d3 and built Tailwind, served by python3 -m http.server and captured with headless Chromium.
  • What they show: a variable mortgage at 6.43% with a recorded change. The contract ends 2052-06, the projection 2054-06, and a $250 extra ends 2047-04. Light and dark, each with and without the extra line.
  • What they don't cover: tooltip and hover were not exercised in a browser at the time; the system tests above now do.

The screenshots are not attached to this PR; the owner's local build is the real check.

Validation

  • CI on 79d3f50 (ci / *, CodeQL, Brakeman): green, as the Gatekeeper light review also records.
  • CI on 5732ec466: running at the time of writing.
  • Full bin/rails test on 79d3f50: 12,394 runs, 1 failure (the known Provider::OpenaiTest#test_extra_headers_stringifies_nested_values_Ruby-style, a Ruby 3.3 vs 3.4 string), 0 errors, 35 skips.
  • On a2c4685f9:
    • accounts_controller_test.rb, payoff_chart_test.rb and test/components: 352 runs, 0 failures;
    • test/system/loan_payoff_chart_test.rb in headless Chromium: 11 runs, 0 failures;
    • bin/rubocop on the two changed test files: no offenses; npm run lint (Biome): clean.
  • On 5732ec466: full bin/rails test, 12,397 runs, 1 failure (the same Provider::OpenaiTest); bin/brakeman 0 warnings.
  • bin/rubocop on 15 changed Ruby files: no offenses. erb_lint on 8 changed ERB files: clean. npm run lint and biome check: clean. bin/brakeman --no-pager -q: 0 warnings.
  • Checked against upstream AGENTS.md.

Review findings

  • Codacy Jshint (via the github-advanced-security summary review, "more than 20 potential problems"): no change. Its check run reports success with 21 annotations, all in loan_payoff_chart_controller.js.

    • Twenty are "const/let/destructuring is available in ES6 (use esversion: 6)": with no .jshintrc, Jshint applies ES5 rules.
    • The 21st, line 83 "Expected an assignment or function call", is this._tooltip?.remove();. That is optional chaining, which Jshint's parser doesn't support.

    The repository lints JavaScript with Biome; npm run lint and ci / lint_js pass.

  • Gatekeeper light review, comment 6102087953, DRAFT_ON_TRACK, MODERATE: "extra_payment parameter is trusted as a plain amount and only range-validated". It recommends either (a) capping the amount at a realistic bound, such as twelve months of the scheduled minimum, or (b) adding a UI hint that the figure is a hypothetical. Declined, no code change, checked against 79d3f50:

    • Not this PR's code. MAX_EXTRA_PAYMENT_AMOUNT = BigDecimal("10000000"), extra_payment_params and valid_extra_payment_amount? are on main already (app/controllers/accounts_controller.rb:528–550), and this PR doesn't change them. It only moves where the resulting extra line is drawn.
    • (b) is already there. The tab's intro (loans.tabs.extra_repayments.intro, config/locales/views/loans/en.yml:53) reads "See how much sooner the loan is paid off, and how much interest you save, if you pay an extra amount each month on top of the current repayment". The review agrees the tab is "explicitly a hypothesis".
    • (a) would block legitimate what-ifs. A user modelling a windfall or a planned lump sum asks exactly the question a large amount answers. An extra above the remaining balance clearing the loan in one or two payments is the correct answer to that question, not a degraded one.
    • The edges are covered. The existing tests reject non-finite, non-positive, malformed and above-cap amounts (test 5 above, and accounts_controller_test).

    If you'd rather add a cap or extra wording anyway, it belongs in its own change to the shared controller, not in this chart move.

  • "code master" reviews, comment 6105940423 and comment 6105960528, both HOLD, on 79d3f50. Merged into one list and checked against that head. One narrow fix and a real test gap went in as a2c4685f9; nothing else needs code.

    • Invalid locale crashes the chart (A8, B3): confirmed, narrowly; fixed.

      • The reviewers' examples don't hold: Intl accepts "xx", and "en-US-xxxx" can't reach the payload.
      • But the payload carries I18n.locale, and one locale the app loads, zh-YUE, is rejected by Intl (RangeError: Incorrect locale information provided). Of the 124 loaded locales checked in Node 22, only that one throws. It is reachable with ?locale=zh-YUE, and it left the chart area empty.
      • intlLocale() now canonicalises the tag and falls back to the browser's locale. Both reads (axis ticks, tooltip) use it.
      • New system test: "a locale Intl rejects still paints the chart". It fails before the fix, and fails again if either read is reverted.
      • Upstream's controller has the same two reads; this could go upstream on its own.
    • Untested error handling (B6, gaps): confirmed as a test gap; fixed. Two upstream tests this description counted as ported were not:

      • "a chart payload that raises degrades to the time-series chart instead of a 500";
      • "a frame request outside the chart card does not build the chart payload".

      Both are now in accounts_controller_test.rb. They pass on the code, and each fails when the code it guards is broken (Mutations above).

    • Heavy work on every loan page (A1, B1): already decided, and upstream's design. Upstream builds the projection and payload on every loan page too (accounts_controller.rb:107-108), and "One addition..." above records it. The schedule was already computed on every loan page on main, by the Overview tab's payoff date and minimum payment, and it is cached per request (171.8 ms the first time, 2.2 ms after that).

      • The projection's per-period offset exists? check is fork-only. Before this PR it ran only on the Schedule and Extra repayments tabs; now it runs on every loan page (237 statements over 228 periods for a 30-year loan in test, before Rails' query cache).
      • That follow-up is now done: 5732ec466 checks once per projection (top of this description).
      • The "10-100x" and "saturate the database" claims aren't supported; nothing was load-tested.
    • The rescue hides bugs (A2): upstream's design. Same code and comment upstream (accounts_controller.rb:343-351). It logs and reports to Sentry. It now has tests (above).

    • Stale data after a rate change (A3, B2): declined. display_rows returns freshly computed rows when the saved ones are stale (amortization_schedule.rb:163-165), and payoff_chart_test.rb:50 asserts that. The Schedule tab doesn't rebuild synchronously either; it queues the same background job.

    • A large extra slows the simulation (A4): declined, measured. An extra of 10,000,000 runs one period (69 ms). An extra of 0.01 runs the same 228 periods as no extra. The loop is capped (simulator.rb:59).

    • Chart cleared before the data is checked (A5): declined. Same as upstream. The server always sends an end date after the start (payoff_chart.rb:161), and clearing first is the correct order for a redraw.

    • Clip-path id collision under Turbo (A6): declined. Same as upstream. The chart element always carries a unique id (chart.html.erb:55), so the counter fallback never runs; each redraw clears the old SVG; and a test asserts one chart per page.

    • Long aria-label (A7, B5): upstream's design. The fork keeps upstream's sr-only description too (chart.html.erb:73). No spec caps an aria-label's length. Real screen readers were not tested.

    • Tooltip overflows on narrow screens (A9, B4): declined, measured. In Chromium with a four-series tooltip, it went at most 0 px past the chart's right edge at both 360 and 320 px wide; the text wraps instead.

    • A balance query on every page (A10): declined. It replaces the plain chart's own balance query for a loan (chart.rb:214-232), so one query is swapped for another. Upstream runs the same one.

    • Tooltip memory leak (A11): declined. The tooltip has no listeners, and it is removed on every redraw and on disconnect.

    • Two requests queue two rebuild jobs (A12): declined. The job is locked per loan (loan_amortization_rebuild_job.rb:6), and the rebuild re-checks under a row lock. This PR doesn't touch that code.

  • Nightly review (comment 6120559035), READY WITH CONDITIONS, on a2c4685f9: no blocking findings.

    • MEDIUM, page-load cost: measured, and it was real. On the loan above, the Overview took 1.18 s on this branch against 0.48 s on main, almost all of it in the per-period offset check. Fixed in 5732ec466 (0.63 s; top of this description).
    • The longest loans: a 1,200-month loan with the same offsets measures 1.62 s on the Overview, after the fix, against 1.57 s on main. The Schedule tab measures 3.63 s against 6.36 s on main. That cost is the simulation over 1,200 periods, which main already pays.
  • Nightly review (comment 6134304680), READY TO MERGE, on 5732ec466. No blocking or other material findings. It confirms the offset regression is gone (offsets resolved once per projection). Nothing to change.

Review responses are recorded here rather than as comments, because comments posted from this session get an assistant footer appended, which this repository's attribution rule forbids.

Risks, blockers, and follow-up

  • Issue Gatekeeper Review: none had landed on #390 when this was built (the owner asked for gatekeeper reviews to be set aside for now), and none has landed since (checked 2026-10-10). Its findings may revise the plan.
  • Projection cost: the projection now runs on every loan page.
    • Since 5732ec466, a resolver reads the offset accounts and today's total once per projection, not once per period.
    • What remains is the simulation itself, which scales with the loan's term.
    • OffsetResolver#change_points still reads Date.current itself on this engine; #405 passes as_of in.
  • Periods: a saved 7D or 30D period shows the whole life, reads "All" in the picker, and the trend reads "since the loan started". This is upstream's behaviour, carried over.
  • The Extra tab's cleared_by_extra notice still ends "as shown above"; it now refers to the cards.
  • Upstream's balloon notice is gone, as the fork has no balloon field.