The personal finance app for everyone (by everyone)
Ruby
Shade the loan chart by each repayment's interest and principal share (#4387)
jaysbeekay45dc1440bcf7
diff --git a/app/components/UI/account/chart.html.erb b/app/components/UI/account/chart.html.erbindex e34f768706..7676bb89d5 100644--- a/app/components/UI/account/chart.html.erb+++ b/app/components/UI/account/chart.html.erb@@ -84,6 +84,12 @@<%= loan_chart[:labels][key.to_sym] %></li><% end %>+ <% loan_share_legend.each do |key, style| %>+ <li class="flex items-center gap-1.5">+ <span class="inline-block w-3 h-3 rounded-sm border" style="<%= loan_share_swatch_style(style) %>" aria-hidden="true"></span>+ <%= loan_chart[:labels][key.to_sym] %>+ </li>+ <% end %></ul><%# Real DOM text, not only the SVG's aria-label. The chart has no datadiff --git a/app/components/UI/account/chart.rb b/app/components/UI/account/chart.rbindex cdf287e268..9909f48a8a 100644--- a/app/components/UI/account/chart.rb+++ b/app/components/UI/account/chart.rb@@ -38,6 +38,29 @@ class UI::Account::Chart < ApplicationComponentLOAN_SERIES_STYLES.select { |key, _| loan_chart[:visible].map(&:to_s).include?(key) }end+ # The shading under the scheduled line, by each repayment's share. Interest+ # is hatched as well as tinted, so the two are told apart without colour.+ LOAN_SHARE_STYLES = {+ "interest_share" => { token: "--color-warning", hatched: true },+ "principal_share" => { token: "--color-info", hatched: false }+ }.freeze++ def loan_share_legend+ loan_chart[:visible].map(&:to_s).include?("scheduled") ? LOAN_SHARE_STYLES : {}+ end++ # The legend swatch matches the chart: hatched for interest, a solid tint+ # for principal, each bordered in its own colour.+ def loan_share_swatch_style(style)+ colour = "var(#{style[:token]})"+ fill = if style[:hatched]+ "background: repeating-linear-gradient(45deg, #{colour} 0 1.5px, transparent 1.5px 4px);"+ else+ "background: #{colour}; opacity: 0.4;"+ end+ "border-color: #{colour}; #{fill}"+ end+def loan_projected_payoff_dateloan_chart[:projected_payoff_date] && Date.iso8601(loan_chart[:projected_payoff_date])enddiff --git a/app/javascript/controllers/loan_payoff_chart_controller.js b/app/javascript/controllers/loan_payoff_chart_controller.jsindex e79952e6ef..3062653bc3 100644--- a/app/javascript/controllers/loan_payoff_chart_controller.js+++ b/app/javascript/controllers/loan_payoff_chart_controller.js@@ -13,6 +13,12 @@ import {// projected where today's balance is heading on the contract's repayment.// Dashed.//+// Under the scheduled line, the area down to zero is split by each repayment's+// interest and principal SHARE: principal from the bottom, interest above it up+// to the line. Shares, not amounts: a repayment is a fraction of a percent of+// the balance, so amounts would be a sliver along the axis. The interest part+// is hatched as well as tinted, for the same reason the lines are dashed.+//// Series are distinguished by DASH PATTERN as well as colour. Hue alone fails// in greyscale and under deuteranopia, and red/green would be the worst// possible pair to rely on. Solid-versus-dashed also keeps "recorded fact"@@ -99,6 +105,8 @@ export default class extends Controller {const success = "var(--color-success)";const destructive = "var(--color-destructive)";const muted = "var(--color-tertiary)";+ const interestShare = "var(--color-warning)";+ const principalShare = "var(--color-info)";// Drawing order: forecasts underneath, fact on top.const series = [@@ -204,10 +212,54 @@ export default class extends Controller {.x((d) => x(d.date)).y((d) => y(d.balance)).curve(d3.curveMonotoneX);- const area = d3+ // The scheduled payments' shares, for the shading. A share is clamped to+ // 0..1 so a payment that adds to the balance cannot draw outside the area+ // under the line.+ const scheduledPoints = series.some((s) => s.key === "scheduled")+ ? (data.scheduled || []).map(toPoint)+ : [];+ const paymentShares = scheduledPoints+ .filter(+ (p) =>+ p.principal != null &&+ p.interest != null &&+ p.principal + p.interest > 0,+ )+ .map((p) => ({+ date: p.date,+ balance: p.balance,+ principalShare: Math.min(+ 1,+ Math.max(0, p.principal / (p.principal + p.interest)),+ ),+ }));+ // The opening point is the amount borrowed, not a payment, so it has no+ // split of its own. It anchors the shading's left end with the first+ // payment's share, so the area under the line is shaded from origination+ // and a loan of one repayment still has an interval to shade.+ const opening = scheduledPoints[0];+ const shares =+ opening && opening.principal == null && paymentShares.length > 0+ ? [+ {+ date: opening.date,+ balance: opening.balance,+ principalShare: paymentShares[0].principalShare,+ },+ ...paymentShares,+ ]+ : paymentShares;+ const principalTop = (d) => y(d.balance * d.principalShare);+ const principalArea = d3+ .area()+ .x((d) => x(d.date))+ .y0(y(0))+ .y1(principalTop)+ .curve(d3.curveMonotoneX);+ const interestArea = d3.area().x((d) => x(d.date))- .y0(height - margin.bottom)+ .y0(principalTop).y1((d) => y(d.balance)).curve(d3.curveMonotoneX);@@ -259,6 +311,50 @@ export default class extends Controller {).call(styleAxis);+ // The shading draws under every line. The hatch lives in the same defs as+ // the clips, so its id is as unique as theirs.+ if (shares.length > 1) {+ const hatch = `${id}-hatch`;+ defs+ .append("pattern")+ .attr("id", hatch)+ .attr("patternUnits", "userSpaceOnUse")+ .attr("width", 6)+ .attr("height", 6)+ .attr("patternTransform", "rotate(45)")+ .append("line")+ .attr("x1", 0)+ .attr("y1", 0)+ .attr("x2", 0)+ .attr("y2", 6)+ .style("stroke", interestShare)+ .style("stroke-width", 1.5)+ .style("stroke-opacity", 0.45);+ svg+ .append("path")+ .datum(shares)+ .attr("d", principalArea)+ .attr("clip-path", `url(#${plotClip})`)+ .attr("data-share", "principal")+ .style("fill", principalShare)+ .style("fill-opacity", 0.16);+ svg+ .append("path")+ .datum(shares)+ .attr("d", interestArea)+ .attr("clip-path", `url(#${plotClip})`)+ .attr("data-share", "interest")+ .style("fill", interestShare)+ .style("fill-opacity", 0.18);+ svg+ .append("path")+ .datum(shares)+ .attr("d", interestArea)+ .attr("clip-path", `url(#${plotClip})`)+ .attr("data-share-hatch", "interest")+ .style("fill", `url(#${hatch})`);+ }+const stroke = (path, s, color) =>path.style("fill", "none")@@ -270,13 +366,6 @@ export default class extends Controller {for (const s of series) {if (s.key === "actual") {- svg- .append("path")- .datum(s.points)- .attr("d", area)- .attr("clip-path", `url(#${plotClip})`)- .style("fill", s.color)- .style("opacity", 0.08);// The greyed remainder sits underneath; the coloured line on top is// the one that carries data-series, so a test asking for the actual// line finds the line that is meant to be seen.diff --git a/app/models/loan/payoff_chart.rb b/app/models/loan/payoff_chart.rbindex da22863492..f25e0476e8 100644--- a/app/models/loan/payoff_chart.rb+++ b/app/models/loan/payoff_chart.rb@@ -25,6 +25,10 @@ class Loanclass PayoffChartSERIES = %i[actual scheduled projected].freeze+ # The accessible description quotes interest's share of the first and the+ # final year's repayments; a shorter schedule would overlap the two.+ FIRST_AND_FINAL_YEAR_MINIMUM = 24+# The periods a loan's chart offers, a subset of the shared Period keys the# picker saves as the user's default. The short ones a loan has no use for# (7D, 30D, a custom range) are left out; any other Period key, including@@ -93,7 +97,7 @@ class Loan# the not-converged notice can quote.balloon: projection.applicable? && !projection.converged? ? projection.balloon_amount.amount.to_f : nil,labels: labels,- aria_description: aria_description(actual: series[:actual])+ aria_description: aria_description(actual: series[:actual], scheduled_visible: visible?(series[:scheduled]))}end@@ -193,16 +197,19 @@ class Loanend# A series is worth a legend entry when it draws a line inside the- # domain: two of its points fall inside, or it enters on one side and- # leaves on the other. One point on the boundary -- the projection's- # opening point sits exactly on the end of every period but "All" -- is- # not a line, and the legend must not promise one.+ # domain. The chart draws every point and clips to the domain, so that+ # is any series of two or more points that starts before the domain+ # ends and finishes after it starts: two points inside, one inside with+ # a neighbour beyond either edge (the final repayment entering a+ # window), or a line crossing it from side to side. One point is not a+ # line, and a series that only touches an edge -- the projection's+ # opening point sits exactly on the end of every period but "All" --+ # draws nothing inside, so the legend must not promise one.def visible?(points)- dates = points.map { |point| Date.iso8601(point[:date]) }- return false if dates.empty?+ return false if points.size < 2- inside = dates.count { |date| date.between?(domain_start, domain_end) }- inside >= 2 || (dates.first < domain_start && dates.last > domain_end)+ dates = points.map { |point| Date.iso8601(point[:date]) }+ dates.first < domain_end && dates.last > domain_startend# The chart controller reads `interactive_chart` for the SVG's@@ -214,13 +221,18 @@ class Loan# name the same figures the same way.principal: I18n.t("loans.tabs.schedule.principal"),interest: I18n.t("loans.tabs.schedule.interest"),+ # The legend's names for the shading under the scheduled line.+ # Shares, because the heights are shares of each repayment.+ interest_share: I18n.t("UI.account.chart.loan.interest_share"),+ principal_share: I18n.t("UI.account.chart.loan.principal_share"),today: I18n.t("UI.account.chart.loan.today"),interactive_chart: I18n.t("UI.account.chart.loan.interactive_chart"))end- # Every series the chart draws is named here, with its payoff date.- def aria_description(actual:)+ # Every series the chart draws is named here, with its payoff date, and+ # the shading under the scheduled line in words when that line is drawn.+ def aria_description(actual:, scheduled_visible:)description = I18n.t("UI.account.chart.loan.aria_description",current_balance: projection.current_balance.format,@@ -236,9 +248,30 @@ class Loan) ].join(" ")end+ description = [ description, interest_share_sentence ].join(" ") if scheduled_visible+descriptionend+ # Interest over what was paid, across the first twelve payments and the+ # last twelve. Under FIRST_AND_FINAL_YEAR_MINIMUM payments those windows+ # overlap, so one clause covers them all.+ def interest_share_sentence+ rows = schedule.payments+ if rows.size < FIRST_AND_FINAL_YEAR_MINIMUM+ I18n.t("UI.account.chart.loan.aria_interest_share_overall", share: interest_percent(rows))+ else+ I18n.t("UI.account.chart.loan.aria_interest_share",+ first: interest_percent(rows.first(12)), last: interest_percent(rows.last(12)))+ end+ end++ def interest_percent(rows)+ interest = rows.sum { |row| row.interest.amount }+ paid = interest + rows.sum { |row| row.principal.amount }+ paid.zero? ? 0 : (interest / paid * 100).round+ end+def long_date(date, fallback)date ? I18n.l(date, format: :long) : fallbackenddiff --git a/config/locales/views/components/de.yml b/config/locales/views/components/de.ymlindex 39d0da12d1..83b0fec39e 100644--- a/config/locales/views/components/de.yml+++ b/config/locales/views/components/de.yml@@ -130,6 +130,10 @@ de:actual: "Erfasster Saldo"aria_description: "Kreditsaldo-Diagramm. Erfasster Saldo %{current_balance}. Ursprünglich geplante Tilgung %{scheduled_payoff_date}. Voraussichtliche Tilgung ab dem heutigen Saldo %{projected_payoff_date}."aria_actual_history_starts: "Die erfasste Saldenhistorie beginnt am %{date}."+ aria_interest_share: "Über die Raten des ersten Jahres sind etwa %{first} % des gezahlten Betrags Zinsen, über die des letzten Jahres etwa %{last} %."+ aria_interest_share_overall: "Über alle Raten sind etwa %{share} % des gezahlten Betrags Zinsen."+ interest_share: "Zinsanteil"+ principal_share: "Tilgungsanteil"interactive_chart: "interaktives Diagramm"interest_saved: "Eingesparte Zinsen"legend: "Diagrammreihen"diff --git a/config/locales/views/components/en.yml b/config/locales/views/components/en.ymlindex f6d6cb0e9e..8f248bfee8 100644--- a/config/locales/views/components/en.yml+++ b/config/locales/views/components/en.yml@@ -69,6 +69,10 @@ en:no_payoff: not on the current repaymentaria_description: Loan balance chart. Recorded balance %{current_balance}. Original scheduled payoff %{scheduled_payoff_date}. Projected payoff from today's balance %{projected_payoff_date}.aria_actual_history_starts: Recorded balance history begins %{date}.+ aria_interest_share: Across the first year's repayments about %{first}% of the amount paid is interest; across the final year's, about %{last}%.+ aria_interest_share_overall: Across all the repayments about %{share}% of the amount paid is interest.+ interest_share: Interest share+ principal_share: Principal shareprojected_payoff: Projected payoffmonths_saved:one: "%{count} month sooner than scheduled"diff --git a/test/components/UI/account/chart_test.rb b/test/components/UI/account/chart_test.rbindex 38c175aee3..760e27bc35 100644--- a/test/components/UI/account/chart_test.rb+++ b/test/components/UI/account/chart_test.rb@@ -100,10 +100,36 @@ class UI::Account::ChartTest < ViewComponent::TestCaserender_inline(UI::Account::Chart.new(account: loan_account, loan_chart: windowed))legend = "ul[aria-label='#{I18n.t("UI.account.chart.loan.legend")}'] li"- assert_selector legend, count: 2+ # The two lines, and the two shares shaded under the scheduled one.+ assert_selector legend, count: 4assert_selector legend, text: payload[:labels][:actual]assert_selector legend, text: payload[:labels][:scheduled]assert_no_selector legend, text: payload[:labels][:projected]+ assert_selector legend, text: payload[:labels][:interest_share]+ assert_selector legend, text: payload[:labels][:principal_share]++ # Interest is told apart by its hatching as well as its colour.+ interest = page.find(legend, text: payload[:labels][:interest_share]).find("span")[:style]+ principal = page.find(legend, text: payload[:labels][:principal_share]).find("span")[:style]+ assert_includes interest, "repeating-linear-gradient"+ assert_includes interest, "var(--color-warning)"+ assert_not_includes principal, "repeating-linear-gradient"+ assert_includes principal, "var(--color-info)"+ end++ # The shares are shaded under the scheduled line, so+ # without that line the legend must not name them.+ test "the legend names the interest and principal shares only with the scheduled line" do+ loan_account = accounts(:loan)+ payload = Loan::PayoffChart.new(loan_account.loan, as_of: Date.current).payload+ assert_not_nil payload, "the loan fixture must have a schedule, or this test asserts nothing"+ legend = "ul[aria-label='#{I18n.t("UI.account.chart.loan.legend")}'] li"++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: payload.merge(visible: %w[actual projected])))++ assert_selector legend, count: 2+ assert_no_selector legend, text: payload[:labels][:interest_share]+ assert_no_selector legend, text: payload[:labels][:principal_share]end# A projection that ran but never clears the balance has a line and nodiff --git a/test/models/loan/payoff_chart_test.rb b/test/models/loan/payoff_chart_test.rbindex 264474eac7..1e3692f760 100644--- a/test/models/loan/payoff_chart_test.rb+++ b/test/models/loan/payoff_chart_test.rb@@ -400,7 +400,118 @@ class Loan::PayoffChartTest < ActiveSupport::TestCaseassert_equal I18n.t("loans.tabs.schedule.interest"), payload[:labels][:interest]end+ # The shading under the scheduled line splits it by each+ # repayment's interest and principal share. The description says the same in+ # words, from the schedule's own rows: interest over what was paid, across+ # the first twelve payments and the last twelve.+ test "the accessible description names the interest share of the first and final year's repayments" do+ loan = older_loan+ rows = loan.amortization_schedule.payments+ first = interest_percent(rows.first(12))+ last = interest_percent(rows.last(12))+ assert_operator first, :>, last, "a long loan front-loads interest, or this cannot tell first from last"++ description = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time).payload[:aria_description]++ assert_includes description, I18n.t("UI.account.chart.loan.aria_interest_share", first: first, last: last)+ end++ # Under 24 payments the first and final years would overlap, so one clause+ # covers every payment. Both sides of the boundary.+ test "a schedule of 23 payments quotes one interest share, and one of 24 quotes two" do+ short = build_loan(term_months: 23)+ long = build_loan(term_months: 24)+ short_rows = short.amortization_schedule.payments+ long_rows = long.amortization_schedule.payments+ assert_equal [ 23, 24 ], [ short_rows.size, long_rows.size ]++ short_description = Loan::PayoffChart.new(short, as_of: @today, period: @all_time).payload[:aria_description]+ long_description = Loan::PayoffChart.new(long, as_of: @today, period: @all_time).payload[:aria_description]++ assert_includes short_description, I18n.t("UI.account.chart.loan.aria_interest_share_overall", share: interest_percent(short_rows))+ assert_not_includes short_description, I18n.t("UI.account.chart.loan.aria_interest_share", first: interest_percent(short_rows.first(12)), last: interest_percent(short_rows.last(12)))+ assert_includes long_description, I18n.t("UI.account.chart.loan.aria_interest_share", first: interest_percent(long_rows.first(12)), last: interest_percent(long_rows.last(12)))+ assert_not_includes long_description, I18n.t("UI.account.chart.loan.aria_interest_share_overall", share: interest_percent(long_rows))+ end++ # The shading reads the scheduled points the payload already carries; it+ # adds no series and no key.+ test "the payload's keys and series are unchanged by the shading" do+ payload = Loan::PayoffChart.new(on_contract_loan, as_of: @today, period: @all_time).payload++ assert_equal %i[today locale currency currency_precision domain_start domain_end actual scheduled projected visible+ scheduled_payoff_date projected_payoff_date months_saved interest_saved balloon labels aria_description],+ payload.keys+ assert_equal %i[actual scheduled projected], Loan::PayoffChart::SERIES+ end++ test "the payload labels the two shares for the legend" do+ payload = Loan::PayoffChart.new(on_contract_loan, as_of: @today).payload++ assert_equal I18n.t("UI.account.chart.loan.interest_share"), payload[:labels][:interest_share]+ assert_equal I18n.t("UI.account.chart.loan.principal_share"), payload[:labels][:principal_share]+ end++ # The chart draws every point and clips to the window, so a series with one+ # point inside and its neighbour outside still crosses the plot: the final+ # repayment entering a window, or the opening point leaving one. Its legend+ # entries, the share swatches among them, follow it. Both sides of the+ # boundary: a segment that only touches the window's edge draws nothing.+ test "a series with one point inside and a neighbour outside is visible" do+ loan = build_loan+ rows = loan.amortization_schedule.payments+ final = rows.last.date+ assert_operator rows[-2].date, :<, final - 1, "the final payment's neighbour must sit outside the window"++ entering = Period.new(key: "current_month", start_date: final - 1, end_date: final + 5)+ payload = Loan::PayoffChart.new(loan, as_of: @today, period: entering).payload+ assert_equal [ final - 1, final ].map(&:iso8601), [ payload[:domain_start], payload[:scheduled].last[:date] ]+ assert_includes payload[:visible].map(&:to_s), "scheduled", "the final repayment enters the window and ends inside it"+ assert_includes payload[:aria_description], interest_share_clause(rows)++ touching = Period.new(key: "current_month", start_date: final, end_date: final + 5)+ payload = Loan::PayoffChart.new(loan, as_of: @today, period: touching).payload+ assert_not_includes payload[:visible].map(&:to_s), "scheduled", "a series that ends on the window's start draws nothing in it"+ assert_not_includes payload[:aria_description], interest_share_clause(rows)++ leaving = Period.new(key: "current_month", start_date: loan.origination_date, end_date: loan.origination_date + 10)+ payload = Loan::PayoffChart.new(loan, as_of: @today, period: leaving).payload+ assert_equal 1, payload[:scheduled].count { |point| Date.iso8601(point[:date]).between?(loan.origination_date, loan.origination_date + 10) }+ assert_includes payload[:visible].map(&:to_s), "scheduled", "the opening point starts inside the window and the line leaves it"+ end++ # One recorded balance strictly inside the domain, away from both edges, is+ # still one point, and the chart draws no line through it.+ test "a single point inside the domain is not visible" do+ account = travel_to(@today) do+ Account.create!(+ family: @family, name: "Loan #{SecureRandom.hex(4)}", balance: 500_000, currency: "USD",+ accountable: Loan.new(subtype: "mortgage", interest_rate: 6, term_months: 24,+ rate_type: "fixed", start_date: @today - 10)+ )+ end+ account.balances.create!(date: @today, balance: 500_000, currency: "USD",+ start_cash_balance: 500_000, flows_factor: -1)++ payload = Loan::PayoffChart.new(account.loan, as_of: @today, period: @all_time).payload++ assert_equal [ @today.iso8601 ], payload[:actual].map { |point| point[:date] }+ assert_operator payload[:domain_start], :<, @today.iso8601+ assert_operator payload[:domain_end], :>, @today.iso8601+ assert_not_includes payload[:visible].map(&:to_s), "actual", "one point is not a line"+ end+private+ def interest_share_clause(rows)+ I18n.t("UI.account.chart.loan.aria_interest_share",+ first: interest_percent(rows.first(12)), last: interest_percent(rows.last(12)))+ end++ def interest_percent(rows)+ interest = rows.sum { |row| row.interest.amount }+ (interest / (interest + rows.sum { |row| row.principal.amount }) * 100).round+ end+# Each bounded window the loan chart offers, with the start date the# shared Period gives it on @today. All is handled by @all_time.def window_starts@@ -439,11 +550,11 @@ class Loan::PayoffChartTest < ActiveSupport::TestCaseaccount.loanend- def build_loan(rate_type: "fixed")+ def build_loan(rate_type: "fixed", term_months: 24)account = Account.create!(family: @family, name: "Loan #{SecureRandom.hex(4)}",balance: 500_000, currency: "USD",- accountable: Loan.new(subtype: "mortgage", interest_rate: 6, term_months: 24,+ accountable: Loan.new(subtype: "mortgage", interest_rate: 6, term_months: term_months,rate_type: rate_type, start_date: Date.new(2026, 1, 1)))# The opening valuation the account form records: Loan#original_balancediff --git a/test/system/loan_payoff_chart_test.rb b/test/system/loan_payoff_chart_test.rbindex 271d06014e..2aca28c7e1 100644--- a/test/system/loan_payoff_chart_test.rb+++ b/test/system/loan_payoff_chart_test.rb@@ -224,7 +224,200 @@ class LoanPayoffChartTest < ApplicationSystemTestCaseendend+ # 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_paintedSERIES.each do |key|path = find("[data-controller='loan-payoff-chart'] svg path[data-series='#{key}']")