The personal finance app for everyone (by everyone)
Ruby
require "application_system_test_case"
# The one thing the Ruby and controller-level tests cannot say.
#
# Loan::PayoffChartTest proves the payload is right, and the controller test
# proves it reaches the data attribute. Neither proves a line is PAINTED --
# which is the failure mode this chart has already been reported for once.
#
# So these assertions are deliberately about the rendered SVG and the DOM
# around it: that each series exists as a path with real geometry and a
# stroke that will mark the screen, in both themes; that the description and
# the keyboard give a screen-reader or keyboard user the figures;
# and that the live region stays quiet under a pointer. A test that
# re-checked payoff dates here would be re-running Loan::PayoffChartTest
# through a browser, slowly.
class LoanPayoffChartTest < ApplicationSystemTestCase
# Pinned so the schedule, the projection and therefore the number of drawn
# series are the same run to run. The loan opens 2026-01-01 over 24 months,
# so this sits mid-term with real history behind it and real term ahead.
TODAY = Date.new(2027, 1, 15)
SERIES = %w[actual scheduled projected].freeze
# Sign in at the later of TODAY and the real clock. The session must not
# count as idle beyond Session::INACTIVITY_TIMEOUT inside travel_to(TODAY),
# nor on the real clock, which serves any request the browser makes between
# travel_to blocks. Either way an idle session lands on the login page.
setup do
travel_to([ Date.current, TODAY ].max) { sign_in @user = users(:family_admin) }
end
test "the chart paints all three lines, in the light theme and the dark" do
travel_to TODAY do
account = on_contract_loan_account
visit account_path(account, period: "all_time")
assert_selector "[data-controller='loan-payoff-chart'] svg"
assert_series_painted
strokes_in_light = SERIES.to_h { |key| [ key, stroke_of(key) ] }
# The strokes are live CSS variables, so the browser repaints them from
# the dark palette without a redraw; nothing in the controller watches
# the theme. Wait on the computed stroke itself.
page.execute_script("document.documentElement.setAttribute('data-theme', 'dark')")
wait_until { stroke_of("actual") != strokes_in_light["actual"] }
assert_series_painted
assert_not_equal strokes_in_light["actual"], stroke_of("actual"),
"the recorded line must repaint from the dark theme's token"
end
end
# The Extra repayments tab's amount reaches the chart as a fourth line,
# through the form a borrower actually uses. The line must paint in its own
# colour in both themes, and the legend must name it.
test "an extra repayment paints its own line beside the others" do
travel_to TODAY do
account = on_contract_loan_account
visit account_path(account, period: "all_time", tab: "extra_repayments")
assert_no_selector "[data-controller='loan-payoff-chart'] svg path[data-series='extra']"
# Laid out as the Bills form is: the amount and how often side by side,
# Apply below them as the form's one full-width action, and nothing
# wider than the tab.
field = find_field(I18n.t("loans.tabs.extra_repayments.amount_label"))
field_box = bounding_box(field.find(:xpath, "ancestor::div[contains(concat(' ', normalize-space(@class), ' '), ' form-field ')][1]"))
select = find_field(I18n.t("loans.tabs.extra_repayments.frequency_label"))
select_box = bounding_box(select.find(:xpath, "ancestor::div[contains(concat(' ', normalize-space(@class), ' '), ' form-field ')][1]"))
apply_box = bounding_box(find_button(I18n.t("loans.tabs.extra_repayments.apply")))
form_box = bounding_box(field.find(:xpath, "ancestor::form[1]"))
assert_in_delta field_box["top"], select_box["top"], 2, "the amount and how often must share a row"
assert_operator select_box["left"], :>=, field_box["right"], "how often sits to the amount's right"
assert_operator apply_box["top"], :>=, field_box["bottom"], "Apply sits below the fields"
assert_in_delta form_box["left"], apply_box["left"], 2, "Apply alone spans the form, from its left edge"
assert_in_delta form_box["right"], apply_box["right"], 2, "to its right edge"
assert_operator select_box["right"], :<=, form_box["right"] + 1, "and nothing overflows the form"
field.fill_in with: "1000"
select I18n.t("loans.tabs.extra_repayments.frequencies.weekly"), from: I18n.t("loans.tabs.extra_repayments.frequency_label")
click_button I18n.t("loans.tabs.extra_repayments.apply")
assert_field I18n.t("loans.tabs.extra_repayments.frequency_label"), with: "weekly"
# With an amount entered, Clear joins Apply as a right-aligned pair:
# Clear first, Apply at the form's right edge, both at natural width.
apply_box = bounding_box(find_button(I18n.t("loans.tabs.extra_repayments.apply")))
clear_box = bounding_box(find_link(I18n.t("loans.tabs.extra_repayments.clear")))
form_box = bounding_box(find_field(I18n.t("loans.tabs.extra_repayments.amount_label")).find(:xpath, "ancestor::form[1]"))
assert_in_delta form_box["right"], apply_box["right"], 2, "Apply ends the pair at the form's right edge"
assert_operator clear_box["right"], :<=, apply_box["left"], "Clear comes before Apply"
assert_in_delta clear_box["top"], apply_box["top"], 2, "on one row"
assert_operator apply_box["left"], :>, form_box["left"] + (form_box["right"] - form_box["left"]) / 2, "at natural width, not spanning the form"
# Each card's figure fits inside its card, at the width the page has with
# both side panels open. Three across only when the tab has room.
page.driver.browser.manage.window.resize_to(1280, 1400)
assert_selector "[data-testid='total-cost']"
overflowing = page.evaluate_script(<<~JS)
Array.from(document.querySelectorAll("[data-testid='extra-cards'] > div p"))
.filter((p) => p.scrollWidth > p.clientWidth + 1)
.map((p) => p.textContent.trim())
JS
assert_empty overflowing, "a card's figure runs past its card"
extra = find("[data-controller='loan-payoff-chart'] svg path[data-series='extra']")
assert extra["d"].to_s.start_with?("M"), "the extra line has no geometry"
assert_not_equal "none", stroke_of("extra"), "the extra line has geometry but no resolved stroke"
assert_not_equal stroke_of("projected"), stroke_of("extra"), "the extra line must not reuse the projection's colour"
assert_selector "ul li", text: I18n.t("UI.account.chart.loan.extra")
assert_series_painted
light = stroke_of("extra")
page.execute_script("document.documentElement.setAttribute('data-theme', 'dark')")
wait_until { stroke_of("extra") != light }
assert_not_equal light, stroke_of("extra"), "the extra line must repaint from the dark theme's token"
end
end
# A loan has five tabs, more than the account column holds beside both side
# panels. Labels stay on one line, and the bar scrolls inside the column
# rather than pushing the page sideways and hiding Statements off-screen.
test "the loan's tab bar keeps one line and stays inside its column" do
travel_to TODAY do
visit account_path(on_contract_loan_account)
details = find("[data-testid='account-details']")
heights = all("[data-testid='account-details'] [role='tab']").map { |tab| bounding_box(tab)["height"] }
assert_equal 5, heights.length
assert_equal 1, heights.uniq.length, "every tab is the same height"
assert_operator heights.first, :<, 40, "a label that wraps doubles the tab's height"
# The bar's own box stays inside the column either way; what must not
# happen is its tabs spilling out and widening the column's content.
overflow = page.evaluate_script("arguments[0].scrollWidth - arguments[0].clientWidth", details)
assert_operator overflow, :<=, 0, "the tabs must not run past their column"
statements = find("[data-testid='account-details'] [role='tab'][data-id='statements']")
statements.click
assert_equal "true", statements["aria-selected"], "the last tab is reachable"
end
end
# The SVG names the balance and every payoff date in its label, the
# same text is real DOM, and it points at no table that is not there.
test "the SVG carries its description and no data table" do
travel_to TODAY do
account = on_contract_loan_account
payload = Loan::PayoffChart.new(account.loan, as_of: TODAY, period: all_time_period).payload
visit account_path(account, period: "all_time")
svg = find("[data-controller='loan-payoff-chart'] svg")
assert_equal payload[:aria_description], svg["aria-label"]
assert_nil svg["aria-details"], "the chart must not point at a table"
assert_selector "p.sr-only", text: payload[:aria_description], visible: :all
assert_no_selector "##{ActionView::RecordIdentifier.dom_id(account, :chart)} table", visible: :all
end
end
# Every plotted date is reachable from the keyboard, and only the
# keyboard talks to the live region -- a pointer sweeping the chart would
# otherwise announce on every movement.
test "arrow keys step the tooltip through the plotted dates and only they announce" do
travel_to TODAY do
account = on_contract_loan_account
visit account_path(account, period: "all_time")
svg = find("[data-controller='loan-payoff-chart'] svg")
assert_equal "0", svg["tabindex"], "the chart must be focusable"
svg.send_keys(:arrow_right)
tooltip = find("[data-controller='loan-payoff-chart'] div[aria-live='polite']", visible: :all)
first = tooltip.text(:all)
assert_match I18n.t("UI.account.chart.loan.scheduled"), first
assert_includes tooltip[:class].to_s.split, "chart-tooltip"
assert_includes tooltip[:class].to_s.split, "z-50"
svg.send_keys(:arrow_right)
assert_not_equal first, tooltip.text(:all), "the second press moves to the next date"
svg.send_keys(:escape)
assert_no_selector "[data-controller='loan-payoff-chart'] div[aria-live='polite']", visible: :all
# A pointer sweep shows the tooltip but never turns it into a live region.
page.execute_script(<<~JS)
const rect = document.querySelector("[data-controller='loan-payoff-chart'] svg rect[style*='cursor']");
const box = rect.getBoundingClientRect();
rect.dispatchEvent(new PointerEvent("pointermove", { clientX: box.left + box.width / 2, clientY: box.top + box.height / 2, bubbles: true }));
JS
assert_selector "[data-controller='loan-payoff-chart'] div.chart-tooltip", text: I18n.t("UI.account.chart.loan.scheduled")
assert_no_selector "[data-controller='loan-payoff-chart'] div[aria-live='polite']", visible: :all
end
end
# we-promise/sure#3958: stopped on a scheduled payment, the tooltip says what
# that payment is made of. The first stop is origination, the amount
# borrowed rather than a payment, so it has no split; the second is the
# first payment.
test "the tooltip splits a scheduled payment into principal and interest" do
travel_to TODAY do
account = on_contract_loan_account
first_payment = account.loan.amortization_schedule.payments.first
visit account_path(account, period: "all_time")
svg = find("[data-controller='loan-payoff-chart'] svg")
principal_label = I18n.t("loans.tabs.schedule.principal")
svg.send_keys(:arrow_right)
tooltip = find("[data-controller='loan-payoff-chart'] div[aria-live='polite']", visible: :all)
assert_not_includes tooltip.text(:all), principal_label, "origination is not a payment"
svg.send_keys(:arrow_right)
# The split at the currency's precision (cents for USD), so a small
# component never shows as zero; the balance stays in whole units.
money = ->(value, digits) { page.evaluate_script("new Intl.NumberFormat('en', { style: 'currency', currency: 'USD', minimumFractionDigits: #{digits}, maximumFractionDigits: #{digits} }).format(#{value})") }
expected = "#{principal_label}: #{money.(first_payment.principal.amount.to_f, 2)} · " \
"#{I18n.t('loans.tabs.schedule.interest')}: #{money.(first_payment.interest.amount.to_f, 2)}"
assert_includes tooltip.text(:all), expected
assert_includes tooltip.text(:all), money.(first_payment.ending_balance.amount.to_f, 0)
end
end
# The tooltip formats its date and its money in the request's locale, which
# the payload carries because the layout hard-codes `lang="en"`. Asserted
# against what the browser's own Intl produces for German, so the expected
# strings are not guessed; and against the English forms, so a formatter
# that ignored the locale would fail here.
test "the tooltip is formatted in the user's locale" do
@user.update!(locale: "de")
travel_to TODAY do
account = on_contract_loan_account
visit account_path(account, period: "all_time")
svg = find("[data-controller='loan-payoff-chart'] svg")
svg.send_keys(:arrow_right)
tooltip = find("[data-controller='loan-payoff-chart'] div[aria-live='polite']", visible: :all)
# The tooltip is one div per line; Capybara joins them without separators.
text = tooltip.text(:all)
german_date = page.evaluate_script("new Intl.DateTimeFormat('de', { month: 'short', year: 'numeric' }).format(new Date(2026, 0, 1))")
german_money = page.evaluate_script("new Intl.NumberFormat('de', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(500000)")
assert text.start_with?(german_date), "expected the tooltip to open with #{german_date.inspect}, got #{text.inspect}"
assert_not text.start_with?("Jan 2026"), "d3's English month name must not leak through"
# Intl separates the number and the symbol with a no-break space that
# Capybara's text normalises to a plain one; compare on plain spaces.
assert_includes text.gsub(/[[:space:]]/, " "), german_money.gsub(/[[:space:]]/, " ")
assert_not_includes text, "$500,000", "the English money format must not leak through"
end
end
# Codex on we-promise/sure#3474: d3's default time ticks print English month
# names, so a German page showed a German tooltip over an English axis. A
# one-year window ticks by month; each month tick must read as the browser's
# own German short month, and never as d3's English month name.
test "the axis labels its month ticks in the user's locale" do
@user.update!(locale: "de")
travel_to TODAY do
account = on_contract_loan_account
visit account_path(account, period: "last_365_days")
find("[data-controller='loan-payoff-chart'] svg path[data-series='scheduled']")
ticks = page.evaluate_script(<<~JS)
Array.from(document.querySelectorAll("[data-controller='loan-payoff-chart'] svg g[transform^='translate(0,'] g.tick"))
.map((tick) => tick.__data__)
.filter((date) => date.getDate() === 1 && date.getMonth() !== 0)
.map((date) => ({
label: Array.from(document.querySelectorAll("[data-controller='loan-payoff-chart'] svg g[transform^='translate(0,'] g.tick"))
.find((tick) => tick.__data__.getTime() === date.getTime()).textContent,
german: new Intl.DateTimeFormat("de", { month: "short" }).format(date),
english: new Intl.DateTimeFormat("en", { month: "long" }).format(date),
}))
JS
assert ticks.any?, "a one-year window must have month ticks, or this asserts nothing"
ticks.each do |tick|
assert_equal tick["german"], tick["label"], "a month tick must be labelled in German"
assert_not_equal tick["english"], tick["label"], "d3's English month name must not leak through"
end
end
end
# Codex on we-promise/sure#3474: the heading showed the cursor's own month
# while every row showed the nearest point's balance, so a cursor just before
# a payment date named one month over the next payment's figures. The pointer
# now snaps to the payment dates, as the keyboard does.
test "a pointer just before a payment date heads the tooltip with that payment's month" do
travel_to TODAY do
account = on_contract_loan_account
payload = Loan::PayoffChart.new(account.loan, as_of: TODAY, period: all_time_period).payload
dates = payload[:scheduled].map { |point| Date.iso8601(point[:date]) }
payment = dates.each_cons(2).map(&:last).find { |date| (date - 2).month != date.month && date - 2 > dates.first }
assert payment, "the schedule must have a payment date two days into a new month, or this asserts nothing"
cursor = payment - 2
visit account_path(account, period: "all_time")
find("[data-controller='loan-payoff-chart'] svg path[data-series='scheduled']")
heading = page.evaluate_script(<<~JS)
(() => {
const at = (iso) => { const [y, m, d] = iso.split("-").map(Number); return new Date(y, m - 1, d).getTime(); };
const start = at("#{payload[:domain_start]}");
const finish = at("#{payload[:domain_end]}");
const rect = document.querySelector("[data-controller='loan-payoff-chart'] svg rect[style*='cursor']");
const box = rect.getBoundingClientRect();
const clientX = box.left + ((at("#{cursor.iso8601}") - start) / (finish - start)) * box.width;
rect.dispatchEvent(new PointerEvent("pointermove", { clientX, clientY: box.top + box.height / 2, bubbles: true }));
return document.querySelector("[data-controller='loan-payoff-chart'] div.chart-tooltip").firstElementChild.textContent;
})()
JS
expected = page.evaluate_script("new Intl.DateTimeFormat('#{payload[:locale]}', { month: 'short', year: 'numeric' }).format(new Date(#{payment.year}, #{payment.month - 1}, 1))")
cursor_month = page.evaluate_script("new Intl.DateTimeFormat('#{payload[:locale]}', { month: 'short', year: 'numeric' }).format(new Date(#{cursor.year}, #{cursor.month - 1}, 1))")
assert_not_equal expected, cursor_month, "the cursor must sit in a different month from the payment, or this asserts nothing"
assert_equal expected, heading, "the heading must name the payment whose figures the tooltip shows"
end
end
# The area under the scheduled line is split by each
# repayment's shares, principal from the bottom and interest above it up to
# the line. Measured from the drawn paths at every scheduled payment, against
# the y-axis's own ticks. The interest part's top must sit on the line: drawn
# as amounts instead of shares, the ratio between the two parts would look the
# same while the whole would be a sliver along the bottom.
test "the shading fills the area under the scheduled line, split by each repayment's shares" do
travel_to TODAY do
account = on_contract_loan_account
payload = Loan::PayoffChart.new(account.loan, as_of: TODAY, period: all_time_period).payload
visit account_path(account, period: "all_time")
find("[data-controller='loan-payoff-chart'] svg path[data-share='interest']")
%w[interest principal].each do |share|
path = find("[data-controller='loan-payoff-chart'] svg path[data-share='#{share}']")
assert path["d"].to_s.start_with?("M"), "the #{share} shading has no geometry"
assert_match(/-clip-plot\)\z/, path["clip-path"].to_s, "the #{share} shading must be clipped to the plot")
end
measured = share_extents(payload)
assert measured.size >= 12, "most of the 24 payments must be measurable, or this asserts little (got #{measured.size})"
measured.each do |m|
line_y = m["axis_y"]
principal_top = m["baseline"] - (m["baseline"] - line_y) * m["principal_share"]
assert_in_delta line_y, m["interest_top"], 1.5, "the interest part must reach the line on #{m["date"]}"
assert_in_delta principal_top, m["interest_bottom"], 1.5, "interest must start at the principal share on #{m["date"]}"
assert_in_delta principal_top, m["principal_top"], 1.5, "principal must reach its share on #{m["date"]}"
assert_in_delta m["baseline"], m["principal_bottom"], 1.5, "principal must start at zero on #{m["date"]}"
end
end
end
# Measured from the paths, not read back from the payload: the point of the
# shading is that interest's share falls as the loan runs.
test "the interest part's share of the shading is larger at the left edge than the right" do
travel_to TODAY do
account = on_contract_loan_account
payload = Loan::PayoffChart.new(account.loan, as_of: TODAY, period: all_time_period).payload
visit account_path(account, period: "all_time")
find("[data-controller='loan-payoff-chart'] svg path[data-share='interest']")
measured = share_extents(payload)
share = ->(m) { (m["interest_bottom"] - m["interest_top"]) / (m["principal_bottom"] - m["interest_top"]) }
assert_operator share.(measured.first), :>, share.(measured.last)
end
end
test "the two shares resolve to different colours in light and dark, and the legend names them" do
travel_to TODAY do
account = on_contract_loan_account
visit account_path(account, period: "all_time")
find("[data-controller='loan-payoff-chart'] svg path[data-share='interest']")
light = %w[interest principal].to_h { |share| [ share, fill_of(share) ] }
light.each { |share, fill| assert_not_equal "none", fill, "the #{share} shading has no resolved fill" }
assert_not_equal light["interest"], light["principal"]
page.execute_script("document.documentElement.setAttribute('data-theme', 'dark')")
wait_until { fill_of("interest") != light["interest"] }
dark = %w[interest principal].to_h { |share| [ share, fill_of(share) ] }
dark.each { |share, fill| assert_not_equal "none", fill, "the #{share} shading has no resolved fill in dark" }
assert_not_equal dark["interest"], dark["principal"]
assert_not_equal light["interest"], dark["interest"], "the interest shading must repaint from the dark token"
legend = "ul[aria-label='#{I18n.t("UI.account.chart.loan.legend")}'] li"
assert_selector legend, text: I18n.t("UI.account.chart.loan.interest_share")
assert_selector legend, text: I18n.t("UI.account.chart.loan.principal_share")
end
end
# The flat fill under the recorded line carried nothing the line did not; the
# shares replace it. Every filled path left in the plot is a share.
test "the only filled areas are the two shares" do
travel_to TODAY do
account = on_contract_loan_account
visit account_path(account, period: "all_time")
find("[data-controller='loan-payoff-chart'] svg path[data-share='interest']")
filled = page.evaluate_script(<<~JS)
Array.from(document.querySelectorAll("[data-controller='loan-payoff-chart'] svg path"))
.filter((path) => !path.closest("g.tick, defs") && path.getAttribute("class") !== "domain")
.filter((path) => getComputedStyle(path).fill !== "none")
.map((path) => path.dataset.share || path.dataset.shareHatch || path.getAttribute("data-series") || "unnamed")
JS
assert_equal %w[interest interest principal], filled.sort
end
end
# The opening point is the amount borrowed, not a payment, so it has no
# split of its own. It carries the first repayment's share as the left end
# of the shading, which is otherwise missing between origination and the
# first payment, and is all there is for a loan of one repayment, whose
# legend still names both shares.
test "the shading starts at origination, so a single repayment is shaded" do
travel_to TODAY do
account = Account.create!(
family: @user.family, name: "One Repayment Loan", balance: 500_000, currency: "USD",
accountable: Loan.new(subtype: "mortgage", interest_rate: 6, term_months: 1,
rate_type: "fixed", start_date: Date.new(2026, 12, 1))
)
account.entries.create!(
date: Date.new(2026, 12, 1), name: "Opening balance", amount: 500_000, currency: "USD",
entryable: Valuation.new(kind: "opening_anchor")
)
payload = Loan::PayoffChart.new(account.loan, as_of: TODAY, period: all_time_period).payload
assert_equal 2, payload[:scheduled].size, "the opening point and the one repayment"
visit account_path(account, period: "all_time")
legend = "ul[aria-label='#{I18n.t("UI.account.chart.loan.legend")}'] li"
assert_selector legend, text: I18n.t("UI.account.chart.loan.principal_share")
%w[interest principal].each do |share|
path = find("[data-controller='loan-payoff-chart'] svg path[data-share='#{share}']")
assert path["d"].to_s.start_with?("M"), "the #{share} shading has no geometry"
end
# Just after origination, halfway up from the axis to the line, the
# principal share is filled: the opening point carries the repayment's
# own share, almost all principal, not an empty or a made-up one.
filled = page.evaluate_script(<<~JS)
(() => {
const svg = document.querySelector("[data-controller='loan-payoff-chart'] svg");
const clip = svg.querySelector("clipPath[id$='-clip-plot'] rect");
const at = (iso) => { const [y, m, d] = iso.split("-").map(Number); return new Date(y, m - 1, d).getTime(); };
const start = at("#{payload[:domain_start]}"), finish = at("#{payload[:domain_end]}");
const left = +clip.getAttribute("x"), width = +clip.getAttribute("width");
const baseline = +clip.getAttribute("y") + +clip.getAttribute("height");
const opened = at("#{payload[:scheduled].first[:date]}");
const near = opened + (at("#{payload[:scheduled].last[:date]}") - opened) * 0.05;
const x = left + ((near - start) / (finish - start)) * width;
const ticks = Array.from(svg.querySelectorAll("g[transform^='translate(48,'] g.tick"))
.map((tick) => [tick.__data__, tick.transform.baseVal.consolidate().matrix.f]);
const [[v0, y0], [v1, y1]] = [ticks[0], ticks.at(-1)];
const lineY = y0 + ((#{payload[:scheduled].first[:balance]} - v0) * (y1 - y0)) / (v1 - v0);
return svg.querySelector("path[data-share='principal']").isPointInFill(new DOMPoint(x, (baseline + lineY) / 2));
})()
JS
assert filled, "the principal share must be shaded from origination, at the repayment's share"
end
end
private
# At each scheduled payment inside the plot, the top and bottom of each
# share's fill, found by scanning the path's own fill down the payment's x,
# and where the y-axis puts that payment's balance. A payment whose
# interest part is under a pixel tall (the last, on a short loan) is
# skipped: there is no fill to find.
def share_extents(payload)
points = payload[:scheduled].drop(1).map do |point|
{ date: point[:date], balance: point[:balance], principal_share: point[:principal] / (point[:principal] + point[:interest]) }
end
page.evaluate_script(<<~JS)
(() => {
const svg = document.querySelector("[data-controller='loan-payoff-chart'] svg");
const at = (iso) => { const [y, m, d] = iso.split("-").map(Number); return new Date(y, m - 1, d).getTime(); };
const start = at("#{payload[:domain_start]}");
const finish = at("#{payload[:domain_end]}");
const clip = svg.querySelector("clipPath[id$='-clip-plot'] rect");
const left = +clip.getAttribute("x"), width = +clip.getAttribute("width");
const top = +clip.getAttribute("y"), height = +clip.getAttribute("height");
const baseline = top + height;
// The y-axis: each tick's value and its translate(0,y), fitted to a line.
const ticks = Array.from(svg.querySelectorAll("g[transform^='translate(48,'] g.tick"))
.map((tick) => [tick.__data__, tick.transform.baseVal.consolidate().matrix.f]);
const [[v0, y0], [v1, y1]] = [ticks[0], ticks.at(-1)];
const axisY = (value) => y0 + ((value - v0) * (y1 - y0)) / (v1 - v0);
const extent = (path, x) => {
let first = null, last = null;
for (let y = top - 2; y <= baseline + 2; y += 0.25) {
if (path.isPointInFill(new DOMPoint(x, y))) { if (first === null) first = y; last = y; }
}
return [first, last];
};
const interest = svg.querySelector("path[data-share='interest']");
const principal = svg.querySelector("path[data-share='principal']");
return #{points.to_json}.map((p) => {
const x = left + ((at(p.date) - start) / (finish - start)) * width;
const lineY = axisY(p.balance);
if (x <= left + 1 || x >= left + width - 1 || (baseline - lineY) * (1 - p.principal_share) < 1) return null;
const [interestTop, interestBottom] = extent(interest, x);
const [principalTop, principalBottom] = extent(principal, x);
return { date: p.date, principal_share: p.principal_share, axis_y: lineY, baseline,
interest_top: interestTop, interest_bottom: interestBottom,
principal_top: principalTop, principal_bottom: principalBottom };
}).filter(Boolean);
})()
JS
end
def fill_of(share)
page.evaluate_script("getComputedStyle(document.querySelector(\"svg path[data-share='#{share}']\")).fill")
end
def assert_series_painted
SERIES.each do |key|
path = find("[data-controller='loan-payoff-chart'] svg path[data-series='#{key}']")
assert path["d"].to_s.start_with?("M"), "the #{key} line has no geometry"
assert_not_equal "none", stroke_of(key),
"the #{key} line has geometry but no resolved stroke, so it does not mark the screen -- #101 exactly"
end
# The greyed remainder of the recorded line is a token too; it must
# resolve without any fallback colour in the controller.
shadow = page.evaluate_script("getComputedStyle(document.querySelector(\"svg path[data-series-shadow='actual']\")).stroke")
assert_not_equal "none", shadow, "the greyed recorded line has no resolved stroke"
end
# `stroke: none` is the initial value, and it is what an unresolvable
# colour leaves behind -- the whole point of reading the computed style
# rather than the attribute we wrote.
def stroke_of(key)
page.evaluate_script(
"getComputedStyle(document.querySelector(\"svg path[data-series='#{key}']\")).stroke"
)
end
def bounding_box(element)
page.evaluate_script("arguments[0].getBoundingClientRect().toJSON()", element)
end
# Capybara retries its own matchers; a value read through evaluate_script
# gets no such patience, so give it the same budget.
def wait_until(timeout: Capybara.default_max_wait_time)
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
sleep 0.05 until yield || Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
end
def all_time_period
Period.new(key: "all_time", start_date: Date.new(2020, 1, 1), end_date: TODAY)
end
# Built the way the account form builds one: with an opening valuation
# for the amount borrowed. Without it Loan#original_balance falls back to
# the current balance, and a loan part-way through its term would appear
# to have borrowed only what it still owes.
def loan_account
account = Account.create!(
family: @user.family, name: "Payoff Chart Loan",
balance: 500_000, currency: "USD",
accountable: Loan.new(subtype: "mortgage", interest_rate: 6, term_months: 24,
rate_type: "fixed", start_date: Date.new(2026, 1, 1))
)
account.entries.create!(
date: Date.new(2026, 1, 1), name: "Opening balance", amount: 500_000, currency: "USD",
entryable: Valuation.new(kind: "opening_anchor")
)
account
end
# A borrower exactly on contract, with the balance history the chart's
# recorded line is drawn from. The projection then has somewhere to go; a
# loan whose balance has run away has no payoff date at all, which is a
# different test.
def on_contract_loan_account
account = loan_account
rows = account.loan.amortization_schedule.payments.select { |p| p.date <= TODAY }
account.update!(balance: rows.last.ending_balance.amount)
account.balances.delete_all
account.balances.create!(date: Date.new(2026, 1, 1), balance: 500_000, currency: "USD",
start_cash_balance: 500_000, flows_factor: -1)
rows.each do |row|
account.balances.create!(date: row.date, balance: row.ending_balance.amount, currency: "USD",
start_cash_balance: row.ending_balance.amount, flows_factor: -1)
end
account.reload
end
end