Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Rescue #1775: loans overview new insights (editable fields, amortization, editable-field insights) (#3327)

jaysbeekay0da863b78971
diff --git a/app/controllers/loans_controller.rb b/app/controllers/loans_controller.rb
index 62918d6475..e1b687567a 100644
--- a/app/controllers/loans_controller.rb
+++ b/app/controllers/loans_controller.rb
@@ -3,6 +3,7 @@ class LoansController < ApplicationController
permitted_accountable_attributes(
:id, :subtype, :rate_type, :interest_rate, :term_months, :initial_balance, :start_date,
+ :down_payment, :insurance_rate, :insurance_rate_type,
{ rate_changes: [ :effective_date, :rate ] }
)
end
diff --git a/app/helpers/loans_helper.rb b/app/helpers/loans_helper.rb
index 18ba2176d6..3fdc353662 100644
--- a/app/helpers/loans_helper.rb
+++ b/app/helpers/loans_helper.rb
@@ -1,4 +1,23 @@
module LoansHelper
+ # The two policies Loan::Insurance knows how to charge. Listed here rather
+ # than built from the constant so each one carries a translated label.
+ def loan_insurance_rate_type_options
+ [
+ [ t("loans.form.insurance_rate_type_level_term"), Loan::Insurance::LEVEL_TERM ],
+ [ t("loans.form.insurance_rate_type_decreasing_life"), Loan::Insurance::DECREASING_LIFE ]
+ ]
+ end
+
+ # How leveraged the loan was at drawdown, as a design-system colour. Bands are
+ # Loan's; the colours are this layer's.
+ def loan_leverage_band_class(band)
+ {
+ conservative: "text-success",
+ moderate: "text-warning",
+ high: "text-destructive"
+ }.fetch(band, "text-secondary")
+ end
+
# The rate types the form offers, plus the loan's own when a provider wrote
# one the form does not know (#100 decision 8). Without it the select has no
# matching option, the browser submits the first one, and saving any other
diff --git a/app/models/demo/generator.rb b/app/models/demo/generator.rb
index f5a09e5d0c..ee722a2d33 100644
--- a/app/models/demo/generator.rb
+++ b/app/models/demo/generator.rb
@@ -302,6 +302,9 @@ class Demo::Generator
accountable: Loan.new(
subtype: "mortgage", rate_type: "adjustable", interest_rate: 6.25, term_months: 360,
start_date: mortgage_start, initial_balance: 320_000,
+ # A deposit and a level-term policy, so the demo mortgage shows the
+ # leverage and insurance cards rather than hiding both.
+ down_payment: 70_000, insurance_rate: 0.36, insurance_rate_type: "level_term",
rate_changes: [
{ effective_date: (mortgage_start >> 24).iso8601, rate: "5.5" },
{ effective_date: (mortgage_start >> 48).iso8601, rate: "6.75" }
@@ -311,7 +314,10 @@ class Demo::Generator
)
@car_loan = family.accounts.create!(
accountable: Loan.new(subtype: "auto", rate_type: "fixed", interest_rate: 6.9, term_months: 60,
- start_date: loans_start, initial_balance: 24_000),
+ start_date: loans_start, initial_balance: 24_000,
+ # The other policy shape, on a fixed loan.
+ down_payment: 4_000, insurance_rate: 0.5,
+ insurance_rate_type: "decreasing_life"),
name: "Car Loan", balance: 0, currency: "USD"
)
@student_loan = family.accounts.create!(
diff --git a/app/models/loan.rb b/app/models/loan.rb
index a657cb2c79..1bc1ba447d 100644
--- a/app/models/loan.rb
+++ b/app/models/loan.rb
@@ -33,6 +33,29 @@ class Loan < ApplicationRecord
# charging a month's interest for the gap.
validates :start_date, comparison: { less_than_or_equal_to: -> { Date.current } }, allow_nil: true
+ # What the borrower put in up front. Not part of the amortisation -- the loan
+ # amortises what was actually lent -- but it is what makes leverage readable:
+ # a 20,000 deposit against an 80,000 loan is a different position from the
+ # same loan against 5,000.
+ validates :down_payment, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
+
+ validates :insurance_rate, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
+ # The form's "None" option submits an empty string, which means no type
+ # recorded (read as decreasing). Stored as NULL: the column's check
+ # constraint admits NULL but not '', so allowing blank here would only move
+ # the rejection from a validation error to a database error.
+ normalizes :insurance_rate_type, with: ->(value) { value.presence }
+ validates :insurance_rate_type, inclusion: { in: Loan::Insurance::RATE_TYPES }, allow_nil: true
+
+ # How much was borrowed for every unit the borrower put in. Nil without a
+ # down payment recorded: a loan with no deposit is not infinitely leveraged,
+ # it is a loan whose leverage nobody has told us.
+ LEVERAGE_BANDS = {
+ conservative: 0..4,
+ moderate: 4..8,
+ high: 8..
+ }.freeze
+
# The contracted repayment, for a loan that has exactly one.
#
# Deliberately still nil for a variable loan even though it now has a
@@ -224,15 +247,183 @@ class Loan < ApplicationRecord
SCHEDULE_INPUTS.each do |input|
define_method(:"#{input}=") do |value|
@amortization_schedule = nil
+ @insurance = nil
+ super(value)
+ end
+ end
+
+ # The premium is charged against the schedule, so it goes stale for both its
+ # own inputs and the schedule's.
+ INSURANCE_INPUTS = %i[insurance_rate insurance_rate_type].freeze
+
+ INSURANCE_INPUTS.each do |input|
+ define_method(:"#{input}=") do |value|
+ @insurance = nil
super(value)
end
end
def reload(*)
@amortization_schedule = nil
+ @insurance = nil
super
end
+ # The insurance policy charged alongside this loan's instalments, or nil when
+ # no premium is recorded. Read #total_insurance for a figure that is always
+ # money.
+ def insurance
+ @insurance ||= Loan::Insurance.for(self)
+ end
+
+ def total_insurance
+ insurance&.total || Money.new(0, account.currency)
+ end
+
+ # Everything the loan costs the borrower: what the schedule has them repay
+ # (principal and interest, the Schedule tab's own "Total Cost") plus the
+ # premium charged alongside. Read off the schedule rather than re-added from
+ # its parts, so with no premium the two figures are the same figure. Nil when
+ # there is no schedule to read an interest figure from, because a cost
+ # without interest in it would understate the loan rather than decline to
+ # answer.
+ def total_cost
+ schedule = amortization_schedule
+ return nil if schedule.nil?
+
+ schedule.total_paid + total_insurance
+ end
+
+ # How far into the term the loan is, measured from origination rather than
+ # from `start_date` alone: a loan drawn down before the account tracking it
+ # was created has no start_date, and #origination_date already answers that
+ # from the account's first valuation.
+ #
+ # A month counts once it has been served in full, so a loan originated on the
+ # 15th is one month in on the 15th of the next month, not on the 1st. Clamped
+ # to the term: a loan running past its last payment is finished, not further
+ # in than it can be.
+ def months_elapsed(as_of: Date.current)
+ origin = origination_date
+ return 0 if origin.nil? || term_months.nil? || as_of < origin
+
+ months = (as_of.year * 12 + as_of.month) - (origin.year * 12 + origin.month)
+ months -= 1 if origin + months.months > as_of
+
+ months.clamp(0, term_months)
+ end
+
+ def remaining_months(as_of: Date.current)
+ return nil if term_months.nil?
+
+ [ term_months - months_elapsed(as_of: as_of), 0 ].max
+ end
+
+ def finished?(as_of: Date.current)
+ return nil if term_months.nil?
+
+ months_elapsed(as_of: as_of) >= term_months
+ end
+
+ # What is still owed after a given scheduled payment, read off the schedule
+ # rather than re-derived, so it cannot drift from the table beside it.
+ def remaining_balance_at(payment_number)
+ return nil unless payment_number&.positive?
+
+ amortization_schedule&.payments&.dig(payment_number - 1)&.ending_balance
+ end
+
+ # One instalment, split into what it repays, what it costs and what it
+ # insures, with each part as a share of the whole. Defaults to the payment
+ # the loan is on as of `as_of`, which the caller supplies so the instalment
+ # agrees with every other figure it shows for that date.
+ #
+ # The ratios are for a progress bar, so they are floats summing to 1 rather
+ # than money. A zero payment -- an interest-free loan repaid in full by its
+ # opening instalment -- gives zeroes rather than a division by zero.
+ def payment_breakdown(payment_number: nil, as_of: Date.current)
+ schedule = amortization_schedule
+ return nil if schedule.nil?
+
+ if payment_number.nil?
+ # A finished loan is on no instalment; the clamp below would otherwise
+ # answer with the final, already-paid one as though it were current. The
+ # same holds once a schedule that rounding cleared early has run out,
+ # though the term has not.
+ elapsed = months_elapsed(as_of: as_of)
+ return nil if elapsed >= term_months || elapsed >= schedule.payments.size
+
+ payment_number = elapsed + 1
+ end
+
+ payment = schedule.payments[payment_number.clamp(1, schedule.payments.size) - 1]
+ return nil if payment.nil?
+
+ premium = insurance&.premium_for(payment.number)&.amount || Money.new(0, account.currency)
+ total = payment.principal + payment.interest + premium
+
+ {
+ number: payment.number,
+ date: payment.date,
+ principal: payment.principal,
+ interest: payment.interest,
+ insurance: premium,
+ total: total,
+ ratios: payment_ratios(payment, premium, total)
+ }
+ end
+
+ # How much of what was borrowed has been repaid, as a fraction, measured
+ # against the account's current balance rather than the schedule: the
+ # schedule says what was promised, the balance says what happened.
+ def balance_paid_ratio
+ borrowed = original_balance.amount
+ return nil unless borrowed.positive?
+
+ balance = account&.balance
+ return nil if balance.nil?
+
+ (1 - balance.abs.fdiv(borrowed)).clamp(0.0, 1.0)
+ end
+
+ # Segments for the repayment ring, in the shape the shared donut-chart
+ # controller takes. Nil when the paydown cannot be computed, which is the
+ # view's cue to leave the ring out rather than draw an empty one.
+ def to_donut_segments
+ ratio = balance_paid_ratio
+ return nil if ratio.nil?
+
+ [
+ { color: "var(--color-warning)", amount: ratio, id: "paid" },
+ { color: "var(--budget-unused-fill)", amount: 1 - ratio, id: "unused" }
+ ]
+ end
+
+ # The same segments as JSON, which is what the shared donut-chart controller
+ # reads. Mirrors Budget#to_donut_segments_json so the two ring call sites
+ # hand the controller the same shape.
+ def to_donut_segments_json
+ to_donut_segments&.to_json
+ end
+
+ # Nil for a negative opening balance too: imports can record one, and it is
+ # no amount borrowed to measure a deposit against.
+ def initial_leverage_ratio
+ return nil unless down_payment&.positive?
+
+ borrowed = original_balance.amount
+ return nil unless borrowed.positive?
+
+ borrowed.fdiv(down_payment)
+ end
+
+ def leverage_band
+ ratio = initial_leverage_ratio
+ return nil if ratio.nil?
+
+ 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)
@@ -247,10 +438,47 @@ class Loan < ApplicationRecord
start_date || account.first_valuation&.date || account.opening_anchor_date
end
+ # What the loan was written for, which is not always what the account has
+ # been seen holding.
+ #
+ # `initial_balance` is the recorded contractual principal. The account form
+ # writes it beside the opening valuation and the demo generator does the
+ # same, so for anything created here the two agree. Plaid's student-loan
+ # import writes `origination_principal_amount` into it, and there they can
+ # disagree by the whole of the repayment history: a loan imported after
+ # years of payments has a first tracked valuation part way down the curve,
+ # not the amount borrowed.
+ #
+ # Every figure measured against what was borrowed reads this: the schedule's
+ # principal, the insurance base, how much has been repaid, and the leverage
+ # against the deposit. Taking the first valuation instead understated all of
+ # them, for the whole life of the loan, and the wrong principal was
+ # amortised from the real origination date -- so the error was spread across
+ # the loan's actual history rather than being visibly recent.
+ #
+ # Falls back to the first tracked valuation when no principal was recorded,
+ # which is every loan whose import does not send one. Non-positive counts as
+ # unrecorded: an import can write a zero or a negative, and neither is an
+ # amount borrowed.
def original_balance
+ recorded_principal = initial_balance
+ return Money.new(recorded_principal, account.currency) if recorded_principal&.positive?
+
Money.new(account.first_valuation_amount, account.currency)
end
+ private def payment_ratios(payment, premium, total)
+ return { principal: 0.0, interest: 0.0, insurance: 0.0 } unless total.amount.positive?
+
+ whole = total.amount.to_f
+
+ {
+ principal: payment.principal.amount.to_f / whole,
+ interest: payment.interest.amount.to_f / whole,
+ insurance: premium.amount.to_f / whole
+ }
+ end
+
class << self
def color
"#D444F1"
diff --git a/app/models/loan/insurance.rb b/app/models/loan/insurance.rb
new file mode 100644
index 0000000000..edb62c65d5
--- /dev/null
+++ b/app/models/loan/insurance.rb
@@ -0,0 +1,110 @@
+# The borrower's insurance premium, period by period.
+#
+# Charged ALONGSIDE the instalment, never inside it. The amortisation repays
+# principal and interest and nothing else -- that is what makes its rows agree
+# with a lender's own table -- so a premium folded into `Payment#payment` would
+# make every figure derived from the schedule disagree with the loan. This
+# reads the schedule and returns a parallel series instead.
+#
+# Two policies, which is what lenders sell:
+#
+# level_term the premium is charged on the ORIGINAL principal for the
+# life of the loan, so it does not fall as the loan is
+# repaid. The same amount every month.
+# decreasing_life the premium is charged on what is still outstanding, so it
+# falls with the balance. This is the default reading when a
+# rate is recorded without a type, because a premium that
+# tracks the debt is the conservative assumption: it never
+# overstates the total cost of a policy the borrower has not
+# described.
+#
+# The rate is annual and in percent, like `interest_rate`, and is charged
+# monthly at a twelfth of it. The base for a decreasing policy is the balance
+# OUTSTANDING AT THE START of the period -- the balance the borrower carried
+# through the month the premium covers, not the one they are left with after
+# paying it.
+class Loan::Insurance
+ Premium = Data.define(:number, :date, :amount)
+
+ LEVEL_TERM = "level_term".freeze
+ DECREASING_LIFE = "decreasing_life".freeze
+ RATE_TYPES = [ LEVEL_TERM, DECREASING_LIFE ].freeze
+
+ MONTHS_PER_YEAR = 12
+
+ attr_reader :schedule, :annual_rate, :rate_type, :principal, :currency
+
+ class << self
+ # Nil when the loan carries no premium to charge, or nothing to charge it
+ # against. Callers read `Loan#total_insurance`, which turns that nil into a
+ # zero of the right currency.
+ def for(loan)
+ return nil unless loan.insurance_rate&.positive?
+
+ schedule = loan.amortization_schedule
+ return nil if schedule.nil?
+
+ new(
+ schedule: schedule,
+ annual_rate: loan.insurance_rate,
+ rate_type: loan.insurance_rate_type,
+ principal: loan.original_balance,
+ currency: loan.account.currency
+ )
+ end
+ end
+
+ def initialize(schedule:, annual_rate:, rate_type:, principal:, currency:)
+ @schedule = schedule
+ @annual_rate = BigDecimal(annual_rate.to_s)
+ @rate_type = rate_type
+ @principal = principal
+ @currency = currency
+ end
+
+ # One premium per scheduled payment, oldest first.
+ def premiums
+ @premiums ||= begin
+ opening = principal.amount
+
+ schedule.payments.map do |payment|
+ base = level_term? ? principal.amount : opening
+ opening = payment.ending_balance.amount
+
+ Premium.new(
+ number: payment.number,
+ date: payment.date,
+ amount: money((base * monthly_rate).round(currency_precision))
+ )
+ end
+ end
+ end
+
+ # What the policy costs over the life of the loan.
+ def total
+ money(premiums.sum(BigDecimal("0")) { |premium| premium.amount.amount })
+ end
+
+ # The premium charged against a given scheduled payment number, or nil when
+ # the schedule holds no such payment.
+ def premium_for(number)
+ premiums.find { |premium| premium.number == number }
+ end
+
+ def level_term?
+ rate_type == LEVEL_TERM
+ end
+
+ private
+ def monthly_rate
+ @monthly_rate ||= annual_rate / (100 * MONTHS_PER_YEAR)
+ end
+
+ def currency_precision
+ @currency_precision ||= Money::Currency.new(currency).default_precision || 2
+ end
+
+ def money(value)
+ Money.new(value, currency)
+ end
+end
diff --git a/app/models/plaid_account/liabilities/student_loan_processor.rb b/app/models/plaid_account/liabilities/student_loan_processor.rb
index 61d6f484c3..205fdb8045 100644
--- a/app/models/plaid_account/liabilities/student_loan_processor.rb
+++ b/app/models/plaid_account/liabilities/student_loan_processor.rb
@@ -10,7 +10,8 @@ class PlaidAccount::Liabilities::StudentLoanProcessor
rate_type: "fixed",
interest_rate: student_loan_data["interest_rate_percentage"],
initial_balance: student_loan_data["origination_principal_amount"],
- term_months: term_months
+ term_months: term_months,
+ start_date: start_date
)
end
@@ -21,10 +22,39 @@ class PlaidAccount::Liabilities::StudentLoanProcessor
plaid_account.current_account
end
+ # The date the loan was actually drawn down, which the payload has been
+ # carrying all along. Without it an imported loan looks originated the day
+ # it was imported, and everything measured from origination -- months
+ # elapsed, months remaining, which instalment the borrower is on -- reads
+ # the whole history of an old loan as its first month.
+ #
+ # Never overwrites a date already recorded: a borrower who corrected the
+ # drawdown by hand knows something the provider does not, and a sync is
+ # not the place to argue with them.
+ #
+ # Nor records one in the future: Loan rejects a start date after today, and
+ # a provider date that says otherwise would fail the whole sync with it.
+ def start_date
+ account.loan.start_date || recordable_origination_date
+ end
+
+ def recordable_origination_date
+ origination_date if origination_date && origination_date <= Date.current
+ end
+
+ # Counted in whole calendar months, as the schedule and Loan#months_elapsed
+ # count them: 30-day blocks made a 30-year loan 365 months long. A month
+ # counts once it is served in full, so a payoff less than a month after
+ # origination, or before it, is nil rather than zero: a term of no months
+ # is not a term, and it would make the loan look amortisable over a
+ # schedule that cannot exist.
def term_months
return nil unless origination_date && expected_payoff_date
- ((expected_payoff_date - origination_date).to_i / 30).to_i
+ months = (expected_payoff_date.year * 12 + expected_payoff_date.month) -
+ (origination_date.year * 12 + origination_date.month)
+ months -= 1 if origination_date + months.months > expected_payoff_date
+ months.positive? ? months : nil
end
def origination_date
diff --git a/app/views/loans/_form.html.erb b/app/views/loans/_form.html.erb
index 41c11ecdde..8fb490c01e 100644
--- a/app/views/loans/_form.html.erb
+++ b/app/views/loans/_form.html.erb
@@ -38,6 +38,15 @@
action: "change->loan-rate-changes#toggle" } } %>
</div>
+ <div class="flex items-center gap-2">
+ <%# What the borrower put in up front. Not part of the amortisation --
+ the loan amortises what was lent -- but it is what makes the
+ leverage figure on the overview readable. %>
+ <%= loan_form.money_field :down_payment,
+ label: t("loans.form.down_payment"),
+ default_currency: Current.family.currency %>
+ </div>
+
<div class="flex items-center gap-2">
<%= loan_form.date_field :start_date,
label: t("loans.form.start_date"),
@@ -56,6 +65,22 @@
max: Loan::Simulator::MAX_PERIODS %>
</div>
+ <div class="flex items-center gap-2">
+ <%# The premium many lenders quote beside the instalment. Charged
+ alongside it rather than inside it, so it moves the loan's total
+ cost without moving its repayment. %>
+ <%= loan_form.number_field :insurance_rate,
+ label: t("loans.form.insurance_rate"),
+ placeholder: t("loans.form.insurance_rate_placeholder"),
+ min: 0,
+ step: 0.005 %>
+ <%= loan_form.select :insurance_rate_type,
+ loan_insurance_rate_type_options,
+ { label: t("loans.form.insurance_rate_type"),
+ include_blank: t("loans.form.none") } %>
+ </div>
+ <p class="text-xs text-secondary"><%= t("loans.form.insurance_rate_hint") %></p>
+
<%# Rate changes only mean something for a loan whose rate can move. The
section is rendered for every rate type, retained rows included, and
for fixed it is hidden AND its inputs disabled -- here, server-side,
diff --git a/app/views/loans/tabs/_overview.html.erb b/app/views/loans/tabs/_overview.html.erb
index ba574935fd..b2b2c6f484 100644
--- a/app/views/loans/tabs/_overview.html.erb
+++ b/app/views/loans/tabs/_overview.html.erb
@@ -66,8 +66,45 @@
<%= summary_card title: t(".type") do %>
<%= account.loan.rate_type&.titleize || t(".unknown") %>
<% end %>
+
+ <%# What the loan costs in total: the Schedule tab's "Total Cost" (principal
+ and interest) plus any premium charged beside it. With a premium the
+ title says so, because both tabs render on one page and the same title
+ over two different amounts reads as a mistake. Unknown without a schedule
+ to read interest from, the same condition the payoff date answers with. %>
+ <%= summary_card title: account.loan.insurance.present? ? t(".total_cost_with_insurance") : t(".total_cost") do %>
+ <% total_cost = account.loan.total_cost %>
+ <%= total_cost ? format_money(total_cost) : t(".unknown") %>
+ <% end %>
+
+ <%# Only for a loan carrying a premium. A card reading zero would say the
+ borrower has insurance costing nothing rather than none recorded. A rate
+ saved on a loan with no schedule to project it against still shows, as
+ the rate, rather than vanishing as though the save had been lost. %>
+ <% if account.loan.insurance.present? %>
+ <%= summary_card title: t(".total_insurance") do %>
+ <%= format_money(account.loan.total_insurance) %>
+ <% end %>
+ <% elsif account.loan.insurance_rate&.positive? %>
+ <%= summary_card title: t(".total_insurance") do %>
+ <%= t(".insurance_rate_only", rate: number_to_percentage(account.loan.insurance_rate, strip_insignificant_zeros: true)) %>
+ <% end %>
+ <% end %>
+
+ <%# Leverage needs a down payment to be a ratio at all, and a loan with none
+ recorded is not unleveraged -- it is one nobody has told us about. %>
+ <% if account.loan.initial_leverage_ratio.present? %>
+ <%= summary_card title: t(".leverage") do %>
+ <span class="<%= loan_leverage_band_class(account.loan.leverage_band) %>">
+ <%= t(".leverage_multiple", ratio: number_with_precision(account.loan.initial_leverage_ratio, precision: 1)) %>
+ <span class="text-sm"><%= t(".leverage_band_#{account.loan.leverage_band}") %></span>
+ </span>
+ <% end %>
+ <% end %>
</div>
+<%= render "loans/tabs/repayment_progress", loan: account.loan, as_of: today %>
+
<div class="flex justify-center py-8">
<%= render DS::Link.new(
text: t(".edit_loan_details"),
diff --git a/app/views/loans/tabs/_repayment_progress.html.erb b/app/views/loans/tabs/_repayment_progress.html.erb
new file mode 100644
index 0000000000..6e174e6d1a
--- /dev/null
+++ b/app/views/loans/tabs/_repayment_progress.html.erb
@@ -0,0 +1,65 @@
+<%# locals: (loan:, as_of:) %>
+
+<%# The repayment ring and the instalment the borrower is on. Rendered only
+ when the paydown can be measured -- an account with no balance to compare
+ against what was borrowed gets no ring rather than an empty one. %>
+<% segments = loan.to_donut_segments_json %>
+<%# The instalment for the Overview's own reference date, so this card and the
+ ones above it answer for the same day. %>
+<% breakdown = loan.payment_breakdown(as_of: as_of) %>
+
+<% if segments.present? || breakdown.present? %>
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
+ <% if segments.present? %>
+ <div class="bg-container rounded-lg border border-primary p-4">
+ <p class="text-sm text-secondary mb-2"><%= t(".repaid") %></p>
+
+ <%# The paid arc is declared as the controller's pass-through segment so
+ its `var(--color-warning)` reaches the SVG fill as written. Every
+ other segment goes through `d3.color()`, which returns null for a
+ CSS variable and takes the whole chart down with it. %>
+ <div class="relative h-40"
+ data-controller="donut-chart"
+ data-donut-chart-segments-value="<%= segments %>"
+ data-donut-chart-overage-segment-id-value="paid">
+ <div data-donut-chart-target="chartContainer" class="absolute inset-0 pointer-events-none"></div>
+
+ <div data-donut-chart-target="contentContainer" class="flex justify-center items-center h-full">
+ <div data-donut-chart-target="defaultContent" class="flex flex-col items-center">
+ <p class="text-3xl font-medium text-primary privacy-sensitive">
+ <%= number_to_percentage(loan.balance_paid_ratio * 100, precision: 0) %>
+ </p>
+ <p class="text-sm text-secondary privacy-sensitive"><%= t(".of_original", amount: format_money(loan.original_balance)) %></p>
+ </div>
+ </div>
+ </div>
+ </div>
+ <% end %>
+
+ <% if breakdown.present? %>
+ <div class="bg-container rounded-lg border border-primary p-4">
+ <p class="text-sm text-secondary mb-2">
+ <%= t(".instalment", number: breakdown[:number], date: l(breakdown[:date], format: :long)) %>
+ </p>
+
+ <dl class="space-y-2">
+ <% [ :principal, :interest, :insurance ].each do |part| %>
+ <% next if part == :insurance && breakdown[:insurance].zero? %>
+ <div class="flex items-center justify-between gap-2">
+ <dt class="text-sm text-secondary"><%= t(".#{part}") %></dt>
+ <dd class="text-sm text-primary privacy-sensitive tabular-nums">
+ <%= format_money(breakdown[part]) %>
+ <span class="text-secondary"><%= number_to_percentage(breakdown[:ratios][part] * 100, precision: 0) %></span>
+ </dd>
+ </div>
+ <% end %>
+
+ <div class="flex items-center justify-between gap-2 pt-2 border-t border-primary">
+ <dt class="text-sm text-secondary"><%= t(".total") %></dt>
+ <dd class="text-sm font-medium text-primary privacy-sensitive tabular-nums"><%= format_money(breakdown[:total]) %></dd>
+ </div>
+ </dl>
+ </div>
+ <% end %>
+ </div>
+<% end %>
diff --git a/config/locales/views/loans/en.yml b/config/locales/views/loans/en.yml
index f13dd48d5b..9ec2a754fb 100644
--- a/config/locales/views/loans/en.yml
+++ b/config/locales/views/loans/en.yml
@@ -25,6 +25,13 @@ en:
rate_change_remove: Remove
start_date: Origination date
start_date_hint: When the loan was drawn down. Leave blank to use the account's opening date.
+ down_payment: Down payment
+ insurance_rate: Insurance rate
+ insurance_rate_placeholder: '0.36'
+ insurance_rate_hint: An annual rate, charged monthly alongside the repayment. Level term is charged on the original balance; decreasing on what is still owed.
+ insurance_rate_type: Insurance type
+ insurance_rate_type_decreasing_life: Decreasing
+ insurance_rate_type_level_term: Level term
new:
title: Enter loan details
overview:
@@ -38,6 +45,14 @@ en:
type: Type
unknown: Unknown
tabs:
+ repayment_progress:
+ instalment: Payment %{number} · %{date}
+ insurance: Insurance
+ interest: Interest
+ of_original: of %{amount}
+ principal: Principal
+ repaid: Repaid
+ total: Total
schedule:
date: Date
description: Projected from the original balance, rate and term, starting %{start_date}. Extra payments are not reflected.
@@ -55,12 +70,21 @@ en:
total_cost: Total Cost
total_interest: Total Interest
overview:
+ insurance_rate_only: "%{rate} a year"
interest_rate: Interest Rate
+ leverage: Leverage
+ leverage_band_conservative: Conservative
+ leverage_band_high: High
+ leverage_band_moderate: Moderate
+ leverage_multiple: "%{ratio}x"
monthly_payment: Monthly Payment
not_applicable: N/A
original_payoff_date: Original Payoff Date
original_principal: Original Loan Amount
remaining_principal: Remaining Loan Amount
+ total_cost: Total Cost
+ total_cost_with_insurance: Total Cost incl. Insurance
+ total_insurance: Insurance
term: Term
type: Type
unknown: Unknown
diff --git a/config/locales/views/loans/fr.yml b/config/locales/views/loans/fr.yml
index d585c8da54..b0069cf2cb 100644
--- a/config/locales/views/loans/fr.yml
+++ b/config/locales/views/loans/fr.yml
@@ -12,6 +12,13 @@ fr:
rate_type_adjustable: Révisable
rate_type_fixed: Fixe
rate_type_variable: Variable
+ down_payment: Apport personnel
+ insurance_rate: Taux d'assurance
+ insurance_rate_hint: Un taux annuel, prélevé chaque mois en complément de la mensualité. L'assurance constante porte sur le capital initial, l'assurance dégressive sur le capital restant dû.
+ insurance_rate_placeholder: '0,36'
+ insurance_rate_type: Type d'assurance
+ insurance_rate_type_decreasing_life: Dégressive
+ insurance_rate_type_level_term: Constante
subtype_none: Aucun
subtype_prompt: Sélectionner le type de prêt
term_months: Durée (mois)
@@ -30,11 +37,28 @@ fr:
tabs:
overview:
edit_loan_details: Modifier les détails du prêt
+ insurance_rate_only: "%{rate} par an"
interest_rate: Taux d'intérêt
+ leverage: Effet de levier
+ leverage_band_conservative: Prudent
+ leverage_band_high: Élevé
+ leverage_band_moderate: Modéré
+ leverage_multiple: "%{ratio}x"
monthly_payment: Paiement mensuel
not_applicable: N/D
original_principal: Capital d'origine
remaining_principal: Capital restant
term: Durée
+ total_cost: Coût total
+ total_cost_with_insurance: Coût total assurance comprise
+ total_insurance: Assurance
type: Type
unknown: Inconnu
+ repayment_progress:
+ instalment: Échéance %{number} · %{date}
+ insurance: Assurance
+ interest: Intérêts
+ of_original: sur %{amount}
+ principal: Capital
+ repaid: Remboursé
+ total: Total
diff --git a/db/migrate/20260916210000_add_down_payment_to_loans.rb b/db/migrate/20260916210000_add_down_payment_to_loans.rb
new file mode 100644
index 0000000000..010ac2e2d7
--- /dev/null
+++ b/db/migrate/20260916210000_add_down_payment_to_loans.rb
@@ -0,0 +1,8 @@
+class AddDownPaymentToLoans < ActiveRecord::Migration[8.1]
+ def change
+ add_column :loans, :down_payment, :decimal, precision: 19, scale: 4
+ add_check_constraint :loans,
+ "down_payment IS NULL OR down_payment >= 0",
+ name: "chk_loans_down_payment_non_negative"
+ end
+end
diff --git a/db/migrate/20260916210100_add_insurance_to_loans.rb b/db/migrate/20260916210100_add_insurance_to_loans.rb
new file mode 100644
index 0000000000..26f3726510
--- /dev/null
+++ b/db/migrate/20260916210100_add_insurance_to_loans.rb
@@ -0,0 +1,21 @@
+# A borrower's loan insurance premium, which many lenders quote as part of the
+# monthly instalment. Two shapes cover what lenders sell: a level-term premium
+# charged on the original principal for the life of the loan, and a decreasing
+# premium charged on what is still outstanding.
+#
+# The rate is annual and expressed in percent, like `interest_rate`, so 0.36
+# means 0.36% a year. precision 8/scale 4 holds a rate to a hundredth of a
+# basis point, which is finer than any lender quotes.
+class AddInsuranceToLoans < ActiveRecord::Migration[8.1]
+ def change
+ add_column :loans, :insurance_rate, :decimal, precision: 8, scale: 4
+ add_column :loans, :insurance_rate_type, :string
+
+ add_check_constraint :loans,
+ "insurance_rate IS NULL OR insurance_rate >= 0",
+ name: "chk_loans_insurance_rate_non_negative"
+ add_check_constraint :loans,
+ "insurance_rate_type IS NULL OR insurance_rate_type IN ('level_term', 'decreasing_life')",
+ name: "chk_loans_insurance_rate_type"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 08961cce9f..61fad25e68 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1579,7 +1579,10 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_29_120000) do
create_table "loans", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.datetime "created_at", null: false
+ t.decimal "down_payment", precision: 19, scale: 4
t.decimal "initial_balance", precision: 19, scale: 4
+ t.decimal "insurance_rate", precision: 8, scale: 4
+ t.string "insurance_rate_type"
t.decimal "interest_rate", precision: 10, scale: 3
t.jsonb "locked_attributes", default: {}
t.string "rate_type"
@@ -1588,6 +1591,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_29_120000) do
t.integer "term_months"
t.datetime "updated_at", null: false
t.jsonb "variable_rate_schedule", default: {}, null: false
+ t.check_constraint "down_payment IS NULL OR down_payment >= 0::numeric", name: "chk_loans_down_payment_non_negative"
+ t.check_constraint "insurance_rate IS NULL OR insurance_rate >= 0::numeric", name: "chk_loans_insurance_rate_non_negative"
+ t.check_constraint "insurance_rate_type IS NULL OR (insurance_rate_type::text = ANY (ARRAY['level_term'::character varying, 'decreasing_life'::character varying]::text[]))", name: "chk_loans_insurance_rate_type"
end
create_table "lunchflow_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
diff --git a/test/controllers/loans_controller_test.rb b/test/controllers/loans_controller_test.rb
index 96ac1c4e0b..33854be725 100644
--- a/test/controllers/loans_controller_test.rb
+++ b/test/controllers/loans_controller_test.rb
@@ -8,6 +8,133 @@ class LoansControllerTest < ActionDispatch::IntegrationTest
@account = accounts(:loan)
end
+ # The overview only shows what the loan actually records: a leverage figure
+ # needs a down payment, and an insurance card needs a premium. A loan with
+ # neither must not grow cards reading zero, which would say the borrower has
+ # insurance costing nothing rather than none.
+ test "the overview shows leverage and insurance once they are recorded" do
+ get account_path(@account)
+ assert_response :success
+ assert_no_match(/Leverage/, response.body, "nothing to compute a ratio from yet")
+ # The summary card's own title, not the word: the repayment breakdown below
+ # the cards has an "Insurance" row of its own, which would satisfy a match
+ # on the page body with the card deleted.
+ assert_select "h4", text: "Insurance", count: 0, message: "and no premium recorded"
+
+ @account.loan.update!(
+ down_payment: 100_000, interest_rate: 5, term_months: 120, rate_type: "fixed",
+ start_date: 2.years.ago.to_date, insurance_rate: 0.36, insurance_rate_type: "level_term"
+ )
+
+ get account_path(@account)
+ assert_response :success
+
+ assert_match(/Leverage/, response.body)
+ assert_match(/5\.0x/, response.body, "500,000 borrowed against 100,000 put in")
+ assert_match(/Moderate/, response.body, "and the band that ratio sits in")
+ assert_select "h4", text: "Insurance", count: 1, message: "the insurance summary card"
+ assert_match(/Total Cost/, response.body)
+ assert_select "[data-controller='donut-chart']", count: 1, message: "the repayment ring"
+ # The amount borrowed is money like the ratio beside it, so Privacy Mode
+ # must blur it too.
+ assert_select "[data-controller='donut-chart'] p.privacy-sensitive", text: /of \$500,000/, count: 1
+ end
+
+ # The Schedule tab's "Total Cost" is what the borrower repays: principal plus
+ # interest. Both tabs render in one request, so the Overview's card must
+ # either show that same figure or say what it adds -- a premium folded in
+ # under the same title put two different "Total Cost" amounts on one page.
+ test "the overview's total cost agrees with the schedule's and names the premium it adds" do
+ loan = @account.loan
+ loan.update!(interest_rate: 5, term_months: 120, rate_type: "fixed", start_date: 2.years.ago.to_date)
+
+ get account_path(@account)
+ uninsured = card_values("Total Cost")
+ assert_equal 2, uninsured.size, "precondition: the Overview and Schedule tabs each render the card"
+ assert_equal 1, uninsured.uniq.size, "with no premium the two figures are the same figure"
+
+ loan.update!(insurance_rate: 0.36, insurance_rate_type: "level_term")
+ loan = Loan.find(loan.id)
+
+ get account_path(@account)
+ assert_equal uninsured.first(1), card_values("Total Cost"),
+ "one card still calls itself Total Cost, and it has not moved"
+ assert_equal [ format_money(loan.amortization_schedule.total_paid + loan.total_insurance) ],
+ card_values("Total Cost incl. Insurance"),
+ "the Overview names the premium it adds, and adds it to the Schedule's figure"
+ end
+
+ # A rate saved on a loan with no term has no schedule to project a premium
+ # against. The card must still say a policy is recorded rather than vanish,
+ # which read as though the save had been lost.
+ test "a recorded insurance rate shows even when no premium can be projected" do
+ @account.loan.update!(term_months: nil, insurance_rate: 0.36, insurance_rate_type: "level_term")
+ assert_nil Loan.find(@account.loan.id).insurance, "precondition: nothing to project against"
+
+ get account_path(@account)
+ assert_response :success
+ assert_equal [ "0.36% a year" ], card_values("Insurance")
+ end
+
+ # A negative opening valuation (imports produce them) has no leverage band,
+ # and the card built its label from the band -- a key that does not exist.
+ test "a negative opening balance shows no leverage card rather than a missing translation" do
+ @account.loan.update!(down_payment: 100_000)
+ @account.entries.create!(
+ date: Date.current - 2.years, name: "Opening balance", amount: -500_000, currency: @account.currency,
+ entryable: Valuation.new(kind: "opening_anchor")
+ )
+ assert @account.loan.original_balance.negative?, "precondition: the opening balance is negative"
+
+ get account_path(@account)
+ assert_response :success
+ assert_no_match(/translation missing: en\.loans/, response.body)
+ assert_select "h4", text: "Leverage", count: 0
+ end
+
+ # The form renders these fields, so a save must keep them. Measured against
+ # the loan's own state before the request: all three start blank.
+ test "updates the down payment and insurance terms from the form" do
+ loan = @account.loan
+ assert_nil loan.down_payment
+ assert_nil loan.insurance_rate
+ assert_nil loan.insurance_rate_type
+
+ patch loan_path(@account), params: {
+ account: {
+ accountable_type: "Loan",
+ accountable_attributes: {
+ id: @account.accountable_id,
+ down_payment: "100000", insurance_rate: "0.36", insurance_rate_type: "level_term"
+ }
+ }
+ }
+
+ assert_redirected_to @account
+ loan.reload
+ assert_equal BigDecimal("100000"), loan.down_payment
+ assert_equal BigDecimal("0.36"), loan.insurance_rate
+ assert_equal "level_term", loan.insurance_rate_type
+ end
+
+ # The type select's blank option is the form's "None": no type recorded, read
+ # as decreasing. It submits an empty string, which must clear the type rather
+ # than fail validation (and the column's check constraint, which admits NULL
+ # but not '').
+ test "the insurance type's blank option clears a recorded type" do
+ @account.loan.update!(insurance_rate: 0.36, insurance_rate_type: "level_term")
+
+ patch loan_path(@account), params: {
+ account: {
+ accountable_type: "Loan",
+ accountable_attributes: { id: @account.accountable_id, insurance_rate_type: "" }
+ }
+ }
+
+ assert_redirected_to @account
+ assert_nil @account.loan.reload.insurance_rate_type
+ end
+
test "creates with loan details" do
assert_difference -> { Account.count } => 1,
-> { Loan.count } => 1,
@@ -746,4 +873,13 @@ class LoansControllerTest < ActionDispatch::IntegrationTest
entryable: Valuation.new(kind: "opening_anchor")
)
end
+
+ # The figure under every summary card titled exactly `title`, in page order.
+ def card_values(title)
+ css_select("h4").select { |h4| h4.text.strip == title }.map { |h4| h4.next_element.text.strip }
+ end
+
+ def format_money(money)
+ ApplicationController.helpers.format_money(money)
+ end
end
diff --git a/test/models/demo/generator_test.rb b/test/models/demo/generator_test.rb
index fdf7ca90dc..5058d38f56 100644
--- a/test/models/demo/generator_test.rb
+++ b/test/models/demo/generator_test.rb
@@ -97,6 +97,13 @@ class Demo::GeneratorTest < ActiveSupport::TestCase
assert mortgage.amortization_schedule.re_amortising?,
"a recorded rate change must move the demo mortgage's repayment"
+ # The leverage card reads the loan's down payment; the cash-flow history
+ # records the deposit as a transaction. The two must be the same figure.
+ checking = generator.instance_variable_get(:@chase_checking)
+ deposit = checking.entries.find_by!(name: "Home Down Payment")
+ assert_equal deposit.amount, mortgage.down_payment,
+ "the mortgage's down payment must match the deposit the demo records"
+
[ "Car Loan", "Student Loan" ].each do |name|
loan = @family.accounts.find_by!(name: name).loan
assert_not loan.variable_rate_type?, "#{name} should be fixed"
diff --git a/test/models/loan_insurance_test.rb b/test/models/loan_insurance_test.rb
new file mode 100644
index 0000000000..75e2e1a28d
--- /dev/null
+++ b/test/models/loan_insurance_test.rb
@@ -0,0 +1,112 @@
+require "test_helper"
+
+class LoanInsuranceTest < ActiveSupport::TestCase
+ # 12,000 over 12 months at 0% interest repays 1,000 a month, so every
+ # outstanding balance in the schedule is a round number and each premium is
+ # hand-computable. 1.2% a year is 0.1% a month.
+ def build_loan(insurance_rate:, insurance_rate_type:, balance: 12_000, term: 12, rate: 0)
+ account = Account.create!(
+ family: families(:dylan_family),
+ name: "Insured Loan #{SecureRandom.hex(3)}",
+ balance: balance,
+ currency: "USD",
+ accountable: Loan.create!(
+ subtype: "mortgage",
+ interest_rate: rate,
+ term_months: term,
+ rate_type: "fixed",
+ start_date: Date.new(2026, 1, 1),
+ insurance_rate: insurance_rate,
+ insurance_rate_type: insurance_rate_type
+ )
+ )
+ account.loan
+ end
+
+ # A level-term premium is charged on what was borrowed, for the life of the
+ # loan, so it does not fall as the loan is repaid: 12,000 * 0.1% = 12 every
+ # month, twelve times.
+ test "a level-term premium is charged on the original principal every period" do
+ loan = build_loan(insurance_rate: 1.2, insurance_rate_type: "level_term")
+
+ amounts = loan.insurance.premiums.map { |premium| premium.amount.amount }
+
+ assert_equal 12, amounts.size
+ assert_equal [ BigDecimal(12) ] * 12, amounts, "a level premium does not decrease"
+ assert_equal BigDecimal(144), loan.total_insurance.amount
+ end
+
+ # A decreasing premium is charged on what is still outstanding at the START
+ # of the period: 12,000 in month one, then 11,000, and so on to 1,000.
+ test "a decreasing premium follows the outstanding balance" do
+ loan = build_loan(insurance_rate: 1.2, insurance_rate_type: "decreasing_life")
+
+ amounts = loan.insurance.premiums.map { |premium| premium.amount.amount }
+
+ assert_equal (1..12).map { |month| BigDecimal(13 - month) }, amounts
+ assert_equal BigDecimal(78), loan.total_insurance.amount, "12 + 11 + ... + 1"
+ end
+
+ # A rate with no type recorded is read as decreasing, which never overstates
+ # the cost of a policy the borrower has not described.
+ test "a premium with no type recorded is read as decreasing" do
+ loan = build_loan(insurance_rate: 1.2, insurance_rate_type: nil)
+
+ assert_equal BigDecimal(78), loan.total_insurance.amount
+ assert_not loan.insurance.level_term?
+ end
+
+ test "no premium is recorded, so there is nothing to charge" do
+ loan = build_loan(insurance_rate: nil, insurance_rate_type: nil)
+
+ assert_nil loan.insurance
+ assert_equal BigDecimal(0), loan.total_insurance.amount, "money, not nil, so a view can add it"
+ assert_equal "USD", loan.total_insurance.currency.iso_code
+ end
+
+ # The cost of the loan is what the schedule has the borrower repay -- the
+ # Schedule tab's own "Total Cost" -- plus the premium beside it. The premium
+ # is NOT inside the instalment, so it has to be added rather than read off
+ # the schedule's total. Measured as a delta: the same loan with and without
+ # the policy.
+ test "the total cost is the schedule's total plus the premium" do
+ loan = build_loan(insurance_rate: nil, insurance_rate_type: nil,
+ balance: 12_000, term: 12, rate: 6)
+ schedule = loan.amortization_schedule
+
+ assert_operator schedule.total_interest.amount, :>, 0, "or this proves nothing about interest"
+ assert_equal schedule.total_paid, loan.total_cost, "no premium: the Schedule tab's figure exactly"
+
+ uninsured = loan.total_cost
+ loan.insurance_rate = 1.2
+ loan.insurance_rate_type = "level_term"
+
+ assert_equal BigDecimal(144), (loan.total_cost - uninsured).amount,
+ "the policy adds its premium and nothing else; a level premium does not care what the interest rate is"
+ end
+
+ test "a loan with nothing to amortise has no cost to report" do
+ loan = build_loan(insurance_rate: 1.2, insurance_rate_type: "level_term", term: 0)
+
+ assert_nil loan.amortization_schedule
+ assert_nil loan.insurance
+ assert_nil loan.total_cost, "nil rather than a cost with no interest in it"
+ end
+
+ # The memo has to drop when either the premium's own inputs or the schedule's
+ # change, or a loan re-read after an edit answers with the old policy.
+ test "changing a rate drops the memoised premium" do
+ loan = build_loan(insurance_rate: 1.2, insurance_rate_type: "level_term")
+
+ assert_equal BigDecimal(144), loan.total_insurance.amount
+
+ loan.insurance_rate = 2.4
+ assert_equal BigDecimal(288), loan.total_insurance.amount, "the premium's own input"
+
+ loan.insurance_rate_type = "decreasing_life"
+ assert_equal BigDecimal(156), loan.total_insurance.amount, "and its type"
+
+ loan.term_months = 6
+ assert_equal 6, loan.insurance.premiums.size, "and the schedule it is charged against"
+ end
+end
diff --git a/test/models/loan_progress_test.rb b/test/models/loan_progress_test.rb
new file mode 100644
index 0000000000..652bd09ee1
--- /dev/null
+++ b/test/models/loan_progress_test.rb
@@ -0,0 +1,201 @@
+require "test_helper"
+
+class LoanProgressTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ # 12,000 over 12 months at 0%: 1,000 of principal a month, so every figure
+ # below is hand-computable and a wrong split shows up as a round number in
+ # the wrong column.
+ setup do
+ @account = Account.create!(
+ family: families(:dylan_family),
+ name: "Progress Loan",
+ balance: 12_000,
+ currency: "USD",
+ accountable: Loan.create!(
+ subtype: "auto", interest_rate: 0, term_months: 12,
+ rate_type: "fixed", start_date: Date.new(2026, 1, 15)
+ )
+ )
+ @loan = @account.loan
+ end
+
+ # A month counts once it has been SERVED. Originated on 15 January, the loan
+ # is not one month in on 1 February -- it is on 15 February.
+ test "a month counts once it has been served in full" do
+ assert_equal 0, @loan.months_elapsed(as_of: Date.new(2026, 1, 15))
+ assert_equal 0, @loan.months_elapsed(as_of: Date.new(2026, 2, 14))
+ assert_equal 1, @loan.months_elapsed(as_of: Date.new(2026, 2, 15))
+ assert_equal 6, @loan.months_elapsed(as_of: Date.new(2026, 7, 20))
+ end
+
+ test "nothing has elapsed before the loan was drawn down" do
+ assert_equal 0, @loan.months_elapsed(as_of: Date.new(2025, 12, 1))
+ end
+
+ # Elapsed is clamped to the term and remaining floors at zero: a loan running
+ # past its last payment is finished, not further in than it can be.
+ test "a loan past its term is finished, not overrun" do
+ past = Date.new(2028, 1, 15)
+
+ assert_equal 12, @loan.months_elapsed(as_of: past)
+ assert_equal 0, @loan.remaining_months(as_of: past)
+ assert @loan.finished?(as_of: past)
+ assert_not @loan.finished?(as_of: Date.new(2026, 7, 15))
+ assert_equal 6, @loan.remaining_months(as_of: Date.new(2026, 7, 15))
+ end
+
+ test "a loan with no term has no remaining months to report" do
+ @loan.term_months = nil
+
+ assert_nil @loan.remaining_months
+ assert_nil @loan.finished?
+ end
+
+ # Read off the schedule rather than re-derived, so it cannot drift from the
+ # table beside it.
+ test "the remaining balance comes from the schedule" do
+ assert_equal BigDecimal(11_000), @loan.remaining_balance_at(1).amount
+ assert_equal BigDecimal(6_000), @loan.remaining_balance_at(6).amount
+ assert_equal BigDecimal(0), @loan.remaining_balance_at(12).amount
+ assert_nil @loan.remaining_balance_at(13), "there is no thirteenth payment"
+ assert_nil @loan.remaining_balance_at(0)
+ end
+
+ test "one instalment splits into principal, interest and premium" do
+ @loan.insurance_rate = 1.2
+ @loan.insurance_rate_type = "level_term"
+
+ breakdown = @loan.payment_breakdown(payment_number: 1)
+
+ assert_equal 1, breakdown[:number]
+ assert_equal BigDecimal(1_000), breakdown[:principal].amount
+ assert_equal BigDecimal(0), breakdown[:interest].amount, "a 0% loan charges none"
+ assert_equal BigDecimal(12), breakdown[:insurance].amount
+ assert_equal BigDecimal(1_012), breakdown[:total].amount
+ assert_in_delta 1_000.0 / 1_012, breakdown[:ratios][:principal], 0.0001
+ assert_in_delta 12.0 / 1_012, breakdown[:ratios][:insurance], 0.0001
+ end
+
+ # The default is the instalment the loan is CURRENTLY on, which is the one a
+ # borrower is about to pay, not the one they last paid.
+ test "the breakdown defaults to the payment the loan is on" do
+ travel_to Date.new(2026, 4, 20) do
+ assert_equal 4, @loan.payment_breakdown[:number]
+ end
+ end
+
+ # A finished loan is on no instalment. Defaulting to months_elapsed + 1 asks
+ # for payment 13 of 12, and the clamp below would answer with the final
+ # payment, presenting a paid instalment as the one the borrower is on.
+ test "a finished loan has no current instalment to break down" do
+ travel_to Date.new(2027, 2, 15) do
+ assert @loan.finished?, "precondition: past the twelfth payment"
+ assert_nil @loan.payment_breakdown
+ end
+
+ travel_to Date.new(2026, 12, 20) do
+ assert_not @loan.finished?, "the month before, the loan is still running"
+ assert_equal 12, @loan.payment_breakdown[:number], "and is on its last payment"
+ end
+ end
+
+ # The reference date is the caller's, like every other progress reader's: an
+ # overview that captured one date for its cards must get the instalment for
+ # that date, not for whatever the clock says when the partial renders.
+ test "the current instalment is the one for the date asked about" do
+ assert_equal 4, @loan.payment_breakdown(as_of: Date.new(2026, 4, 20))[:number]
+ assert_equal 7, @loan.payment_breakdown(as_of: Date.new(2026, 7, 20))[:number]
+ assert_nil @loan.payment_breakdown(as_of: Date.new(2027, 2, 15)), "finished by then"
+ end
+
+ # Rounding can clear the balance before the term ends, leaving the schedule
+ # shorter than term_months. Once its last payment is behind the borrower
+ # there is no current instalment, even though the term is still running; the
+ # clamp below would otherwise present the final, paid one as current.
+ test "a loan whose schedule ended before its term has no current instalment" do
+ short = @loan.amortization_schedule.payments.first(10)
+ @loan.amortization_schedule.stubs(:payments).returns(short)
+
+ assert_equal 10, @loan.payment_breakdown(as_of: Date.new(2026, 10, 20))[:number], "still on its last payment"
+ assert_not @loan.finished?(as_of: Date.new(2026, 11, 20)), "precondition: the term runs on"
+ assert_nil @loan.payment_breakdown(as_of: Date.new(2026, 11, 20)), "but the schedule has nothing left"
+ end
+
+ test "a payment number past the end clamps to the last instalment" do
+ assert_equal 12, @loan.payment_breakdown(payment_number: 99)[:number]
+ end
+
+ test "a loan with nothing to amortise has no breakdown" do
+ @loan.term_months = 0
+
+ assert_nil @loan.payment_breakdown
+ end
+
+ # Measured against the account's balance, not the schedule: the schedule says
+ # what was promised, the balance says what happened.
+ #
+ # The fixture records what was BORROWED as a valuation at drawdown and then
+ # moves the account's balance column directly.
+ #
+ # `account.update!(balance:)` and the current-balance anchor both rewrite the
+ # account's only valuation, and with no valuation at all
+ # #first_valuation_amount falls back to the current balance -- either way
+ # original_balance tracks the current balance and the ratio is always zero,
+ # so the fixture would be measuring nothing.
+ test "paydown is measured against the balance, not the schedule" do
+ assert_equal 0.0, @loan.balance_paid_ratio
+
+ record_balance(3_000)
+
+ assert_equal BigDecimal(12_000), reloaded_loan.original_balance.amount, "the opening balance stands"
+ assert_in_delta 0.75, reloaded_loan.balance_paid_ratio, 0.0001
+
+ segments = reloaded_loan.to_donut_segments
+ assert_in_delta 0.75, segments.first[:amount], 0.0001
+ assert_in_delta 0.25, segments.second[:amount], 0.0001
+ end
+
+ # A negative balance is the same debt written with the other sign, which
+ # imports and manual entry both produce.
+ # A fresh read through the account, because balance_paid_ratio asks the
+ # ACCOUNT for its balance and a loan holding a stale association would answer
+ # with the balance it was loaded with.
+ def reloaded_loan
+ Account.find(@account.id).loan
+ end
+
+ # A later valuation, which is what a repayment recorded against a manual loan
+ # looks like. Dated after the opening one so #first_valuation -- which is
+ # date-ordered -- still answers with what was borrowed.
+ def record_balance(amount)
+ unless @opening_recorded
+ create_valuation(account: @account, amount: 12_000, date: Date.new(2026, 1, 15), currency: "USD")
+ @opening_recorded = true
+ end
+
+ @account.update_column(:balance, amount)
+ @account.reload
+ end
+
+ test "a debt recorded negative reads the same as one recorded positive" do
+ record_balance(-3_000)
+
+ assert_in_delta 0.75, reloaded_loan.balance_paid_ratio, 0.0001
+ end
+
+ test "a cleared loan is fully repaid" do
+ record_balance(0)
+
+ assert_equal 1.0, reloaded_loan.balance_paid_ratio
+ end
+
+ # A balance above what was borrowed -- arrears, capitalised interest, a
+ # redraw -- is no progress rather than negative progress. The ring cannot
+ # draw a negative arc and the figure would read as a gain.
+ test "owing more than was borrowed is not negative progress" do
+ record_balance(15_000)
+
+ assert_equal 0.0, reloaded_loan.balance_paid_ratio
+ end
+end
diff --git a/test/models/loan_test.rb b/test/models/loan_test.rb
index 1d5d2fb985..5beddd1bd1 100644
--- a/test/models/loan_test.rb
+++ b/test/models/loan_test.rb
@@ -1,6 +1,61 @@
require "test_helper"
class LoanTest < ActiveSupport::TestCase
+ # Leverage is what the down payment is FOR: 80,000 borrowed against 20,000 put
+ # in is 4x, and the same loan against 5,000 is 16x. Bands are read off the
+ # ratio rather than stored, so a loan re-read after an edit cannot disagree
+ # with its own figure.
+ test "leverage is the borrowed amount over the down payment" do
+ loan = build_loan_account(balance: 80_000, down_payment: 20_000).loan
+
+ assert_in_delta 4.0, loan.initial_leverage_ratio, 0.001
+ assert_equal :conservative, loan.leverage_band, "4x sits on the conservative boundary"
+
+ loan.down_payment = 5_000
+ assert_in_delta 16.0, loan.initial_leverage_ratio, 0.001
+ assert_equal :high, loan.leverage_band
+ end
+
+ test "a moderate loan lands in the middle band" do
+ loan = build_loan_account(balance: 80_000, down_payment: 16_000).loan
+
+ assert_in_delta 5.0, loan.initial_leverage_ratio, 0.001
+ assert_equal :moderate, loan.leverage_band
+ end
+
+ # No deposit recorded is not a deposit of zero: a loan nobody has told us
+ # about is not infinitely leveraged, and a view must be able to tell the two
+ # apart to decide whether to show the figure at all.
+ test "a loan with no down payment recorded has no leverage figure" do
+ loan = build_loan_account(balance: 80_000, down_payment: nil).loan
+
+ assert_nil loan.initial_leverage_ratio
+ assert_nil loan.leverage_band
+
+ loan.down_payment = 0
+ assert_nil loan.initial_leverage_ratio, "zero is not a deposit either"
+ end
+
+ # Imports can open a loan at a negative valuation. That is no amount borrowed
+ # to measure a deposit against, and a ratio from it has no band to name.
+ test "a negative opening balance has no leverage figure" do
+ loan = loans(:one)
+ loan.down_payment = 100_000
+ loan.stubs(:original_balance).returns(Money.new(-500_000, "USD"))
+
+ assert_nil loan.initial_leverage_ratio
+ assert_nil loan.leverage_band
+ end
+
+ test "rejects a negative down payment or insurance rate" do
+ loan = Loan.new(down_payment: -1, insurance_rate: -1, insurance_rate_type: "nonsense")
+
+ assert_not loan.valid?
+ assert_includes loan.errors[:down_payment], "must be greater than or equal to 0"
+ assert_includes loan.errors[:insurance_rate], "must be greater than or equal to 0"
+ assert_includes loan.errors[:insurance_rate_type], "is not included in the list"
+ end
+
test "rejects invalid subtype" do
loan = Loan.new(subtype: "invalid")
@@ -107,4 +162,106 @@ class LoanTest < ActiveSupport::TestCase
loan.start_date = nil
assert loan.valid?
end
+
+ # An imported loan is the case where what was borrowed and what has been seen
+ # are different numbers. Plaid sends `origination_principal_amount`, which
+ # lands in `initial_balance`; the first valuation the account carries is
+ # whatever the balance was on the day it was linked, years of repayments in.
+ #
+ # 20,000 borrowed, 10,000 outstanding, 5,000 deposit, a level-term policy at
+ # 0.36% a year. Every figure below was measured against the 10,000 before
+ # this: the schedule amortised half a loan, the borrower had repaid "none" of
+ # it, the deposit looked twice as effective as it was, and the premium was
+ # half what the policy charges.
+ # Four separate tests rather than four assertions, so each figure is observed
+ # to fail on its own: one of them failing first would otherwise hide the rest.
+ test "the principal is the recorded one, not the first tracked balance" do
+ loan = build_imported_loan_account.loan
+
+ assert_equal 20_000, loan.original_balance.amount
+ end
+
+ test "the schedule amortises what was borrowed" do
+ loan = build_imported_loan_account.loan
+
+ repaid = loan.amortization_schedule.payments.sum(BigDecimal("0")) { |payment| payment.principal.amount }
+
+ assert_in_delta 20_000, repaid, 1, "half a loan was being amortised"
+ end
+
+ test "repaid is measured against what was borrowed" do
+ loan = build_imported_loan_account.loan
+
+ assert_in_delta 0.5, loan.balance_paid_ratio, 0.0001, "10,000 outstanding on 20,000 borrowed is half repaid"
+ end
+
+ test "leverage is measured against what was borrowed" do
+ loan = build_imported_loan_account.loan
+
+ assert_in_delta 4.0, loan.initial_leverage_ratio, 0.001, "20,000 against a 5,000 deposit"
+ end
+
+ test "a level-term premium is charged on what was borrowed" do
+ loan = build_imported_loan_account.loan
+
+ assert_equal 6, Loan::Insurance.for(loan).premium_for(1).amount.amount, "0.36% a year on 20,000"
+ end
+
+ # The fallback, which is every loan created here: no principal is recorded
+ # separately from the opening valuation, and the two must not disagree.
+ test "a loan with no recorded principal still reads its first valuation" do
+ loan = build_loan_account(balance: 80_000, down_payment: 20_000).loan
+
+ assert_nil loan.initial_balance
+ assert_equal 80_000, loan.original_balance.amount
+ end
+
+ # An import can write either, and neither is an amount borrowed, so both fall
+ # back rather than producing a zero or a negative principal.
+ test "a zero or negative recorded principal falls back to the first valuation" do
+ account = build_loan_account(balance: 80_000, down_payment: 20_000)
+
+ account.loan.update!(initial_balance: 0)
+ assert_equal 80_000, account.loan.reload.original_balance.amount
+
+ account.loan.update!(initial_balance: -5_000)
+ assert_equal 80_000, account.loan.reload.original_balance.amount
+ end
+
+ private
+ # A loan imported part way through its life: the principal it was written
+ # for is recorded, and the only valuation the account carries is the
+ # balance on the day it was linked.
+ def build_imported_loan_account
+ account = Account.create!(
+ family: families(:dylan_family),
+ name: "Imported #{SecureRandom.hex(3)}",
+ balance: 10_000,
+ currency: "USD",
+ accountable: Loan.create!(
+ subtype: "mortgage", interest_rate: 5, term_months: 120, rate_type: "fixed",
+ initial_balance: 20_000, down_payment: 5_000,
+ insurance_rate: 0.36, insurance_rate_type: "level_term",
+ start_date: 5.years.ago.to_date
+ )
+ )
+ account.entries.create!(
+ name: "Starting balance", amount: 10_000, currency: "USD",
+ date: 5.years.ago.to_date, entryable: Valuation.new(kind: "opening_anchor")
+ )
+ account
+ end
+
+ def build_loan_account(balance:, down_payment:)
+ Account.create!(
+ family: families(:dylan_family),
+ name: "Leveraged #{SecureRandom.hex(3)}",
+ balance: balance,
+ currency: "USD",
+ accountable: Loan.create!(
+ subtype: "mortgage", interest_rate: 5, term_months: 120,
+ rate_type: "fixed", down_payment: down_payment
+ )
+ )
+ end
end
diff --git a/test/models/plaid_account/liabilities/student_loan_processor_test.rb b/test/models/plaid_account/liabilities/student_loan_processor_test.rb
index 53819044f5..0fca641809 100644
--- a/test/models/plaid_account/liabilities/student_loan_processor_test.rb
+++ b/test/models/plaid_account/liabilities/student_loan_processor_test.rb
@@ -33,6 +33,123 @@ class PlaidAccount::Liabilities::StudentLoanProcessorTest < ActiveSupport::TestC
assert_equal 24, loan.term_months
end
+ # The payload has carried the drawdown date all along and nothing wrote it
+ # down, so every imported loan looked originated on import day.
+ test "records the provider's origination date as the loan's start date" do
+ @plaid_account.update!(raw_liabilities_payload: {
+ student: {
+ interest_rate_percentage: 5.5,
+ origination_principal_amount: 20000,
+ origination_date: Date.new(2020, 1, 1),
+ expected_payoff_date: Date.new(2022, 1, 1)
+ }
+ })
+
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(@plaid_account).process
+
+ assert_equal Date.new(2020, 1, 1), @plaid_account.current_account.loan.start_date
+ end
+
+ # A borrower who corrected the drawdown by hand knows something the provider
+ # does not.
+ test "a start date already recorded is not overwritten by the sync" do
+ @plaid_account.current_account.loan.update!(start_date: Date.new(2019, 3, 4))
+ @plaid_account.update!(raw_liabilities_payload: {
+ student: {
+ interest_rate_percentage: 5.5,
+ origination_principal_amount: 20000,
+ origination_date: Date.new(2020, 1, 1),
+ expected_payoff_date: Date.new(2022, 1, 1)
+ }
+ })
+
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(@plaid_account).process
+
+ assert_equal Date.new(2019, 3, 4), @plaid_account.current_account.loan.start_date
+ end
+
+ # A payoff less than a month after origination is zero months. Stored
+ # as nil, because a term of no months is not a term -- and the rest of the
+ # payload must still land rather than being lost with it.
+ test "a term of under a month is no term, and does not cost the rest of the sync" do
+ @plaid_account.update!(raw_liabilities_payload: {
+ student: {
+ interest_rate_percentage: 6.25,
+ origination_principal_amount: 900,
+ origination_date: Date.new(2026, 1, 1),
+ expected_payoff_date: Date.new(2026, 1, 20)
+ }
+ })
+
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(@plaid_account).process
+
+ loan = @plaid_account.current_account.loan
+
+ assert_nil loan.term_months
+ assert_equal 6.25, loan.interest_rate, "the rest of the payload still lands"
+ assert_equal 900, loan.initial_balance
+ end
+
+ # Counted in calendar months, not 30-day blocks: thirty years is 10,958 days,
+ # which divided by 30 made a 360-month loan a 365-month one and put its payoff
+ # date and current instalment five months out.
+ test "the term is counted in calendar months" do
+ @plaid_account.update!(raw_liabilities_payload: {
+ student: {
+ interest_rate_percentage: 5.5,
+ origination_principal_amount: 20000,
+ origination_date: Date.new(2000, 1, 1),
+ expected_payoff_date: Date.new(2030, 1, 1)
+ }
+ })
+
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(@plaid_account).process
+
+ assert_equal 360, @plaid_account.current_account.loan.term_months
+ end
+
+ # Both sides of the boundary: a month counts once it has been served in full,
+ # which is how Loan#months_elapsed counts the same loan's progress.
+ test "a term month counts once it is served in full" do
+ [ [ Date.new(2026, 2, 24), nil ], [ Date.new(2026, 2, 25), 1 ], [ Date.new(2027, 1, 24), 11 ] ].each do |payoff, expected|
+ @plaid_account.update!(raw_liabilities_payload: {
+ student: {
+ interest_rate_percentage: 5.5,
+ origination_principal_amount: 20000,
+ origination_date: Date.new(2026, 1, 25),
+ expected_payoff_date: payoff
+ }
+ })
+
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(@plaid_account).process
+
+ assert_equal expected, @plaid_account.current_account.loan.reload.term_months, "payoff on #{payoff}"
+ end
+ end
+
+ # A loan cannot start in the future (Loan validates it), and a provider date
+ # that says otherwise must not fail the whole liabilities sync with it. The
+ # date is left unrecorded and the rest of the payload lands.
+ test "a future origination date is not recorded and does not fail the sync" do
+ travel_to Date.new(2026, 1, 10) do
+ @plaid_account.update!(raw_liabilities_payload: {
+ student: {
+ interest_rate_percentage: 5.5,
+ origination_principal_amount: 20000,
+ origination_date: Date.new(2026, 3, 1),
+ expected_payoff_date: Date.new(2036, 3, 1)
+ }
+ })
+
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(@plaid_account).process
+
+ loan = @plaid_account.current_account.loan.reload
+ assert_nil loan.start_date
+ assert_equal 5.5, loan.interest_rate, "the rest of the payload still lands"
+ assert_equal 120, loan.term_months
+ end
+ end
+
test "handles missing payoff dates gracefully" do
@plaid_account.update!(raw_liabilities_payload: {
student: {
@@ -53,6 +170,35 @@ class PlaidAccount::Liabilities::StudentLoanProcessorTest < ActiveSupport::TestC
assert_equal 15000, loan.initial_balance
end
+ # End to end: what the processor writes has to be what the loan then measures
+ # itself against. The account carries a balance part way through the term --
+ # which is all an import ever sees -- and the figures on the overview read the
+ # origination principal the payload sent, not that balance.
+ test "an imported loan measures its figures against the principal Plaid sent" do
+ @plaid_account.update!(raw_liabilities_payload: {
+ student: {
+ interest_rate_percentage: 5.0,
+ origination_principal_amount: 20_000,
+ origination_date: 5.years.ago.to_date,
+ expected_payoff_date: 5.years.from_now.to_date
+ }
+ })
+ account = @plaid_account.current_account
+ account.update!(balance: 10_000)
+ account.entries.create!(
+ name: "Starting balance", amount: 10_000, currency: account.currency,
+ date: 5.years.ago.to_date, entryable: Valuation.new(kind: "opening_anchor")
+ )
+
+ PlaidAccount::Liabilities::StudentLoanProcessor.new(@plaid_account).process
+
+ loan = account.reload.loan
+
+ assert_equal 20_000, loan.initial_balance
+ assert_equal 20_000, loan.original_balance.amount, "the overview reads the origination principal"
+ assert_in_delta 0.5, loan.balance_paid_ratio, 0.0001
+ end
+
test "does nothing when loan data absent" do
@plaid_account.update!(raw_liabilities_payload: {})
diff --git a/test/system/loan_overview_test.rb b/test/system/loan_overview_test.rb
new file mode 100644
index 0000000000..b33673f8e2
--- /dev/null
+++ b/test/system/loan_overview_test.rb
@@ -0,0 +1,36 @@
+require "application_system_test_case"
+
+class LoanOverviewTest < ApplicationSystemTestCase
+ setup do
+ sign_in @user = users(:family_admin)
+ @account = accounts(:loan)
+ @account.loan.update!(
+ subtype: "mortgage", rate_type: "fixed", interest_rate: 5.25, term_months: 360,
+ start_date: 3.years.ago.to_date, down_payment: 100_000,
+ insurance_rate: 0.36, insurance_rate_type: "level_term"
+ )
+ @account.entries.create!(
+ name: "Drawdown", date: 3.years.ago.to_date, amount: 500_000, currency: "USD",
+ entryable: Valuation.new(kind: "opening_anchor")
+ )
+ @account.update_column(:balance, 415_000)
+ end
+
+ # The ring is the one part of this tab a request test cannot see. Its colours
+ # are CSS variables, and the donut controller passes a colour through to the
+ # SVG fill ONLY for the segment ids it is told to -- every other one goes
+ # through `d3.color()`, which returns null for `var(...)` and takes the whole
+ # chart down with it. The arc simply does not appear, and every server-side
+ # assertion still passes.
+ test "the repayment ring draws its arc" do
+ visit account_url(@account)
+ click_on "Overview"
+
+ assert_text "Repaid"
+ assert_text "17%"
+
+ within "[data-controller='donut-chart']" do
+ assert_selector "svg path", minimum: 1, wait: 5
+ end
+ end
+end
diff --git a/test/views/loans/overview_view_test.rb b/test/views/loans/overview_view_test.rb
new file mode 100644
index 0000000000..56a4ce685d
--- /dev/null
+++ b/test/views/loans/overview_view_test.rb
@@ -0,0 +1,29 @@
+require "test_helper"
+
+# The Overview tab captures one reference date and every date-sensitive figure
+# on it -- the repayment card's current instalment included -- answers for it.
+class LoanOverviewViewTest < ActionView::TestCase
+ helper AccountsHelper, LoansHelper
+
+ setup do
+ @account = Account.create!(
+ family: families(:dylan_family),
+ name: "Overview Loan",
+ balance: 12_000,
+ currency: "USD",
+ accountable: Loan.create!(
+ subtype: "auto", interest_rate: 0, term_months: 12,
+ rate_type: "fixed", start_date: Date.new(2026, 1, 15)
+ )
+ )
+ end
+
+ test "the current instalment is the one for the page's date, not the clock's" do
+ travel_to Date.new(2026, 9, 28) do
+ render partial: "loans/tabs/overview", locals: { account: @account, as_of: Date.new(2026, 4, 20) }
+ end
+
+ assert_includes rendered, "Payment 4 ·", "the instalment on the page's date"
+ assert_not_includes rendered, "Payment 9 ·", "not the one the clock is on"
+ end
+end