Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Show what each scheduled payment is made of in the loan chart tooltip (#4006)

jaysbeekaycd7cb2197cdd
diff --git a/app/javascript/controllers/loan_payoff_chart_controller.js b/app/javascript/controllers/loan_payoff_chart_controller.js
index 50942a6172..e79952e6ef 100644
--- a/app/javascript/controllers/loan_payoff_chart_controller.js
+++ b/app/javascript/controllers/loan_payoff_chart_controller.js
@@ -75,7 +75,14 @@ export default class extends Controller {
root.innerHTML = "";
const data = this.dataValue || {};
- const toPoint = (p) => ({ date: parseDate(p.date), balance: p.balance });
+ // `principal`/`interest` are on the scheduled payment points only; the
+ // tooltip checks for them rather than assuming.
+ const toPoint = (p) => ({
+ date: parseDate(p.date),
+ balance: p.balance,
+ principal: p.principal,
+ interest: p.interest,
+ });
const domainStart = parseDate(data.domain_start);
const domainEnd = parseDate(data.domain_end);
@@ -372,6 +379,22 @@ export default class extends Controller {
}
})();
const money = (value) => formatter.format(value);
+ // The balance reads in whole units; the principal/interest split keeps the
+ // currency's minor units so a small component never rounds to nothing.
+ const splitFormatter = (() => {
+ const digits = data.currency_precision ?? 2;
+ try {
+ return new Intl.NumberFormat(locale, {
+ style: "currency",
+ currency: data.currency || "USD",
+ minimumFractionDigits: digits,
+ maximumFractionDigits: digits,
+ });
+ } catch {
+ return formatter;
+ }
+ })();
+ const splitMoney = (value) => splitFormatter.format(value);
const showAt = (date) => {
const px = x(date);
@@ -381,12 +404,18 @@ export default class extends Controller {
if (date < s.points[0].date || date > s.points.at(-1).date)
return null;
const point = nearest(s.points, date);
- return point
- ? {
- label: data.labels?.[s.key] || s.key,
- value: money(point.balance),
- }
- : null;
+ if (!point) return null;
+ // What the scheduled payment on this date is made of (#3958).
+ const split =
+ point.principal != null && point.interest != null
+ ? `${data.labels?.principal || "Principal"}: ${splitMoney(point.principal)} · ` +
+ `${data.labels?.interest || "Interest"}: ${splitMoney(point.interest)}`
+ : null;
+ return {
+ label: data.labels?.[s.key] || s.key,
+ value: money(point.balance),
+ split,
+ };
})
.filter(Boolean);
// The domain can open before the first series point (a period that
@@ -402,13 +431,18 @@ export default class extends Controller {
const dateRow = document.createElement("div");
dateRow.className = CHART_TOOLTIP_CONTEXT_CLASSES;
dateRow.textContent = monthYear.format(date);
- const valueRows = rows.map(({ label, value }) => {
+ const valueRows = rows.flatMap(({ label, value, split }) => {
const row = document.createElement("div");
const amount = document.createElement("span");
amount.className = CHART_TOOLTIP_VALUE_CLASSES;
amount.textContent = value;
row.append(`${label}: `, amount);
- return row;
+ if (!split) return [row];
+ // Secondary styling, under the balance it explains.
+ const splitRow = document.createElement("div");
+ splitRow.className = CHART_TOOLTIP_CONTEXT_CLASSES;
+ splitRow.textContent = split;
+ return [row, splitRow];
});
tooltip.replaceChildren(dateRow, ...valueRows);
tooltip.style.display = "block";
diff --git a/app/models/loan/payoff_chart.rb b/app/models/loan/payoff_chart.rb
index f35cc8b5b6..da22863492 100644
--- a/app/models/loan/payoff_chart.rb
+++ b/app/models/loan/payoff_chart.rb
@@ -74,6 +74,9 @@ class Loan
# hard-codes `lang="en"`, so the document cannot tell the chart.
locale: I18n.locale.to_s,
currency: currency,
+ # The split is shown to the currency's own precision, as the Schedule
+ # tab shows it. Intl's default can differ from the app's (BTC).
+ currency_precision: Money::Currency.new(currency).default_precision || 2,
domain_start: domain_start.iso8601,
domain_end: domain_end.iso8601,
**series,
@@ -163,8 +166,13 @@ class Loan
rows = schedule.payments
return [] if rows.empty?
+ # Each payment carries what it is made of, for the tooltip. The opening
+ # point is the amount borrowed, not a payment, so it carries no split.
opening = { date: loan.origination_date.iso8601, balance: schedule.principal.to_f }
- [ opening ] + series(rows) { |p| [ p.date, p.ending_balance.amount ] }
+ [ opening ] + rows.map do |p|
+ { date: p.date.iso8601, balance: p.ending_balance.amount.to_f,
+ principal: p.principal.amount.to_f, interest: p.interest.amount.to_f }
+ end
end
# A projection opens at today's real balance, so the line starts there
@@ -202,6 +210,10 @@ class Loan
def labels
SERIES.index_with { |key| I18n.t("UI.account.chart.loan.#{key}") }
.merge(
+ # The Schedule tab's column labels, so the tooltip and the table
+ # name the same figures the same way.
+ principal: I18n.t("loans.tabs.schedule.principal"),
+ interest: I18n.t("loans.tabs.schedule.interest"),
today: I18n.t("UI.account.chart.loan.today"),
interactive_chart: I18n.t("UI.account.chart.loan.interactive_chart")
)
diff --git a/test/models/loan/payoff_chart_test.rb b/test/models/loan/payoff_chart_test.rb
index beba4f0293..264474eac7 100644
--- a/test/models/loan/payoff_chart_test.rb
+++ b/test/models/loan/payoff_chart_test.rb
@@ -336,6 +336,70 @@ class Loan::PayoffChartTest < ActiveSupport::TestCase
"a 360-payment schedule ran #{long_count} statements where a 24-payment one ran #{short_count}"
end
+ # we-promise/sure#3958: the tooltip says what each scheduled payment is made
+ # of. The figures are the schedule's own rows, so the chart and the Schedule
+ # tab's table cannot disagree.
+ test "each scheduled payment point carries the payment's principal and interest" do
+ loan = on_contract_loan
+ payload = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time).payload
+ rows = loan.amortization_schedule.payments.index_by { |row| row.date.iso8601 }
+
+ payments = payload[:scheduled].drop(1)
+ assert_equal rows.size, payments.size
+ payments.each do |point|
+ row = rows.fetch(point[:date])
+ assert_equal row.principal.amount.to_f, point[:principal], "principal on #{point[:date]}"
+ assert_equal row.interest.amount.to_f, point[:interest], "interest on #{point[:date]}"
+ assert_in_delta row.payment.amount.to_f, point[:principal] + point[:interest], 0.005,
+ "the split on #{point[:date]} must add up to the payment"
+ end
+ end
+
+ # The point of showing the split: early payments are mostly interest, late
+ # ones mostly principal. If this ever fails the tooltip is telling users
+ # something comfortable and false.
+ test "the split on a long loan is interest-heavy at the start and principal-heavy at the end" do
+ payments = Loan::PayoffChart.new(older_loan, as_of: @today, period: @all_time).payload[:scheduled].drop(1)
+
+ assert_operator payments.first[:interest], :>, payments.first[:principal]
+ assert_operator payments.last[:principal], :>, payments.last[:interest]
+ assert_operator payments.first[:interest], :>, payments.last[:interest]
+ end
+
+ # Only contracted payments are split. The opening point is the amount
+ # borrowed, not a payment, and the projection is a forecast.
+ test "the opening point, the projection and the recorded balance carry no split" do
+ payload = Loan::PayoffChart.new(on_contract_loan, as_of: @today, period: @all_time).payload
+
+ assert_not payload[:scheduled].first.key?(:principal)
+ assert_not payload[:scheduled].first.key?(:interest)
+ [ :projected, :actual ].each do |key|
+ assert payload[key].any?, "#{key} must have points for this to mean anything"
+ assert payload[key].none? { |point| point.key?(:principal) || point.key?(:interest) },
+ "the #{key} series must not carry a split"
+ end
+ end
+
+ # CodeRabbit on #305: the split is shown at the currency's own precision, as
+ # the Schedule tab shows it, so a small component never rounds to zero. The
+ # payload carries that precision because Intl's default can differ from the
+ # app's (BTC is 8 here, 2 to Intl).
+ test "the payload carries the loan currency's precision for the split" do
+ loan = on_contract_loan
+ assert_equal 2, Loan::PayoffChart.new(loan, as_of: @today).payload[:currency_precision]
+
+ loan.account.update_columns(currency: "JPY")
+ assert_equal 0, Loan::PayoffChart.new(loan.reload, as_of: @today).payload[:currency_precision]
+ end
+
+ # The tooltip names the figures with the Schedule tab's own column labels.
+ test "the payload labels the split with the schedule table's own words" do
+ payload = Loan::PayoffChart.new(on_contract_loan, as_of: @today).payload
+
+ assert_equal I18n.t("loans.tabs.schedule.principal"), payload[:labels][:principal]
+ assert_equal I18n.t("loans.tabs.schedule.interest"), payload[:labels][:interest]
+ end
+
private
# Each bounded window the loan chart offers, with the start date the
# shared Period gives it on @today. All is handled by @all_time.
diff --git a/test/system/loan_payoff_chart_test.rb b/test/system/loan_payoff_chart_test.rb
index 7438246aab..7eeb93ae44 100644
--- a/test/system/loan_payoff_chart_test.rb
+++ b/test/system/loan_payoff_chart_test.rb
@@ -97,6 +97,34 @@ class LoanPayoffChartTest < ApplicationSystemTestCase
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