Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add an Extra repayments tab for weekly, fortnightly or monthly extras (#4319)

jaysbeekayaae7b8cbf2d1
diff --git a/app/components/UI/account/chart.html.erb b/app/components/UI/account/chart.html.erb
index 7676bb89d5..a4db421551 100644
--- a/app/components/UI/account/chart.html.erb
+++ b/app/components/UI/account/chart.html.erb
@@ -32,7 +32,7 @@
<%= render UI::PeriodPicker.new(
selected: period_picker_selected,
url: account_path(account),
- extra_params: account.supports_trades? ? { chart_view: view } : {},
+ extra_params: period_picker_extra_params,
options: period_picker_options
) %>
</div>
diff --git a/app/components/UI/account/chart.rb b/app/components/UI/account/chart.rb
index 9909f48a8a..476c887b1b 100644
--- a/app/components/UI/account/chart.rb
+++ b/app/components/UI/account/chart.rb
@@ -8,12 +8,14 @@ class UI::Account::Chart < ApplicationComponent
# (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)
+ # component takes no date of its own. `extra_repayment` is the Extra
+ # repayments tab's Loan::ExtraRepayment, which the period picker keeps.
+ def initialize(account:, period: nil, view: nil, loan_chart: nil, extra_repayment: nil)
@account = account
@period = period
@view = view
@loan_chart = loan_chart
+ @extra_repayment = extra_repayment
end
def loan_chart?
@@ -31,7 +33,8 @@ class UI::Account::Chart < ApplicationComponent
LOAN_SERIES_STYLES = {
"actual" => { token: "--color-success", dashed: false },
"scheduled" => { token: "--color-destructive", dashed: true },
- "projected" => { token: "--color-success", dashed: true }
+ "projected" => { token: "--color-success", dashed: true },
+ "extra" => { token: "--color-info", dashed: true }
}.freeze
def loan_legend
@@ -204,6 +207,16 @@ class UI::Account::Chart < ApplicationComponent
Loan::PayoffChart.window_options if loan_chart?
end
+ # What each period link carries besides the period. Picking one reloads
+ # the page, which rebuilds an applied extra only from its params, so the
+ # links keep it, and the tab it was applied from.
+ def period_picker_extra_params
+ return { chart_view: view } if account.supports_trades?
+ return {} unless @extra_repayment&.applied?
+
+ { tab: "extra_repayments", extra_payment: @extra_repayment.to_params }
+ end
+
# A saved period the loan chart does not offer shows the whole life, so its
# picker reads All.
def period_picker_selected
diff --git a/app/components/UI/account_page.html.erb b/app/components/UI/account_page.html.erb
index c46114ea8d..c0b586e3dd 100644
--- a/app/components/UI/account_page.html.erb
+++ b/app/components/UI/account_page.html.erb
@@ -4,7 +4,8 @@
<%= 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, loan_chart: loan_chart) %>
+ <%= render UI::Account::Chart.new(account: account, period: chart_period, view: chart_view, loan_chart: loan_chart,
+ extra_repayment: extra_repayment) %>
<% if (fx_coverage_start = fx_coverage_start_date).present? %>
<div class="px-3">
@@ -18,9 +19,13 @@
<div data-testid="account-details">
<% if tabs.count > 1 %>
<%= render DS::Tabs.new(active_tab: active_tab, url_param_key: "tab") do |tabs_container| %>
- <% tabs_container.with_nav(classes: "max-w-fit") do |nav| %>
+ <%# As wide as its tabs and no wider than the column. A loan's five
+ tabs can outgrow the column beside the side panels; the bar then
+ scrolls on its own instead of wrapping labels or pushing the
+ page sideways. %>
+ <% tabs_container.with_nav(classes: "w-max max-w-full overflow-x-auto") do |nav| %>
<% tabs.each do |tab| %>
- <% nav.with_btn(id: tab, label: t("accounts.show.tabs.#{tab}", default: tab.to_s.humanize), classes: "px-6") %>
+ <% nav.with_btn(id: tab, label: t("accounts.show.tabs.#{tab}", default: tab.to_s.humanize), classes: "px-6 whitespace-nowrap") %>
<% end %>
<% end %>
diff --git a/app/components/UI/account_page.rb b/app/components/UI/account_page.rb
index e34eb5f569..e90e7e8c2d 100644
--- a/app/components/UI/account_page.rb
+++ b/app/components/UI/account_page.rb
@@ -9,14 +9,19 @@ class UI::AccountPage < ApplicationComponent
# `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.
+ # `extra_repayment` is the Extra repayments tab's Loan::ExtraRepayment, and
+ # `loan_extra_projection` the projection with it applied, on the same
+ # `as_of`; nil when no extra applies.
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)
+ loan_projection: nil, loan_extra_projection: nil, extra_repayment: nil)
@account = account
@chart_view = chart_view
@chart_period = chart_period
@loan_chart = loan_chart
@loan_projection = loan_projection
+ @loan_extra_projection = loan_extra_projection
+ @extra_repayment = extra_repayment
@as_of = as_of
@active_tab = active_tab
@statement_coverage = statement_coverage
@@ -56,7 +61,7 @@ class UI::AccountPage < ApplicationComponent
when "Investment", "Crypto"
[ :activity, :holdings ]
when "Loan"
- account.loan.amortizable? ? [ :activity, :overview, :schedule ] : [ :activity, :overview ]
+ account.loan.amortizable? ? [ :activity, :overview, :schedule, :extra_repayments ] : [ :activity, :overview ]
when "CreditCard"
[ :activity, :overview ]
when "Property", "Vehicle"
@@ -91,6 +96,12 @@ class UI::AccountPage < ApplicationComponent
@loan_projection ||= account.loan.payoff_projection(as_of: as_of)
end
+ # The controller's when it built one; otherwise no extra, as before anything
+ # is entered.
+ def extra_repayment
+ @extra_repayment ||= Loan::ExtraRepayment.new(amount: nil, currency: account.currency)
+ end
+
def tab_content_for(tab)
case tab
when :activity
@@ -107,6 +118,10 @@ class UI::AccountPage < ApplicationComponent
render "#{accountable_view_folder}/tabs/#{tab}", account: account
when :schedule
render "loans/tabs/schedule", account: account, as_of: as_of, projection: loan_projection
+ when :extra_repayments
+ render "loans/tabs/extra_repayments",
+ account: account, projection: loan_projection, extra_projection: @loan_extra_projection,
+ extra_repayment: extra_repayment
when :statements
render_statement_tab
end
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index f07daa3743..47e65a8542 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -111,9 +111,19 @@ class AccountsController < ApplicationController
# 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?
+ # so it is built once here and handed to both. The Extra repayments tab's
+ # projection is built on the same date, and only when there is an extra
+ # to model; the chart draws it beside the others.
+ if @account.accountable.is_a?(Loan)
+ @loan_projection = @account.loan.payoff_projection(as_of: @as_of)
+ @extra_repayment = loan_extra_repayment
+ if @extra_repayment.applied?
+ @loan_extra_projection = @account.loan.payoff_projection(as_of: @as_of, extra: @extra_repayment.amount,
+ extra_frequency: @extra_repayment.frequency)
+ end
+ end
+ @loan_chart = loan_payoff_chart(@account, as_of: @as_of, period: @period, projection: @loan_projection,
+ extra_projection: @loan_extra_projection) if chart_card_requested?
per_page = safe_per_page(stored_per_page_default)
store_per_page!(per_page) if params[:per_page].present?
@@ -379,16 +389,27 @@ class AccountsController < ApplicationController
# 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)
+ def loan_payoff_chart(account, as_of:, period:, projection: nil, extra_projection: nil)
return nil unless account.accountable.is_a?(Loan)
- Loan::PayoffChart.new(account.loan, as_of: as_of, period: period, projection: projection).payload
+ Loan::PayoffChart.new(account.loan, as_of: as_of, period: period, projection: projection,
+ extra_projection: extra_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
+ # The Extra repayments tab's form submits `extra_payment[amount]` and
+ # `extra_payment[frequency]` over GET. Params of any other shape -- a scalar
+ # for the hash, an array for either field -- are no extra rather than an
+ # error.
+ def loan_extra_repayment
+ extra_payment = params[:extra_payment]
+ permitted = extra_payment.permit(:amount, :frequency) if extra_payment.is_a?(ActionController::Parameters)
+ Loan::ExtraRepayment.new(amount: permitted&.[](:amount), frequency: permitted&.[](:frequency), currency: @account.currency)
+ 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.
diff --git a/app/javascript/controllers/loan_payoff_chart_controller.js b/app/javascript/controllers/loan_payoff_chart_controller.js
index 3062653bc3..6818119b24 100644
--- a/app/javascript/controllers/loan_payoff_chart_controller.js
+++ b/app/javascript/controllers/loan_payoff_chart_controller.js
@@ -6,12 +6,16 @@ import {
createChartTooltip,
} from "utils/chart_tooltip";
-// The loan balance chart: three series on one axis.
+// The loan balance chart: three series on one axis, and a fourth when the
+// Extra repayments tab has an amount applied.
//
// 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.
+// extra the projection with the extra amount on top of every
+// repayment. Dashed, in its own pattern. Absent from the
+// payload when no extra applies.
//
// Under the scheduled line, the area down to zero is split by each repayment's
// interest and principal SHARE: principal from the bottom, interest above it up
@@ -104,6 +108,7 @@ export default class extends Controller {
// chart on a theme change by itself; no redraw is needed for that.
const success = "var(--color-success)";
const destructive = "var(--color-destructive)";
+ const info = "var(--color-info)";
const muted = "var(--color-tertiary)";
const interestShare = "var(--color-warning)";
const principalShare = "var(--color-info)";
@@ -124,6 +129,13 @@ export default class extends Controller {
dash: "4 4",
width: 2,
},
+ {
+ key: "extra",
+ points: (data.extra || []).map(toPoint),
+ color: info,
+ dash: "10 3 2 3",
+ width: 2,
+ },
{
key: "actual",
points: (data.actual || []).map(toPoint),
diff --git a/app/models/loan.rb b/app/models/loan.rb
index 2e2cfca532..0363317c8f 100644
--- a/app/models/loan.rb
+++ b/app/models/loan.rb
@@ -474,10 +474,11 @@ class Loan < ApplicationRecord
LEVERAGE_BANDS.find { |_band, range| range.cover?(ratio) }&.first
end
- # 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)
+ # Where the loan is heading from today's balance, optionally with an extra
+ # amount paid weekly, fortnightly or with every repayment. Not memoised:
+ # each argument makes each call a different question.
+ def payoff_projection(as_of: Date.current, extra: nil, extra_frequency: "monthly")
+ PayoffProjection.new(self, as_of: as_of, extra: extra, extra_frequency: extra_frequency)
end
# The date the loan was drawn down. Recorded explicitly when the borrower
diff --git a/app/models/loan/extra_repayment.rb b/app/models/loan/extra_repayment.rb
new file mode 100644
index 0000000000..693e8c97ab
--- /dev/null
+++ b/app/models/loan/extra_repayment.rb
@@ -0,0 +1,69 @@
+class Loan
+ # The extra amount, and how often it is paid, that a borrower asks the Extra
+ # repayments tab to model, as submitted by its form.
+ #
+ # The form submits over GET, so its `min: 0` is a hint the server cannot rely
+ # on. Blank and zero mean "no extra". Anything that is not a plain,
+ # non-negative decimal is refused rather than coerced: a negative extra would
+ # shrink every repayment and manufacture a balloon, and quietly reading "abc"
+ # as zero would show the borrower a figure for something they did not ask.
+ class ExtraRepayment
+ include ActiveModel::Validations
+
+ # What a number field submits: digits, with an optional fractional part.
+ # No sign, exponent or spelled-out infinity.
+ AMOUNT_FORMAT = /\A\d+(\.\d+)?\z/
+
+ # What the form's select offers. Blank is monthly, the default.
+ FREQUENCIES = PayoffProjection::EXTRA_FREQUENCIES
+
+ attr_reader :input, :currency, :frequency
+
+ validate :amount_is_a_plain_non_negative_decimal
+ validates :frequency, inclusion: { in: FREQUENCIES, message: ->(*) { I18n.t("loans.tabs.extra_repayments.invalid_frequency") } }
+
+ def initialize(amount:, currency:, frequency: nil)
+ @input = amount.to_s.strip
+ @currency = currency
+ @frequency = frequency.presence || "monthly"
+ end
+
+ # The extra per period in the loan's currency, or nil when there is none
+ # to apply: blank, zero once taken to the currency's precision, or refused.
+ def amount
+ return nil if input.blank? || !valid?
+
+ rounded = BigDecimal(input).round(currency_precision)
+ rounded.positive? ? rounded : nil
+ end
+
+ def applied?
+ amount.present?
+ end
+
+ # The params the form submitted, for a link that reloads the page and
+ # must keep the extra: the account page rebuilds it only from these.
+ def to_params
+ { amount: input, frequency: frequency }
+ end
+
+ # What the amount field shows: the typed amount when it is a plain decimal,
+ # sign allowed, so a refused "-1" comes back as typed. nil otherwise: "abc"
+ # cannot sit in a number field, and "1e3" or "Infinity" would come back as
+ # a figure nobody typed.
+ def field_value
+ BigDecimal(input) if input.match?(/\A-?\d+(\.\d+)?\z/)
+ end
+
+ private
+ def amount_is_a_plain_non_negative_decimal
+ return if input.blank? || input.match?(AMOUNT_FORMAT)
+
+ errors.add(:amount, I18n.t("loans.tabs.extra_repayments.invalid_amount"))
+ end
+
+ def currency_precision
+ Money::Currency.new(currency).default_precision || 2
+ end
+ end
+end
diff --git a/app/models/loan/payoff_chart.rb b/app/models/loan/payoff_chart.rb
index e422b1cebc..2efc3967b4 100644
--- a/app/models/loan/payoff_chart.rb
+++ b/app/models/loan/payoff_chart.rb
@@ -10,6 +10,10 @@ class Loan
# made are in here without being named: they are why today's
# balance is what it is.
#
+ # extra the projection again, with the Extra repayments tab's extra
+ # amount on top of every repayment. Drawn only when the page
+ # was given one; without it the payload is exactly as above.
+ #
# 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
@@ -54,11 +58,14 @@ class Loan
# `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)
+ # `extra_projection`, when given, is the same loan and `as_of` with an
+ # extra amount, and adds the `extra` series.
+ def initialize(loan, as_of: Date.current, period: nil, projection: nil, extra_projection: nil)
@loan = loan
@as_of = as_of
@period = period
@projection = projection
+ @extra_projection = extra_projection
end
# nil when there is nothing to draw. The page falls back to the plain
@@ -71,6 +78,7 @@ class Loan
scheduled: scheduled_series,
projected: projection_series(projection)
}
+ series[:extra] = projection_series(extra_projection) if extra_projection
{
today: as_of.iso8601,
@@ -84,9 +92,10 @@ class Loan
domain_start: domain_start.iso8601,
domain_end: domain_end.iso8601,
**series,
- visible: SERIES.select { |key| visible?(series[key]) },
+ visible: series_keys.select { |key| visible?(series[key]) },
scheduled_payoff_date: schedule.payoff_date&.iso8601,
projected_payoff_date: projection.payoff_date&.iso8601,
+ **extra_payoff,
# 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.
@@ -102,7 +111,18 @@ class Loan
end
private
- attr_reader :loan, :as_of, :period
+ attr_reader :loan, :as_of, :period, :extra_projection
+
+ # SERIES, plus `extra` when the page was given an extra projection.
+ def series_keys
+ extra_projection ? SERIES + [ :extra ] : SERIES
+ end
+
+ # The extra line's payoff date, nil when even the extra does not clear
+ # the loan. No key at all without an extra projection.
+ def extra_payoff
+ extra_projection ? { extra_payoff_date: extra_projection.payoff_date&.iso8601 } : {}
+ end
def schedule
@schedule ||= loan.amortization_schedule
@@ -215,7 +235,7 @@ class Loan
# 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}") }
+ series_keys.index_with { |key| I18n.t("UI.account.chart.loan.#{key}") }
.merge(
# The Schedule tab's column labels, so the tooltip and the table
# name the same figures the same way.
@@ -243,6 +263,13 @@ class Loan
projected_payoff_date: long_date(projection.payoff_date, I18n.t("UI.account.chart.loan.no_payoff"))
)
+ if extra_projection
+ description = [ description, I18n.t(
+ "UI.account.chart.loan.aria_extra_payoff",
+ date: long_date(extra_projection.payoff_date, I18n.t("UI.account.chart.loan.no_payoff"))
+ ) ].join(" ")
+ end
+
actual_start_date = actual.first && Date.iso8601(actual.first[:date])
if actual_start_date && actual_start_date > domain_start
description = [ description, I18n.t(
diff --git a/app/models/loan/payoff_projection.rb b/app/models/loan/payoff_projection.rb
index c6fee05623..024265c01f 100644
--- a/app/models/loan/payoff_projection.rb
+++ b/app/models/loan/payoff_projection.rb
@@ -17,12 +17,28 @@ class Loan
#
# Extra payments the borrower has already made are in here without being
# named: they are why today's balance is what it is.
+ #
+ # `extra` is a hypothetical: an amount paid on top of the contract's
+ # repayment from here on, for the Extra repayments tab's "what if I pay
+ # more?". nil, the default, is the projection above. `extra_frequency` says
+ # how often: monthly puts one extra in every repayment period; weekly and
+ # fortnightly extras fall on their own dates (see #extra_for).
class PayoffProjection
- attr_reader :loan, :as_of
+ EXTRA_FREQUENCIES = %w[weekly fortnightly monthly].freeze
+
+ # Days between dated extras. Monthly is not dated: it rides on every
+ # repayment, as the schedule's own payments do.
+ EXTRA_INTERVAL_DAYS = { "weekly" => 7, "fortnightly" => 14 }.freeze
+
+ attr_reader :loan, :as_of, :extra, :extra_frequency
+
+ def initialize(loan, as_of: Date.current, extra: nil, extra_frequency: "monthly")
+ raise ArgumentError, "Unknown extra frequency: #{extra_frequency.inspect}" unless EXTRA_FREQUENCIES.include?(extra_frequency)
- def initialize(loan, as_of: Date.current)
@loan = loan
@as_of = as_of
+ @extra = extra.nil? ? nil : BigDecimal(extra.to_s)
+ @extra_frequency = extra_frequency
end
# False when there is nothing to project: no schedule, nothing left to owe,
@@ -38,6 +54,13 @@ class Loan
contracted_payment&.positive? || false
end
+ # True when nothing is owed. Only one of the reasons applicable? can be
+ # false: a loan past its last scheduled repayment with a balance still
+ # owing is not settled, and the Extra repayments tab says so differently.
+ def settled?
+ !current_balance.amount.positive?
+ end
+
def currency
loan.account.currency
end
@@ -89,6 +112,45 @@ class Loan
Money.new(remaining_contracted_interest - (simulation&.total_interest || 0), currency)
end
+ # What is still to repay from today: the balance plus the interest of
+ # every remaining period, which is what the payments add up to. nil for a
+ # run that never clears: a balloon would still be owed on top.
+ def total_cost
+ return nil unless converged?
+
+ current_balance + total_interest
+ end
+
+ # How much less this projection costs from today than `other`, on the same
+ # terms as #months_sooner_than. Both repay the same balance, so this is
+ # the interest saved, put as the loan's total.
+ def total_cost_saved_versus(other)
+ return nil unless converged? && other.converged?
+
+ other.total_cost - total_cost
+ end
+
+ # How much sooner this projection clears the loan than `other`, a
+ # projection of the same loan on the same `as_of`. Both walk the same
+ # remaining payment dates, so the difference in rows is the difference in
+ # months. nil unless both clear the loan: one that never does has no
+ # payoff date to be sooner than.
+ def months_sooner_than(other)
+ return nil unless converged? && other.converged?
+
+ other.payments.length - payments.length
+ end
+
+ # The interest this projection saves against `other`, on the same terms
+ # as #months_sooner_than. Measured against another projection, not the
+ # contract: #interest_saved already answers that, and folds in how far
+ # ahead or behind the loan is today.
+ def interest_saved_versus(other)
+ return nil unless converged? && other.converged?
+
+ other.total_interest - total_interest
+ end
+
private
def schedule
@schedule ||= loan.amortization_schedule
@@ -120,9 +182,37 @@ class Loan
# 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.
+ #
+ # Plus the period's extra, when there is one. The simulator settles the
+ # final period at whatever the balance needs, so an extra larger than
+ # what is left is never overpaid.
def scheduled_payment_for(index:, **)
row = remaining_scheduled_payments[index] || remaining_scheduled_payments.last
- row.payment.amount
+ row.payment.amount + extra_for(index)
+ end
+
+ # The extra paid in period `index`. Monthly: one extra, every period.
+ # Weekly and fortnightly: the extras dated inside the period, which runs
+ # from the previous payment date (exclusive) to its own (inclusive). The
+ # first extra falls the day after as_of, so the first period runs from
+ # as_of. The simulator charges interest once a period on the balance it
+ # opened with, so an extra paid mid-period starts saving from the next.
+ def extra_for(index)
+ return 0 unless extra
+ return extra unless (interval = EXTRA_INTERVAL_DAYS[extra_frequency])
+
+ opens = index.zero? ? as_of : remaining_payment_dates[index - 1]
+ closes = remaining_payment_dates[index]
+ return 0 unless closes
+
+ extra * (dated_extras_through(closes, interval) - dated_extras_through(opens, interval))
+ end
+
+ # How many dated extras fall on or before `date`: the first is the day
+ # after as_of, then one every `interval` days.
+ def dated_extras_through(date, interval)
+ first = as_of + 1
+ date < first ? 0 : ((date - first).to_i / interval) + 1
end
def remaining_contracted_interest
diff --git a/app/views/accounts/show.html.erb b/app/views/accounts/show.html.erb
index 975c618def..db5eb278ec 100644
--- a/app/views/accounts/show.html.erb
+++ b/app/views/accounts/show.html.erb
@@ -4,6 +4,8 @@
chart_period: @period,
loan_chart: @loan_chart,
loan_projection: @loan_projection,
+ loan_extra_projection: @loan_extra_projection,
+ extra_repayment: @extra_repayment,
as_of: @as_of,
active_tab: @tab,
statement_coverage: @statement_coverage,
diff --git a/app/views/loans/tabs/_extra_repayments.html.erb b/app/views/loans/tabs/_extra_repayments.html.erb
new file mode 100644
index 0000000000..ce445bf709
--- /dev/null
+++ b/app/views/loans/tabs/_extra_repayments.html.erb
@@ -0,0 +1,115 @@
+<%# locals: (account:, projection:, extra_projection:, extra_repayment:) %>
+
+<%# What paying an extra amount on top of every repayment does to the payoff
+ date and the interest. `projection` is the page's projection with no extra
+ and `extra_projection` the same loan on the same date with the extra, nil
+ when none applies. The chart above draws both, so the cards and the lines
+ quote one date. Each comparison is against paying no extra, not against
+ the contract: the Schedule tab and the chart already say how far ahead or
+ behind the loan is. %>
+<% extra_repayment.validate %>
+<% amount_invalid = extra_repayment.errors[:amount].any? %>
+<% frequency_invalid = extra_repayment.errors[:frequency].any? %>
+
+<%# @container: the cards go three across only when the tab itself has room,
+ not when the window does. With both side panels open the tab is narrow
+ on a wide screen, and three figures side by side ran past their cards. %>
+<div class="@container space-y-4">
+ <p class="text-sm text-secondary"><%= t(".intro") %></p>
+
+ <% if projection.applicable? %>
+ <%# Built as the Bills form is: the shared money field, with the loan's
+ currency shown and fixed, and a select for how often. GET, so the
+ figures below are a link that can be shared or reloaded. %>
+ <%= styled_form_with url: account_path(account), method: :get, scope: :extra_payment,
+ id: "extra_repayments_form", data: { turbo_action: "advance" }, class: "space-y-2" do |f| %>
+ <%= hidden_field_tag :tab, "extra_repayments", id: nil %>
+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ <%= f.money_field :amount,
+ label: t(".amount_label"),
+ currency_value_override: account.currency,
+ disable_currency: true,
+ value: extra_repayment.field_value,
+ placeholder: t(".amount_placeholder"),
+ min: 0,
+ input_class: "privacy-sensitive privacy-sensitive-interactive",
+ aria: { invalid: (amount_invalid ? "true" : nil),
+ describedby: (dom_id(account, :extra_amount_error) if amount_invalid) }.compact.presence %>
+ <%= f.select :frequency,
+ Loan::ExtraRepayment::FREQUENCIES.map { |frequency| [ t(".frequencies.#{frequency}"), frequency ] },
+ { label: t(".frequency_label"), selected: extra_repayment.frequency },
+ { "aria-invalid": (frequency_invalid ? "true" : nil),
+ "aria-describedby": (dom_id(account, :extra_frequency_error) if frequency_invalid) }.compact %>
+ </div>
+ <% if amount_invalid %>
+ <p id="<%= dom_id(account, :extra_amount_error) %>" class="text-xs text-destructive" data-testid="extra-amount-error"><%= extra_repayment.errors[:amount].first %></p>
+ <% end %>
+ <% if frequency_invalid %>
+ <p id="<%= dom_id(account, :extra_frequency_error) %>" class="text-xs text-destructive" data-testid="extra-frequency-error"><%= extra_repayment.errors[:frequency].first %></p>
+ <% end %>
+ <%# The design system's form actions: Apply alone is the form's
+ full-width submit; with Clear it is a right-aligned pair, Clear
+ first. %>
+ <% if extra_repayment.input.present? %>
+ <div class="flex justify-end gap-2">
+ <%= render DS::Link.new(text: t(".clear"), href: account_path(account, tab: "extra_repayments"), variant: "ghost") %>
+ <%= render DS::Button.new(text: t(".apply"), type: :submit) %>
+ </div>
+ <% else %>
+ <%= f.submit t(".apply") %>
+ <% end %>
+ <% end %>
+
+ <div class="grid grid-cols-1 @lg:grid-cols-3 gap-2" data-testid="extra-cards">
+ <% if extra_projection&.payoff_date %>
+ <%= summary_card title: t(".payoff_with_extra") do %>
+ <span data-testid="extra-payoff-date"><%= l extra_projection.payoff_date, format: :long %></span>
+ <% if (sooner = extra_projection.months_sooner_than(projection)) %>
+ <span class="block text-xs text-secondary mt-1" data-testid="extra-months-sooner"><%= t(".months_sooner", count: sooner) %></span>
+ <% end %>
+ <% end %>
+
+ <% if (saved = extra_projection.interest_saved_versus(projection)) %>
+ <%= summary_card title: t(".interest_saved") do %>
+ <span data-testid="extra-interest-saved"><%= format_money saved %></span>
+ <% end %>
+ <% end %>
+ <% end %>
+
+ <%# The total still to repay: with the extra when one applies, and the
+ saving against paying no extra beneath it. %>
+ <% costed = extra_projection || projection %>
+ <%= summary_card title: t(".total_cost") do %>
+ <% if (total = costed.total_cost) %>
+ <span class="privacy-sensitive" data-testid="total-cost"><%= format_money total %></span>
+ <% if extra_projection && (saved = extra_projection.total_cost_saved_versus(projection)) %>
+ <span class="block text-xs text-secondary mt-1 privacy-sensitive" data-testid="total-cost-saved"><%= t(".total_cost_saved", amount: format_money(saved)) %></span>
+ <% end %>
+ <% else %>
+ <%= t(".total_cost_not_cleared") %>
+ <% end %>
+ <% end %>
+ </div>
+
+ <% if extra_projection %>
+ <% if !extra_projection.converged? %>
+ <p class="text-sm text-secondary" data-testid="extra-not-cleared"><%= t(".extra_not_cleared") %></p>
+ <% elsif !projection.converged? %>
+ <p class="text-sm text-secondary privacy-sensitive" data-testid="baseline-not-cleared"><%= t(".baseline_not_cleared", balloon: format_money(projection.balloon_amount)) %></p>
+ <% else %>
+ <p class="text-xs text-secondary"><%= t(".comparison_basis") %></p>
+ <% unless extra_repayment.frequency == "monthly" %>
+ <p class="text-xs text-secondary" data-testid="extra-dated-note"><%= t(".dated_note") %></p>
+ <% end %>
+ <% end %>
+ <% end %>
+
+ <% if account.loan.variable_rate_type? %>
+ <p class="text-xs text-secondary"><%= t(".variable_rate_notice") %></p>
+ <% end %>
+ <% else %>
+ <%# Repaid, or past the last scheduled repayment with a balance still
+ owing: the second is not repaid and must not read as if it were. %>
+ <p class="text-sm text-secondary" data-testid="extra-not-applicable"><%= t(projection.settled? ? ".not_applicable" : ".no_scheduled_repayments") %></p>
+ <% end %>
+</div>
diff --git a/app/views/shared/_money_field.html.erb b/app/views/shared/_money_field.html.erb
index f8f1d9651c..5c27450bf1 100644
--- a/app/views/shared/_money_field.html.erb
+++ b/app/views/shared/_money_field.html.erb
@@ -79,6 +79,7 @@
action: [ options.dig(:amount_data, :action), "paste->money-field#pasteAmount", "blur->money-field#normalizeAmount" ].compact.join(" ")
}.compact),
required: options[:required],
+ aria: options[:aria],
**options.slice(:name) %>
</div>
diff --git a/config/locales/views/accounts/de.yml b/config/locales/views/accounts/de.yml
index 878f5214c2..e637d2b900 100644
--- a/config/locales/views/accounts/de.yml
+++ b/config/locales/views/accounts/de.yml
@@ -117,6 +117,7 @@ de:
limited_fx_history_warning: Wechselkurse liegen erst ab %{date} vor. Transaktionen davor rechnen mit Näherungswerten, was vorkommt, wenn der Kursanbieter nur einen begrenzten Verlauf liefert.
tabs:
activity: Aktivität
+ extra_repayments: Sondertilgungen
holdings: Bestände
overview: Übersicht
schedule: Tilgungsplan
diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.yml
index be1f7cf50e..aecdacf2a2 100644
--- a/config/locales/views/accounts/en.yml
+++ b/config/locales/views/accounts/en.yml
@@ -85,6 +85,7 @@ en:
limited_fx_history_warning: "Exchange rate history is only available from %{date} onwards. Transactions before this date use approximate currency conversions — this can happen when the FX provider only offers a limited historical window."
tabs:
activity: Activity
+ extra_repayments: Extra repayments
holdings: Holdings
overview: Overview
schedule: Schedule
diff --git a/config/locales/views/components/de.yml b/config/locales/views/components/de.yml
index b7e8a1777b..da4a10ca77 100644
--- a/config/locales/views/components/de.yml
+++ b/config/locales/views/components/de.yml
@@ -129,6 +129,8 @@ de:
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_extra_payoff: "Voraussichtliche Tilgung mit der Sondertilgung %{date}."
+ extra: "Mit Sondertilgung"
aria_actual_history_starts: "Die erfasste Saldenhistorie beginnt am %{date}."
aria_interest_share: "Über die Raten des ersten Jahres sind etwa %{first} % des gezahlten Betrags Zinsen, über die des letzten Jahres etwa %{last} %."
aria_interest_share_overall: "Über alle Raten sind etwa %{share} % des gezahlten Betrags Zinsen."
diff --git a/config/locales/views/components/en.yml b/config/locales/views/components/en.yml
index 61657aab54..bd98a16daf 100644
--- a/config/locales/views/components/en.yml
+++ b/config/locales/views/components/en.yml
@@ -68,6 +68,8 @@ en:
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_extra_payoff: Projected payoff with the extra repayment %{date}.
+ extra: With extra repayment
aria_actual_history_starts: Recorded balance history begins %{date}.
aria_interest_share: Across the first year's repayments about %{first}% of the amount paid is interest; across the final year's, about %{last}%.
aria_interest_share_overall: Across all the repayments about %{share}% of the amount paid is interest.
diff --git a/config/locales/views/loans/de.yml b/config/locales/views/loans/de.yml
index 9fe684d3f8..90e6d63628 100644
--- a/config/locales/views/loans/de.yml
+++ b/config/locales/views/loans/de.yml
@@ -46,6 +46,35 @@ de:
type: Typ
unknown: Unbekannt
tabs:
+ extra_repayments:
+ amount_label: Sondertilgung
+ amount_placeholder: "0,00"
+ apply: Anwenden
+ baseline_not_cleared: "Mit der aktuellen Rate ist dieser Kredit bis zum ursprünglichen Laufzeitende nicht getilgt, und %{balloon} blieben offen. Es gibt daher kein früheres Datum und keine Zinsersparnis zum Vergleich. Mit diesem Zusatzbetrag ist er zum oben genannten Datum getilgt."
+ clear: Zurücksetzen
+ comparison_basis: Verglichen mit der aktuellen Rate ohne Zusatzbetrag, ab dem heutigen Saldo.
+ dated_note: Wöchentliche und zweiwöchentliche Zusatzbeträge werden jeweils bei der nächsten Rate nach ihrer Zahlung angerechnet; die Zinsersparnis ist daher eher zu niedrig angegeben.
+ extra_not_cleared: Auch mit diesem Zusatzbetrag ist der Kredit bis zum ursprünglichen Laufzeitende nicht getilgt. Versuch es mit einem höheren Betrag.
+ frequencies:
+ fortnightly: Alle zwei Wochen
+ monthly: Monatlich
+ weekly: Wöchentlich
+ frequency_label: Wie oft
+ interest_saved: Gesparte Zinsen
+ intro: Sieh dir an, wie viel früher der Kredit getilgt ist und wie viel Zinsen du sparst, wenn du zusätzlich zu deinen Raten wöchentlich, alle zwei Wochen oder monatlich einen Zusatzbetrag zahlst.
+ invalid_amount: Gib einen Betrag von null oder mehr in Ziffern ein.
+ invalid_frequency: Wähle wöchentlich, alle zwei Wochen oder monatlich.
+ months_sooner:
+ zero: Im selben Monat getilgt
+ one: "%{count} Monat früher"
+ other: "%{count} Monate früher"
+ no_scheduled_repayments: Für diesen Kredit sind keine planmäßigen Raten mehr vorgesehen, aber es ist noch ein Saldo offen. Daher gibt es keine Rate, zu der du einen Zusatzbetrag zahlen kannst.
+ not_applicable: Auf diesen Kredit ist nichts mehr zu tilgen, daher gibt es keine Sondertilgung zu berechnen.
+ payoff_with_extra: Tilgung mit Zusatzbetrag
+ total_cost: Gesamtkosten ab heute
+ total_cost_not_cleared: Bis zum ursprünglichen Laufzeitende nicht getilgt
+ total_cost_saved: "%{amount} weniger als ohne Zusatzbetrag"
+ variable_rate_notice: Der Zinssatz dieses Kredits ändert sich. Diese Zahlen berücksichtigen die bereits erfassten Zinsänderungen; eine noch nicht erfasste Änderung verschiebt sie.
schedule:
date: Datum
description: Hochgerechnet aus ursprünglicher Kreditsumme, Zinssatz und Laufzeit, beginnend am %{start_date}. Sondertilgungen sind nicht berücksichtigt.
diff --git a/config/locales/views/loans/en.yml b/config/locales/views/loans/en.yml
index 504995c9fa..d1fc2c186b 100644
--- a/config/locales/views/loans/en.yml
+++ b/config/locales/views/loans/en.yml
@@ -53,6 +53,35 @@ en:
type: Type
unknown: Unknown
tabs:
+ extra_repayments:
+ amount_label: Extra repayment
+ amount_placeholder: "0.00"
+ apply: Apply
+ baseline_not_cleared: On the current repayment this loan is not paid off by the original maturity, and %{balloon} would still be owed, so there is no earlier date or interest saving to compare. With this extra it is paid off on the date above.
+ clear: Clear
+ comparison_basis: Compared with paying the current repayment and nothing extra, from today's balance.
+ dated_note: Weekly and fortnightly extras are counted at the next repayment after each one is paid, so the interest saved is, if anything, understated.
+ extra_not_cleared: Even with this extra, the loan is not paid off by the original maturity. Try a larger amount.
+ frequencies:
+ fortnightly: Fortnightly
+ monthly: Monthly
+ weekly: Weekly
+ frequency_label: How often
+ interest_saved: Interest saved
+ intro: See how much sooner the loan is paid off, and how much interest you save, if you pay an extra amount each week, fortnight or month on top of your repayments.
+ invalid_amount: Enter an amount of zero or more, in digits.
+ invalid_frequency: Choose weekly, fortnightly or monthly.
+ months_sooner:
+ zero: Paid off in the same month
+ one: "%{count} month sooner"
+ other: "%{count} months sooner"
+ no_scheduled_repayments: No scheduled repayments remain on this loan, but a balance is still owing, so there is no repayment to add an extra to.
+ not_applicable: There is nothing left to repay on this loan, so there is no extra repayment to model.
+ payoff_with_extra: Payoff with extra
+ total_cost: Total cost from today
+ total_cost_not_cleared: Not paid off by the original maturity
+ total_cost_saved: "%{amount} less than without the extra"
+ variable_rate_notice: This loan's rate changes over time. These figures apply the rate changes already recorded; a change that has not been recorded yet will shift them.
repayment_progress:
instalment: Payment %{number} · %{date}
insurance: Insurance
diff --git a/test/controllers/loans_controller_test.rb b/test/controllers/loans_controller_test.rb
index df974b5686..06589217c6 100644
--- a/test/controllers/loans_controller_test.rb
+++ b/test/controllers/loans_controller_test.rb
@@ -517,15 +517,28 @@ class LoansControllerTest < ActionDispatch::IntegrationTest
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
+ # The what-if left #100's tranche (decision 10) and returns as the Extra
+ # repayments tab. An extra adds its own line and moves nothing else: every
+ # other series, date and figure is what the page shows without one.
+ test "an extra-payment parameter adds the extra line and leaves the rest of the chart as it was" 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
+ with_extra = chart_payload
+ described = %w[visible labels aria_description]
+ assert_equal baseline.except(*described), with_extra.except("extra", "extra_payoff_date", *described)
+ assert_equal baseline["visible"] + [ "extra" ], with_extra["visible"]
+ assert_equal baseline["labels"].merge("extra" => I18n.t("UI.account.chart.loan.extra")), with_extra["labels"]
+ # Sentences, not the whole string: #4387 appends the interest/principal
+ # share sentence to every description and the what-if sentence lands
+ # before it, so a start_with? over the full string fails by construction.
+ # The invariant the test means: the extra repayment adds its one sentence
+ # and every baseline sentence still appears.
+ sentences = ->(d) { d.split(/(?<=\.)\s+/) }
+ assert_equal 1, (sentences.(with_extra["aria_description"]) - sentences.(baseline["aria_description"])).size
+ assert_empty sentences.(baseline["aria_description"]) - sentences.(with_extra["aria_description"])
end
test "a loan with no schedule renders the page without a loan chart" do
@@ -995,7 +1008,267 @@ class LoansControllerTest < ActionDispatch::IntegrationTest
assert_select "input[name='account[accountable_attributes][interest_rate]']", minimum: 1
end
+ test "the extra repayments tab shows for a loan that can be amortized, and not otherwise" do
+ get account_path(@account)
+ assert_select "button[role='tab'][data-id='extra_repayments']", count: 1
+
+ @account.loan.update!(rate_type: "")
+ get account_path(@account)
+ assert_select "button[role='tab'][data-id='extra_repayments']", count: 0
+ end
+
+ test "an extra amount adds the extra's cards and the chart's extra line" do
+ get account_path(@account, tab: "extra_repayments")
+
+ assert_response :success
+ assert_select "[data-testid='extra-payoff-date']", count: 0
+ # With nothing entered, the total is the loan's own, with no saving to quote.
+ no_extra = @account.loan.payoff_projection(as_of: Date.current)
+ assert_select "[data-testid='total-cost']", text: format_money(no_extra.total_cost)
+ assert_select "[data-testid='total-cost-saved']", count: 0
+ assert_not_includes chart_payload["visible"], "extra"
+
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "500" })
+
+ assert_response :success
+ loan = @account.loan.reload
+ baseline = loan.payoff_projection(as_of: Date.current)
+ extra = loan.payoff_projection(as_of: Date.current, extra: 500)
+ assert_select "[data-testid='extra-payoff-date']", text: I18n.l(extra.payoff_date, format: :long)
+ assert_select "[data-testid='extra-months-sooner']",
+ text: I18n.t("loans.tabs.extra_repayments.months_sooner", count: extra.months_sooner_than(baseline))
+ assert_select "[data-testid='extra-interest-saved']", text: format_money(extra.interest_saved_versus(baseline))
+ # The third card is the total still to repay with the extra, and how much
+ # less that is than paying no extra, over the rest of the loan.
+ assert_select "[data-testid='total-cost']", text: format_money(extra.total_cost)
+ assert_select "[data-testid='total-cost-saved']",
+ text: I18n.t("loans.tabs.extra_repayments.total_cost_saved", amount: format_money(extra.total_cost_saved_versus(baseline)))
+ assert_operator extra.total_cost, :<, baseline.total_cost
+ assert_select "[data-testid='baseline-payoff-date']", count: 0
+ assert_select "input[name='extra_payment[amount]'][value='500.00']", count: 1
+ assert_select "select[name='extra_payment[frequency]'] option[selected][value='monthly']", count: 1
+ assert_select "[data-testid='extra-dated-note']", count: 0
+ assert_includes chart_payload["visible"], "extra"
+ assert_equal extra.payoff_date.iso8601, chart_payload["extra_payoff_date"]
+ end
+
+ # One reference date for the page: the cards, the tab and the chart all read
+ # projections built on the controller's `as_of`, each built once.
+ test "the baseline and the extra projections are built once each, on the page's one date" do
+ travel_to Time.zone.local(2026, 10, 16, 23, 59, 59) do
+ as_of = Date.current
+ loan = @account.loan
+ baseline = loan.payoff_projection(as_of: as_of)
+ extra = loan.payoff_projection(as_of: as_of, extra: BigDecimal("500"))
+ Loan.any_instance.expects(:payoff_projection).with(as_of: as_of).once.returns(baseline)
+ Loan.any_instance.expects(:payoff_projection).with(as_of: as_of, extra: BigDecimal("500"), extra_frequency: "monthly").once.returns(extra)
+
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "500" })
+
+ assert_response :success
+ assert_equal extra.payoff_date.iso8601, chart_payload["extra_payoff_date"]
+ assert_select "[data-testid='extra-payoff-date']", text: I18n.l(extra.payoff_date, format: :long)
+ end
+ end
+
+ # The amount field is a number field, which can hold "-1" but not "abc": the
+ # first comes back as typed, the second as an empty field beside the message.
+ test "a refused amount shows a message and no extra, keeping what a number field can hold" do
+ { "-1" => "input[value='-1.00']", "abc" => "input:not([value])" }.each do |input, kept|
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: input })
+
+ assert_response :success
+ assert_select "[data-testid='extra-amount-error']", text: I18n.t("loans.tabs.extra_repayments.invalid_amount")
+ assert_select "#{kept}[name='extra_payment[amount]'][aria-invalid='true']", count: 1
+ assert_select "[data-testid='extra-payoff-date']", count: 0
+ assert_not_includes chart_payload["visible"], "extra"
+ end
+ end
+
+ # Weekly extras fall on their own dates, so the figures are the weekly
+ # projection's, not the monthly one's, and the tab says how a mid-period
+ # extra is counted.
+ test "a weekly extra shows the weekly projection's figures, with the choice kept" do
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "100", frequency: "weekly" })
+
+ assert_response :success
+ loan = @account.loan.reload
+ baseline = loan.payoff_projection(as_of: Date.current)
+ weekly = loan.payoff_projection(as_of: Date.current, extra: 100, extra_frequency: "weekly")
+ monthly = loan.payoff_projection(as_of: Date.current, extra: 100)
+ assert_not_equal monthly.total_interest, weekly.total_interest, "the fixture must tell weekly from monthly"
+ assert_select "[data-testid='extra-interest-saved']", text: format_money(weekly.interest_saved_versus(baseline))
+ assert_select "[data-testid='extra-payoff-date']", text: I18n.l(weekly.payoff_date, format: :long)
+ assert_select "select[name='extra_payment[frequency]'] option[selected][value='weekly']", count: 1
+ assert_select "[data-testid='extra-dated-note']", text: I18n.t("loans.tabs.extra_repayments.dated_note")
+ end
+
+ test "a frequency the form does not offer shows a message and no extra" do
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "100", frequency: "daily" })
+
+ assert_response :success
+ assert_select "[data-testid='extra-frequency-error']", text: I18n.t("loans.tabs.extra_repayments.invalid_frequency")
+ assert_select "select[name='extra_payment[frequency]'][aria-invalid='true']", count: 1
+ assert_select "[data-testid='extra-payoff-date']", count: 0
+ assert_not_includes chart_payload["visible"], "extra"
+ end
+
+ # The form is built as Sure's other forms are: the shared money field shows
+ # the loan's currency, which cannot be changed here (and so is not
+ # submitted), and how often is a select of the three choices.
+ test "the extra repayments form uses the money field and a frequency select" do
+ get account_path(@account, tab: "extra_repayments")
+
+ assert_select "form[method='get'] [data-controller='money-field']" do
+ assert_select "[data-money-field-target='symbol']", text: Money::Currency.new(@account.currency).symbol
+ assert_select "select[name='extra_payment[currency]'][disabled]", count: 1
+ end
+ assert_select "select[name='extra_payment[frequency]'] option",
+ count: 3, text: /#{%w[weekly fortnightly monthly].map { |f| I18n.t("loans.tabs.extra_repayments.frequencies.#{f}") }.join("|")}/
+ end
+
+ test "a zero or blank amount shows no extra and no message" do
+ [ "0", "" ].each do |input|
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: input })
+
+ assert_response :success
+ assert_select "[data-testid='extra-amount-error']", count: 0
+ assert_select "[data-testid='extra-payoff-date']", count: 0
+ assert_not_includes chart_payload["visible"], "extra"
+ end
+ end
+
+ # The params are the borrower's to shape. A scalar where the form sends a
+ # hash, or an array where it sends a scalar, is no extra rather than a 500.
+ test "extra repayment params of the wrong shape are ignored" do
+ get account_path(@account, tab: "extra_repayments", extra_payment: "500")
+ assert_response :success
+ assert_select "[data-testid='extra-payoff-date']", count: 0
+
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: [ "500" ] })
+ assert_response :success
+ assert_select "[data-testid='extra-payoff-date']", count: 0
+ end
+
+ # A balance the current repayment never clears has no payoff date, so there
+ # is no "months sooner" or "interest saved" to quote. The tab gives the
+ # extra's own date and says why the comparison is missing.
+ test "when only the extra clears the loan, the tab gives its date and says the repayment alone never does" do
+ draw_down_loan_two_years_ago
+ @account.update!(balance: 600_000)
+ loan = @account.loan.reload
+ baseline = loan.payoff_projection(as_of: Date.current)
+ extra = loan.payoff_projection(as_of: Date.current, extra: 5_000)
+ assert_not baseline.converged?, "the fixture must be too far behind to clear"
+ assert extra.converged?, "and the extra must clear it"
+
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "5000" })
+
+ assert_response :success
+ assert_select "[data-testid='extra-payoff-date']", text: I18n.l(extra.payoff_date, format: :long)
+ assert_select "[data-testid='extra-months-sooner']", count: 0
+ assert_select "[data-testid='extra-interest-saved']", count: 0
+ assert_select "[data-testid='baseline-not-cleared']",
+ text: I18n.t("loans.tabs.extra_repayments.baseline_not_cleared", balloon: format_money(baseline.balloon_amount))
+ end
+
+ test "an extra too small to clear the loan says so instead of quoting a date" do
+ draw_down_loan_two_years_ago
+ @account.update!(balance: 600_000)
+
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "1" })
+
+ assert_response :success
+ assert_select "[data-testid='extra-payoff-date']", count: 0
+ assert_select "[data-testid='extra-not-cleared']", text: I18n.t("loans.tabs.extra_repayments.extra_not_cleared")
+ end
+
+ # The design system's form actions: one action is the form's full-width
+ # primary submit; Clear and Apply are a right-aligned pair, Clear first as
+ # a ghost link and Apply the primary submit.
+ test "the extra repayments form ends in the design system's form actions" do
+ clear_href = account_path(@account, tab: "extra_repayments")
+ form = "form#extra_repayments_form[method='get']"
+
+ get account_path(@account, tab: "extra_repayments")
+ assert_select "#{form} button[type='submit']", count: 1 do |buttons|
+ assert_includes buttons.first["class"], "w-full", "a single action is full width"
+ assert_includes buttons.first["class"], "bg-inverse", "and primary, not outline"
+ end
+ assert_select "#{form} a[href='#{clear_href}']", count: 0
+
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "500" })
+ assert_select "#{form} div.justify-end", count: 1 do
+ assert_select "> a[href='#{clear_href}'] + button[type='submit']", count: 1
+ end
+ assert_select "#{form} button[type='submit']", count: 1 do |buttons|
+ assert_not_includes buttons.first["class"], "w-full", "a pair keeps natural widths"
+ assert_includes buttons.first["class"], "bg-inverse", "Apply stays the primary"
+ end
+ end
+
+ # The tab says why there is nothing to model. A repaid loan has nothing
+ # left to repay; a loan past its last scheduled repayment with a balance
+ # still owing has no repayment to add an extra to, and must not be told
+ # it is repaid.
+ test "the extra repayments tab tells a repaid loan from one past maturity with a balance owing" do
+ # The opening valuation keeps the loan amortizable, and so its tab shown,
+ # once the balance is zero.
+ draw_down_loan_two_years_ago
+ @account.update_columns(balance: 0)
+ assert @account.loan.reload.amortizable?, "the tab must still be offered"
+ get account_path(@account, tab: "extra_repayments")
+
+ assert_response :success
+ assert_select "[data-testid='extra-not-applicable']", text: I18n.t("loans.tabs.extra_repayments.not_applicable")
+ assert_select "input[name='extra_payment[amount]']", count: 0
+
+ @account.update_columns(balance: 500_000)
+ @account.loan.update!(start_date: Date.current - 3.years, term_months: 24)
+ assert_not @account.loan.reload.payoff_projection(as_of: Date.current).applicable?, "the fixture must be past maturity"
+ get account_path(@account, tab: "extra_repayments")
+
+ assert_response :success
+ assert_select "[data-testid='extra-not-applicable']", text: I18n.t("loans.tabs.extra_repayments.no_scheduled_repayments")
+ assert_select "input[name='extra_payment[amount]']", count: 0
+ end
+
+ # The page rebuilds an extra only from its params, and picking a chart
+ # period reloads the page. Each period link carries the applied extra and
+ # the tab it was applied from, so the extra line, the cards and the tab
+ # survive the pick.
+ test "the chart's period links keep an applied extra and its tab" do
+ get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "100", frequency: "weekly" })
+
+ assert_response :success
+ queries = period_link_queries
+ assert_not_empty queries
+ queries.each do |query|
+ assert_equal({ "amount" => "100", "frequency" => "weekly" }, query["extra_payment"])
+ assert_equal "extra_repayments", query["tab"]
+ end
+ end
+
+ # Nothing to keep: no amount, a zero or a refused one. The links stay as
+ # they were before the tab existed, a period and nothing else.
+ test "the chart's period links carry nothing when no extra applies" do
+ [ nil, { amount: "0" }, { amount: "abc" }, { amount: "100", frequency: "daily" } ].each do |extra_payment|
+ get account_path(@account, tab: "extra_repayments", extra_payment: extra_payment)
+
+ assert_response :success
+ queries = period_link_queries
+ assert_not_empty queries
+ queries.each { |query| assert_equal [ "period" ], query.keys, "for #{extra_payment.inspect}" }
+ end
+ end
+
private
+ # The query of every period link in the chart card's picker.
+ def period_link_queries
+ chart_card = "##{ActionView::RecordIdentifier.dom_id(@account, :chart)}"
+ css_select("#{chart_card} a[href*='period=']").map { |link| Rack::Utils.parse_nested_query(URI(link["href"]).query) }
+ end
+
# Posts the new-loan form as a browser does: the "Opening balance date"
# field is always sent, defaulting to today minus two years.
def create_loan(start_date:, initial_balance: 400_000, opening_balance_date: Date.current - 2.years)
diff --git a/test/models/loan/extra_repayment_test.rb b/test/models/loan/extra_repayment_test.rb
new file mode 100644
index 0000000000..a2e8497a75
--- /dev/null
+++ b/test/models/loan/extra_repayment_test.rb
@@ -0,0 +1,78 @@
+require "test_helper"
+
+class Loan::ExtraRepaymentTest < ActiveSupport::TestCase
+ # Blank and zero both mean "no extra": the tab then shows the loan without
+ # one, exactly as it does before anything is entered.
+ test "a blank or zero amount is no extra, and no error" do
+ [ nil, "", " ", "0", "0.00" ].each do |input|
+ extra = Loan::ExtraRepayment.new(amount: input, currency: "USD")
+
+ assert extra.valid?, "#{input.inspect} is not an error"
+ assert_not extra.applied?, "#{input.inspect} applies no extra"
+ assert_nil extra.amount
+ end
+ end
+
+ # The params arrive over GET, so the form's `min: 0` is a hint and nothing
+ # more. A negative extra would shrink each repayment and manufacture a
+ # balloon; it is refused rather than coerced to zero or to its absolute value.
+ test "a negative or non-numeric amount is refused, not coerced" do
+ [ "-1", "-0.01", "abc", "12abc", "1e3", "Infinity", "NaN" ].each do |input|
+ extra = Loan::ExtraRepayment.new(amount: input, currency: "USD")
+
+ assert_not extra.valid?, "#{input.inspect} must be refused"
+ assert_not extra.applied?
+ assert_nil extra.amount
+ assert_equal [ I18n.t("loans.tabs.extra_repayments.invalid_amount") ], extra.errors[:amount]
+ end
+ end
+
+ test "the smallest positive amount applies" do
+ extra = Loan::ExtraRepayment.new(amount: "0.01", currency: "USD")
+
+ assert extra.valid?
+ assert extra.applied?
+ assert_equal BigDecimal("0.01"), extra.amount
+ end
+
+ test "an amount keeps what was typed for the field" do
+ assert_equal "250.50", Loan::ExtraRepayment.new(amount: " 250.50 ", currency: "USD").input
+ assert_equal "abc", Loan::ExtraRepayment.new(amount: "abc", currency: "USD").input
+ end
+
+ # More decimals than the currency has would ask the engine for a repayment
+ # nobody can pay. Rounded to the currency, a fraction of a cent is no extra.
+ test "an amount is taken to the currency's precision" do
+ assert_equal BigDecimal("10.13"), Loan::ExtraRepayment.new(amount: "10.125", currency: "USD").amount
+ assert_not Loan::ExtraRepayment.new(amount: "0.004", currency: "USD").applied?
+ assert_equal BigDecimal("10"), Loan::ExtraRepayment.new(amount: "10.4", currency: "JPY").amount
+ end
+
+ # How often the extra is paid. Blank is monthly, the tab's default, so a form
+ # submitted before the choice existed models what it always did.
+ test "blank frequency is monthly, and each offered frequency is accepted" do
+ assert_equal "monthly", Loan::ExtraRepayment.new(amount: "100", currency: "USD").frequency
+ assert_equal "monthly", Loan::ExtraRepayment.new(amount: "100", frequency: "", currency: "USD").frequency
+
+ %w[weekly fortnightly monthly].each do |frequency|
+ extra = Loan::ExtraRepayment.new(amount: "100", frequency: frequency, currency: "USD")
+
+ assert extra.valid?, frequency
+ assert extra.applied?, frequency
+ assert_equal frequency, extra.frequency
+ end
+ end
+
+ # Like the amount, the frequency arrives over GET. Anything the select does
+ # not offer is refused, not read as monthly: that would quote a figure for a
+ # schedule nobody chose.
+ test "a frequency the form does not offer is refused, not coerced" do
+ [ "daily", "Weekly", "weekly ", "yearly" ].each do |input|
+ extra = Loan::ExtraRepayment.new(amount: "100", frequency: input, currency: "USD")
+
+ assert_not extra.valid?, "#{input.inspect} must be refused"
+ assert_not extra.applied?
+ assert_equal [ I18n.t("loans.tabs.extra_repayments.invalid_frequency") ], extra.errors[:frequency]
+ end
+ end
+end
diff --git a/test/models/loan/payoff_chart_test.rb b/test/models/loan/payoff_chart_test.rb
index 139bce5655..d4b1177271 100644
--- a/test/models/loan/payoff_chart_test.rb
+++ b/test/models/loan/payoff_chart_test.rb
@@ -330,6 +330,58 @@ class Loan::PayoffChartTest < ActiveSupport::TestCase
assert_nil Loan::PayoffChart.new(on_contract_loan, as_of: @today).payload[:balloon]
end
+ # Without an extra the payload is exactly what it was before the extra
+ # existed: no key, no visible entry, no label.
+ test "without an extra projection the payload is unchanged" do
+ payload = Loan::PayoffChart.new(on_contract_loan, as_of: @today, period: @all_time).payload
+
+ assert_equal %i[actual scheduled projected], Loan::PayoffChart::SERIES
+ assert_equal %i[
+ today locale currency currency_precision domain_start domain_end actual scheduled projected visible
+ scheduled_payoff_date projected_payoff_date months_saved interest_saved balloon labels aria_description
+ ], payload.keys
+ assert_equal %i[actual scheduled projected], payload[:visible]
+ assert_equal %i[actual scheduled projected principal interest interest_share principal_share today interactive_chart], payload[:labels].keys
+ end
+
+ test "an extra projection draws its own line, named in the legend and the description" do
+ loan = on_contract_loan
+ projection = loan.payoff_projection(as_of: @today)
+ extra = loan.payoff_projection(as_of: @today, extra: 5_000)
+
+ payload = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time,
+ projection: projection, extra_projection: extra).payload
+
+ assert_equal({ date: @today.iso8601, balance: projection.current_balance.amount.to_f }, payload[:extra].first,
+ "the extra line opens at today's balance, as the projection does")
+ assert_equal extra.payoff_date.iso8601, payload[:extra].last[:date]
+ assert_equal extra.payoff_date.iso8601, payload[:extra_payoff_date]
+ assert_includes payload[:visible], :extra
+ assert_equal I18n.t("UI.account.chart.loan.extra"), payload[:labels][:extra]
+ assert_includes payload[:aria_description], I18n.t(
+ "UI.account.chart.loan.aria_extra_payoff", date: I18n.l(extra.payoff_date, format: :long)
+ )
+ # The other series do not move for it.
+ plain = Loan::PayoffChart.new(loan, as_of: @today, period: @all_time, projection: projection).payload
+ assert_equal plain[:projected], payload[:projected]
+ assert_equal plain[:scheduled], payload[:scheduled]
+ end
+
+ # An extra too small to clear a loan that is far behind still draws, and the
+ # description says it does not pay the loan off rather than quoting nil.
+ test "the description says so when even the extra does not pay the loan off" do
+ loan = build_loan
+ loan.account.update!(balance: 400_000)
+ extra = loan.payoff_projection(as_of: @today, extra: 10)
+
+ payload = Loan::PayoffChart.new(loan, as_of: @today, extra_projection: extra).payload
+
+ assert_nil payload[:extra_payoff_date]
+ assert_includes payload[:aria_description], I18n.t(
+ "UI.account.chart.loan.aria_extra_payoff", date: I18n.t("UI.account.chart.loan.no_payoff")
+ )
+ 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
diff --git a/test/models/loan/payoff_projection_test.rb b/test/models/loan/payoff_projection_test.rb
index 7a8ef5b9ba..3e8a3bc019 100644
--- a/test/models/loan/payoff_projection_test.rb
+++ b/test/models/loan/payoff_projection_test.rb
@@ -162,6 +162,26 @@ class Loan::PayoffProjectionTest < ActiveSupport::TestCase
assert_not matured.payoff_projection(as_of: Date.new(2040, 1, 1)).applicable?
end
+ # Two reasons a projection does not apply, which the Extra repayments tab
+ # words differently: nothing is owed, or something is owed with no
+ # scheduled repayment left to pay it. Both sides of zero.
+ test "settled only when nothing is owed, not when the schedule has run out" do
+ loan = build_loan(term_months: 24)
+
+ { 0 => true, -1 => true, BigDecimal("0.01") => false, 500_000 => false }.each do |balance, settled|
+ loan.account.update_columns(balance: balance)
+ assert_equal settled, loan.reload.payoff_projection(as_of: @today).settled?, "balance #{balance}"
+ end
+
+ loan.account.update_columns(balance: nil)
+ assert loan.reload.payoff_projection(as_of: @today).settled?, "no balance yet reads as zero"
+
+ loan.account.update_columns(balance: 500_000)
+ matured = loan.reload.payoff_projection(as_of: Date.new(2040, 1, 1))
+ assert_not matured.applicable?
+ assert_not matured.settled?, "past maturity with a balance still owing is not settled"
+ 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
@@ -217,6 +237,179 @@ class Loan::PayoffProjectionTest < ActiveSupport::TestCase
"on contract, the projection must charge the running month what the schedule charges it"
end
+ # The extra rides on top of the contract's repayment in every period, so
+ # each period pays exactly the extra more than the same loan without it.
+ # The last row settles the balance and is the one exception.
+ test "a monthly extra adds to every period's repayment" do
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: scheduled_balance_at(loan, @today))
+
+ baseline = loan.payoff_projection(as_of: @today)
+ with_extra = loan.payoff_projection(as_of: @today, extra: 1_000)
+
+ assert_operator with_extra.payments.length, :>, 1
+ with_extra.payments[0..-2].each_with_index do |payment, index|
+ assert_equal BigDecimal("1000"), payment[:payment_amount] - baseline.payments[index][:payment_amount],
+ "period #{index + 1} must pay the extra on top of the contract's repayment"
+ end
+ end
+
+ # Months sooner and interest saved are measured against the same loan paying
+ # no extra, not against the contract. On an overpaid loan the two differ, so
+ # comparing against the contract would fold in how far ahead the borrower
+ # already is.
+ test "the extra clears the loan sooner, and saves interest against no extra" do
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: scheduled_balance_at(loan, @today) - 50_000)
+
+ baseline = loan.payoff_projection(as_of: @today)
+ with_extra = loan.payoff_projection(as_of: @today, extra: 5_000)
+
+ # The first period by hand: 6% a year is 0.5% a month on the balance the
+ # period opened with, and the payment is the contract's plus the extra.
+ opening = loan.account.balance
+ first = with_extra.payments.first
+ expected_interest = (opening * BigDecimal("0.005")).round(2)
+ assert_equal expected_interest, first[:interest_payment]
+ assert_equal baseline.payments.first[:payment_amount] + 5_000 - expected_interest, first[:principal_payment]
+
+ assert_equal baseline.payments.length - with_extra.payments.length, with_extra.months_sooner_than(baseline)
+ assert_operator with_extra.months_sooner_than(baseline), :>, 0
+ saved = baseline.total_interest.amount - with_extra.total_interest.amount
+ assert_equal Money.new(saved, "USD"), with_extra.interest_saved_versus(baseline)
+ assert_operator saved, :>, 0
+ assert_not_equal with_extra.interest_saved, with_extra.interest_saved_versus(baseline),
+ "against no extra, not against the contract: this loan was already ahead"
+ end
+
+ # A baseline that never clears has no payoff date, so there is no "sooner"
+ # to quote and no comparable total interest. Nor is there for an extra that
+ # does not clear the loan either.
+ test "a baseline that never clears quotes no months sooner or interest saved" do
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: 400_000)
+
+ baseline = loan.payoff_projection(as_of: @today)
+ clearing = loan.payoff_projection(as_of: @today, extra: 20_000)
+ too_small = loan.payoff_projection(as_of: @today, extra: 10)
+
+ assert_not baseline.converged?
+ assert clearing.converged?, "an extra this large clears the loan"
+ assert clearing.payoff_date
+ assert_nil clearing.months_sooner_than(baseline)
+ assert_nil clearing.interest_saved_versus(baseline)
+
+ assert_not too_small.converged?
+ assert_nil too_small.months_sooner_than(baseline)
+ assert_nil too_small.interest_saved_versus(baseline)
+ end
+
+ # Weekly extras are dated, starting the day after as_of, and each period is
+ # credited with the extras falling in (previous payment date, payment date].
+ # Payments land on the 1st and as_of is Friday 15 January 2027, so the
+ # extras fall on Saturdays from the 16th: three before 1 February, then four,
+ # four, and five before 1 May. The fifth is on 1 May itself, so a payment
+ # date belongs to the period it closes.
+ test "a weekly extra credits each date in its period" do
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: scheduled_balance_at(loan, @today))
+
+ baseline = loan.payoff_projection(as_of: @today)
+ weekly = loan.payoff_projection(as_of: @today, extra: 100, extra_frequency: "weekly")
+
+ assert_equal [ 3, 4, 4, 5, 4 ], extra_counts(weekly, baseline, 100).first(5)
+ end
+
+ # The first dated extra is the day after as_of, never as_of itself: that
+ # day's period is already open. With as_of the day before a payment, the
+ # first extra lands on the payment date, so that period carries exactly one.
+ test "the first weekly extra falls the day after as_of" do
+ as_of = Date.new(2027, 1, 31)
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: scheduled_balance_at(loan, as_of))
+
+ baseline = loan.payoff_projection(as_of: as_of)
+ weekly = loan.payoff_projection(as_of: as_of, extra: 100, extra_frequency: "weekly")
+
+ assert_equal 1, extra_counts(weekly, baseline, 100).first, "1 February, the day after as_of, is in the first period"
+ end
+
+ # Every fourteen days from the 16th: two in most periods, three in the
+ # period that closes on 1 August (3, 17 and 31 July).
+ test "a fortnightly extra credits two or three times a period" do
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: scheduled_balance_at(loan, @today))
+
+ baseline = loan.payoff_projection(as_of: @today)
+ fortnightly = loan.payoff_projection(as_of: @today, extra: 100, extra_frequency: "fortnightly")
+
+ assert_equal [ 2, 2, 2, 2, 2, 2, 3 ], extra_counts(fortnightly, baseline, 100).first(7)
+ end
+
+ test "monthly is the default, one extra in every period" do
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: scheduled_balance_at(loan, @today))
+
+ default = loan.payoff_projection(as_of: @today, extra: 100)
+ monthly = loan.payoff_projection(as_of: @today, extra: 100, extra_frequency: "monthly")
+
+ assert_equal default.payments, monthly.payments
+ end
+
+ # A programming error, not user input: Loan::ExtraRepayment refuses an
+ # unknown frequency before it reaches the projection.
+ test "an unknown frequency is refused" do
+ loan = build_loan(term_months: 24)
+
+ error = assert_raises(ArgumentError) { loan.payoff_projection(as_of: @today, extra: 100, extra_frequency: "daily") }
+ assert_equal "Unknown extra frequency: \"daily\"", error.message
+ end
+
+ # What is still to repay from today: the balance plus every remaining
+ # period's interest. The extra pays the same principal, so its total is
+ # lower by exactly the interest it saves.
+ test "total cost is today's balance plus the interest still to pay" do
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: scheduled_balance_at(loan, @today))
+
+ baseline = loan.payoff_projection(as_of: @today)
+ with_extra = loan.payoff_projection(as_of: @today, extra: 1_000)
+
+ assert_equal Money.new(loan.account.balance + baseline.total_interest.amount, "USD"), baseline.total_cost
+ assert_equal baseline.payments.sum { |payment| payment[:payment_amount] }, baseline.total_cost.amount,
+ "the total is what the payments add up to"
+ assert_equal baseline.total_cost - with_extra.total_cost, with_extra.total_cost_saved_versus(baseline)
+ assert_equal with_extra.interest_saved_versus(baseline), with_extra.total_cost_saved_versus(baseline)
+ end
+
+ # A run that never clears the balance has no total: a balloon would still
+ # be owed, and adding it in would quote a cost the borrower never agreed.
+ test "a projection that never clears has no total cost" do
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: 400_000)
+
+ baseline = loan.payoff_projection(as_of: @today)
+ clearing = loan.payoff_projection(as_of: @today, extra: 20_000)
+
+ assert_nil baseline.total_cost
+ assert clearing.total_cost
+ assert_nil clearing.total_cost_saved_versus(baseline)
+ end
+
+ test "no extra leaves the projection identical" do
+ loan = build_loan(term_months: 24)
+ loan.account.update!(balance: scheduled_balance_at(loan, @today) - 10_000)
+
+ baseline = loan.payoff_projection(as_of: @today)
+
+ [ nil, 0 ].each do |extra|
+ projection = loan.payoff_projection(as_of: @today, extra: extra)
+ assert_equal baseline.payments, projection.payments, "extra: #{extra.inspect}"
+ assert_equal 0, projection.months_sooner_than(baseline)
+ assert_equal Money.new(0, "USD"), projection.interest_saved_versus(baseline)
+ end
+ end
+
# The projection is the second caller of Loan::Simulator, and it builds its
# own. A loan on actual/365 must be projected on actual/365: otherwise the
# schedule reconciles to the lender's statement while the projection beside
@@ -265,6 +458,15 @@ class Loan::PayoffProjectionTest < ActiveSupport::TestCase
account.loan
end
+ # How many extras each period carried: its payment above the same loan's
+ # without the extra, in units of the extra. The last row settles the
+ # balance and is left out.
+ def extra_counts(projection, baseline, extra)
+ projection.payments[0..-2].each_with_index.map do |payment, index|
+ ((payment[:payment_amount] - baseline.payments[index][:payment_amount]) / extra).to_i
+ end
+ end
+
def scheduled_balance_at(loan, date)
loan.amortization_schedule.payments
.select { |p| p.date <= date }.last.ending_balance.amount
diff --git a/test/system/loan_payoff_chart_test.rb b/test/system/loan_payoff_chart_test.rb
index 2aca28c7e1..09c93887ae 100644
--- a/test/system/loan_payoff_chart_test.rb
+++ b/test/system/loan_payoff_chart_test.rb
@@ -48,6 +48,96 @@ class LoanPayoffChartTest < ApplicationSystemTestCase
end
end
+ # The Extra repayments tab's amount reaches the chart as a fourth line,
+ # through the form a borrower actually uses. The line must paint in its own
+ # colour in both themes, and the legend must name it.
+ test "an extra repayment paints its own line beside the others" do
+ travel_to TODAY do
+ account = on_contract_loan_account
+
+ visit account_path(account, period: "all_time", tab: "extra_repayments")
+ assert_no_selector "[data-controller='loan-payoff-chart'] svg path[data-series='extra']"
+
+ # Laid out as the Bills form is: the amount and how often side by side,
+ # Apply below them as the form's one full-width action, and nothing
+ # wider than the tab.
+ field = find_field(I18n.t("loans.tabs.extra_repayments.amount_label"))
+ field_box = bounding_box(field.find(:xpath, "ancestor::div[contains(concat(' ', normalize-space(@class), ' '), ' form-field ')][1]"))
+ select = find_field(I18n.t("loans.tabs.extra_repayments.frequency_label"))
+ select_box = bounding_box(select.find(:xpath, "ancestor::div[contains(concat(' ', normalize-space(@class), ' '), ' form-field ')][1]"))
+ apply_box = bounding_box(find_button(I18n.t("loans.tabs.extra_repayments.apply")))
+ form_box = bounding_box(field.find(:xpath, "ancestor::form[1]"))
+ assert_in_delta field_box["top"], select_box["top"], 2, "the amount and how often must share a row"
+ assert_operator select_box["left"], :>=, field_box["right"], "how often sits to the amount's right"
+ assert_operator apply_box["top"], :>=, field_box["bottom"], "Apply sits below the fields"
+ assert_in_delta form_box["left"], apply_box["left"], 2, "Apply alone spans the form, from its left edge"
+ assert_in_delta form_box["right"], apply_box["right"], 2, "to its right edge"
+ assert_operator select_box["right"], :<=, form_box["right"] + 1, "and nothing overflows the form"
+
+ field.fill_in with: "1000"
+ select I18n.t("loans.tabs.extra_repayments.frequencies.weekly"), from: I18n.t("loans.tabs.extra_repayments.frequency_label")
+ click_button I18n.t("loans.tabs.extra_repayments.apply")
+ assert_field I18n.t("loans.tabs.extra_repayments.frequency_label"), with: "weekly"
+
+ # With an amount entered, Clear joins Apply as a right-aligned pair:
+ # Clear first, Apply at the form's right edge, both at natural width.
+ apply_box = bounding_box(find_button(I18n.t("loans.tabs.extra_repayments.apply")))
+ clear_box = bounding_box(find_link(I18n.t("loans.tabs.extra_repayments.clear")))
+ form_box = bounding_box(find_field(I18n.t("loans.tabs.extra_repayments.amount_label")).find(:xpath, "ancestor::form[1]"))
+ assert_in_delta form_box["right"], apply_box["right"], 2, "Apply ends the pair at the form's right edge"
+ assert_operator clear_box["right"], :<=, apply_box["left"], "Clear comes before Apply"
+ assert_in_delta clear_box["top"], apply_box["top"], 2, "on one row"
+ assert_operator apply_box["left"], :>, form_box["left"] + (form_box["right"] - form_box["left"]) / 2, "at natural width, not spanning the form"
+
+ # Each card's figure fits inside its card, at the width the page has with
+ # both side panels open. Three across only when the tab has room.
+ page.driver.browser.manage.window.resize_to(1280, 1400)
+ assert_selector "[data-testid='total-cost']"
+ overflowing = page.evaluate_script(<<~JS)
+ Array.from(document.querySelectorAll("[data-testid='extra-cards'] > div p"))
+ .filter((p) => p.scrollWidth > p.clientWidth + 1)
+ .map((p) => p.textContent.trim())
+ JS
+ assert_empty overflowing, "a card's figure runs past its card"
+
+ extra = find("[data-controller='loan-payoff-chart'] svg path[data-series='extra']")
+ assert extra["d"].to_s.start_with?("M"), "the extra line has no geometry"
+ assert_not_equal "none", stroke_of("extra"), "the extra line has geometry but no resolved stroke"
+ assert_not_equal stroke_of("projected"), stroke_of("extra"), "the extra line must not reuse the projection's colour"
+ assert_selector "ul li", text: I18n.t("UI.account.chart.loan.extra")
+ assert_series_painted
+
+ light = stroke_of("extra")
+ page.execute_script("document.documentElement.setAttribute('data-theme', 'dark')")
+ wait_until { stroke_of("extra") != light }
+ assert_not_equal light, stroke_of("extra"), "the extra line must repaint from the dark theme's token"
+ end
+ end
+
+ # A loan has five tabs, more than the account column holds beside both side
+ # panels. Labels stay on one line, and the bar scrolls inside the column
+ # rather than pushing the page sideways and hiding Statements off-screen.
+ test "the loan's tab bar keeps one line and stays inside its column" do
+ travel_to TODAY do
+ visit account_path(on_contract_loan_account)
+
+ details = find("[data-testid='account-details']")
+ heights = all("[data-testid='account-details'] [role='tab']").map { |tab| bounding_box(tab)["height"] }
+
+ assert_equal 5, heights.length
+ assert_equal 1, heights.uniq.length, "every tab is the same height"
+ assert_operator heights.first, :<, 40, "a label that wraps doubles the tab's height"
+ # The bar's own box stays inside the column either way; what must not
+ # happen is its tabs spilling out and widening the column's content.
+ overflow = page.evaluate_script("arguments[0].scrollWidth - arguments[0].clientWidth", details)
+ assert_operator overflow, :<=, 0, "the tabs must not run past their column"
+
+ statements = find("[data-testid='account-details'] [role='tab'][data-id='statements']")
+ statements.click
+ assert_equal "true", statements["aria-selected"], "the last tab is reachable"
+ end
+ end
+
# The SVG names the balance and every payoff date in its label, the
# same text is real DOM, and it points at no table that is not there.
test "the SVG carries its description and no data table" do
@@ -441,6 +531,10 @@ class LoanPayoffChartTest < ApplicationSystemTestCase
)
end
+ def bounding_box(element)
+ page.evaluate_script("arguments[0].getBoundingClientRect().toJSON()", element)
+ end
+
# Capybara retries its own matchers; a value read through evaluate_script
# gets no such patience, so give it the same budget.
def wait_until(timeout: Capybara.default_max_wait_time)