The personal finance app for everyone (by everyone)
Ruby
feat(loans): payoff projection and the loan balance chart (#3474)
jaysbeekaye931fae4f1db
diff --git a/app/components/UI/account/chart.html.erb b/app/components/UI/account/chart.html.erbindex 1bfe5997d6..e34f768706 100644--- a/app/components/UI/account/chart.html.erb+++ b/app/components/UI/account/chart.html.erb@@ -30,9 +30,10 @@<% end %><%= render UI::PeriodPicker.new(- selected: period,+ selected: period_picker_selected,url: account_path(account),- extra_params: account.supports_trades? ? { chart_view: view } : {}+ extra_params: account.supports_trades? ? { chart_view: view } : {},+ options: period_picker_options) %></div></div>@@ -42,19 +43,68 @@<%= render partial: "shared/trend_change", locals: { trend: trend, comparison_label: comparison_label } %></div>- <div class="h-64 pb-4">- <% if series.any? %>- <div- id="lineChart"- class="w-full h-full privacy-sensitive"- data-controller="time-series-chart"- data-time-series-chart-data-value="<%= series.to_json %>"- data-time-series-chart-selectable-value="true"></div>- <% else %>- <div class="w-full h-full flex items-center justify-center">- <p class="text-secondary text-sm"><%= t("UI.account.chart.no_data_available") %></p>- </div>- <% end %>- </div>+ <% if loan_chart? %>+ <%# The loan balance chart: recorded balance, original schedule and+ projection on one axis, with the figures the projection produces beside+ it. Everything in this branch is loan-only; the else branch below is the+ chart every other account type has always had. %>+ <div class="px-4 mb-2 grid grid-cols-2 gap-2">+ <% if loan_projected_payoff_date %>+ <%= render "accounts/summary_card", title: t("UI.account.chart.loan.projected_payoff"), content: capture { %>+ <%= I18n.l(loan_projected_payoff_date, format: :long) %>+ <span class="block text-xs text-secondary mt-1"><%= loan_schedule_comparison %></span>+ <% } %>+ <%= render "accounts/summary_card", title: t("UI.account.chart.loan.interest_saved"), content: capture { %>+ <%= loan_interest_saved_money.format %>+ <% } %>+ <%# The basis of the comparison, beside the figures it governs: the+ schedule's dates are anniversaries of origination, not the+ lender's posting dates, so a payment posted before its date+ reads as ahead until that date and one posted after as behind. %>+ <p class="col-span-2 text-xs text-secondary"><%= t("UI.account.chart.loan.projection_basis") %></p>+ <% elsif loan_projection_not_converged? %>+ <p class="col-span-2 text-sm text-secondary"><%= t("UI.account.chart.loan.not_converged", balloon: loan_balloon_money.format) %></p>+ <% end %>+ </div>++ <div class="h-64 px-4">+ <%# privacy-sensitive: the axis, the lines and the tooltip are all+ balances, and Privacy Mode blurs balances everywhere else here.+ text-primary so the axis can draw in currentColor. %>+ <div id="<%= loan_chart_id %>"+ class="w-full h-full privacy-sensitive text-primary"+ data-controller="loan-payoff-chart"+ data-loan-payoff-chart-data-value="<%= loan_chart.to_json %>"></div>+ </div>++ <ul class="flex flex-wrap gap-x-4 gap-y-1 px-4 pt-2 pb-4 text-xs text-secondary" aria-label="<%= t("UI.account.chart.loan.legend") %>">+ <% loan_legend.each do |key, style| %>+ <li class="flex items-center gap-1.5">+ <span class="inline-block w-4 h-0 border-t-2 <%= "border-dashed" if style[:dashed] %>" style="border-color: var(<%= style[:token] %>);" 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 data+ table of its own: the Schedule tab carries the figures. It quotes the+ balance, so it is privacy-sensitive like every other balance here. %>+ <p class="sr-only privacy-sensitive"><%= loan_chart[:aria_description] %></p>+ <% else %>+ <div class="h-64 pb-4">+ <% if series.any? %>+ <div+ id="lineChart"+ class="w-full h-full privacy-sensitive"+ data-controller="time-series-chart"+ data-time-series-chart-selectable-value="true"+ data-time-series-chart-data-value="<%= series.to_json %>"></div>+ <% else %>+ <div class="w-full h-full flex items-center justify-center">+ <p class="text-secondary text-sm"><%= t("UI.account.chart.no_data_available") %></p>+ </div>+ <% end %>+ </div>+ <% end %><% end %></div>diff --git a/app/components/UI/account/chart.rb b/app/components/UI/account/chart.rbindex 64794049ae..cdf287e268 100644--- a/app/components/UI/account/chart.rb+++ b/app/components/UI/account/chart.rb@@ -1,10 +1,74 @@class UI::Account::Chart < ApplicationComponent- attr_reader :account-- def initialize(account:, period: nil, view: nil)+ attr_reader :account, :loan_chart++ # `loan_chart` is a Loan::PayoffChart payload, built by the controller for a+ # loan account with a schedule and nil for everything else. When present the+ # inner chart element becomes the loan balance chart -- recorded balance,+ # original schedule and projection on one axis -- and the rest of this card+ # (title, hero figure, trend, period picker, Turbo frame) is unchanged. Every+ # other account type takes the branch it always took.+ # The page's reference date travels inside the payload (`today`), so the+ # component takes no date of its own.+ def initialize(account:, period: nil, view: nil, loan_chart: nil)@account = account@period = period@view = view+ @loan_chart = loan_chart+ end++ def loan_chart?+ loan_chart.present?+ end++ def loan_chart_id+ dom_id(account, :loan_chart)+ end++ # The series with a line inside the domain, in drawing order, each with the+ # style the controller gives it. Style is carried by the legend as well as+ # the line: solid is fact, dashed is forecast, and hue alone would fail in+ # greyscale and under deuteranopia.+ LOAN_SERIES_STYLES = {+ "actual" => { token: "--color-success", dashed: false },+ "scheduled" => { token: "--color-destructive", dashed: true },+ "projected" => { token: "--color-success", dashed: true }+ }.freeze++ def loan_legend+ LOAN_SERIES_STYLES.select { |key, _| loan_chart[:visible].map(&:to_s).include?(key) }+ end++ def loan_projected_payoff_date+ loan_chart[:projected_payoff_date] && Date.iso8601(loan_chart[:projected_payoff_date])+ end++ # The projection ran but the contracted repayment never clears the balance:+ # there is a line to draw and no payoff date to quote.+ def loan_projection_not_converged?+ loan_chart[:projected].any? && loan_projected_payoff_date.nil?+ end++ # Never "behind": the projection walks only the remaining contracted dates,+ # so months_saved is zero or positive. A borrower whose balance the contract+ # no longer clears has no payoff date at all and takes the not-converged+ # notice instead, with the balloon it would leave.+ def loan_schedule_comparison+ months = loan_chart[:months_saved].to_i+ return I18n.t("UI.account.chart.loan.on_schedule") if months.zero?++ I18n.t("UI.account.chart.loan.months_saved", count: months)+ end++ def loan_balloon_money+ Money.new(loan_chart[:balloon].to_f, loan_chart[:currency])+ end++ # Never negative: the card renders only with a projected payoff date, and the+ # projection converges only when today's balance is at or below the+ # contract's, so it can only save interest. A larger balance takes the+ # not-converged notice instead.+ def loan_interest_saved_money+ Money.new(loan_chart[:interest_saved].to_f, loan_chart[:currency])enddef period@@ -70,7 +134,10 @@ class UI::Account::Chart < ApplicationComponentwhen "CreditCard", "OtherLiability"I18n.t("UI.account.chart.title.debt_balance")when "Loan"- I18n.t("UI.account.chart.title.remaining_principal_balance")+ # The loan balance chart plots what is still owed, principal and any+ # capitalised interest, so its title drops "principal". A loan without+ # a schedule keeps the chart, and the title, it always had.+ loan_chart? ? I18n.t("UI.account.chart.title.loan_remaining_balance") : I18n.t("UI.account.chart.title.remaining_principal_balance")elseI18n.t("UI.account.chart.title.balance")end@@ -97,8 +164,9 @@ class UI::Account::Chart < ApplicationComponent@view ||= "balance"end+ # Read by the trend, its comparison label and the chart mount; built once.def series- account.balance_series(period: period, view: view)+ @series ||= account.balance_series(period: period, view: view)end# Current total unrealized gains, taken from the series so the main indicator@@ -107,11 +175,32 @@ class UI::Account::Chart < ApplicationComponentseries.values.last&.value || Money.new(0, account.currency)end+ # A loan's chart offers a subset of the shared periods+ # (Loan::PayoffChart::WINDOW_KEYS); every other chart offers every period.+ def period_picker_options+ Loan::PayoffChart.window_options if loan_chart?+ end++ # A saved period the loan chart does not offer shows the whole life, so its+ # picker reads All.+ def period_picker_selected+ return period unless loan_chart?++ Loan::PayoffChart::WINDOW_KEYS.include?(period.key.to_s) ? period.key.to_s : "all_time"+ end++ # On a loan the change line compares today's balance with the amount+ # borrowed, whatever window is picked (owner review of #3474).def trend- series.trend+ return series.trend unless loan_chart?++ Trend.new(current: account.balance_money, previous: account.loan.original_balance,+ favorable_direction: account.favorable_direction)enddef comparison_label+ return I18n.t("UI.account.chart.loan.since_start") if loan_chart?+start_date = series.start_datereturn period.comparison_label if start_date.blank?diff --git a/app/components/UI/account_page.html.erb b/app/components/UI/account_page.html.erbindex 820d3a5214..c46114ea8d 100644--- a/app/components/UI/account_page.html.erb+++ b/app/components/UI/account_page.html.erb@@ -4,7 +4,7 @@<%= tag.div class: "space-y-4 pb-5 lg:pb-32" do %><%= render "accounts/show/header", account: account, title: title, subtitle: subtitle %>- <%= render UI::Account::Chart.new(account: account, period: chart_period, view: chart_view) %>+ <%= render UI::Account::Chart.new(account: account, period: chart_period, view: chart_view, loan_chart: loan_chart) %><% if (fx_coverage_start = fx_coverage_start_date).present? %><div class="px-3">diff --git a/app/components/UI/account_page.rb b/app/components/UI/account_page.rbindex 10e3b3223f..dadf391f9c 100644--- a/app/components/UI/account_page.rb+++ b/app/components/UI/account_page.rb@@ -1,14 +1,23 @@class UI::AccountPage < ApplicationComponent- attr_reader :account, :chart_view, :chart_period, :statement_coverage, :statements, :reconciliation_statuses,- :can_manage_statements+ attr_reader :account, :chart_view, :chart_period, :loan_chart, :as_of, :statement_coverage, :statements,+ :reconciliation_statuses, :can_manage_statementsrenders_one :activity_feed, ->(feed_data:, pagy:, search:) { UI::Account::ActivityFeed.new(feed_data: feed_data, pagy: pagy, search: search) }- def initialize(account:, chart_view: nil, chart_period: nil, active_tab: nil, statement_coverage: nil, statements: [],- reconciliation_statuses: {}, can_manage_statements: false)+ # `loan_chart` is the Loan::PayoffChart payload the controller built for a+ # loan account, nil for every other type and for a loan with no schedule.+ # `as_of` is the page's one reference date, captured by the controller.+ # `loan_projection` is the projection the controller already built for the+ # chart, so the Schedule tab's forecast card does not simulate it again.+ def initialize(account:, chart_view: nil, chart_period: nil, loan_chart: nil, as_of: Date.current, active_tab: nil,+ statement_coverage: nil, statements: [], reconciliation_statuses: {}, can_manage_statements: false,+ loan_projection: nil)@account = account@chart_view = chart_view@chart_period = chart_period+ @loan_chart = loan_chart+ @loan_projection = loan_projection+ @as_of = as_of@active_tab = active_tab@statement_coverage = statement_coverage@statements = statements@@ -74,13 +83,28 @@ class UI::AccountPage < ApplicationComponent@fx_coverage_start_date = resultend+ # The controller's projection when it built one; otherwise built here, once+ # per render, for callers that construct the page without it.+ def loan_projection+ @loan_projection ||= account.loan.payoff_projection(as_of: as_of)+ end+def tab_content_for(tab)case tabwhen :activityactivity_feed- when :holdings, :overview, :schedule+ when :overview+ # Accountable is responsible for implementing the partial in the correct+ # folder. The loan's tab shows date-sensitive figures and takes the+ # page's one reference date, like its Schedule tab.+ locals = { account: account }+ locals[:as_of] = as_of if account.accountable_type == "Loan"+ render "#{account.accountable_type.downcase.pluralize}/tabs/#{tab}", **locals+ when :holdings# Accountable is responsible for implementing the partial in the correct folderrender "#{account.accountable_type.downcase.pluralize}/tabs/#{tab}", account: account+ when :schedule+ render "loans/tabs/schedule", account: account, as_of: as_of, projection: loan_projectionwhen :statementsrender_statement_tabenddiff --git a/app/components/UI/period_picker.html.erb b/app/components/UI/period_picker.html.erbindex b4296cd1ef..2cc66922e8 100644--- a/app/components/UI/period_picker.html.erb+++ b/app/components/UI/period_picker.html.erb@@ -14,19 +14,19 @@a stale ?start_date/&end_date from a chart drag-select would outlive apreset pick and come back on refresh. See `turbo_action_for` for why thechecked row replaces rather than advances. %>- <% periods.each do |period| %>- <% period_selected = selected?(period.key) %>+ <% items.each do |key, label| %>+ <% item_selected = selected?(key) %><% menu.with_item(variant: :link,- text: period.label_short,- href: href_for(period.key),+ text: label,+ href: href_for(key),frame: frame,- selected: period_selected,- data: { turbo_action: turbo_action_for(period_selected) }+ selected: item_selected,+ data: { turbo_action: turbo_action_for(item_selected) }) %><% end %>- <% if custom_selected? %>+ <% if custom_row? %><%# Last, so the presets keep their positions. Without this row a customrange leaves the list with nothing checked, which reads as "no selection"and hides the fact that picking a preset is how you leave it. %>diff --git a/app/components/UI/period_picker.rb b/app/components/UI/period_picker.rbindex 9dd04efa53..d13ad9f71a 100644--- a/app/components/UI/period_picker.rb+++ b/app/components/UI/period_picker.rb@@ -15,22 +15,31 @@ class UI::PeriodPicker < ApplicationComponent## NOTE: `url` must be a path without a query string; pass query state via# `extra_params` so the picker can compose `?period=…` cleanly.- attr_reader :selected, :selected_key, :url, :frame, :extra_params, :placement+ attr_reader :selected, :selected_key, :url, :frame, :extra_params, :placement, :options- def initialize(selected:, url:, frame: nil, extra_params: {}, placement: "bottom-end")+ # `options` narrows the menu to [key, label] pairs, for a chart that offers+ # its own timescales under the shared period keys (the loan chart). Without+ # it every Period is offered under its own short label.+ def initialize(selected:, url:, frame: nil, extra_params: {}, placement: "bottom-end", options: nil)@selected = selected@selected_key = selected.respond_to?(:key) ? selected.key : selected.to_s@url = url@frame = frame@extra_params = (extra_params || {}).symbolize_keys@placement = placement+ @options = optionsend- def periods- Period.all+ # [key, label] pairs, in menu order.+ def items+ options || Period.all.map { |period| [ period.key, period.label_short ] }enddef selected_label+ # A chart that supplies its own timescales labels them itself.+ option_label = options&.to_h&.fetch(selected_key, nil)+ return option_label if option_label+# A custom range's own label is just "Custom", which says nothing about what# the chart is showing. Show the dates instead.return selected.label_range if custom_selected?@@ -45,6 +54,13 @@ class UI::PeriodPicker < ApplicationComponentselected_key.blank? && selected.is_a?(Period)end+ # The trailing custom row belongs to the full Period menu. A chart that+ # narrows the menu to its own timescales offers no custom range, so the row+ # would be a choice that chart cannot show.+ def custom_row?+ options.nil? && custom_selected?+ end+def selected?(key)key == selected_keyenddiff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex 984f4aeca1..c29562e550 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -83,6 +83,11 @@ class AccountsController < ApplicationControllerdef show@chart_view = params[:chart_view] || "balance"@tab = params[:tab]+ # One reference date for everything on the page that is date-sensitive:+ # the chart, its projection, the cards and the Schedule tab. Read+ # separately, a render crossing midnight shows a chart projecting from one+ # date beside a table shaded against another.+ @as_of = Date.current@accessible_account_ids = Current.user.accessible_accounts.pluck(:id).to_set@q = params.fetch(:q, {}).permit(:search, status: [])entries = @account.entries.excluding_split_parents.search(@q).reverse_chronological.includes(:entryable)@@ -91,6 +96,17 @@ class AccountsController < ApplicationControllerreturn render_statement_tab_frame if statement_tab_frame_request?end+ # Only for a response that will actually show the chart card. The payload+ # runs the schedule and the projection; a Turbo frame request for the+ # activity feed's `entries` frame (its pagination) renders the whole page+ # and keeps one frame, so building it there was a full simulation per page+ # turn for nothing. Same reasoning as the statements-frame return above.+ #+ # The chart and the Schedule tab's forecast card read the same projection,+ # so it is built once here and handed to both.+ @loan_projection = @account.loan.payoff_projection(as_of: @as_of) if @account.accountable.is_a?(Loan)+ @loan_chart = loan_payoff_chart(@account, as_of: @as_of, period: @period, projection: @loan_projection) if chart_card_requested?+per_page = safe_per_page(stored_per_page_default)store_per_page!(per_page) if params[:per_page].present?@@ -312,6 +328,39 @@ class AccountsController < ApplicationControllerendprivate+ # Built here rather than in the template: assembling a chart payload is+ # domain work, and `show` asks for it exactly once per request, so there+ # is nothing to memoise.+ #+ # The payload runs the schedule, the projection and a balance query from+ # inputs this app does not fully control: `term_months` and `rate_type`+ # arrive from providers, `start_date` and the rate schedule from the form,+ # balances from sync. A raise in any of them costs the chart, not the page:+ # nil is what the component already takes as "no chart", and the account+ # page then renders exactly as it did before the chart existed. Reported,+ # because a loan silently losing its chart is a bug someone has to see.+ def loan_payoff_chart(account, as_of:, period:, projection: nil)+ return nil unless account.accountable.is_a?(Loan)++ Loan::PayoffChart.new(account.loan, as_of: as_of, period: period, projection: projection).payload+ rescue StandardError => e+ Rails.logger.error("Loan payoff chart failed for account #{account.id}: #{e.class} - #{e.message}")+ Sentry.capture_exception(e) { |scope| scope.set_tags(record_type: "Account", record_id: account.id) } if defined?(Sentry)+ nil+ end++ # A plain visit, or a frame request for one of the two frames the chart+ # card sits inside: the account's container frame and the chart card's own+ # chart_details frame. Any other frame is rendered and then discarded.+ def chart_card_requested?+ return true unless turbo_frame_request?++ request.headers["Turbo-Frame"].in?([+ helpers.dom_id(@account, :container),+ helpers.dom_id(@account, :chart_details)+ ])+ end+def ensure_linked_accountreturn if @account.linked?diff --git a/app/javascript/controllers/loan_payoff_chart_controller.js b/app/javascript/controllers/loan_payoff_chart_controller.jsnew file mode 100644index 0000000000..50942a6172--- /dev/null+++ b/app/javascript/controllers/loan_payoff_chart_controller.js@@ -0,0 +1,520 @@+import { Controller } from "@hotwired/stimulus";+import * as d3 from "d3";+import {+ CHART_TOOLTIP_CONTEXT_CLASSES,+ CHART_TOOLTIP_VALUE_CLASSES,+ createChartTooltip,+} from "utils/chart_tooltip";++// The loan balance chart: three series on one axis.+//+// actual the recorded balance, origination -> today. Solid: fact.+// scheduled the original contract, origination -> maturity. Dashed.+// projected where today's balance is heading on the contract's repayment.+// 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"+// and "forecast" visually separable.+//+// The x-domain comes from the payload, not from the data: the period picker+// governs it (#100, decision 4). Series are drawn through a clip so a line+// that leaves the window is cut at its edge rather than stretching the axis.++// Date-only strings parse as UTC midnight in `new Date`, shifting the day+// back for anyone west of Greenwich. Parse the components instead.+const parseDate = (s) => {+ if (!s) return null;+ const [y, m, d] = s.split("-").map(Number);+ return new Date(y, m - 1, d);+};++let clipSerial = 0;++export default class extends Controller {+ static values = { data: Object };++ connect() {+ this._draw = this._draw.bind(this);+ // A window resize also changes the element's box, so the resize listener+ // and the ResizeObserver both fire for one event. Each draw rebuilds the+ // whole SVG; coalesce them into one per animation frame.+ this._scheduleDraw = () => {+ if (this._frame) return;+ this._frame = requestAnimationFrame(() => {+ this._frame = null;+ this._draw();+ });+ };+ window.addEventListener("resize", this._scheduleDraw);+ // The container can be zero-width on first connect (a Turbo restore, a+ // hidden parent). Draw when the box settles.+ if (typeof ResizeObserver !== "undefined") {+ this._observer = new ResizeObserver(this._scheduleDraw);+ this._observer.observe(this.element);+ } else {+ this._draw();+ }+ }++ disconnect() {+ window.removeEventListener("resize", this._scheduleDraw);+ if (this._frame) cancelAnimationFrame(this._frame);+ this._frame = null;+ this._observer?.disconnect();+ this._tooltip?.remove();+ }++ _draw() {+ const root = this.element;+ const width = root.clientWidth;+ const height = root.clientHeight;+ if (width <= 0 || height <= 0) return;++ root.innerHTML = "";+ const data = this.dataValue || {};++ const toPoint = (p) => ({ date: parseDate(p.date), balance: p.balance });++ const domainStart = parseDate(data.domain_start);+ const domainEnd = parseDate(data.domain_end);+ const today = parseDate(data.today);+ if (!domainStart || !domainEnd || domainEnd <= domainStart) return;++ // Functional tokens, referenced as CSS variables and applied with+ // .style(), never .attr(): a variable is substituted in an inline style+ // property but not in an SVG presentation attribute, where it leaves the+ // stroke at `none`. No fallback colours: a token that fails to+ // resolve must fail visibly, and the browser test checks the resolved+ // stroke. Because these are live variables the browser recolours the+ // chart on a theme change by itself; no redraw is needed for that.+ const success = "var(--color-success)";+ const destructive = "var(--color-destructive)";+ const muted = "var(--color-tertiary)";++ // Drawing order: forecasts underneath, fact on top.+ const series = [+ {+ key: "scheduled",+ points: (data.scheduled || []).map(toPoint),+ color: destructive,+ dash: "6 4",+ width: 1.5,+ },+ {+ key: "projected",+ points: (data.projected || []).map(toPoint),+ color: success,+ dash: "4 4",+ width: 2,+ },+ {+ key: "actual",+ points: (data.actual || []).map(toPoint),+ color: success,+ dash: null,+ width: 2,+ },+ ].filter((s) => s.points.length > 1);+ if (series.length === 0) return;++ const margin = { top: 12, right: 12, bottom: 24, left: 48 };+ const x = d3+ .scaleTime()+ .domain([domainStart, domainEnd])+ .range([margin.left, width - margin.right]);+ // Scale the y-axis to what is inside the window plus each line's first+ // point either side of it, so a line crossing the window fits without the+ // window being sized for points it never shows.+ const inWindow = (points) => {+ const inside = points.filter(+ (p) => p.date >= domainStart && p.date <= domainEnd,+ );+ const before = points.filter((p) => p.date < domainStart).at(-1);+ const after = points.find((p) => p.date > domainEnd);+ return [before, ...inside, after].filter(Boolean);+ };+ const scalePoints = series.flatMap((s) => inWindow(s.points));+ const yMax = (d3.max(scalePoints, (d) => d.balance) || 1) * 1.05;+ const y = d3+ .scaleLinear()+ .domain([0, yMax])+ .range([height - margin.bottom, margin.top]);++ const svg = d3+ .select(root)+ .append("svg")+ .attr("width", width)+ .attr("height", height)+ .attr("role", "img")+ .attr("aria-label", data.aria_description || "")+ // The picture is also a keyboard control: arrow keys step the tooltip+ // through the plotted dates. Say so, since role=img alone would not.+ .attr("aria-roledescription", data.labels?.interactive_chart || "interactive chart")+ .attr("aria-keyshortcuts", "ArrowLeft ArrowRight Home End Escape");+ // Clip-path ids must be unique in the document. The mount carries the+ // account's own dom_id, which already is; a counter covers a mount without+ // one. Nothing random: the ids are read by url(#...) only.+ const id = `${root.id || `loan-chart-${++clipSerial}`}-clip`;+ const defs = svg.append("defs");+ const plotClip = `${id}-plot`;+ defs+ .append("clipPath")+ .attr("id", plotClip)+ .append("rect")+ .attr("x", margin.left)+ .attr("y", margin.top)+ .attr("width", Math.max(0, width - margin.left - margin.right))+ .attr("height", Math.max(0, height - margin.top - margin.bottom));+ // The hover split on the actual series: the recorded line stays coloured up+ // to the cursor and greys past it. Two clips share one edge, moved on+ // pointer events; at rest the edge sits at the window's end and the whole+ // line is coloured. Forecasts have no "before the cursor" to speak of.+ const splitAt = (px) => {+ pastClip.attr("width", Math.max(0, px - margin.left));+ futureClip+ .attr("x", px)+ .attr("width", Math.max(0, width - margin.right - px));+ };+ const pastClip = defs+ .append("clipPath")+ .attr("id", `${id}-past`)+ .append("rect")+ .attr("x", margin.left)+ .attr("y", margin.top)+ .attr("height", Math.max(0, height - margin.top - margin.bottom));+ const futureClip = defs+ .append("clipPath")+ .attr("id", `${id}-future`)+ .append("rect")+ .attr("y", margin.top)+ .attr("height", Math.max(0, height - margin.top - margin.bottom));+ splitAt(width - margin.right);++ const line = d3+ .line()+ .x((d) => x(d.date))+ .y((d) => y(d.balance))+ .curve(d3.curveMonotoneX);+ const area = d3+ .area()+ .x((d) => x(d.date))+ .y0(height - margin.bottom)+ .y1((d) => y(d.balance))+ .curve(d3.curveMonotoneX);++ // The request's locale travels in the payload: the layout hard-codes+ // lang="en", so the document cannot say. d3's default time ticks print+ // English month names, so the x-axis formats its own: the same choice of+ // unit as d3's (a year on 1 January, a month on the 1st, a day otherwise),+ // in that locale.+ const locale = data.locale || undefined;+ const tickYear = new Intl.DateTimeFormat(locale, { year: "numeric" });+ const tickMonth = new Intl.DateTimeFormat(locale, { month: "short" });+ const tickDay = new Intl.DateTimeFormat(locale, {+ day: "numeric",+ month: "short",+ });+ const timeTick = (date) => {+ if (d3.timeMonth(date) < date) return tickDay.format(date);+ if (d3.timeYear(date) < date) return tickMonth.format(date);+ return tickYear.format(date);+ };++ // Axes first, so the series draw over them. Text in currentColor: the+ // container carries the text token, so the axis follows the theme.+ const styleAxis = (g) => {+ g.selectAll("text")+ .style("fill", "currentColor")+ .style("opacity", 0.7)+ .style("font-size", "11px");+ g.selectAll("line,path")+ .style("stroke", "currentColor")+ .style("opacity", 0.2);+ };+ svg+ .append("g")+ .attr("transform", `translate(0,${height - margin.bottom})`)+ .call(+ d3+ .axisBottom(x)+ .ticks(Math.max(2, Math.floor(width / 140)))+ .tickFormat(timeTick)+ .tickSizeOuter(0),+ )+ .call(styleAxis);+ svg+ .append("g")+ .attr("transform", `translate(${margin.left},0)`)+ .call(+ d3.axisLeft(y).ticks(4).tickFormat(d3.format("~s")).tickSizeOuter(0),+ )+ .call(styleAxis);++ const stroke = (path, s, color) =>+ path+ .style("fill", "none")+ .style("stroke", color)+ .style("stroke-width", s.width)+ .style("stroke-linecap", "round")+ .style("stroke-linejoin", "round")+ .style("stroke-dasharray", s.dash || "none");++ 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.+ stroke(svg.append("path").datum(s.points).attr("d", line), s, muted)+ .attr("clip-path", `url(#${id}-future)`)+ .attr("data-series-shadow", s.key)+ .style("opacity", 0.6);+ stroke(svg.append("path").datum(s.points).attr("d", line), s, s.color)+ .attr("clip-path", `url(#${id}-past)`)+ .attr("data-series", s.key);+ } else {+ stroke(svg.append("path").datum(s.points).attr("d", line), s, s.color)+ .attr("clip-path", `url(#${plotClip})`)+ .attr("data-series", s.key);+ }++ // Interval markers, thinned to roughly one per 60px so a 360-payment+ // schedule does not become a solid band of circles. Not the accessible+ // signal: dash pattern is.+ const step = Math.max(+ 1,+ Math.ceil(s.points.length / Math.max(2, width / 60)),+ );+ svg+ .append("g")+ .attr("clip-path", `url(#${plotClip})`)+ .selectAll("circle")+ .data(s.points.filter((_, i) => i % step === 0))+ .join("circle")+ .attr("cx", (d) => x(d.date))+ .attr("cy", (d) => y(d.balance))+ .attr("r", 2.5)+ .style("fill", s.color);+ }++ if (today && today >= domainStart && today <= domainEnd) {+ svg+ .append("line")+ .attr("x1", x(today))+ .attr("x2", x(today))+ .attr("y1", margin.top)+ .attr("y2", height - margin.bottom)+ .style("stroke", "currentColor")+ .style("stroke-dasharray", "2 3")+ .style("opacity", 0.4);+ }++ this._installInteraction(svg, {+ x,+ series,+ width,+ height,+ margin,+ data,+ domainStart,+ domainEnd,+ splitAt,+ });+ }++ _installInteraction(+ svg,+ { x, series, width, height, margin, data, domainStart, domainEnd, splitAt },+ ) {+ this._tooltip?.remove();+ this.element.style.position = "relative";+ // The shared visual contract the other chart controllers use: the+ // .chart-tooltip surface, z-50 and privacy-sensitive.+ const tooltip = createChartTooltip(this.element);+ this._tooltip = tooltip;++ const bisect = d3.bisector((d) => d.date).left;+ const nearest = (points, date) => {+ if (!points.length) return null;+ const i = bisect(points, date);+ const a = points[Math.max(0, i - 1)];+ const b = points[Math.min(points.length - 1, i)];+ if (!a) return b;+ if (!b) return a;+ return date - a.date <= b.date - date ? a : b;+ };+ // The request's locale travels in the payload: the layout hard-codes+ // lang="en", so the document cannot say. Both the date and the money in+ // the tooltip follow it.+ const locale = data.locale || undefined;+ const monthYear = new Intl.DateTimeFormat(locale, {+ month: "short",+ year: "numeric",+ });+ const formatter = (() => {+ try {+ return new Intl.NumberFormat(locale, {+ style: "currency",+ currency: data.currency || "USD",+ maximumFractionDigits: 0,+ });+ } catch {+ // A currency code Intl does not know must not take hover with it.+ return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 });+ }+ })();+ const money = (value) => formatter.format(value);++ const showAt = (date) => {+ const px = x(date);+ const rows = series+ .map((s) => {+ // A series says nothing about dates outside its own span.+ 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;+ })+ .filter(Boolean);+ // The domain can open before the first series point (a period that+ // starts before origination). Off every series there is nothing to+ // say, and the previous position must not stay on screen.+ if (!rows.length) {+ hide();+ return;+ }++ // Text nodes, never innerHTML. Date and figures take the shared content+ // classes, as the other charts' tooltips do.+ const dateRow = document.createElement("div");+ dateRow.className = CHART_TOOLTIP_CONTEXT_CLASSES;+ dateRow.textContent = monthYear.format(date);+ const valueRows = rows.map(({ label, value }) => {+ 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;+ });+ tooltip.replaceChildren(dateRow, ...valueRows);+ tooltip.style.display = "block";+ // Measured once the content is in: the shared surface is padded, so a+ // fixed allowance would let a long row run past the chart's right edge.+ const left = Math.min(px + 12, width - tooltip.offsetWidth - 4);+ tooltip.style.left = `${Math.max(margin.left, left)}px`;+ tooltip.style.top = `${margin.top}px`;+ splitAt(Math.max(margin.left, Math.min(px, width - margin.right)));+ };+ // The live region announces only what the keyboard asks for. Under a+ // pointer the tooltip rewrites on every movement, and a live region that+ // announces every one of those is noise for anyone using a pointer with a+ // screen reader.+ const announce = (on) => {+ if (on) {+ tooltip.setAttribute("role", "status");+ tooltip.setAttribute("aria-live", "polite");+ } else {+ tooltip.removeAttribute("role");+ tooltip.removeAttribute("aria-live");+ }+ };++ const hide = () => {+ tooltip.style.display = "none";+ announce(false);+ splitAt(width - margin.right);+ };++ // The dates the tooltip stops at: the scheduled payment dates in the window,+ // or every plotted date when there is no schedule in it. The recorded+ // line's own points are weekly and would otherwise repeat the same month+ // several times over.+ const scheduledDates = (data.scheduled || [])+ .map((point) => parseDate(point.date))+ .filter((date) => date && date >= domainStart && date <= domainEnd);+ const stops = Array.from(+ new Set(+ (scheduledDates.length+ ? scheduledDates+ : series.flatMap((s) => s.points).map((p) => p.date)+ )+ .filter((date) => date >= domainStart && date <= domainEnd)+ .map((date) => date.getTime()),+ ),+ )+ .sort((a, b) => a - b)+ .map((t) => new Date(t));+ // The pointer snaps to those dates too, so the tooltip's heading is the+ // date its figures come from. Unsnapped, a cursor just before a payment+ // date headed the tooltip with the month it sat in while every row showed+ // that payment's balance.+ const stopPoints = stops.map((date) => ({ date }));+ const snap = (date) =>+ stopPoints.length ? nearest(stopPoints, date).date : date;++ svg+ .append("rect")+ .attr("x", margin.left)+ .attr("y", margin.top)+ .attr("width", Math.max(0, width - margin.left - margin.right))+ .attr("height", Math.max(0, height - margin.top - margin.bottom))+ .style("fill", "transparent")+ .style("cursor", "crosshair")+ .on("pointermove", (event) => {+ announce(false);+ const [px] = d3.pointer(event);+ showAt(snap(x.invert(px)));+ })+ .on("pointerleave", hide);++ // Keyboard traversal: the same stops, stepped with the arrow keys.+ // Arrow keys move, Home/End jump, Escape clears.+ if (!stops.length) return;++ svg.attr("tabindex", 0);+ let focused = null;+ svg.on("keydown", (event) => {+ if (+ !["ArrowLeft", "ArrowRight", "Home", "End", "Escape"].includes(+ event.key,+ )+ )+ return;+ event.preventDefault();+ if (event.key === "Escape") {+ focused = null;+ hide();+ return;+ }+ if (focused === null)+ focused = event.key === "ArrowLeft" ? stops.length - 1 : 0;+ else if (event.key === "ArrowLeft") focused = Math.max(0, focused - 1);+ else if (event.key === "ArrowRight")+ focused = Math.min(stops.length - 1, focused + 1);+ else if (event.key === "Home") focused = 0;+ else focused = stops.length - 1;+ announce(true);+ // `focused` is clamped to the array above; `.at()` reads the same+ // element without the bracket form object-injection scanners flag.+ showAt(stops.at(focused));+ });+ svg.on("blur", () => {+ focused = null;+ hide();+ });+ }+}diff --git a/app/models/loan.rb b/app/models/loan.rbindex d5ffdcc6d7..a657cb2c79 100644--- a/app/models/loan.rb+++ b/app/models/loan.rb@@ -233,6 +233,12 @@ class Loan < ApplicationRecordsuperend+ # Where the loan is heading from today's balance. Not memoised: `as_of`+ # makes each call a different question.+ def payoff_projection(as_of: Date.current)+ PayoffProjection.new(self, as_of: as_of)+ end+# The date the loan was drawn down. Recorded explicitly when the borrower# knows it -- a loan is often drawn down before the account tracking it is# created -- and otherwise taken from the account's first valuation (thediff --git a/app/models/loan/payoff_chart.rb b/app/models/loan/payoff_chart.rbnew file mode 100644index 0000000000..f35cc8b5b6--- /dev/null+++ b/app/models/loan/payoff_chart.rb@@ -0,0 +1,234 @@+class Loan+ # The series the loan balance chart draws, and the figures its accessible+ # description quotes.+ #+ # actual the recorded balances, origination -> today (or the period's+ # end, whichever is earlier). Solid: this is fact.+ # scheduled the original contract, origination -> maturity. Dashed.+ # projected where today's recorded balance is heading on the contract's+ # repayment. Dashed. Extra payments the borrower has already+ # made are in here without being named: they are why today's+ # balance is what it is.+ #+ # The picked period governs the x-domain, and it means what it means on+ # every other chart: 1Y is the last year, YTD the current calendar year,+ # clamped so no window opens before the loan does. Under "All" the domain+ # runs origination -> the later payoff date so every series has room. A+ # bounded window ends today, so the forward series draw under All alone;+ # the cards beside the chart quote the projection whatever the window.+ # `Period` is not touched to achieve this: the payload carries the domain+ # and the controller draws to it.+ #+ # The actual series is never queried past today. Balance::ChartSeriesBuilder+ # carries the last observation forward, so asking it for future dates would+ # draw a flat line asserting the balance never moves again.+ class PayoffChart+ SERIES = %i[actual scheduled projected].freeze++ # 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+ # one added to Period::PERIODS later, shows the whole life, because the+ # picker's choice is shared with every account page. A test keeps these+ # keys a subset of Period::PERIODS so a renamed period cannot silently+ # stop matching.+ WINDOW_KEYS = %w[+ current_month+ last_90_days+ current_year+ last_365_days+ last_5_years+ last_10_years+ all_time+ ].freeze++ # [key, label] pairs for the loan chart's period picker, in WINDOW_KEYS+ # order, under the shared periods' own labels.+ def self.window_options+ WINDOW_KEYS.map { |key| [ key, Period.from_key(key).label_short ] }+ end++ # `projection` lets a caller that also shows the forecast elsewhere on the+ # page build it once; it must be the loan's projection for this `as_of`.+ def initialize(loan, as_of: Date.current, period: nil, projection: nil)+ @loan = loan+ @as_of = as_of+ @period = period+ @projection = projection+ end++ # nil when there is nothing to draw. The page falls back to the plain+ # balance chart, so the chart's absence is not the page's absence.+ def payload+ return nil unless schedule&.payments&.any?++ series = {+ actual: actual_series,+ scheduled: scheduled_series,+ projected: projection_series(projection)+ }++ {+ today: as_of.iso8601,+ # The tooltip formats dates and money in this locale. The layout+ # hard-codes `lang="en"`, so the document cannot tell the chart.+ locale: I18n.locale.to_s,+ currency: currency,+ domain_start: domain_start.iso8601,+ domain_end: domain_end.iso8601,+ **series,+ visible: SERIES.select { |key| visible?(series[key]) },+ scheduled_payoff_date: schedule.payoff_date&.iso8601,+ projected_payoff_date: projection.payoff_date&.iso8601,+ # The figures the cards beside the chart quote. nil when the projection+ # cannot run or never clears the balance, so a card is not shown for a+ # comparison that does not exist.+ months_saved: projection.converged? ? projection.months_saved : nil,+ interest_saved: projection.converged? ? projection.interest_saved.amount.to_f : nil,+ # What the contracted repayment leaves owing at the original maturity+ # when it does not clear the balance; nil when it does. The one figure+ # 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])+ }+ end++ private+ attr_reader :loan, :as_of, :period++ def schedule+ @schedule ||= loan.amortization_schedule+ end++ def projection+ @projection ||= loan.payoff_projection(as_of: as_of)+ end++ def currency+ loan.account.currency+ end++ # No period, "All", and any period the loan chart does not offer -- the+ # picker's choice is shared with every account -- mean the whole life.+ # Upstream's "All" starts at the family's oldest entry, which for a loan+ # younger than the family is years before it existed, so the whole life+ # takes its own dates from the loan rather than from the period.+ def whole_life?+ period.nil? || period.key.to_s == "all_time" || !WINDOW_KEYS.include?(period.key.to_s)+ end++ # Memoised, as is domain_end: visible? reads the domain for every point,+ # and a loan with no start date finds its origination through the+ # account's first valuation, which is a lookup each time it is asked.+ #+ # A window opens where the period does, but never before the loan: a+ # lead-in before origination would read as a balance that was not there.+ def domain_start+ @domain_start ||= whole_life? ? loan.origination_date : [ period.start_date, loan.origination_date ].max+ end++ # The whole life reaches far enough to hold every line: the contract's+ # payoff and the projection's, whichever is later, and never before today.+ # A window ends where the period does, but never past that and never on+ # its start.+ def domain_end+ @domain_end ||= begin+ whole_life_end = [ schedule.payoff_date, projection.payoff_date, as_of ].compact.max+ whole_life? ? whole_life_end : [ [ period.end_date, whole_life_end ].min, domain_start + 1 ].max+ end+ end++ # Recorded balances inside the domain and no later than today. Nothing+ # before the first materialised balance: the series builder carries the+ # last observation forward and reports zero before there is one, and a+ # flat zero lead-in reads as a balance that was not there.+ def actual_series+ first_balance_date = loan.account.balances.minimum(:date)+ return [] if first_balance_date.nil?++ from = [ domain_start, first_balance_date ].compact.max+ to = [ domain_end, as_of ].min+ return [] if from > to++ loan.account.balance_series(period: Period.custom(start_date: from, end_date: to)).values.map do |value|+ { date: value.date.iso8601, balance: value.value.amount.to_f }+ end+ end++ # Opens at origination with the full principal. Starting at the first+ # payment omits the amount borrowed entirely, and leaves a one-payment+ # loan with a single point and therefore no line at all.+ def scheduled_series+ rows = schedule.payments+ return [] if rows.empty?++ opening = { date: loan.origination_date.iso8601, balance: schedule.principal.to_f }+ [ opening ] + series(rows) { |p| [ p.date, p.ending_balance.amount ] }+ end++ # A projection opens at today's real balance, so the line starts there+ # rather than at its first payment -- otherwise it appears to begin+ # wherever the first payment happens to leave it.+ def projection_series(source)+ return [] unless source&.applicable?++ opening = { date: as_of.iso8601, balance: source.current_balance.amount.to_f }+ [ opening ] + series(source.payments) { |p| [ p[:payment_date], p[:ending_balance] ] }+ end++ def series(rows)+ rows.map do |row|+ date, balance = yield(row)+ { date: date.iso8601, balance: balance.to_f }+ end+ end++ # 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.+ def visible?(points)+ dates = points.map { |point| Date.iso8601(point[:date]) }+ return false if dates.empty?++ inside = dates.count { |date| date.between?(domain_start, domain_end) }+ inside >= 2 || (dates.first < domain_start && dates.last > domain_end)+ end++ # The chart controller reads `interactive_chart` for the SVG's+ # aria-roledescription; without it every locale gets its English default.+ def labels+ SERIES.index_with { |key| I18n.t("UI.account.chart.loan.#{key}") }+ .merge(+ 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:)+ description = I18n.t(+ "UI.account.chart.loan.aria_description",+ current_balance: projection.current_balance.format,+ scheduled_payoff_date: long_date(schedule.payoff_date, I18n.t("loans.tabs.overview.unknown")),+ projected_payoff_date: long_date(projection.payoff_date, I18n.t("UI.account.chart.loan.no_payoff"))+ )++ actual_start_date = actual.first && Date.iso8601(actual.first[:date])+ if actual_start_date && actual_start_date > domain_start+ description = [ description, I18n.t(+ "UI.account.chart.loan.aria_actual_history_starts",+ date: I18n.l(actual_start_date, format: :long)+ ) ].join(" ")+ end++ description+ end++ def long_date(date, fallback)+ date ? I18n.l(date, format: :long) : fallback+ end+ end+enddiff --git a/app/models/loan/payoff_projection.rb b/app/models/loan/payoff_projection.rbnew file mode 100644index 0000000000..8c0b563b21--- /dev/null+++ b/app/models/loan/payoff_projection.rb@@ -0,0 +1,178 @@+class Loan+ # Where the loan is actually heading, starting from today's real balance+ # rather than from the contract.+ #+ # The contracted schedule answers "what did you agree to?". This answers "what+ # is going to happen?", and the gap between them is the whole point: a+ # borrower who has overpaid is ahead of the schedule, one whose balance has+ # grown is behind, and neither is visible from the contract alone.+ #+ # It pays the repayment the CONTRACT requires in each period -- the+ # schedule's own row, re-amortised wherever the schedule re-amortises --+ # against a balance that is no longer the contracted one. That is deliberate:+ # re-sizing the repayment to today's balance would answer a different and much+ # less useful question, and would land every borrower who is ahead back on+ # the original maturity. Paying what the contract asks against a smaller+ # balance is how they finish sooner.+ #+ # Extra payments the borrower has already made are in here without being+ # named: they are why today's balance is what it is.+ class PayoffProjection+ attr_reader :loan, :as_of++ def initialize(loan, as_of: Date.current)+ @loan = loan+ @as_of = as_of+ end++ # False when there is nothing to project: no schedule, nothing left to owe,+ # no payments remaining, or no repayment to hold.+ #+ # `&&` binds tighter than `||`, so the trailing `|| false` applies to the+ # whole chain. It turns the nil that `contracted_payment&.positive?` gives for+ # a missing payment into false, so callers always get a boolean.+ def applicable?+ schedule.present? &&+ current_balance.amount.positive? &&+ remaining_payment_dates.any? &&+ contracted_payment&.positive? || false+ end++ def currency+ loan.account.currency+ end++ # `accounts.balance` is nullable, and Money.new(nil) raises. A loan with no+ # balance yet has nothing to project, so it reads as zero: applicable? is+ # then false and the Schedule tab's card says so instead of the page failing.+ def current_balance+ @current_balance ||= Money.new(loan.account.balance || 0, currency)+ end++ def payments+ simulation&.payments || []+ end++ def payoff_date+ simulation&.payoff_date+ end++ def total_interest+ Money.new(simulation&.total_interest || 0, currency)+ end++ # False when the contracted repayment does not clear the balance by the+ # original maturity -- the borrower is far enough behind that the contract+ # no longer pays the loan off. There is no payoff date in that case.+ def converged?+ simulation ? simulation.converged? : false+ end++ def balloon_amount+ Money.new(simulation&.balloon_amount || 0, currency)+ end++ # Positive means the loan finishes earlier than the contract said. Zero for+ # a run that never clears the balance: it walks every remaining date, so+ # there is nothing to subtract -- no convergence guard is needed here, and+ # one would be untestable, which is why it is not.+ def months_saved+ return 0 unless applicable?++ remaining_payment_dates.length - payments.length+ end++ # Positive means less interest than the contract's remaining interest.+ def interest_saved+ return Money.new(0, currency) unless applicable?++ Money.new(remaining_contracted_interest - (simulation&.total_interest || 0), currency)+ end++ private+ def schedule+ @schedule ||= loan.amortization_schedule+ end++ # The contract's rows still ahead, in order. The projection walks exactly+ # these dates, so position `index` in its run is position `index` here.+ def remaining_scheduled_payments+ @remaining_scheduled_payments ||= (schedule&.payments || [])+ .select { |payment| payment.date > as_of }+ end++ # The payment dates still ahead. A projection runs to the ORIGINAL+ # maturity and no further: extending it would invent a term the borrower+ # never agreed to.+ def remaining_payment_dates+ @remaining_payment_dates ||= remaining_scheduled_payments.map(&:date)+ end++ # The repayment in force: the next scheduled payment's amount. For a+ # re-amortising loan that is the figure the current rate produced, which+ # is what the borrower is actually paying.+ def contracted_payment+ @contracted_payment ||= remaining_scheduled_payments.first&.payment&.amount+ end++ # What the contract asks for in the projection's period `index`: the+ # schedule's row for the same date. The two walks share their dates, so a+ # recorded rate change re-sizes this exactly where the schedule re-sizes+ # its own repayment. Past the last row -- unreachable today, since the+ # projection stops at the original maturity -- the last amount holds.+ def scheduled_payment_for(index:, **)+ row = remaining_scheduled_payments[index] || remaining_scheduled_payments.last+ row.payment.amount+ end++ def remaining_contracted_interest+ remaining_scheduled_payments.sum(BigDecimal("0")) { |payment| payment.interest.amount }+ end++ # The date the period containing `as_of` opened: the last scheduled+ # payment on or before it, or origination before the first. The simulator+ # charges a period at the rate in force when it OPENED, so the projection's+ # first period opens where the schedule's does. Opened at `as_of`, a rate+ # change recorded between the last payment and today re-rated a month the+ # schedule charges at the old rate, and a borrower exactly on contract was+ # quoted interest they will never pay.+ def current_period_start+ schedule.payments.reverse_each.find { |payment| payment.date <= as_of }&.date || schedule.start_date+ end++ def simulation+ return nil unless applicable?++ @simulation ||= Simulator.new(+ starting_balance: current_balance.amount,+ accrual_start_date: current_period_start,+ payment_schedule: remaining_payment_dates,+ accrual_rate_for: rate_resolver.method(:accrual_rate_for),+ re_amortisation_events: rate_resolver.method(:re_amortisation_events),+ # The contract's own repayment, period by period. Not :reamortize:+ # that re-sizes off the balance in front of it, and for a borrower+ # who is ahead that shrinks the repayment until the loan lands back+ # on the original maturity -- the opposite of what paying the+ # contracted amount against a smaller balance actually does. On a+ # fixed loan every row carries the same figure, so this is the held+ # contracted payment; on a variable loan it moves exactly where the+ # schedule's does.+ payment_amount: method(:scheduled_payment_for),+ payment_strategy: :scheduled,+ currency_precision: currency_precision,+ # A projection that cannot clear the balance must SAY so. Settling the+ # final payment regardless would manufacture a payoff date for a loan+ # the contract no longer pays off.+ settle_at_schedule_end: false+ ).run+ end++ def rate_resolver+ @rate_resolver ||= RateResolver.for(loan)+ end++ def currency_precision+ @currency_precision ||= Money::Currency.new(currency).default_precision || 2+ end+ end+enddiff --git a/app/models/loan/simulation_result.rb b/app/models/loan/simulation_result.rbindex 58e57eb461..17e40723e3 100644--- a/app/models/loan/simulation_result.rb+++ b/app/models/loan/simulation_result.rb@@ -5,23 +5,33 @@ class Loan# live schedule -- and later a payoff projection -- reads from, rather than# each caller deciding for itself what a run produced.#- # There is no "did it converge?" here, because in this engine it always does:- # the simulator sizes its own level payment from the balance and the periods- # remaining, and settles the final period exactly. A run that ends with a- # balance outstanding only becomes possible once a caller can impose a- # payment the simulator did not choose -- and that belongs with the change- # that introduces it, not as unreachable state carried in advance.+ # A run does not always clear the balance. It does whenever the simulator+ # sizes its own payment, but a caller can impose one it did not choose -- a+ # projection holds the CONTRACTED repayment against today's balance -- and+ # against a balance that has grown, the contracted repayment may not be+ # enough. That leaves a balloon, and #payoff_date refuses to give a date for+ # a loan that was never paid off.class SimulationResult- attr_reader :payments, :total_interest+ attr_reader :payments, :balloon_amount, :total_interest- def initialize(payments:, currency_precision:)+ def initialize(payments:, currency_precision:, converged: true, balloon_amount: BigDecimal("0"))+ @converged = converged+ @balloon_amount = BigDecimal(balloon_amount.to_s).round(currency_precision).freeze@payments = deep_freeze(payments)@total_interest = @payments.sum(BigDecimal("0")) { |p| p[:interest_payment] }.round(currency_precision).freezefreezeend+ def converged?+ @converged+ end++ # nil for a run that ended with a balance outstanding. A balloon quoted as+ # a payoff date is the reading that costs someone money.def payoff_date+ return nil unless converged?+payments.last&.fetch(:payment_date)enddiff --git a/app/models/loan/simulator.rb b/app/models/loan/simulator.rbindex a2dd3beff0..756edf40e7 100644--- a/app/models/loan/simulator.rb+++ b/app/models/loan/simulator.rb@@ -39,7 +39,19 @@ class Loan# was never asked for, and loses the remaining balance without saying so.MAX_PERIODS = 1200- PAYMENT_STRATEGIES = %i[reamortize hold].freeze+ # How the repayment behaves from one period to the next:+ #+ # :reamortize sized from the balance in front of it, and re-sized+ # whenever the sizing rate moves -- what a lender does to a+ # contracted schedule+ # :hold one figure, seeded or sized on the first period, held to+ # the end whatever the rate does+ # :scheduled asked for every period from a callable, regardless of the+ # balance -- what a projection uses to pay the CONTRACT's+ # repayment against a balance that is no longer the+ # contracted one, so a borrower who is ahead finishes early+ # instead of being re-sized back onto the original maturity+ PAYMENT_STRATEGIES = %i[reamortize hold scheduled].freeze# Built once: `monthly_rate` runs twice per period, up to MAX_PERIODS times# per simulation. The two-step division is kept as it was so results stay@@ -55,6 +67,7 @@ class Loancurrency_precision:,re_amortisation_events: nil,payment_strategy: :reamortize,+ payment_amount: nil,settle_at_schedule_end: true)@starting_balance = BigDecimal(starting_balance.to_s)@@ -66,6 +79,14 @@ class Loan)@currency_precision = currency_precision@payment_strategy = payment_strategy.to_sym+ # A caller-supplied repayment. Under :hold and :reamortize a number that+ # seeds the run; under :scheduled a callable, asked every period for the+ # amount the contract requires then -- see #run.+ @payment_amount =+ if payment_amount.respond_to?(:call) then payment_amount+ elsif payment_amount.nil? then nil+ else BigDecimal(payment_amount.to_s)+ end@settle_at_schedule_end = settle_at_schedule_endraise ArgumentError, "payment schedule must not be empty" if @payment_schedule.empty?@@ -77,6 +98,9 @@ class Loanunless PAYMENT_STRATEGIES.include?(@payment_strategy)raise ArgumentError, "unsupported payment strategy: #{@payment_strategy.inspect}"end+ if (@payment_strategy == :scheduled) != @payment_amount.respond_to?(:call)+ raise ArgumentError, ":scheduled takes a callable payment_amount; the other strategies take a number"+ endenddef run@@ -95,29 +119,53 @@ class Loanaccrual_rate = monthly_rate(@accrual_rate_for.call(period_start))sizing_rate = monthly_rate(rate_on(payment_date))- # Interest first, on the balance the period opened with: one charge- # per period under monthly accrual. Sizing needs it when the two rates+ # Interest first, on the balance the period OPENED with: one charge per+ # period under monthly accrual. Sizing needs it when the two rates# differ, see below.interest = (balance * accrual_rate).round(@currency_precision)- # Resize only when the sizing rate actually moves. Recomputing every- # period would be arithmetically identical while the rate holds, but it- # would also silently absorb a payment the borrower is contracted to,- # which is what `:hold` exists to refuse.- #- # When the period straddles the change -- accrued at the old rate,- # sized at the new -- the annuity formula alone over-covers this- # period and the payment is not level to maturity (a final settlement- # thousands short). The sizing is told what this period actually- # charged so the figure covers it and amortises the rest evenly.- if payment.nil? || (@payment_strategy == :reamortize && sizing_rate != previous_sizing_rate)- payment = AmortizationMath.level_payment(+ if @payment_strategy == :scheduled+ # The contract's repayment for THIS period, whatever balance is in+ # front of it. Sizing from the balance would shrink a borrower who is+ # ahead back onto the original maturity; paying what the contract+ # asks is how they finish sooner.+ payment = BigDecimal(@payment_amount.call(+ index: index,balance: balance,- monthly_rate: sizing_rate,- remaining_payments: @payment_schedule.length - index,- currency_precision: @currency_precision,- first_period_interest: (interest if sizing_rate != accrual_rate)- )+ sizing_rate: sizing_rate,+ remaining_payments: @payment_schedule.length - index+ ).to_s)+ else+ # Resize only when the sizing rate actually moves. Recomputing every+ # period would be arithmetically identical while the rate holds, but+ # it would also silently absorb a payment the borrower is contracted+ # to, which is what `:hold` exists to refuse.+ if payment.nil?+ # A supplied amount seeds the run -- a projection opens on the+ # repayment the borrower is contracted to, not one re-derived from+ # today's balance, which would make every loan look on track.+ payment = @payment_amount+ end+ # `previous_sizing_rate.nil?` guards the first period: there is no+ # earlier rate to have moved away from, so the opening rate is not a+ # rate CHANGE. Without it, a seeded repayment is overwritten on the+ # very first period it was supposed to govern.+ rate_moved = !previous_sizing_rate.nil? && sizing_rate != previous_sizing_rate+ # When the period straddles the change -- accrued at the old rate,+ # sized at the new -- the annuity formula alone over-covers this+ # period and the payment is not level to maturity (a final+ # settlement thousands short). The sizing is told what this period+ # actually charged so the figure covers it and amortises the rest+ # evenly.+ if payment.nil? || (@payment_strategy == :reamortize && rate_moved)+ payment = AmortizationMath.level_payment(+ balance: balance,+ monthly_rate: sizing_rate,+ remaining_payments: @payment_schedule.length - index,+ currency_precision: @currency_precision,+ first_period_interest: (interest if sizing_rate != accrual_rate)+ )+ endendprevious_sizing_rate = sizing_rate@@ -149,7 +197,12 @@ class Loanbalance = step[:ending_balance]end- SimulationResult.new(payments: payments, currency_precision: @currency_precision)+ SimulationResult.new(+ payments: payments,+ converged: balance.zero?,+ balloon_amount: balance,+ currency_precision: @currency_precision+ )endprivatediff --git a/app/views/accounts/show.html.erb b/app/views/accounts/show.html.erbindex a2c663b6be..edb1548d97 100644--- a/app/views/accounts/show.html.erb+++ b/app/views/accounts/show.html.erb@@ -2,6 +2,9 @@account: @account,chart_view: @chart_view,chart_period: @period,+ loan_chart: @loan_chart,+ loan_projection: @loan_projection,+ as_of: @as_of,active_tab: @tab,statement_coverage: @statement_coverage,statements: @account_statements,diff --git a/app/views/loans/tabs/_schedule.html.erb b/app/views/loans/tabs/_schedule.html.erbindex 02ed316f37..3ab5fc4935 100644--- a/app/views/loans/tabs/_schedule.html.erb+++ b/app/views/loans/tabs/_schedule.html.erb@@ -1,11 +1,15 @@-<%# locals: (account:) %>+<%# locals: (account:, projection:, as_of: Date.current) %>+<%# `as_of` is the page's one reference date: the chart above the tabs and+ this table shade "past" against the same day. `projection` is the loan's+ payoff projection for that date, built once for the page and shared with+ the chart. %>+<% today = as_of %><% schedule = account.loan.amortization_schedule %><% payments = schedule.payments %>-<% today = Date.current %><div class="space-y-4">- <div class="grid grid-cols-2 md:grid-cols-3 gap-2">+ <div class="grid grid-cols-2 md:grid-cols-4 gap-2"><%# A re-amortising loan has no single monthly payment, so the card sayswhich one this is rather than implying the figure holds for the term. %><%= summary_card title: schedule.re_amortising? ? t(".opening_payment") : t(".monthly_payment") do %>@@ -19,6 +23,20 @@<%= summary_card title: t(".total_cost") do %><%= format_money schedule.total_paid %><% end %>++ <%# When the loan will actually be paid off: the projection from today's+ balance at the contract's repayment, as the chart above draws it. The+ Overview tab has the contract's own date. A balance that repayment no+ longer clears has no date to give. %>+ <%= summary_card title: t(".forecasted_payoff_date") do %>+ <% if projection.payoff_date %>+ <%= l projection.payoff_date, format: :long %>+ <% elsif projection.applicable? %>+ <%= t(".forecasted_payoff_not_converged") %>+ <% else %>+ <%= t(".not_applicable") %>+ <% end %>+ <% end %></div><p class="text-sm text-secondary">diff --git a/config/locales/views/components/de.yml b/config/locales/views/components/de.ymlindex b8afd62724..39d0da12d1 100644--- a/config/locales/views/components/de.yml+++ b/config/locales/views/components/de.yml@@ -126,6 +126,25 @@ de:start_principal: Die Restschuld zu Beginn dieses Tagesstart_value: Der Vermögenswert zu Beginn dieses Tageschart:+ loan:+ 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}."+ interactive_chart: "interaktives Diagramm"+ interest_saved: "Eingesparte Zinsen"+ legend: "Diagrammreihen"+ months_saved:+ one: "%{count} Monat früher als geplant"+ other: "%{count} Monate früher als geplant"+ no_payoff: "mit der aktuellen Rate nicht erreicht"+ not_converged: "Mit der aktuellen Rate ist dieser Saldo bis zum ursprünglichen Laufzeitende nicht getilgt; %{balloon} blieben offen."+ on_schedule: "Im Plan"+ projected: "Prognose ab heute"+ projected_payoff: "Voraussichtliche Tilgung"+ projection_basis: "Vergleicht den heute erfassten Saldo mit dem Saldo laut Tilgungsplan am selben Tag. Eine vor ihrem Fälligkeitstermin gebuchte Zahlung erscheint bis zu diesem Termin als Vorsprung, eine danach gebuchte als Rückstand."+ scheduled: "Ursprünglicher Tilgungsplan"+ since_start: "seit Kreditbeginn"+ today: "Heute"no_data_available: Keine Daten vorhandentitle:balance: Saldo@@ -134,6 +153,7 @@ de:estimated_property_value: Geschätzter Immobilienwertestimated_vehicle_value: Geschätzter Fahrzeugwertholdings_value: Wert der Bestände+ loan_remaining_balance: Verbleibender Saldoremaining_principal_balance: Verbleibende Restschuldtotal_account_value: Gesamtwert des Kontostotal_gains: Gesamtgewinndiff --git a/config/locales/views/components/en.yml b/config/locales/views/components/en.ymlindex fcf8b23f61..f6d6cb0e9e 100644--- a/config/locales/views/components/en.yml+++ b/config/locales/views/components/en.yml@@ -60,6 +60,25 @@ en:start_principal: The principal balance at the beginning of this daystart_value: The asset value at the beginning of this daychart:+ loan:+ actual: Recorded balance+ scheduled: Original schedule+ projected: Projected from today+ today: Today+ interactive_chart: interactive chart+ no_payoff: not on the current repayment+ aria_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}.+ projected_payoff: Projected payoff+ months_saved:+ one: "%{count} month sooner than scheduled"+ other: "%{count} months sooner than scheduled"+ on_schedule: On schedule+ interest_saved: Interest saved+ not_converged: On the current repayment this balance is not paid off by the original maturity; %{balloon} would still be owed.+ projection_basis: Compares today's recorded balance with the schedule's balance on the same day. A payment posted before its scheduled date reads as ahead until that date; one posted after reads as behind.+ legend: Chart series+ since_start: since the loan startedno_data_available: "No data available"title:balance: Balance@@ -68,6 +87,7 @@ en:estimated_property_value: Estimated property valueestimated_vehicle_value: Estimated vehicle valueholdings_value: Holdings value+ loan_remaining_balance: Remaining balanceremaining_principal_balance: Remaining principal balancetotal_account_value: Total account valuetotal_gains: Total gainsdiff --git a/config/locales/views/loans/de.yml b/config/locales/views/loans/de.ymlindex 53ec2739c3..e4ea44612d 100644--- a/config/locales/views/loans/de.yml+++ b/config/locales/views/loans/de.yml@@ -43,8 +43,11 @@ de:description: Hochgerechnet aus ursprünglicher Kreditsumme, Zinssatz und Laufzeit, beginnend am %{start_date}. Sondertilgungen sind nicht berücksichtigt.variable_rate_notice: Der Zinssatz dieses Kredits ändert sich im Laufe der Zeit. Der Tilgungsplan wird bei jeder erfassten Änderung neu berechnet; das ursprüngliche Ablösedatum bleibt, die Rate passt sich an. Eine noch nicht erfasste Änderung verschiebt diese Zahlen.opening_payment: Anfangsrate+ forecasted_payoff_date: Voraussichtliches Ablösedatum+ forecasted_payoff_not_converged: Mit der aktuellen Rate nicht getilgtinterest: Zinsenmonthly_payment: Monatsrate+ not_applicable: "–"number: "Nr."payment: Rateprincipal: Tilgungdiff --git a/config/locales/views/loans/en.yml b/config/locales/views/loans/en.ymlindex 1df3da1169..f13dd48d5b 100644--- a/config/locales/views/loans/en.yml+++ b/config/locales/views/loans/en.yml@@ -43,8 +43,11 @@ en:description: Projected from the original balance, rate and term, starting %{start_date}. Extra payments are not reflected.variable_rate_notice: This loan's rate changes over time. The schedule re-amortises at each recorded change, keeping the original payoff date and resizing the repayment; a change that has not been recorded yet will shift these figures.opening_payment: Opening Payment+ forecasted_payoff_date: Forecasted Payoff Date+ forecasted_payoff_not_converged: Not paid off on the current repaymentinterest: Interestmonthly_payment: Monthly Payment+ not_applicable: N/Anumber: "#"payment: Paymentprincipal: Principaldiff --git a/test/components/UI/account/chart_test.rb b/test/components/UI/account/chart_test.rbindex 57c930db3a..38c175aee3 100644--- a/test/components/UI/account/chart_test.rb+++ b/test/components/UI/account/chart_test.rb@@ -40,6 +40,151 @@ class UI::Account::ChartTest < ViewComponent::TestCaseassert_equal "+$110.00", component.converted_balance_displayend+ # A loan with a schedule takes the loan balance chart; every other+ # account keeps the chart it always had. Asserted on the mounted controller,+ # because "unchanged for everyone else" is the blast-radius promise this+ # branch makes.+ test "a loan account with a chart payload mounts the loan balance chart and nothing else" 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"++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: payload))++ assert_selector "[data-controller='loan-payoff-chart']"+ assert_no_selector "[data-controller='time-series-chart']"+ assert_no_selector "table", visible: :all+ assert_selector "p.sr-only", text: payload[:aria_description], visible: :all+ end++ test "a non-loan account mounts the time-series chart and no loan chart" do+ render_inline(UI::Account::Chart.new(account: @account, view: "balance"))++ assert_no_selector "[data-controller='loan-payoff-chart']"+ end++ # The balance a loan's chart plots is what is still owed, and the title says+ # so without "principal". Only the loan chart: a loan without a schedule+ # keeps the title every loan had.+ test "a loan account's chart is titled remaining balance only when it has the loan chart" 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"++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: payload))+ assert_selector "p", exact_text: "Remaining balance"++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: nil))+ assert_selector "p", exact_text: "Remaining principal balance"+ end++ test "a loan without a chart payload falls back to the chart every account has" do+ loan_account = accounts(:loan)++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: nil))++ assert_no_selector "[data-controller='loan-payoff-chart']"+ assert_selector "[data-controller='time-series-chart']", count: 1+ end++ # Degradation matrix: the legend promises only the lines+ # the payload says are drawn. Under a period that ends today the forward+ # lines have no room, and a legend entry for a line that is not there is a+ # chart lying about itself.+ test "the legend lists only the series the payload marks visible" 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"+ windowed = payload.merge(visible: %w[actual scheduled])++ render_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+ assert_selector legend, text: payload[:labels][:actual]+ assert_selector legend, text: payload[:labels][:scheduled]+ assert_no_selector legend, text: payload[:labels][:projected]+ end++ # A projection that ran but never clears the balance has a line and no+ # payoff date. The cards would quote a date that does not exist; the notice+ # says why there is none instead.+ test "a projection with no payoff date shows the not-converged notice in place of the cards" 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"+ assert payload[:projected].any?, "the fixture loan must project, or this asserts nothing"+ stalled = payload.merge(projected_payoff_date: nil, months_saved: nil, interest_saved: nil, balloon: 12_345.67)++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: stalled))++ # The notice quotes the balloon, so the page says how far behind rather+ # than only that it is.+ assert_text I18n.t("UI.account.chart.loan.not_converged", balloon: Money.new(12_345.67, "USD").format)+ # The card title; the accessible description also says "projected payoff",+ # and must, so the text alone would not tell the two apart.+ assert_no_selector "h4", text: I18n.t("UI.account.chart.loan.projected_payoff")+ assert_selector "[data-controller='loan-payoff-chart']"+ end++ # The cards compare today's recorded balance with the schedule's balance on+ # the same day, and a payment posted before its scheduled date reads as+ # ahead until that date. The basis is stated beside the figures it governs.+ test "the projection cards state the basis of their comparison" 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"+ assert_not_nil payload[:projected_payoff_date], "the fixture loan must project a payoff, or this asserts nothing"++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: payload))++ assert_text I18n.t("UI.account.chart.loan.projection_basis")+ end++ # jjmata on we-promise/sure#3474: the trend, its comparison label and the+ # chart mount all read the series. It is built once per render, not once per+ # reader.+ test "the card builds its balance series once per render" do+ loan_account = accounts(:loan)+ series = loan_account.balance_series(period: Period.last_30_days, view: "balance")+ loan_account.expects(:balance_series).once.returns(series)++ render_inline(UI::Account::Chart.new(account: loan_account))+ end++ # A loan's picker offers a subset of the shared periods, under their own+ # labels, so a pick stays the user's default everywhere and means the same+ # dates it does on every other chart. A saved period the loan chart does not+ # offer reads as All.+ test "a loan's period picker offers a subset of the shared periods" 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"++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: payload, period: Period.from_key("last_5_years")))++ %w[current_month last_90_days current_year last_365_days last_5_years last_10_years all_time].each do |key|+ # The label's own span: the link also holds the menu's check-mark slot.+ assert_selector "a[href*='period=#{key}'] span", exact_text: Period.from_key(key).label_short, visible: :all+ end+ assert_no_selector "a[href*='period=last_30_days']", visible: :all+ assert_selector "button", text: "5Y"++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: payload, period: Period.from_key("last_30_days")))+ assert_selector "button", text: "All"+ end++ test "a loan's change line compares with the original loan amount" 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"++ render_inline(UI::Account::Chart.new(account: loan_account, loan_chart: payload, period: Period.from_key("last_5_years")))++ assert_text I18n.t("UI.account.chart.loan.since_start")+ assert_no_text Period.from_key("last_5_years").comparison_label+ end+test "scopes all_time period to account history_start_date when history postdates family oldest entry date" doaccount_opening = 60.days.ago.to_date@account.stubs(:history_start_date).returns(account_opening)diff --git a/test/components/UI/period_picker_test.rb b/test/components/UI/period_picker_test.rbindex fe0dee217f..e3ec67bb3a 100644--- a/test/components/UI/period_picker_test.rb+++ b/test/components/UI/period_picker_test.rb@@ -125,4 +125,43 @@ class UI::PeriodPickerTest < ViewComponent::TestCase# and stays reachable with Back — the drag-select that set it advanced too.assert_equal "advance", links.first["data-turbo-action"]end++ # The loan chart offers its own timescales under the shared period keys.+ LOAN_OPTIONS = [ [ "current_month", "M" ], [ "last_5_years", "5Y" ], [ "all_time", "All" ] ].freeze++ test "options narrow the menu to their pairs, labelled from the options" do+ render_inline(UI::PeriodPicker.new(selected: "last_5_years", url: "/accounts/abc", options: LOAN_OPTIONS))++ links = page.all("a[role='menuitemradio']")+ assert_equal LOAN_OPTIONS.size, links.size+ LOAN_OPTIONS.zip(links).each do |(key, label), link|+ assert_match(/period=#{key}/, link[:href])+ assert_equal label, link.text.strip+ end+ assert_no_selector "a[href*='period=last_30_days']"++ checked = page.all("a[role='menuitemradio'][aria-checked='true']")+ assert_equal 1, checked.size+ assert_equal "replace", checked.first["data-turbo-action"]+ assert_selector "a[role='menuitemradio'][aria-checked='false'][data-turbo-action='advance']", count: LOAN_OPTIONS.size - 1+ end++ test "with options the trigger shows the option's label for the selected key" do+ # A label no Period uses, so the assertion cannot pass on Period's own label.+ options = [ [ "last_5_years", "Five years" ], [ "all_time", "Whole life" ] ]+ assert_not_equal "Five years", Period.from_key("last_5_years").label_short++ render_inline(UI::PeriodPicker.new(selected: "last_5_years", url: "/", options: options))++ assert_selector "button[aria-label='Time period: Five years']"+ end++ test "options leave out the custom range row" do+ custom_period = Period.custom(start_date: 15.days.ago.to_date, end_date: Date.current)++ render_inline(UI::PeriodPicker.new(selected: custom_period, url: "/", options: LOAN_OPTIONS))++ assert_equal LOAN_OPTIONS.size, page.all("a[role='menuitemradio']").size+ assert_no_selector "a[href*='start_date=']"+ endenddiff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex 3f53fb3c3a..8636c5e3be 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -423,6 +423,20 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_select "p", text: I18n.t("UI.account.chart.title.total_gains")end+ # The chart and the Schedule tab's forecast card read one projection. The+ # chart used to build one and the Schedule partial a second, for the same+ # date, on every render of a loan's page.+ test "a loan account page builds its payoff projection once for the chart and the Schedule tab" do+ loan_account = accounts(:loan)+ projection = loan_account.loan.payoff_projection(as_of: Date.current)+ Loan.any_instance.expects(:payoff_projection).once.returns(projection)++ get account_url(loan_account)++ assert_response :success+ assert_includes response.body, I18n.t("loans.tabs.schedule.forecasted_payoff_date")+ end+test "remembers selected per_page across account navigation" doother_account = accounts(:credit_card)diff --git a/test/controllers/loans_controller_test.rb b/test/controllers/loans_controller_test.rbindex 9c72aabc49..96ac1c4e0b 100644--- a/test/controllers/loans_controller_test.rb+++ b/test/controllers/loans_controller_test.rb@@ -140,7 +140,7 @@ class LoansControllerTest < ActionDispatch::IntegrationTest@account.loan.update!(rate_type: "variable", interest_rate: 6, term_months: 24)get account_path(@account, tab: "schedule")- flat_body = response.body+ flat_payments = schedule_table_cells# A year into the 24-month term, whatever today is. The fixture loan has no# start_date, so its origination moves with the clock; a fixed date would@@ -151,8 +151,11 @@ class LoansControllerTest < ActionDispatch::IntegrationTestget account_path(@account, tab: "schedule")assert_response :success- assert_not_equal flat_body, response.body,- "recording a rate change must change what the schedule tab renders"+ # The schedule's own cells, not the whole body: the chart card above the+ # tabs moves for the same change.+ assert_equal flat_payments.length, schedule_table_cells.length+ assert_not_equal flat_payments, schedule_table_cells,+ "recording a rate change must change the payments the schedule tab renders"# A substring free of characters ERB escapes -- the full string contains an# apostrophe and renders as '.assert_match "re-amortises at each recorded change", response.body@@ -227,6 +230,70 @@ class LoansControllerTest < ActionDispatch::IntegrationTestassert_empty @account.loan.reload.variable_rate_scheduleend+ # Reads the payload off the mounted controller's own data attribute rather+ # than parsing rendered SVG paths, which would be a brittle way to assert on+ # data that already has model-level coverage. This test's job is to prove the+ # right payload reaches the browser and mounts the controller.+ def chart_payload+ node = css_select("[data-controller='loan-payoff-chart']").first+ node && JSON.parse(node["data-loan-payoff-chart-data-value"])+ end++ # The chart lives at the top of the account page, inside the chart+ # card's Turbo frame, on whichever tab is open. The Schedule tab keeps its+ # table and cards and no longer carries a chart of its own.+ test "the account page mounts the loan balance chart with its three series" do+ # All three lines need somewhere to be: a period that reaches past today+ # for the forecasts, and a recorded history for the actual line. The+ # earlier intersection assertion here passed with `visible` empty.+ origination = Date.current.prev_year+ @account.loan.update!(start_date: origination)+ @account.balances.create!(date: origination, balance: 500_000, currency: "USD",+ start_cash_balance: 500_000, flows_factor: -1)+ @account.balances.create!(date: Date.current, balance: 490_000, currency: "USD",+ start_cash_balance: 490_000, flows_factor: -1)++ get account_path(@account, period: "all_time")++ assert_response :success+ payload = chart_payload+ assert payload["scheduled"].length > 1+ assert payload["projected"].length > 1+ assert_equal %w[actual projected scheduled], payload.fetch("visible").sort+ assert_select "turbo-frame##{ActionView::RecordIdentifier.dom_id(@account, :chart_details)} [data-controller='loan-payoff-chart']", count: 1+ # Owner review of #3474: the chart card carries no data table; the Schedule+ # tab has the figures.+ assert_select "turbo-frame##{ActionView::RecordIdentifier.dom_id(@account, :chart_details)} table", count: 0+ end++ test "the schedule tab renders its table without a chart of its own" do+ get account_path(@account, tab: "schedule")++ assert_response :success+ assert_select "[data-controller='loan-payoff-chart']", { count: 1 }, "one chart on the page, in the chart card"+ assert_select "table", { count: 1 }, "the Schedule tab's table is the only one: the chart has no data table"+ end++ # A stray what-if parameter from an old link must change nothing: the+ # feature is not in this tranche (#100 decision 10).+ test "an extra-payment parameter is ignored" do+ get account_path(@account)+ baseline = chart_payload+ get account_path(@account, extra_payment: { amount: "2000", frequency: "monthly" })++ assert_response :success+ assert_equal baseline, chart_payload+ end++ test "a loan with no schedule renders the page without a loan chart" do+ @account.loan.update!(rate_type: "")++ get account_path(@account)++ assert_response :success+ assert_nil chart_payload+ assert_select "[data-controller='time-series-chart']", count: 1+ end# The validation lives on Loan and is reached through nested attributes, which# validate the nested record only when it has changes. Resubmitting the stored# rows plus a typo'd one leaves the column equal to its stored value, so@@ -302,6 +369,21 @@ class LoansControllerTest < ActionDispatch::IntegrationTestassert_select "[data-loan-rate-changes-target=section] input[name='account[accountable_attributes][rate_changes][]']:not([disabled])", count: 1end+ # The payload runs the schedule, the projection and a balance query on every+ # loan page view, from provider-written and user-written inputs. A raise in+ # any of them must cost the chart, not the page: before this guard the whole+ # account page was a 500 for a loan that rendered fine without the chart.+ test "a chart payload that raises degrades to the time-series chart instead of a 500" do+ Loan::PayoffChart.any_instance.stubs(:payload).raises(ArgumentError, "boom")++ get account_path(@account, tab: "schedule")++ assert_response :success+ assert_select "[data-controller='time-series-chart']", count: 1+ assert_select "[data-controller='loan-payoff-chart']", count: 0+ assert_match "Total Interest", response.body, "the Schedule tab still renders"+ end+# Owner review of #3474: the rate changes open from a collapsed disclosure,# as Additional details does, and the loan's fields keep the form's spacing# instead of stacking flush against each other.@@ -393,6 +475,37 @@ class LoansControllerTest < ActionDispatch::IntegrationTestassert_match "2,997.75", response.bodyend+ # The period picker re-renders the chart card's frame, and+ # the cards and the mount must both live inside it.+ test "a chart_details frame request carries the mount and both cards inside the frame" do+ frame_id = ActionView::RecordIdentifier.dom_id(@account, :chart_details)++ get account_path(@account, period: "all_time"), headers: { "Turbo-Frame" => frame_id }++ assert_response :success+ assert_select "turbo-frame##{frame_id} [data-controller='loan-payoff-chart']", count: 1+ assert_select "turbo-frame##{frame_id} h4", text: I18n.t("UI.account.chart.loan.projected_payoff"), count: 1+ assert_select "turbo-frame##{frame_id} h4", text: I18n.t("UI.account.chart.loan.interest_saved"), count: 1+ end++ # The activity feed paginates through its own `entries` frame. That request+ # renders the whole page and keeps one frame, so building the chart payload+ # for it ran a full simulation per page turn for nothing.+ test "a frame request outside the chart card does not build the chart payload" do+ Loan::PayoffChart.any_instance.expects(:payload).never++ get account_path(@account, page: 2), headers: { "Turbo-Frame" => ActionView::RecordIdentifier.dom_id(@account, "entries") }++ assert_response :success+ end++ test "the account's container frame request still builds the chart payload" do+ get account_path(@account, period: "all_time"), headers: { "Turbo-Frame" => ActionView::RecordIdentifier.dom_id(@account, :container) }++ assert_response :success+ assert_select "[data-controller='loan-payoff-chart']", count: 1+ end+# Owner review of #3474: the Overview cards name the amounts as the loan# amount rather than "principal".test "the overview tab names the original and remaining loan amounts" do@@ -423,6 +536,45 @@ class LoansControllerTest < ActionDispatch::IntegrationTestassert_select "h4", text: "Payoff Date", count: 0end+ # Beside the contract's figures, the Schedule tab says+ # when the loan will actually be paid off -- the projection from today's+ # balance that the chart above it draws.+ test "the schedule tab forecasts the payoff date from today's balance" do+ draw_down_loan_two_years_ago+ schedule = @account.loan.amortization_schedule+ scheduled_today = schedule.payments.select { |payment| payment.date <= Date.current }.last+ assert scheduled_today, "the fixture loan must be part-way through its schedule"+ @account.update!(balance: scheduled_today.ending_balance.amount / 2)++ forecast = @account.loan.reload.payoff_projection(as_of: Date.current).payoff_date+ assert forecast, "a loan ahead of schedule has a forecast payoff date"+ assert_operator forecast, :<, schedule.payoff_date,+ "the fixture must be ahead, or this cannot tell the forecast from the original date"++ get account_path(@account, tab: "schedule")++ assert_response :success+ card = css_select("h4").find { |title| title.text.strip == "Forecasted Payoff Date" }&.parent+ assert card, "the schedule tab has a forecasted payoff date card"+ assert_equal I18n.l(forecast, format: :long), card.at_css("p").text.strip+ assert card.parent.css("h4").any? { |title| title.text.strip == "Total Interest" },+ "the card sits among the Schedule cards"+ end++ test "the forecasted payoff date card says when the repayment no longer clears the loan" do+ draw_down_loan_two_years_ago+ @account.update!(balance: @account.loan.original_balance.amount * 10)+ assert_not @account.loan.reload.payoff_projection(as_of: Date.current).converged?,+ "the fixture must be too far behind to clear, or this cannot reach the notice"++ get account_path(@account, tab: "schedule")++ assert_response :success+ card = css_select("h4").find { |title| title.text.strip == "Forecasted Payoff Date" }&.parent+ assert card, "the schedule tab has a forecasted payoff date card"+ assert_equal "Not paid off on the current repayment", card.at_css("p").text.strip+ end+# Codex on we-promise/sure#3473: `update` persisted the balance change (a# valuation and the account's cached balance) before the loan's validation# ran, so a rejected form had committed half of itself.@@ -572,5 +724,26 @@ class LoansControllerTest < ActionDispatch::IntegrationTestassert_response :unprocessable_entityassert_select "form[action='#{loans_path}']", count: 1+ # Rebuilt from the submission, not a blank account: what was typed comes+ # back for correction.end++ private+ # The payment cells of the Schedule tab's table, the only table on the page.+ def schedule_table_cells+ css_select("table tbody td").map { |cell| cell.text.strip }+ end++ # The fixture loan starts today with no opening valuation. Drawn down two+ # years ago, it has payments behind it; with the valuation the account form+ # records, its principal stays the amount borrowed when a test then moves+ # the balance -- without one the schedule would amortise the new balance.+ def draw_down_loan_two_years_ago+ start_date = Date.current - 2.years+ @account.loan.update!(start_date: start_date)+ @account.entries.create!(+ date: start_date, name: "Opening balance", amount: @account.balance, currency: @account.currency,+ entryable: Valuation.new(kind: "opening_anchor")+ )+ endenddiff --git a/test/i18n_test.rb b/test/i18n_test.rbindex 9e0d590b63..6af763896e 100644--- a/test/i18n_test.rb+++ b/test/i18n_test.rb@@ -26,6 +26,21 @@ class I18nTest < ActiveSupport::TestCaseendend+ # The loan chart's labels, cards, table and accessible description all read+ # this subtree. Fallbacks would show a German user English rather than a raw+ # key, but the rest of UI.account.chart is translated, so a missing subtree+ # is a gap and not a choice. Placeholders are compared too: a translation+ # that drops %{projected_payoff_date} silently loses the figure it names.+ def test_german_loan_chart_keys_and_placeholders_match_english+ en = loan_chart_leaves("en")+ de = loan_chart_leaves("de")++ assert_equal en.keys.sort, de.keys.sort, "UI.account.chart.loan in de.yml must carry every key en.yml does"+ en.each do |key, value|+ assert_equal value.scan(/%\{\w+\}/).sort, de.fetch(key).to_s.scan(/%\{\w+\}/).sort, "placeholders differ for #{key}"+ end+ end+def test_no_missing_keysskip "Skipping missing keys test"missing_keys = @i18n.missing_keys(locales: [ :en ])@@ -97,6 +112,20 @@ class I18nTest < ActiveSupport::TestCaseendprivate+ # { "months_saved.one" => "...", ... } for UI.account.chart.loan in one locale.+ def loan_chart_leaves(locale)+ tree = YAML.load_file(Pathname.pwd.join("config/locales/views/components/#{locale}.yml"), aliases: true)+ .dig(locale, "UI", "account", "chart", "loan") || {}+ flatten_leaves(tree)+ end++ def flatten_leaves(tree, prefix = nil)+ tree.each_with_object({}) do |(key, value), leaves|+ path = [ prefix, key ].compact.join(".")+ value.is_a?(Hash) ? leaves.merge!(flatten_leaves(value, path)) : leaves[path] = value+ end+ end+def german_locale_paths@german_locale_paths ||= locale_paths.select { |path| path.basename.to_s.match?(/(^|[._-])de\.yml\z/) }enddiff --git a/test/models/demo/generator_test.rb b/test/models/demo/generator_test.rbindex 79e5a899a5..fdf7ca90dc 100644--- a/test/models/demo/generator_test.rb+++ b/test/models/demo/generator_test.rb@@ -137,6 +137,36 @@ class Demo::GeneratorTest < ActiveSupport::TestCase"the interest booked must be the schedule's interest, not a flat figure"end+ # What the chart says about the demo loans follows+ # from their balances. The mortgage and the car loan sit on their schedules,+ # so each pays off on time; the student loan is ahead by its extra payment,+ # so it pays off early. None of them is quoted early while it is not ahead.+ test "demo loans project payoffs that match their balances" do+ @family.update!(currency: "USD")+ generator = Demo::Generator.new(seed: 42)+ generator.send(:create_realistic_categories!, @family)+ generator.send(:create_realistic_accounts!, @family)+ generator.send(:generate_housing_transactions!)+ generator.send(:generate_transportation_transactions!)+ generator.send(:generate_major_purchases!)+ generator.send(:generate_loan_payments!)+ today = Date.current++ projections = [ "Home Mortgage", "Car Loan", "Student Loan" ].to_h do |name|+ account = @family.accounts.find_by!(name: name)+ Sync.create!(syncable: account).perform+ [ name, account.reload.loan.payoff_projection(as_of: today) ]+ end++ [ "Home Mortgage", "Car Loan" ].each do |name|+ assert projections[name].converged?, "#{name} is on schedule, so its projection must clear the balance"+ assert_equal 0, projections[name].months_saved, "#{name} is on schedule, so it must pay off on time"+ end+ assert projections["Student Loan"].converged?, "the student loan's projection must clear the balance"+ assert_operator projections["Student Loan"].months_saved, :>, 0,+ "the extra payment must bring the student loan's payoff forward"+ end+private# Exercise the actual account/transaction orchestration without generating# years of unrelated spending, securities, budgets and goals in each test.diff --git a/test/models/loan/payoff_chart_test.rb b/test/models/loan/payoff_chart_test.rbnew file mode 100644index 0000000000..beba4f0293--- /dev/null+++ b/test/models/loan/payoff_chart_test.rb@@ -0,0 +1,454 @@+require "test_helper"++class Loan::PayoffChartTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @today = Date.new(2027, 1, 15)+ # What the picker hands over for "All" on @today. The real all-time period+ # ends on Date.current, and these tests sit on a pinned date.+ @all_time = Period.new(key: "all_time", start_date: Date.new(2020, 1, 1), end_date: @today)+ end++ test "carries the recorded balance, the original schedule and the projection" do+ loan = on_contract_loan+ payload = Loan::PayoffChart.new(loan, as_of: @today).payload++ assert payload[:actual].length > 1+ assert payload[:scheduled].length > 1+ assert payload[:projected].length > 1+ assert_equal %w[actual scheduled projected], payload[:visible].map(&:to_s)+ assert_equal @today.iso8601, payload[:today]+ assert_equal "USD", payload[:currency]+ assert_not payload.key?(:accelerated), "the what-if left this tranche (#100 decision 10)"+ end++ # The amount borrowed is the first thing a payoff chart should show, and+ # every point after it is the schedule's own row for that date.+ test "the scheduled series is the schedule, opening at origination with the full principal" do+ loan = on_contract_loan+ payload = Loan::PayoffChart.new(loan, as_of: @today).payload+ rows = loan.amortization_schedule.payments.index_by { |row| row.date.iso8601 }++ assert_equal loan.origination_date.iso8601, payload[:scheduled].first[:date]+ assert_equal loan.amortization_schedule.principal.to_f, payload[:scheduled].first[:balance]+ payload[:scheduled].drop(1).each do |point|+ assert_equal rows.fetch(point[:date]).ending_balance.amount.to_f, point[:balance],+ "the scheduled point on #{point[:date]} must be the schedule's own row"+ end+ assert_equal loan.amortization_schedule.payoff_date.iso8601, payload[:scheduled].last[:date]+ end++ test "the projection opens at today's real balance" do+ loan = on_contract_loan+ payload = Loan::PayoffChart.new(loan, as_of: @today).payload++ assert_equal @today.iso8601, payload[:projected].first[:date]+ assert_equal loan.account.balance.to_f, payload[:projected].first[:balance]+ end++ # A period picked on a loan's chart means what it means on every other+ # chart: 90D is the last ninety days.+ # The recorded series runs from the window's start to today, and never before+ # origination. Queried past today it would carry today's balance forward as+ # a flat line.+ test "the actual series runs from the window's start to today, in the loan's currency" do+ loan = on_contract_loan++ whole_life = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time).payload+ assert_equal @today.iso8601, whole_life[:actual].last[:date]+ assert_operator Date.iso8601(whole_life[:actual].first[:date]), :>=, loan.origination_date++ window_start = @today - 90+ ninety_days = Period.new(key: "last_90_days", start_date: window_start, end_date: @today)+ clipped = Loan::PayoffChart.new(loan, as_of: @today, period: ninety_days).payload+ assert_equal window_start.iso8601, clipped[:actual].first[:date]+ assert_equal @today.iso8601, clipped[:actual].last[:date]+ assert clipped[:actual].all? { |point| Date.iso8601(point[:date]).between?(window_start, @today) }++ assert_equal "USD", clipped[:currency]+ assert_equal loan.account.balance.to_f, whole_life[:actual].last[:balance],+ "the recorded balance is read in the loan's own currency, so no exchange rate applies"+ end++ # Under All the domain is the loan's whole life. Under a window it is the+ # period's own dates, opening no earlier than the loan: a 5Y window on a+ # one-year-old loan opens at origination.+ test "the domain is the whole life under All and the picked period otherwise, clamped at origination" do+ loan = on_contract_loan+ start = loan.origination_date+ whole_life_end = [ loan.amortization_schedule.payoff_date, loan.payoff_projection(as_of: @today).payoff_date ].max++ whole_life = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time).payload+ assert_equal start.iso8601, whole_life[:domain_start]+ assert_equal whole_life_end.iso8601, whole_life[:domain_end]++ window_starts.each do |key, window_start|+ period = Period.new(key: key, start_date: window_start, end_date: @today)+ windowed = Loan::PayoffChart.new(loan, as_of: @today, period: period).payload+ expected_start = [ window_start, start ].max+ assert_equal expected_start.iso8601, windowed[:domain_start], "#{key} must open on #{expected_start}"+ assert_equal @today.iso8601, windowed[:domain_end], "#{key} must end today, where the period does"+ end+ end++ # A window ends today, so the projection has at most one point inside the+ # domain -- today -- and a point is not a line. The legend must not promise+ # one; All reaches past today and draws it.+ test "forward series are visible under All alone" do+ loan = on_contract_loan++ window_starts.each do |key, window_start|+ period = Period.new(key: key, start_date: window_start, end_date: @today)+ windowed = Loan::PayoffChart.new(loan, as_of: @today, period: period).payload+ assert_equal %w[actual scheduled], windowed[:visible].map(&:to_s), key+ assert windowed[:projected].length > 1, "the series is still in the payload; only its legend entry is withheld"+ end++ whole_life = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time).payload+ assert_includes whole_life[:visible].map(&:to_s), "projected"+ end++ # A loan drawn down years before the app+ # tracked it -- a 2016 mortgage added in 2024 -- must draw its recorded+ # balance under every period it offers, not the contract alone. Windows that+ # counted forward from origination ended before the history began.+ test "an older loan whose history starts after origination draws recorded balances under every window" do+ loan = older_loan+ first_recorded = Date.new(2024, 1, 1)++ window_starts.each do |key, window_start|+ period = Period.new(key: key, start_date: window_start, end_date: @today)+ payload = Loan::PayoffChart.new(loan, as_of: @today, period: period).payload++ assert_equal [ window_start, loan.origination_date ].max.iso8601, payload[:domain_start], key+ assert_equal @today.iso8601, payload[:domain_end], key+ assert_equal [ window_start, first_recorded ].max.iso8601, payload[:actual].first[:date],+ "#{key}: the recorded series starts where the window or the history does, whichever is later"+ assert_equal @today.iso8601, payload[:actual].last[:date], key+ assert_equal %w[actual scheduled], payload[:visible].map(&:to_s), "#{key}: both the recorded balance and the contract draw a line"+ end++ whole_life = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time).payload+ assert_equal loan.origination_date.iso8601, whole_life[:domain_start]+ assert_equal first_recorded.iso8601, whole_life[:actual].first[:date]+ assert_equal %w[actual scheduled projected], whole_life[:visible].map(&:to_s)+ end++ # The picker's choice is shared with every account, so a loan page can be+ # opened under a period its chart does not offer. That shows the whole life.+ test "a saved period the loan chart does not offer shows the loan's whole life" do+ loan = on_contract_loan+ whole_life = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time).payload++ %w[last_7_days last_30_days current_week last_month].each do |key|+ period = Period.new(key: key, start_date: @today - 30, end_date: @today)+ payload = Loan::PayoffChart.new(loan, as_of: @today, period: period).payload+ assert_equal whole_life.values_at(:domain_start, :domain_end), payload.values_at(:domain_start, :domain_end),+ "#{key} is not a loan window, so the chart shows the whole life"+ end+ end++ # WINDOW_KEYS is matched against the saved Period key. A key that is not a+ # real Period key would never match, and that window would silently show the+ # whole life instead.+ test "every loan window is a shared period key" do+ assert_empty Loan::PayoffChart::WINDOW_KEYS - Period::PERIODS.keys,+ "loan chart windows must use Period::PERIODS keys"+ end++ # Overlapping the schedule IS the on-track picture; the projection is not+ # withheld for agreeing with the contract.+ test "the projection is drawn when it overlaps the schedule and withheld only when it cannot run" do+ on_track = Loan::PayoffChart.new(on_contract_loan, as_of: @today).payload+ assert on_track[:projected].length > 1+ assert_includes on_track[:visible].map(&:to_s), "projected"++ cleared = build_loan+ cleared.account.update!(balance: 0)+ paid_off = Loan::PayoffChart.new(cleared.reload, as_of: @today).payload+ assert_empty paid_off[:projected]+ assert_not_includes paid_off[:visible].map(&:to_s), "projected"+ end++ # A loan drawn down today has one recorded point at most and no history to+ # compare against; the page must still render.+ test "a loan originated today renders a valid payload with no exception" do+ # Created on the pinned day itself: an origination date may not lie in the+ # future, and @today is ahead of the calendar.+ account = travel_to(@today) do+ Account.create!(+ family: @family, name: "New Loan", balance: 500_000, currency: "USD",+ accountable: Loan.new(subtype: "mortgage", interest_rate: 6, term_months: 24,+ rate_type: "fixed", start_date: @today)+ )+ 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[:scheduled].first[:date]+ assert_equal @today.iso8601, payload[:domain_start]+ assert_operator payload[:actual].length, :<=, 1+ assert_not_includes payload[:visible].map(&:to_s), "actual", "one point is not a line"+ assert_includes payload[:visible].map(&:to_s), "projected"+ end++ test "no payload at all for a loan with no schedule" do+ loan = build_loan(rate_type: "")++ assert_nil Loan::PayoffChart.new(loan, as_of: @today).payload+ end++ test "a loan with no recorded balances yet draws no actual series and does not raise" do+ loan = build_loan+ loan.account.balances.delete_all++ payload = Loan::PayoffChart.new(loan.reload, as_of: @today).payload++ assert_empty payload[:actual]+ assert payload[:scheduled].length > 1+ end++ test "the accessible description names the balance and each payoff date separately" do+ loan = on_contract_loan+ payload = Loan::PayoffChart.new(loan, as_of: @today).payload+ schedule = loan.amortization_schedule+ projection = loan.payoff_projection(as_of: @today)++ assert_includes payload[:aria_description], projection.current_balance.format+ assert_includes payload[:aria_description], I18n.l(schedule.payoff_date, format: :long)+ assert_includes payload[:aria_description], I18n.l(projection.payoff_date, format: :long)+ assert_not_includes payload[:aria_description], I18n.t(+ "UI.account.chart.loan.aria_actual_history_starts",+ date: I18n.l(loan.origination_date, format: :long)+ )+ end++ test "the accessible description dates recorded history when it starts after origination" do+ loan = on_contract_loan+ first_recorded_date = loan.origination_date >> 6+ loan.account.balances.where(date: ...first_recorded_date).delete_all++ payload = Loan::PayoffChart.new(loan.reload, as_of: @today).payload++ assert_equal first_recorded_date.iso8601, payload[:actual].first[:date]+ assert_includes payload[:aria_description], I18n.t(+ "UI.account.chart.loan.aria_actual_history_starts",+ date: I18n.l(first_recorded_date, format: :long)+ )+ end++ test "German loan chart translations cover the English chart keys" do+ english = I18n.t("UI.account.chart.loan", locale: :en)+ german = I18n.t("UI.account.chart.loan", locale: :de)++ assert_equal english.keys.sort, german.keys.sort+ end++ # The chart controller sets aria-roledescription from labels.interactive_chart+ # and falls back to English when the payload does not carry it.+ test "the payload carries a localized interactive chart role description" do+ english = Loan::PayoffChart.new(on_contract_loan, as_of: @today).payload+ assert_equal "interactive chart", english[:labels][:interactive_chart]++ german = I18n.with_locale(:de) { Loan::PayoffChart.new(on_contract_loan, as_of: @today).payload }+ assert_equal "interaktives Diagramm", german[:labels][:interactive_chart]+ end++ # A borrower too far behind has no payoff date. The description must say so+ # rather than interpolating a bare nil into a sentence.+ test "the description says so when the contract no longer pays the loan off" do+ loan = build_loan+ loan.account.update!(balance: 400_000)++ payload = Loan::PayoffChart.new(loan, as_of: @today).payload++ assert_nil payload[:projected_payoff_date]+ assert_match I18n.t("UI.account.chart.loan.no_payoff"), payload[:aria_description]+ # The balloon travels with the payload for the notice; on a loan that does+ # pay off it is nil, so a card is never quoted a figure of zero.+ assert_operator payload[:balloon], :>, 0+ assert_nil Loan::PayoffChart.new(on_contract_loan, as_of: @today).payload[:balloon]+ end++ # Owner review of #3474: the chart has no data table any more; the Schedule+ # tab carries the figures, so the payload builds no rows for one.+ test "the payload carries no data table rows" do+ payload = Loan::PayoffChart.new(on_contract_loan, as_of: @today, period: @all_time).payload++ assert_not payload.key?(:rows), "nothing renders table rows, so the payload must not build them"+ end++ # The recorded series never starts before the loan does. A balance row dated+ # before origination (an account opened, then a loan recorded against it+ # later) must not become a lead-in, whatever window is picked: a window that+ # opens before the loan is clamped at origination.+ test "the actual series never starts before origination, whatever the window" do+ loan = on_contract_loan+ loan.account.balances.create!(date: Date.new(2025, 12, 1), balance: 0, currency: "USD",+ start_cash_balance: 0, flows_factor: -1)+ five_years = Period.new(key: "last_5_years", start_date: @today - 5.years, end_date: @today)++ [ @all_time, five_years ].each do |period|+ payload = Loan::PayoffChart.new(loan.reload, as_of: @today, period: period).payload++ assert_equal loan.origination_date.iso8601, payload[:actual].first[:date],+ "the first recorded point is origination, not the pre-origination row (#{period.key})"+ assert payload[:actual].none? { |point| Date.iso8601(point[:date]) < loan.origination_date }+ end+ end++ # #100 acceptance criterion: the chart's endpoint and the card quote one date.+ test "the projected series ends on the projected payoff date" do+ loan = on_contract_loan+ payload = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time).payload++ assert_equal payload[:projected_payoff_date], payload[:projected].last[:date]+ assert_equal payload[:scheduled_payoff_date], payload[:scheduled].last[:date]+ end++ # The layout hard-codes `lang="en"`, so the chart cannot learn the locale+ # from the document; the payload carries it for the tooltip's date and+ # money formatting (Codex on we-promise/sure#3474).+ test "the payload carries the request locale for the tooltip" do+ loan = on_contract_loan++ assert_equal "en", Loan::PayoffChart.new(loan, as_of: @today).payload[:locale]+ I18n.with_locale(:de) do+ assert_equal "de", Loan::PayoffChart.new(loan, as_of: @today).payload[:locale]+ end+ end+++ # The domain was recomputed for every plotted+ # point and table row, and for a loan with no start date each computation+ # looked origination up again -- about 4,400 statements for one page under+ # All. The work a payload does must not grow with the length of the schedule.+ test "building the payload does not repeat its lookups per scheduled payment" do+ short = build_undated_loan(term_months: 24)+ long = build_undated_loan(term_months: 360)++ short_count = sql_statements { Loan::PayoffChart.new(short, as_of: @today, period: @all_time).payload }+ long_count = sql_statements { Loan::PayoffChart.new(long, as_of: @today, period: @all_time).payload }++ assert_equal short_count, long_count,+ "a 360-payment schedule ran #{long_count} statements where a 24-payment one ran #{short_count}"+ 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.+ def window_starts+ {+ "current_month" => @today.beginning_of_month,+ "last_90_days" => @today - 90,+ "current_year" => @today.beginning_of_year,+ "last_365_days" => @today - 365,+ "last_5_years" => @today - 5.years,+ "last_10_years" => @today - 10.years+ }+ end++ # Every statement, including those the query cache answers: a cached+ # lookup still builds its relation and records.+ def sql_statements(&block)+ count = 0+ counter = ->(*, payload) { count += 1 unless payload[:name] == "SCHEMA" }+ ActiveSupport::Notifications.subscribed(counter, "sql.active_record", &block)+ count+ end++ # A loan with no recorded start date, as a loan created before the field+ # existed has: origination falls back to the account's first valuation.+ def build_undated_loan(term_months:)+ account = Account.create!(+ family: @family, name: "Undated Loan #{SecureRandom.hex(4)}",+ balance: 500_000, currency: "USD",+ accountable: Loan.new(subtype: "mortgage", interest_rate: 6, term_months: term_months, rate_type: "fixed")+ )+ account.entries.create!(+ date: Date.new(2026, 1, 1), name: "Opening balance", amount: 500_000, currency: "USD",+ entryable: Valuation.new(kind: "opening_anchor")+ )+ record_balances(account)+ account.loan+ end++ def build_loan(rate_type: "fixed")+ 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,+ rate_type: rate_type, start_date: Date.new(2026, 1, 1))+ )+ # The opening valuation the account form records: Loan#original_balance+ # reads it, and without it the principal would follow whatever the+ # current balance is later set to.+ account.entries.create!(+ date: Date.new(2026, 1, 1), name: "Opening balance", amount: 500_000, currency: "USD",+ entryable: Valuation.new(kind: "opening_anchor")+ )+ record_balances(account)+ account.loan+ end++ # Loans exactly on contract at `@today`. The schedule then agrees with the+ # recorded history and the projection has somewhere to go.+ def on_contract_loan+ loan = build_loan+ scheduled = scheduled_balance_at(loan, @today)+ loan.account.update!(balance: scheduled)+ record_balances(loan.account, through: @today, closing: scheduled)+ loan.reload+ end++ # A thirty-year mortgage drawn down in 2016 and added to the app in 2024:+ # eight years of contract with no recorded balance, then history from+ # 2024 that follows the schedule, exactly on contract at `@today`.+ def older_loan+ origination = Date.new(2016, 1, 1)+ account = Account.create!(+ family: @family, name: "Old Loan #{SecureRandom.hex(4)}",+ balance: 500_000, currency: "USD",+ accountable: Loan.new(subtype: "mortgage", interest_rate: 6, term_months: 360,+ rate_type: "fixed", start_date: origination)+ )+ account.entries.create!(+ date: origination, name: "Opening balance", amount: 500_000, currency: "USD",+ entryable: Valuation.new(kind: "opening_anchor")+ )+ scheduled = scheduled_balance_at(account.loan, @today)+ account.update!(balance: scheduled)+ record_balances(account, from: Date.new(2024, 1, 1), through: @today, closing: scheduled)+ account.loan.reload+ end++ def scheduled_balance_at(loan, date)+ loan.amortization_schedule.payments.select { |p| p.date <= date }.last.ending_balance.amount+ end++ # Materialised balance rows the way the balance calculator writes them for+ # a liability: the outstanding amount in start_cash_balance with a -1 flows+ # factor, which Balance::ChartSeriesBuilder reads back as a positive debt.+ # One row a month from `from`, following the schedule's balances so the+ # recorded history is a plausible loan rather than a flat line. The row on+ # `from` carries the schedule's balance on that day, the principal before+ # the first payment.+ def record_balances(account, from: Date.new(2026, 1, 1), through: Date.new(2026, 6, 30), closing: nil)+ account.balances.delete_all+ schedule_rows = account.loan.amortization_schedule&.payments || []+ opening = schedule_rows.select { |p| p.date <= from }.last&.ending_balance&.amount || 500_000+ rows = schedule_rows.select { |p| p.date > from && p.date <= through }+ account.balances.create!(date: from, balance: opening, currency: "USD",+ start_cash_balance: opening, 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+ return if closing.nil?++ account.balances.create!(date: through, balance: closing, currency: "USD",+ start_cash_balance: closing, flows_factor: -1)+ end+enddiff --git a/test/models/loan/payoff_projection_test.rb b/test/models/loan/payoff_projection_test.rbnew file mode 100644index 0000000000..d0ced4b9e7--- /dev/null+++ b/test/models/loan/payoff_projection_test.rb@@ -0,0 +1,244 @@+require "test_helper"++class Loan::PayoffProjectionTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @today = Date.new(2027, 1, 15)+ end++ test "a loan exactly on contract projects the schedule it is already on" do+ loan = build_loan(term_months: 24)+ on_contract = scheduled_balance_at(loan, @today)+ loan.account.update!(balance: on_contract)++ projection = loan.payoff_projection(as_of: @today)++ assert projection.applicable?+ assert projection.converged?+ assert_equal loan.amortization_schedule.payoff_date, projection.payoff_date+ assert_equal 0, projection.months_saved+ end++ # Extra payments already made need no input of their own: they are why the+ # recorded balance sits below the scheduled one, and the projection starts+ # from that balance (#100, decision 10).+ test "an overpaid loan finishes early and pays less interest, with no extra-payment input" do+ loan = build_loan(term_months: 24)+ loan.account.update!(balance: scheduled_balance_at(loan, @today) - 50_000)++ projection = loan.payoff_projection(as_of: @today)++ assert projection.converged?+ assert_operator projection.months_saved, :>, 0+ assert_operator projection.interest_saved.amount, :>, 0+ assert_operator projection.payoff_date, :<, loan.amortization_schedule.payoff_date+ end++ # Decision 1 on #100. A variable loan that is ahead keeps paying what the+ # contract currently asks and therefore finishes early. Re-amortising the+ # smaller balance would shrink the repayment and land it back on the+ # original maturity, which is what this test exists to refuse.+ test "a variable loan ahead of schedule pays the contract's repayment and finishes early" do+ loan = build_loan(term_months: 24, rate_type: "variable")+ loan.update!(variable_rate_schedule: { Date.new(2026, 7, 1).iso8601 => "12.0" })+ loan.account.update!(balance: scheduled_balance_at(loan, @today) - 30_000)+ loan.reload++ projection = loan.payoff_projection(as_of: @today)+ schedule_by_date = loan.amortization_schedule.payments.index_by(&:date)++ projection.payments[0..-2].each do |payment|+ assert_equal schedule_by_date.fetch(payment[:payment_date]).payment.amount, payment[:payment_amount],+ "on #{payment[:payment_date]} the projection must pay what the contract asks, not a re-sized figure"+ end+ assert_operator projection.payoff_date, :<, loan.amortization_schedule.payoff_date+ assert_operator projection.months_saved, :>, 0+ end++ # A variable loan's CONTRACT resizes the repayment at each rate change, and+ # the projection follows the schedule's own resized figure -- not one+ # re-derived from the balance in front of it.+ test "a future recorded rate change moves the projected repayment by the schedule's amount" do+ loan = build_loan(term_months: 24, rate_type: "variable")+ change_date = @today >> 3+ loan.update!(variable_rate_schedule: { change_date.iso8601 => "18.0" })+ loan.account.update!(balance: scheduled_balance_at(loan, @today) - 20_000)+ loan.reload++ projection = loan.payoff_projection(as_of: @today)+ schedule_by_date = loan.amortization_schedule.payments.index_by(&:date)+ first_resized = projection.payments.find { |p| p[:payment_date] >= change_date }++ assert_operator first_resized[:payment_amount], :>, projection.payments.first[:payment_amount],+ "the repayment must resize when the recorded rate rises"+ assert_equal schedule_by_date.fetch(first_resized[:payment_date]).payment.amount, first_resized[:payment_amount],+ "and it resizes to the schedule's figure, not to one sized from the smaller balance"+ end++ # On a fixed loan every scheduled row carries the same repayment, so paying+ # the schedule's rows is the held contracted payment. Byte-identical to a+ # :hold run seeded with that payment, which pins that decision 1 changed+ # nothing for fixed loans.+ test "a fixed loan's projection is identical to holding the contracted payment" do+ loan = build_loan(term_months: 24)+ loan.account.update!(balance: scheduled_balance_at(loan, @today) - 10_000)+ loan.reload+ projection = loan.payoff_projection(as_of: @today)+ schedule = loan.amortization_schedule+ remaining = schedule.payments.select { |p| p.date > @today }+ resolver = Loan::RateResolver.for(loan)++ held = Loan::Simulator.new(+ starting_balance: loan.account.balance,+ accrual_start_date: @today,+ payment_schedule: remaining.map(&:date),+ accrual_rate_for: resolver.method(:accrual_rate_for),+ re_amortisation_events: resolver.method(:re_amortisation_events),+ payment_amount: remaining.first.payment.amount,+ payment_strategy: :hold,+ currency_precision: 2,+ settle_at_schedule_end: false+ ).run++ assert_equal held.payments, projection.payments+ end++ # The case that was unreachable in #103, and the reason convergence came back+ # with this change. A borrower far enough behind is not paying the loan off on+ # the contracted repayment -- and must not be shown a payoff date implying+ # otherwise.+ test "a loan too far behind to clear reports a balloon and no payoff date" do+ loan = build_loan(term_months: 24)+ loan.account.update!(balance: 400_000)++ projection = loan.payoff_projection(as_of: @today)++ assert projection.applicable?+ assert_not projection.converged?+ assert_nil projection.payoff_date+ assert_operator projection.balloon_amount.amount, :>, 0+ assert_equal 0, projection.months_saved, "no months are saved by a loan that never finishes"+ end++ # CodeRabbit on #3474: `accounts.balance` is nullable and Money.new(nil)+ # raises, and the Schedule tab reads the projection outside the chart's+ # rescue. A loan with no balance yet has nothing to project.+ test "a loan with no balance yet is not applicable rather than raising" do+ loan = build_loan(term_months: 24)+ loan.account.update_columns(balance: nil)++ projection = loan.payoff_projection(as_of: @today)++ assert_not projection.applicable?+ assert_nil projection.payoff_date+ assert_equal 0, projection.current_balance.amount+ end++ # The projection pays the contract's own repayment and never+ # settles early, so it converges only when today's balance is at or below+ # the contract's. A converged projection therefore never adds interest, which+ # is why the chart has no "additional interest" card.+ test "a loan even slightly behind does not converge, so a converged projection never adds interest" do+ loan = build_loan(term_months: 24)+ loan.account.update!(balance: scheduled_balance_at(loan, @today) + 500)++ projection = loan.payoff_projection(as_of: @today)++ assert projection.applicable?+ assert_not projection.converged?+ assert_nil projection.payoff_date+ assert_operator projection.balloon_amount.amount, :>, 0+ end++ test "is not applicable to a loan with no schedule or nothing left to owe" do+ unamortizable = build_loan(term_months: 24, rate_type: "")+ assert_not unamortizable.payoff_projection(as_of: @today).applicable?++ cleared = build_loan(term_months: 24)+ cleared.account.update!(balance: 0)+ assert_not cleared.payoff_projection(as_of: @today).applicable?++ matured = build_loan(term_months: 24)+ assert_not matured.payoff_projection(as_of: Date.new(2040, 1, 1)).applicable?+ end+++ # A variable loan's CONTRACT resizes the repayment at each rate change.+ # Holding one figure to maturity projects a repayment the lender will never+ # ask for, and the further out the change, the more wrong the payoff date.+ test "a variable projection re-amortises at a recorded rate change" do+ loan = build_loan(term_months: 24, rate_type: "variable")+ loan.update!(variable_rate_schedule: { (@today >> 3).iso8601 => "18.0" })+ loan.account.update!(balance: scheduled_balance_at(loan, @today))+ projection = loan.reload.payoff_projection(as_of: @today)++ before = projection.payments.first[:payment_amount]+ after = projection.payments.find { |p| p[:payment_date] >= (@today >> 3) }[:payment_amount]++ assert_operator after, :>, before,+ "the repayment must resize when the recorded rate rises"+ end++ # The comparison the cards quote: a balance recorded on a scheduled date,+ # equal to the schedule's balance for that date, saves nothing. The+ # projection's first period then charges exactly what the schedule's next+ # row charges, so `interest_saved` is zero, not merely small.+ test "a loan exactly on contract saves no interest" do+ loan = build_loan(term_months: 24)+ on_date = loan.amortization_schedule.payments.find { |p| p.date > @today }.date+ loan.account.update!(balance: loan.amortization_schedule.payments.find { |p| p.date == on_date }.ending_balance.amount)++ projection = loan.reload.payoff_projection(as_of: on_date)++ assert_equal 0, projection.months_saved+ assert_equal BigDecimal("0"), projection.interest_saved.amount+ end++ # Under monthly accrual a period is charged at the rate in force when it+ # OPENED (Loan::Simulator's class comment), so a change recorded between the+ # last payment and today belongs to the next period. Opening the projection's+ # first period at `as_of` instead re-rated the month already running, and a+ # variable borrower exactly on contract was quoted interest the schedule+ # never charges.+ test "a rate change between the last payment and today does not re-rate the month already running" do+ loan = build_loan(term_months: 24, rate_type: "variable")+ last_paid = loan.amortization_schedule.payments.select { |p| p.date <= @today }.last.date+ change_date = last_paid + 5+ assert_operator change_date, :<, @today, "the change must fall inside the period already running"++ loan.update!(variable_rate_schedule: { change_date.iso8601 => "12.0" })+ # Fresh records: the schedule read above is memoised without the change.+ loan.account.update!(balance: scheduled_balance_at(Loan.find(loan.id), @today))+ projection = Loan.find(loan.id).payoff_projection(as_of: @today)++ assert projection.converged?+ assert_equal 0, projection.months_saved+ assert_equal BigDecimal("0"), projection.interest_saved.amount,+ "on contract, the projection must charge the running month what the schedule charges it"+ end++ private+ # Built the way the account form builds one: with an opening valuation for+ # the amount borrowed. `Loan#original_balance` reads it; without it the+ # principal follows whatever the current balance is later set to, and a+ # schedule read after a balance update would amortise a different loan.+ def build_loan(term_months:, rate_type: "fixed", interest_rate: 6)+ account = Account.create!(+ family: @family, name: "Loan #{SecureRandom.hex(4)}",+ balance: 500_000, currency: "USD",+ accountable: Loan.new(subtype: "mortgage", interest_rate: interest_rate,+ term_months: term_months, rate_type: rate_type,+ 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.loan+ end++ def scheduled_balance_at(loan, date)+ loan.amortization_schedule.payments+ .select { |p| p.date <= date }.last.ending_balance.amount+ end+enddiff --git a/test/models/loan/simulator_test.rb b/test/models/loan/simulator_test.rbindex fc05f09815..d393edd25b 100644--- a/test/models/loan/simulator_test.rb+++ b/test/models/loan/simulator_test.rb@@ -150,6 +150,46 @@ class Loan::SimulatorTest < ActiveSupport::TestCaseassert_equal BigDecimal("24"), after[:sizing_rate]end+ # The strategy a projection uses. Asked every period, and never re-sized off+ # the balance: a borrower ahead of schedule keeps paying what the contract+ # asks and finishes early, rather than being sized back onto the maturity.+ test "scheduled asks the callable every period and keeps its answer whatever the balance" do+ asked = []+ result = Loan::Simulator.new(+ starting_balance: 12_000,+ accrual_start_date: Date.new(2026, 1, 1),+ payment_schedule: SCHEDULE,+ accrual_rate_for: ->(_date) { 6 },+ currency_precision: 2,+ payment_strategy: :scheduled,+ payment_amount: ->(index:, balance:, **) { asked << [ index, balance ]; 2_000 },+ settle_at_schedule_end: false+ ).run++ assert_operator result.payment_count, :<, SCHEDULE.length, "2,000 a month clears 12,000 well inside a year"+ assert result.converged?+ assert_equal (0...result.payment_count).to_a, asked.map(&:first), "one call per period walked, in order"+ assert_equal result.payments.first[:ending_balance], asked[1].last, "each call sees the running balance"+ result.payments[0..-2].each do |payment|+ assert_equal BigDecimal("2000"), payment[:payment_amount],+ "the callable's answer is the payment, not a level payment re-derived from the balance"+ end+ end++ test "scheduled needs a callable, and the other strategies need a number" do+ build = ->(strategy, amount) {+ Loan::Simulator.new(+ starting_balance: 12_000, accrual_start_date: Date.new(2026, 1, 1),+ payment_schedule: SCHEDULE, accrual_rate_for: ->(_date) { 6 },+ currency_precision: 2, payment_strategy: strategy, payment_amount: amount+ )+ }++ assert_raises(ArgumentError) { build.call(:scheduled, 1_000) }+ assert_raises(ArgumentError) { build.call(:hold, ->(**) { 1_000 }) }+ assert_nothing_raised { build.call(:scheduled, ->(**) { 1_000 }) }+ end+# A resized payment must stay level to maturity. The period that closes on a# rate change accrued at the OLD rate, but the annuity formula assumes every# remaining period, this one included, accrues at the new one; sized thatdiff --git a/test/system/loan_payoff_chart_test.rb b/test/system/loan_payoff_chart_test.rbnew file mode 100644index 0000000000..7438246aab--- /dev/null+++ b/test/system/loan_payoff_chart_test.rb@@ -0,0 +1,266 @@+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++ setup do+ 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 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++ # 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++ private+ 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++ # 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