Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(loans): amortisation engine and variable-rate loans (#3473)

jaysbeekay117dd80c128d
diff --git a/app/controllers/concerns/accountable_resource.rb b/app/controllers/concerns/accountable_resource.rb
index 1b3e8c040f..083e70fe27 100644
--- a/app/controllers/concerns/accountable_resource.rb
+++ b/app/controllers/concerns/accountable_resource.rb
@@ -56,30 +56,74 @@ module AccountableResource
return_path = safe_return_to(account_params[:return_to]) || session.delete(:return_to).presence || @account
redirect_to return_path,
notice: t("accounts.create.success", type: accountable_type.name.underscore.humanize)
+ rescue ActiveRecord::RecordInvalid => e
+ # `create_and_sync` saves with `save!`. A validation the user can trip from
+ # the form (a half-filled loan rate change, say) must come back as the form
+ # with the error and what they typed, not as the generic 422 page. The
+ # transaction above has already rolled back. The record on the exception is
+ # usually the unsaved account with its nested accountable still attached --
+ # but the opening valuation's `entries.create!` or `lock_saved_attributes!`
+ # can raise too, and then it is an Entry or the accountable, neither of
+ # which the form can render. Recover the account through it, or start from
+ # a fresh one as `new` does.
+ @account = if e.record.is_a?(Account)
+ e.record
+ else
+ e.record.try(:account) || Current.family.accounts.build(currency: Current.family.currency, accountable: accountable_type.new)
+ end
+ @error_message = e.record.errors.full_messages.join(", ").presence || e.message
+ # The `new` template's method-selection branch reads `@provider_configs`,
+ # which the `new` action's before_action sets up; this render needs it too.
+ set_link_options
+ render :new, status: :unprocessable_entity
end
def update
- # Handle balance update if the value actually changed
- if account_params[:balance].present? && account_params[:balance].to_d != @account.balance
- result = @account.set_current_balance(account_params[:balance].to_d)
- unless result.success?
- @error_message = result.error_message
- render :edit, status: :unprocessable_entity
- return
+ # Assigning a balance can fail before the normal update path assigns the
+ # other submitted fields. Keep them available for the 422 form without
+ # persisting them.
+ update_params = account_params.except(:return_to, :balance, :opening_balance_date)
+
+ # The balance change and the attribute update are one form, so they commit
+ # or roll back as one. `set_current_balance` writes a valuation and the
+ # account's cached balance; before this, a validation failing on the
+ # attributes (a half-filled loan rate change, say) returned 422 with the
+ # balance half of the rejected form already committed.
+ saved = Account.transaction do
+ # Handle balance update if the value actually changed
+ if account_params[:balance].present? && account_params[:balance].to_d != @account.balance
+ result = @account.set_current_balance(account_params[:balance].to_d)
+ unless result.success?
+ @account.assign_attributes(update_params)
+ @error_message = result.error
+ raise ActiveRecord::Rollback
+ end
+ end
+
+ # Update remaining account attributes. Note: currency is intentionally allowed
+ # here so all account types (depositories, credit cards, loans, etc.) can
+ # have their currency changed via this shared update path.
+ unless @account.update(update_params)
+ @error_message = @account.errors.full_messages.join(", ")
+ raise ActiveRecord::Rollback
end
+
+ # Inside the transaction, as `create` does: the locks are saved with
+ # `update!`, and a raise there after the commit left the balance and the
+ # attributes above in place behind a failed request.
+ @account.lock_saved_attributes!
+
+ true
+ rescue ActiveRecord::RecordInvalid => e
+ @error_message = e.record.errors.full_messages.join(", ").presence || e.message
+ raise ActiveRecord::Rollback
end
- # Update remaining account attributes. Note: currency is intentionally allowed
- # here so all account types (depositories, credit cards, loans, etc.) can
- # have their currency changed via this shared update path.
- update_params = account_params.except(:return_to, :balance, :opening_balance_date)
- unless @account.update(update_params)
- @error_message = @account.errors.full_messages.join(", ")
+ unless saved
render :edit, status: :unprocessable_entity
return
end
- @account.lock_saved_attributes!
redirect_back_or_to account_path(@account), notice: t("accounts.update.success", type: accountable_type.name.underscore.humanize)
end
diff --git a/app/controllers/loans_controller.rb b/app/controllers/loans_controller.rb
index e6066f4ade..62918d6475 100644
--- a/app/controllers/loans_controller.rb
+++ b/app/controllers/loans_controller.rb
@@ -2,6 +2,7 @@ class LoansController < ApplicationController
include AccountableResource
permitted_accountable_attributes(
- :id, :subtype, :rate_type, :interest_rate, :term_months, :initial_balance
+ :id, :subtype, :rate_type, :interest_rate, :term_months, :initial_balance, :start_date,
+ { rate_changes: [ :effective_date, :rate ] }
)
end
diff --git a/app/helpers/loans_helper.rb b/app/helpers/loans_helper.rb
new file mode 100644
index 0000000000..18ba2176d6
--- /dev/null
+++ b/app/helpers/loans_helper.rb
@@ -0,0 +1,16 @@
+module LoansHelper
+ # 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
+ # field silently turns an "arm" loan into a fixed one.
+ def loan_rate_type_options(loan)
+ options = [
+ [ t("loans.form.rate_type_fixed"), Loan::FIXED_RATE_TYPE ],
+ [ t("loans.form.rate_type_variable"), "variable" ],
+ [ t("loans.form.rate_type_adjustable"), "adjustable" ]
+ ]
+ return options if loan.rate_type.blank? || options.any? { |_, value| value == loan.rate_type }
+
+ options << [ loan.rate_type.titleize, loan.rate_type ]
+ end
+end
diff --git a/app/javascript/controllers/loan_rate_changes_controller.js b/app/javascript/controllers/loan_rate_changes_controller.js
new file mode 100644
index 0000000000..28cde3a535
--- /dev/null
+++ b/app/javascript/controllers/loan_rate_changes_controller.js
@@ -0,0 +1,60 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Add and remove rate-change rows, and show the section only for a loan whose
+// rate can actually move.
+//
+// Rows are plain inputs named as an array, so the form submits and the server
+// reads them with no JavaScript at all — this controller saves a round trip
+// per row and keeps the section honest about whether it applies.
+//
+// Hidden means DISABLED, not merely invisible. A disabled input is not
+// submitted, so a fixed-rate loan sends no `rate_changes` key at all and its
+// recorded changes are retained rather than cleared. The server renders the
+// section already hidden and disabled for a fixed loan, retained rows
+// included, so this holds without JavaScript too; `toggle()` only follows the
+// select from there. Switching to variable enables the retained rows, and the
+// next save resubmits them rather than the bare sentinel that would clear them.
+export default class extends Controller {
+ static targets = ["rows", "template", "empty", "section", "rateType"];
+ // The one rate type that cannot move. Anything else non-blank is variable,
+ // the same reading as Loan#variable_rate_type?, so a provider-written value
+ // such as "arm" keeps its editor rather than being hidden by a list the
+ // form never offered it in.
+ static values = { fixedType: String };
+
+ connect() {
+ this.toggle();
+ }
+
+ add(event) {
+ event.preventDefault();
+ const row = this.templateTarget.content.firstElementChild.cloneNode(true);
+ this.rowsTarget.appendChild(row);
+ row.querySelector("input[type='date']")?.focus();
+ this.#sync();
+ }
+
+ remove(event) {
+ event.preventDefault();
+ event.target.closest("[data-rate-change-row]")?.remove();
+ this.#sync();
+ }
+
+ toggle() {
+ const rateType = this.rateTypeTarget?.value ?? "";
+ const applies = rateType !== "" && rateType !== this.fixedTypeValue;
+ this.sectionTarget.hidden = !applies;
+ for (const el of this.sectionTarget.querySelectorAll(
+ "input, select, button",
+ )) {
+ el.disabled = !applies;
+ }
+ this.#sync();
+ }
+
+ #sync() {
+ if (this.hasEmptyTarget) {
+ this.emptyTarget.hidden = this.rowsTarget.children.length > 0;
+ }
+ }
+}
diff --git a/app/models/account.rb b/app/models/account.rb
index dc7932d5b9..77f5516ae9 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -720,10 +720,15 @@ class Account < ApplicationRecord
if Current.user.present? && Current.user.family_id == family_id
self.owner = Current.user
else
+ # `id` breaks ties on `created_at`. Two users of the same role can share
+ # a timestamp (they are created in one transaction, or the column is
+ # backfilled), and ordering on `created_at` alone leaves the winner to
+ # the query plan — so the same family can get a different default owner
+ # from one call to the next.
self.owner =
- family&.users&.where(role: "admin")&.order(:created_at)&.first ||
- family&.users&.where(role: "super_admin")&.order(:created_at)&.first ||
- family&.users&.order(:created_at)&.first
+ family&.users&.where(role: "admin")&.order(:created_at, :id)&.first ||
+ family&.users&.where(role: "super_admin")&.order(:created_at, :id)&.first ||
+ family&.users&.order(:created_at, :id)&.first
end
end
diff --git a/app/models/demo/generator.rb b/app/models/demo/generator.rb
index 5777336486..19109de3f8 100644
--- a/app/models/demo/generator.rb
+++ b/app/models/demo/generator.rb
@@ -290,10 +290,35 @@ class Demo::Generator
# Crypto (USD)
@coinbase_usdc = family.accounts.create!(accountable: Crypto.new, name: "Coinbase USDC", balance: 0, currency: "USD")
- # Loans / Liabilities (USD)
- @mortgage = family.accounts.create!(accountable: Loan.new, name: "Home Mortgage", balance: 0, currency: "USD")
- @car_loan = family.accounts.create!(accountable: Loan.new, name: "Car Loan", balance: 0, currency: "USD")
- @student_loan = family.accounts.create!(accountable: Loan.new, name: "Student Loan", balance: 0, currency: "USD")
+ # Loans / Liabilities (USD). Each carries the terms its amortisation
+ # schedule is built from; its principal is the opening valuation written
+ # by open_demo_loan!. The mortgage is adjustable with two recorded rate
+ # changes -- a cut two years in, a rise two years later -- so the demo
+ # shows a schedule re-amortising. The car and student loans start the
+ # month before generate_loan_payments! makes their first payment.
+ mortgage_start = 5.years.ago.to_date
+ loans_start = 37.months.ago.beginning_of_month.to_date
+ @mortgage = family.accounts.create!(
+ accountable: Loan.new(
+ subtype: "mortgage", rate_type: "adjustable", interest_rate: 6.25, term_months: 360,
+ start_date: mortgage_start, initial_balance: 320_000,
+ rate_changes: [
+ { effective_date: (mortgage_start >> 24).iso8601, rate: "5.5" },
+ { effective_date: (mortgage_start >> 48).iso8601, rate: "6.75" }
+ ]
+ ),
+ name: "Home Mortgage", balance: 0, currency: "USD"
+ )
+ @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),
+ name: "Car Loan", balance: 0, currency: "USD"
+ )
+ @student_loan = family.accounts.create!(
+ accountable: Loan.new(subtype: "student", rate_type: "fixed", interest_rate: 5.5, term_months: 120,
+ start_date: loans_start, initial_balance: 42_000),
+ name: "Student Loan", balance: 0, currency: "USD"
+ )
@personal_loc = family.accounts.create!(accountable: OtherLiability.new, name: "Personal Line of Credit", balance: 0, currency: "USD")
@@ -465,16 +490,9 @@ class Demo::Generator
start_date = 3.years.ago.to_date # Reduced from 12 years
base_rent = 2500 # Higher starting amount for higher income family
- # Monthly rent/mortgage payments
- (start_date..Date.current).each do |date|
- next unless date.day == 1 # First of month
-
- # Mortgage payment from checking account (positive expense)
- create_transaction!(@chase_checking, 2800, "Mortgage Payment", @rent_cat, date)
- # Principal payment reduces mortgage debt (negative transaction)
- principal_payment = 800 # ~$800 goes to principal
- create_transaction!(@mortgage, -principal_payment, "Principal Payment", nil, date)
- end
+ # The mortgage is paid by generate_loan_payments!, from its own schedule.
+ # A flat payment booked here as well moved the loan's balance a second
+ # time, so the demo mortgage owed less than any schedule could explain.
# Monthly utilities (reduced frequency)
utilities = [
@@ -528,9 +546,11 @@ class Demo::Generator
create_transaction!(@chase_checking, amount, "#{stations.sample} Gas", @gas_cat, date)
end
- # Car payment (monthly for 6 years)
+ # Payments on the previous car, up to the day before the demo car loan
+ # starts: from then on generate_loan_payments! pays the car loan from its
+ # schedule, and a flat payment alongside it would count the car twice.
car_payment_start = 6.years.ago.to_date
- car_payment_end = 1.year.ago.to_date
+ car_payment_end = [ 1.year.ago.to_date, @car_loan.loan.start_date - 1 ].min
(car_payment_start..car_payment_end).each do |date|
next unless date.day == 15 # 15th of month
@@ -721,9 +741,14 @@ class Demo::Generator
def generate_major_purchases!
# Home purchase (5 years ago) - only record the down payment, not full value
# Property value will be set by valuation in reconcile_balances!
- home_date = 5.years.ago.to_date
+ home_date = @mortgage.loan.start_date
create_transaction!(@chase_checking, 70_000, "Home Down Payment", @housing_cat, home_date)
- create_transaction!(@mortgage, 320_000, "Mortgage Principal", nil, home_date) # Initial mortgage debt
+
+ # Each loan opens at its principal on its start date -- the mortgage's
+ # 320,000 among them. A valuation rather than a transaction, because
+ # Loan#original_balance reads the first valuation: recorded as a
+ # transaction, the debt left the schedule with no principal to amortise.
+ [ @mortgage, @car_loan, @student_loan ].each { |loan_account| open_demo_loan!(loan_account) }
# Initial account funding (realistic amounts)
create_transaction!(@chase_checking, -5_000, "Initial Deposit", @salary_cat, 12.years.ago.to_date)
@@ -743,6 +768,19 @@ class Demo::Generator
create_transaction!(@chase_checking, 15_000, "Wedding Expenses", @entertainment_cat, 9.years.ago.to_date)
end
+ # The opening anchor valuation a loan account created through the form
+ # would carry: the loan's principal on its start date.
+ def open_demo_loan!(account)
+ loan = account.loan
+ account.entries.create!(
+ entryable: Valuation.new(kind: "opening_anchor"),
+ amount: loan.initial_balance,
+ name: Valuation.build_opening_anchor_name(account.accountable_type),
+ currency: account.currency,
+ date: loan.start_date
+ )
+ end
+
def generate_transfers_and_payments!
generate_credit_card_cycles!
@@ -1018,43 +1056,37 @@ class Demo::Generator
# ---------------------------------------------------------------------------
# Loan payments (Task 8)
# ---------------------------------------------------------------------------
+ # The one extra principal payment the student loan makes, a year ago.
+ STUDENT_LOAN_EXTRA_PAYMENT = 2_000
+
+ # Each demo loan pays what its own schedule asks, split into that payment's
+ # principal and interest, on every scheduled date up to today, so its
+ # balance is the one its schedule gives. Flat figures here (600 principal
+ # and 1,100 interest on the mortgage, whatever its rate) left the balances
+ # disagreeing with the schedules beside them. The student loan also makes
+ # one extra payment, so the demo shows a loan ahead of schedule for a real
+ # reason; the mortgage and the car loan sit on theirs.
def generate_loan_payments!
- date_cursor = 36.months.ago.beginning_of_month
- while date_cursor <= Date.current
- payment_date = first_business_day(date_cursor)
-
- # Mortgage
- make_loan_payment!(
- principal_account: @mortgage,
- principal_amount: 600,
- interest_amount: 1_100,
- interest_category: @housing_cat,
- date: payment_date,
- memo: "Mortgage Payment"
- )
-
- # Student loan
- make_loan_payment!(
- principal_account: @student_loan,
- principal_amount: 350,
- interest_amount: 100,
- interest_category: @interest_cat,
- date: payment_date,
- memo: "Student Loan Payment"
- )
-
- # Car loan – assume 300 principal / 130 interest
- make_loan_payment!(
- principal_account: @car_loan,
- principal_amount: 300,
- interest_amount: 130,
- interest_category: @transportation_cat,
- date: payment_date,
- memo: "Auto Loan Payment"
- )
-
- date_cursor = date_cursor.next_month.beginning_of_month
+ [
+ [ @mortgage, "Mortgage Payment", @rent_cat ],
+ [ @student_loan, "Student Loan Payment", @interest_cat ],
+ [ @car_loan, "Auto Loan Payment", @transportation_cat ]
+ ].each do |account, memo, interest_category|
+ account.loan.amortization_schedule.payments.each do |payment|
+ break if payment.date > Date.current
+
+ make_loan_payment!(
+ principal_account: account,
+ principal_amount: payment.principal.amount,
+ interest_amount: payment.interest.amount,
+ interest_category: interest_category,
+ date: payment.date,
+ memo: memo
+ )
+ end
end
+
+ create_transfer!(@chase_checking, @student_loan, STUDENT_LOAN_EXTRA_PAYMENT, "Student Loan Extra Payment", 1.year.ago.to_date)
end
def make_loan_payment!(principal_account:, principal_amount:, interest_amount:, interest_category:, date:, memo:)
diff --git a/app/models/loan.rb b/app/models/loan.rb
index 87547517c7..d5ffdcc6d7 100644
--- a/app/models/loan.rb
+++ b/app/models/loan.rb
@@ -11,10 +11,37 @@ class Loan < ApplicationRecord
"other" => { short: "Other Loan", long: "Other Loan" }
}.freeze
+ # The rate types the form offers. They are not the only ones a loan can
+ # carry: PlaidAccount::Liabilities::MortgageProcessor writes Plaid's raw
+ # `interest_rate.type` straight through ("arm", among others), and a loan
+ # whose rate can move is variable whatever the provider's word for it.
+ # So the predicates below read the column as: "fixed" is fixed, any other
+ # non-blank value is variable, and blank says nothing -- such a loan is
+ # not amortizable and gets what it got before schedules existed: no
+ # schedule, no tab. VARIABLE_RATE_TYPES is the form's vocabulary only,
+ # for the rate-change editor to know which of its options to open for.
+ FIXED_RATE_TYPE = "fixed".freeze
+ VARIABLE_RATE_TYPES = %w[variable adjustable].freeze
+
+ # An annual percentage, matching the bound the rate-change input declares.
+ MAX_INTEREST_RATE = 100
+
validates :subtype, inclusion: { in: SUBTYPES.keys }, allow_blank: true
+ # The form caps the date picker at today; this is the same bound where a
+ # crafted request cannot skip it. A loan drawn down in the future has no
+ # history to chart and would schedule a first payment months away while
+ # charging a month's interest for the gap.
+ validates :start_date, comparison: { less_than_or_equal_to: -> { Date.current } }, allow_nil: true
+ # The contracted repayment, for a loan that has exactly one.
+ #
+ # Deliberately still nil for a variable loan even though it now has a
+ # schedule: such a loan does not HAVE a single monthly payment, and quoting
+ # the one it opened with would be a stale figure presented as a current one.
+ # Answering it properly means re-amortising today's balance at today's rate,
+ # which needs the projection this engine does not yet carry.
def monthly_payment
- return nil if term_months.nil? || interest_rate.nil? || rate_type.nil? || rate_type != "fixed"
+ return nil if term_months.nil? || interest_rate.nil? || rate_type.nil? || rate_type != FIXED_RATE_TYPE
# Non-positive, not just zero: `amortizable?` rejects both, so anything that
# slips past here would fall through to a nil schedule instead of a payment.
return Money.new(0, account.currency) if original_balance.amount <= 0 || term_months <= 0
@@ -22,24 +49,196 @@ class Loan < ApplicationRecord
amortization_schedule&.periodic_payment
end
- # A loan can be amortized once we know what was borrowed, at what fixed rate,
- # and over how long. Variable-rate loans are excluded: their payment changes
- # with the rate, so a schedule built off today's rate would be fiction.
+ # A loan can be amortised once we know what was borrowed, at what rate, and
+ # over how long.
+ #
+ # Variable loans are included. They were excluded while a schedule could only
+ # be built off a single rate -- "a schedule built off today's rate would be
+ # fiction" -- but the schedule now re-amortises at each recorded rate change,
+ # so the objection no longer holds. A variable loan with no changes recorded
+ # yet simply runs at its base rate, which is what it is actually doing.
def amortizable?
- rate_type == "fixed" &&
+ # `account` first: original_balance reads through it, and a Loan can exist
+ # without one (Loan.new in a form, a fixture built in isolation). #2984's
+ # `rate_type == "fixed"` guard happened to short-circuit before that read;
+ # widening the rate types removed the accident, so the requirement is
+ # stated rather than relied upon.
+ account.present? &&
+ rate_type.present? &&
interest_rate.present? &&
term_months.to_i.positive? &&
+ term_months.to_i <= Loan::Simulator::MAX_PERIODS &&
original_balance.amount.positive?
end
+ private def rate_changes_must_be_parseable
+ Array(invalid_rate_changes).each do |row|
+ errors.add(:base, I18n.t("activerecord.errors.models.loan.invalid_rate_change"))
+ break
+ end
+ end
+
+ private def rate_changes_must_not_precede_origination
+ errors.add(:base, :rate_change_before_origination) if rate_changes_precede_origination?
+ end
+
+ private def rate_changes_precede_origination?
+ return false unless variable_rate_type?
+ rate_changes = variable_rates
+ return false if rate_changes.empty?
+
+ loan_origination_date = start_date
+ unless loan_origination_date.present?
+ # Do not call `account` here. Loan validations can run before a separate
+ # Account is attached; caching that missing has_one result leaves the
+ # later persisted Loan unable to see its Account through the association.
+ loan_account = association(:account).target || association(:account).scope.first
+ return false unless loan_account
+
+ loan_origination_date = loan_account.first_valuation&.date || loan_account.opening_anchor_date
+ end
+
+ loan_origination_date.present? && rate_changes.any? { |date, _rate| date < loan_origination_date }
+ end
+
+ # Whether this loan's rate can move over its life. The one place the answer
+ # is defined -- callers must not compare rate_type to a string. Anything
+ # non-blank that is not "fixed" counts, so a provider's own vocabulary is
+ # variable rather than unknown (see the constants above).
+ def variable_rate_type?
+ rate_type.present? && rate_type != FIXED_RATE_TYPE
+ end
+
+ # Recorded rate changes as [Date, BigDecimal] pairs, oldest first. The one
+ # place the column is parsed: RateResolver and the form rows read these
+ # pairs rather than the raw JSON, so every reader agrees on what a row means.
+ def variable_rates
+ (variable_rate_schedule || {})
+ .map { |date, rate| [ Date.iso8601(date.to_s), BigDecimal(rate.to_s) ] }
+ .sort_by(&:first)
+ end
+
+ # The rate in force on a given date: the latest change effective on or before
+ # it, falling back to the loan's own rate before any change applies. One
+ # implementation of that lookup, RateResolver's, so the Overview tab and the
+ # schedule cannot disagree about which rate a date carries.
+ def current_variable_rate(as_of = Date.current)
+ RateResolver.for(self).accrual_rate_for(as_of)
+ end
+
+ # Rows the form submitted that could not be parsed. Kept so the save can be
+ # rejected and the form re-rendered with what the user actually typed --
+ # dropping them silently loses a typo'd row between submit and redisplay,
+ # and the user is never told which one went.
+ attr_reader :invalid_rate_changes
+
+ validate :rate_changes_must_be_parseable
+ validate :rate_changes_must_not_precede_origination
+
+ # Assembles variable_rate_schedule from the form's rows.
+ #
+ # Keyed by effective date, so re-entering a date replaces that row rather
+ # than adding a second one for the same day -- two rates in force on one date
+ # is not a state the schedule can represent, and silently keeping both would
+ # make which one wins depend on hash ordering.
+ #
+ # A submission from the form always carries its hidden sentinel, a bare
+ # `rate_changes[]` with no value. Rack parses that as "" and strong
+ # parameters drop it, so what arrives here when the user removed every row
+ # is an empty array -- which correctly clears the schedule. Absent the
+ # sentinel, removing the last row would send no `rate_changes` key at all,
+ # nested assignment would never call this, and the removed rows would stay
+ # persisted. Blank rows that do reach this method (a row the user added and
+ # left empty) are skipped for the same reason.
+ def rate_changes=(rows)
+ invalid = []
+
+ parsed = Array(rows).each_with_object({}) do |row, acc|
+ next unless row.respond_to?(:[]) && !row.is_a?(String)
+
+ date = row[:effective_date].presence || row["effective_date"].presence
+ rate = row[:rate].presence || row["rate"].presence
+ next if date.blank? && rate.blank?
+
+ begin
+ raise ArgumentError, "incomplete" if date.blank? || rate.blank?
+
+ # The form's own input already declares `min="0" max="100"`, so this is
+ # the same contract enforced where a crafted PATCH cannot skip it. A
+ # negative or absurd rate parses perfectly well and then produces a
+ # schedule nobody can act on, which is worse than a rejected row.
+ parsed_rate = BigDecimal(rate.to_s)
+ unless parsed_rate.finite? && parsed_rate >= 0 && parsed_rate <= MAX_INTEREST_RATE
+ raise ArgumentError, "rate out of range"
+ end
+
+ # ISO 8601 only, as variable_rates reads it back. Date.parse would
+ # accept "1" as the first of the current month.
+ acc[Date.iso8601(date.to_s).iso8601] = parsed_rate.to_s("F")
+ rescue ArgumentError, TypeError, Date::Error, FloatDomainError
+ invalid << { effective_date: date.to_s, rate: rate.to_s }
+ end
+ end
+
+ @invalid_rate_changes = invalid
+ self.variable_rate_schedule = parsed
+ end
+
+ # The form reaches this record through Account's nested attributes, which
+ # validate it only when it has changes. Resubmitting the stored rows plus a
+ # typo'd one leaves `variable_rate_schedule` equal to its stored value, so
+ # without this the account saved, the typo'd row vanished, and the
+ # validation above only fired when some other field happened to change.
+ #
+ # Autosave asks this on every save of the parent Account. The origination
+ # check can load the Account and its first valuation, but only for a variable
+ # loan that has recorded rate changes and no start date; every other loan
+ # answers from its own attributes.
+ def changed_for_autosave?
+ super || invalid_rate_changes.present? || rate_changes_precede_origination?
+ end
+
+ # Form rows, in a shape the form can render without parsing anything.
+ #
+ # Rendered for every rate type, including fixed: switching a loan to fixed
+ # leaves its recorded changes in the column, `current_variable_rate` ignores
+ # them, and the form hides and disables the section. They are retained rather
+ # than deleted so switching back reveals them, and a save then resubmits them
+ # instead of the sentinel alone, which would clear them.
+ #
+ # Invalid rows come back too, so a rejected save redisplays what was typed.
+ def rate_change_rows
+ variable_rates.map { |date, rate| { effective_date: date.iso8601, rate: rate.to_s("F") } } +
+ Array(invalid_rate_changes)
+ end
+
def amortization_schedule
@amortization_schedule ||= AmortizationSchedule.for(self)
end
- # The date the loan was drawn down. Sure records that as the account's first
- # valuation (the opening balance), falling back to the opening anchor.
+ # The columns AmortizationSchedule.for reads from the loan itself. Assigning
+ # any of them drops the memoised schedule, as reload does, so a read after the
+ # change answers with the new terms rather than the ones it was built from.
+ SCHEDULE_INPUTS = %i[interest_rate term_months rate_type start_date variable_rate_schedule].freeze
+
+ SCHEDULE_INPUTS.each do |input|
+ define_method(:"#{input}=") do |value|
+ @amortization_schedule = nil
+ super(value)
+ end
+ end
+
+ def reload(*)
+ @amortization_schedule = nil
+ super
+ end
+
+ # The date the loan was drawn down. Recorded explicitly when the borrower
+ # knows it -- a loan is often drawn down before the account tracking it is
+ # created -- and otherwise taken from the account's first valuation (the
+ # opening balance), falling back to the opening anchor.
def origination_date
- account.first_valuation&.date || account.opening_anchor_date
+ start_date || account.first_valuation&.date || account.opening_anchor_date
end
def original_balance
diff --git a/app/models/loan/amortization_math.rb b/app/models/loan/amortization_math.rb
new file mode 100644
index 0000000000..af206a596f
--- /dev/null
+++ b/app/models/loan/amortization_math.rb
@@ -0,0 +1,72 @@
+class Loan
+ # Shared per-period amortisation math. Kept in one place so a rounding or
+ # edge-case fix only has to be made once: the contracted schedule sizes
+ # payments from the original balance over the original term, and a
+ # re-amortisation part-way through sizes them from the balance then
+ # outstanding over the periods still remaining. Two callers, one formula.
+ module AmortizationMath
+ module_function
+
+ # The level payment that amortises `balance` to zero over
+ # `remaining_payments` periods at `monthly_rate` -- the standard annuity
+ # formula, and the figure a lender quotes.
+ #
+ # A zero rate is not a degenerate case to guard against, it is an
+ # interest-free loan: the balance divided by the periods left.
+ #
+ # `first_period_interest` is for a resize on a rate change: the period
+ # that closes on the change accrued at the OLD rate, and the annuity
+ # formula assumes every remaining period, this one included, accrues at
+ # `monthly_rate`. Sized that way the payment over-covers the first period
+ # and the final settlement becomes a discount of thousands. Given the
+ # interest actually charged this period, the figure returned is the one
+ # payment that covers it and then amortises what is left over the
+ # remaining periods at `monthly_rate` -- level to maturity. With the
+ # interest at `monthly_rate` the two formulas agree exactly, so the plain
+ # one is kept for the common case and stays bit-identical.
+ def level_payment(balance:, monthly_rate:, remaining_payments:, currency_precision:, first_period_interest: nil)
+ return BigDecimal("0") if remaining_payments <= 0 || balance <= 0
+
+ if first_period_interest
+ later = remaining_payments - 1
+ annuity = if later.zero?
+ BigDecimal("0")
+ elsif monthly_rate.zero?
+ BigDecimal(later)
+ else
+ later_growth = (1 + monthly_rate)**later
+ (later_growth - 1) / (monthly_rate * later_growth)
+ end
+ return ((balance + first_period_interest) / (1 + annuity)).round(currency_precision)
+ end
+
+ return (balance / remaining_payments).round(currency_precision) if monthly_rate.zero?
+
+ growth = (1 + monthly_rate)**remaining_payments
+ ((balance * monthly_rate * growth) / (growth - 1)).round(currency_precision)
+ end
+
+ # One period's interest/principal split for a fixed payment against a given
+ # balance.
+ #
+ # `final: true` settles the remaining principal exactly rather than leaving
+ # rounding dust, and re-derives the payment from it -- so the last payment
+ # of a schedule can differ from the level payment by a few cents, exactly as
+ # a lender's own table does.
+ def step(balance:, payment:, monthly_rate:, currency_precision:, final: false, interest: nil)
+ interest ||= (balance * monthly_rate).round(currency_precision)
+ principal = final ? balance : payment - interest
+
+ ending_balance = (balance - principal).round(currency_precision)
+ ending_balance = BigDecimal("0") if ending_balance.negative?
+
+ {
+ payment_amount: final ? (principal + interest).round(currency_precision) : payment.round(currency_precision),
+ principal_payment: principal.round(currency_precision),
+ interest_payment: interest.round(currency_precision),
+ beginning_balance: balance.round(currency_precision),
+ ending_balance: ending_balance
+ }
+ end
+ end
+end
diff --git a/app/models/loan/amortization_schedule.rb b/app/models/loan/amortization_schedule.rb
index 483db06cfb..88843070ac 100644
--- a/app/models/loan/amortization_schedule.rb
+++ b/app/models/loan/amortization_schedule.rb
@@ -1,13 +1,17 @@
-# Builds a constant-payment ("French") amortization schedule for a fixed-rate loan.
+# Builds a constant-payment ("French") amortisation schedule for a loan.
#
# Each period charges interest on the outstanding principal and applies the
-# remainder of the fixed payment to principal, so the principal/interest split
+# remainder of the level payment to principal, so the principal/interest split
# shifts over the life of the loan. This is the standard system for European
# mortgages and for most US fixed-rate loans.
#
# All arithmetic runs in BigDecimal and every payment is rounded to the
# currency's precision, exactly as a lender's own table does. The final payment
# absorbs whatever rounding residue is left so the balance lands on zero.
+#
+# The period-by-period walk itself lives in Loan::Simulator. This class owns
+# what a *schedule* is -- the dates, the term, and the presentation of a run as
+# Payment records -- and nothing about how interest accrues.
class Loan::AmortizationSchedule
Payment = Data.define(:number, :date, :payment, :principal, :interest, :ending_balance)
@@ -15,7 +19,7 @@ class Loan::AmortizationSchedule
class << self
# Returns a schedule for the loan, or nil when the loan isn't amortizable
- # (variable rate, or missing rate/term/principal).
+ # (missing rate/term/principal).
def for(loan)
return nil unless loan.amortizable?
@@ -24,46 +28,84 @@ class Loan::AmortizationSchedule
annual_rate: loan.interest_rate,
term_months: loan.term_months,
start_date: loan.origination_date,
- currency: loan.account.currency
+ currency: loan.account.currency,
+ rate_resolver: (Loan::RateResolver.for(loan) if loan.variable_rate_type?)
)
end
end
- def initialize(principal:, annual_rate:, term_months:, start_date:, currency:)
- @principal = BigDecimal(principal.to_s)
+ # `rate_resolver` is how a variable loan's recorded rate changes reach the
+ # simulator. Omitted, the schedule runs at one rate for its whole life, which
+ # is what a fixed loan does.
+ def initialize(principal:, annual_rate:, term_months:, start_date:, currency:, rate_resolver: nil)
+ @currency = currency
+ # Rounded to the currency at the door. A balance carrying more fractional
+ # units than the currency has -- `first_valuation_amount` is decimal(19,4)
+ # against two-decimal USD -- otherwise loses its residue in the first
+ # period's rounding, and the principal portions then sum to less than the
+ # loan. A schedule is denominated in its currency; sub-unit precision in
+ # the opening balance is not a thing it can represent.
+ @principal = BigDecimal(principal.to_s).round(currency_precision)
@annual_rate = BigDecimal(annual_rate.to_s)
@term_months = term_months.to_i
@start_date = start_date
- @currency = currency
+ @rate_resolver = rate_resolver
+ end
+
+ # True when this schedule re-amortises part-way through, i.e. the repayment
+ # is re-sized at some payment after the first. Views use it to decide whether
+ # "the monthly payment" is a meaningful thing to say. Asked of the run rather
+ # than of the recorded changes: a change to the same rate, or one effective
+ # on the first payment, is an event that moves nothing in-term, and a
+ # constant payment must not be labelled an opening one.
+ def re_amortising?
+ return false unless @rate_resolver
+ return false unless schedulable?
+
+ simulation.payments.each_cons(2).any? { |previous, current| previous[:sizing_rate] != current[:sizing_rate] }
end
# Every scheduled payment, oldest first. Empty when there is nothing to
- # amortize; shorter than the term when rounding clears the balance early.
+ # amortise; shorter than the term when rounding clears the balance early.
def payments
- @payments ||= build_payments
+ @payments ||= simulation.payments.map do |row|
+ Payment.new(
+ number: row[:payment_number],
+ date: row[:payment_date],
+ payment: money(row[:payment_amount]),
+ principal: money(row[:principal_payment]),
+ interest: money(row[:interest_payment]),
+ ending_balance: money(row[:ending_balance])
+ )
+ end
end
- # The level payment charged every period. The last payment can differ by a
- # few cents — read it off #payments when the exact figure matters.
+ # The level payment the schedule opens with. The last payment can differ by
+ # a few cents, and on a re-amortising loan every payment after a rate change
+ # differs too -- read them off #payments when the exact figures matter, and
+ # see #re_amortising? before presenting this as "the" monthly payment.
def periodic_payment
- return money(0) unless schedulable?
-
- money(raw_periodic_payment)
+ # Read off the first simulated payment rather than re-deriving it from the
+ # base rate. A rate change effective ON the first payment date already
+ # sizes that payment, and re-deriving would quote the rate the loan was
+ # written at for a payment the borrower will never make. For a fixed loan
+ # the two are the same number.
+ payments.first&.payment || money(0)
end
# What the loan costs in interest over its whole life. Sits slightly above
# the naive periodic_payment * term figure because interest is rounded to
# the currency's precision every period.
def total_interest
- money(payments.sum(BigDecimal(0)) { |payment| payment.interest.amount })
+ money(simulation.total_interest)
end
- # Principal plus total_interest — everything the borrower pays.
+ # Principal plus total_interest -- everything the borrower pays.
def total_paid
- money(payments.sum(BigDecimal(0)) { |payment| payment.payment.amount })
+ money(payments.sum(BigDecimal("0")) { |payment| payment.payment.amount })
end
- # The date of the final payment, or nil when there's nothing to amortize.
+ # The date of the final payment, or nil when there's nothing to amortise.
def payoff_date
payments.last&.date
end
@@ -74,68 +116,43 @@ class Loan::AmortizationSchedule
payments.find { |payment| payment.date.year == date.year && payment.date.month == date.month }
end
- private
- def monthly_rate
- @monthly_rate ||= annual_rate / 100 / 12
- end
+ # The repayment in force on `as_of`: the next scheduled payment on or after
+ # it, sized at every rate change recorded before that payment. A variable
+ # loan has no single monthly payment, but it always has this one. Nil once
+ # the schedule has run out.
+ def payment_in_force(as_of)
+ payments.find { |payment| payment.date >= as_of }&.payment
+ end
- # P·i·(1+i)^n / ((1+i)^n − 1), degrading to straight-line for a 0% loan.
- def raw_periodic_payment
- @raw_periodic_payment ||= begin
- if monthly_rate.zero?
- round_to_currency(principal / term_months)
- else
- growth = (1 + monthly_rate)**term_months
- round_to_currency(principal * monthly_rate * growth / (growth - 1))
- end
- end
+ private
+ # One payment per month of the term, stepping from origination. `>>` gives
+ # the calendar-correct answer at month ends: 31 January plus one month is
+ # 28 February, not 3 March.
+ def payment_schedule
+ @payment_schedule ||= (1..term_months).map { |number| start_date >> number }
end
- def build_payments
- return [] unless schedulable?
-
- balance = principal
- level_payment = raw_periodic_payment
- built = []
-
- (1..term_months).each do |number|
- # Rounding can make the level payment slightly over-cover the loan, so
- # the balance can reach zero before the nominal term is up. Stop, and
- # keep the periods built so far.
- break if balance <= 0
-
- interest = round_to_currency(balance * monthly_rate)
- principal_portion = level_payment - interest
-
- # Final period, or a payment large enough to clear the balance: settle
- # the remaining principal exactly rather than leaving rounding dust.
- if number == term_months || principal_portion >= balance
- principal_portion = balance
- end
-
- balance -= principal_portion
-
- built << Payment.new(
- number: number,
- date: start_date >> number,
- payment: money(principal_portion + interest),
- principal: money(principal_portion),
- interest: money(interest),
- ending_balance: money(balance)
- )
+ # The simulator refuses an empty schedule rather than inventing a
+ # degenerate run, so a loan with nothing to amortise is answered here.
+ def simulation
+ @simulation ||= if schedulable?
+ Loan::Simulator.new(
+ starting_balance: principal,
+ accrual_start_date: start_date,
+ payment_schedule: payment_schedule,
+ accrual_rate_for: @rate_resolver ? @rate_resolver.method(:accrual_rate_for) : ->(_date) { annual_rate },
+ re_amortisation_events: @rate_resolver&.method(:re_amortisation_events),
+ currency_precision: currency_precision
+ ).run
+ else
+ Loan::SimulationResult.new(payments: [], currency_precision: currency_precision)
end
-
- built
end
def schedulable?
term_months.positive? && principal.positive?
end
- def round_to_currency(value)
- value.round(currency_precision)
- end
-
def currency_precision
@currency_precision ||= Money::Currency.new(currency).default_precision || 2
end
diff --git a/app/models/loan/rate_resolver.rb b/app/models/loan/rate_resolver.rb
new file mode 100644
index 0000000000..ed1350c325
--- /dev/null
+++ b/app/models/loan/rate_resolver.rb
@@ -0,0 +1,65 @@
+class Loan
+ # Answers "what rate applies?" for a loan, without making Loan::Simulator
+ # depend on the Loan model.
+ #
+ # A fixed loan answers the same rate for every date. A variable loan reads
+ # its recorded rate changes.
+ #
+ # ## Why two questions, not one
+ #
+ # A rate change moves two different things on different days, and conflating
+ # them bills the borrower wrongly:
+ #
+ # * `accrual_rate_for(date)` -- the rate in force on a given day. The
+ # simulator asks this at each period's OPENING date, so a change takes
+ # effect from the period that begins on it.
+ # * `re_amortisation_events` -- the dates on which the contracted repayment
+ # is resized. The simulator applies these ON the payment date.
+ #
+ # Both read the same recorded changes; they are separate methods because the
+ # simulator must be able to be told different answers. A rate that moves what
+ # is charged without immediately moving what is owed each month is exactly
+ # what a variable loan does between payment dates.
+ class RateResolver
+ def self.for(loan)
+ new(loan)
+ end
+
+ def initialize(loan)
+ @loan = loan
+ end
+
+ # The rate in force on `date`: the latest change effective on or before it,
+ # falling back to the loan's own rate before any change applies.
+ def accrual_rate_for(date)
+ return loan.interest_rate unless loan.variable_rate_type?
+
+ rate_changes.reverse_each.find { |effective_date, _| effective_date <= date }&.last || loan.interest_rate
+ end
+
+ # Every recorded change falling inside [from_date, to_date], as the
+ # {date:, rate:} pairs the simulator consumes. Bounds are inclusive at both
+ # ends: a change effective on the final payment date still resizes it.
+ def re_amortisation_events(from_date, to_date)
+ return [] unless loan.variable_rate_type?
+
+ rate_changes.filter_map do |effective_date, rate|
+ next unless effective_date >= from_date && effective_date <= to_date
+
+ { date: effective_date, rate: rate }
+ end
+ end
+
+ private
+ attr_reader :loan
+
+ # Loan#variable_rates, read once. The simulator asks for a rate up to
+ # three times a period over as many as 1,200 periods; reparsing and
+ # re-sorting the column each time is the kind of cost that only shows up
+ # on the longest loans. Parsing stays in Loan, so this reader and that one
+ # cannot drift apart.
+ def rate_changes
+ @rate_changes ||= loan.variable_rates
+ end
+ end
+end
diff --git a/app/models/loan/simulation_result.rb b/app/models/loan/simulation_result.rb
new file mode 100644
index 0000000000..58e57eb461
--- /dev/null
+++ b/app/models/loan/simulation_result.rb
@@ -0,0 +1,41 @@
+class Loan
+ # Immutable result of one Loan::Simulator run.
+ #
+ # The simulator is deliberately independent of persistence: this is what a
+ # live schedule -- and later a payoff projection -- reads from, rather than
+ # each caller deciding for itself what a run produced.
+ #
+ # There is no "did it converge?" here, because in this engine it always does:
+ # the simulator sizes its own level payment from the balance and the periods
+ # remaining, and settles the final period exactly. A run that ends with a
+ # balance outstanding only becomes possible once a caller can impose a
+ # payment the simulator did not choose -- and that belongs with the change
+ # that introduces it, not as unreachable state carried in advance.
+ class SimulationResult
+ attr_reader :payments, :total_interest
+
+ def initialize(payments:, currency_precision:)
+ @payments = deep_freeze(payments)
+ @total_interest = @payments.sum(BigDecimal("0")) { |p| p[:interest_payment] }
+ .round(currency_precision).freeze
+ freeze
+ end
+
+ def payoff_date
+ payments.last&.fetch(:payment_date)
+ end
+
+ def payment_count
+ payments.length
+ end
+
+ private
+ def deep_freeze(value)
+ case value
+ when Array then value.map { |item| deep_freeze(item) }.freeze
+ when Hash then value.transform_values { |item| deep_freeze(item) }.freeze
+ else value.freeze
+ end
+ end
+ end
+end
diff --git a/app/models/loan/simulator.rb b/app/models/loan/simulator.rb
new file mode 100644
index 0000000000..a2dd3beff0
--- /dev/null
+++ b/app/models/loan/simulator.rb
@@ -0,0 +1,183 @@
+class Loan
+ # The period engine. Walks a payment schedule, charging interest and applying
+ # payments, and returns a SimulationResult.
+ #
+ # It takes values and callables rather than a Loan, so the contracted schedule
+ # and (later) a projection from today's balance can share one loop instead of
+ # growing two implementations that drift.
+ #
+ # ## Accrual is monthly
+ #
+ # One interest charge per period, on the balance outstanding when the period
+ # opened. Daily accrual is a different engine and is deliberately not here.
+ #
+ # ## Two rates, not one
+ #
+ # A period is bounded by two dates, and on a variable loan they can sit either
+ # side of a rate change. Which rate applies depends on what is being asked:
+ #
+ # * **Interest** for the period [previous payment date, this payment date)
+ # accrues at the rate in force when the period **opened**. A rate that
+ # becomes effective on this period's closing date belongs to the NEXT
+ # window, not to the month that has already run at the old rate.
+ # * **Payment sizing** uses the rate in force **on** the payment date, so a
+ # change effective on a payment date resizes that payment.
+ #
+ # Reading a single rate for both re-rates the period ending on the boundary --
+ # the borrower is charged a rate that did not apply for any day of the month
+ # being billed. Keeping them apart is the whole reason `accrual_rate_for` is
+ # called twice with different dates below.
+ #
+ # Under monthly accrual a rate change *mid*-period cannot move that period's
+ # interest: there is one charge, computed at the period's opening rate. It
+ # takes effect from the following period. That is a property of monthly
+ # accrual, not an approximation to be corrected here.
+ class Simulator
+ # Guards a runaway schedule: a hundred years of monthly payments. Refused
+ # outright rather than truncated -- silently walking the first 1,200 of a
+ # longer schedule returns totals and a payoff date describing a loan that
+ # was never asked for, and loses the remaining balance without saying so.
+ MAX_PERIODS = 1200
+
+ PAYMENT_STRATEGIES = %i[reamortize hold].freeze
+
+ # Built once: `monthly_rate` runs twice per period, up to MAX_PERIODS times
+ # per simulation. The two-step division is kept as it was so results stay
+ # bit-identical to the schedules already asserted in the tests.
+ PERCENT = BigDecimal("100")
+ MONTHS_PER_YEAR = BigDecimal("12")
+
+ def initialize(
+ starting_balance:,
+ accrual_start_date:,
+ payment_schedule:,
+ accrual_rate_for:,
+ currency_precision:,
+ re_amortisation_events: nil,
+ payment_strategy: :reamortize,
+ settle_at_schedule_end: true
+ )
+ @starting_balance = BigDecimal(starting_balance.to_s)
+ @accrual_start_date = accrual_start_date
+ @payment_schedule = payment_schedule.to_a.freeze
+ @accrual_rate_for = callable!(accrual_rate_for, :accrual_rate_for)
+ @re_amortisation_events = callable!(
+ re_amortisation_events || ->(_from, _to) { [] }, :re_amortisation_events
+ )
+ @currency_precision = currency_precision
+ @payment_strategy = payment_strategy.to_sym
+ @settle_at_schedule_end = settle_at_schedule_end
+
+ raise ArgumentError, "payment schedule must not be empty" if @payment_schedule.empty?
+ if @payment_schedule.length > MAX_PERIODS
+ raise ArgumentError,
+ "payment schedule has #{@payment_schedule.length} periods (#{@payment_schedule.first} to #{@payment_schedule.last}), " \
+ "more than the #{MAX_PERIODS} allowed"
+ end
+ unless PAYMENT_STRATEGIES.include?(@payment_strategy)
+ raise ArgumentError, "unsupported payment strategy: #{@payment_strategy.inspect}"
+ end
+ end
+
+ def run
+ balance = @starting_balance
+ payments = []
+ payment = nil
+ previous_sizing_rate = nil
+ (0...@payment_schedule.length).each do |index|
+ break if balance <= 0
+
+ payment_date = @payment_schedule[index]
+ period_start = index.zero? ? @accrual_start_date : @payment_schedule[index - 1]
+
+ # See the class comment: opening rate charges the period, closing rate
+ # sizes the payment.
+ accrual_rate = monthly_rate(@accrual_rate_for.call(period_start))
+ sizing_rate = monthly_rate(rate_on(payment_date))
+
+ # Interest first, on the balance the period opened with: one charge
+ # per period under monthly accrual. Sizing needs it when the two rates
+ # differ, see below.
+ interest = (balance * accrual_rate).round(@currency_precision)
+
+ # Resize only when the sizing rate actually moves. Recomputing every
+ # period would be arithmetically identical while the rate holds, but it
+ # would also silently absorb a payment the borrower is contracted to,
+ # which is what `:hold` exists to refuse.
+ #
+ # When the period straddles the change -- accrued at the old rate,
+ # sized at the new -- the annuity formula alone over-covers this
+ # period and the payment is not level to maturity (a final settlement
+ # thousands short). The sizing is told what this period actually
+ # charged so the figure covers it and amortises the rest evenly.
+ if payment.nil? || (@payment_strategy == :reamortize && sizing_rate != previous_sizing_rate)
+ payment = AmortizationMath.level_payment(
+ balance: balance,
+ monthly_rate: sizing_rate,
+ remaining_payments: @payment_schedule.length - index,
+ currency_precision: @currency_precision,
+ first_period_interest: (interest if sizing_rate != accrual_rate)
+ )
+ end
+ previous_sizing_rate = sizing_rate
+
+ final = (@settle_at_schedule_end && index == @payment_schedule.length - 1) ||
+ payment >= balance + interest
+
+ step = AmortizationMath.step(
+ balance: balance,
+ payment: payment,
+ monthly_rate: accrual_rate,
+ currency_precision: @currency_precision,
+ final: final,
+ interest: interest
+ )
+
+ # Two rates on the row, named for what each did: `interest_rate` is
+ # the one the interest column was computed with, so a reader who
+ # recomputes beginning_balance * rate / 12 gets this row's figure;
+ # `sizing_rate` is the one the payment was sized at. They differ only
+ # on a row whose period straddles a rate change.
+ payments << {
+ payment_number: index + 1,
+ payment_date: payment_date,
+ interest_rate: BigDecimal(@accrual_rate_for.call(period_start).to_s),
+ sizing_rate: BigDecimal(rate_on(payment_date).to_s),
+ **step
+ }
+
+ balance = step[:ending_balance]
+ end
+
+ SimulationResult.new(payments: payments, currency_precision: @currency_precision)
+ end
+
+ private
+ # The contracted rate on a given payment date: a re-amortisation event
+ # effective that day, otherwise whatever the rate curve says.
+ def rate_on(date)
+ event = re_amortisation_rates.reverse.find { |effective, _| effective <= date }
+ event ? event.last : @accrual_rate_for.call(date)
+ end
+
+ def re_amortisation_rates
+ @re_amortisation_rates ||= @re_amortisation_events
+ .call(@payment_schedule.first, @payment_schedule.last)
+ .map { |event| [ event.fetch(:date), event.fetch(:rate) ] }
+ .sort_by(&:first)
+ end
+
+ # `annual_percentage` is whatever the caller's rate callable returned --
+ # an Integer in the tests, a BigDecimal from RateResolver -- so the
+ # coercion at this boundary stays.
+ def monthly_rate(annual_percentage)
+ (BigDecimal(annual_percentage.to_s) / PERCENT) / MONTHS_PER_YEAR
+ end
+
+ def callable!(value, name)
+ raise ArgumentError, "#{name} must respond to #call" unless value.respond_to?(:call)
+
+ value
+ end
+ end
+end
diff --git a/app/views/loans/_form.html.erb b/app/views/loans/_form.html.erb
index e5cb07351b..41c11ecdde 100644
--- a/app/views/loans/_form.html.erb
+++ b/app/views/loans/_form.html.erb
@@ -1,10 +1,20 @@
<%# locals: (account:, url:) %>
<%= render "accounts/form", account: account, url: url do |form| %>
- <%= render "shared/ruler", classes: "my-4" %>
+ <%= form.fields_for :accountable do |loan_form| %>
+ <%# What kind of loan it is sits with the account's own fields, straight
+ after the balance, above the divider and the loan's terms. %>
+ <div>
+ <%= loan_form.select :subtype,
+ Loan.subtype_options_for_select,
+ { label: true, prompt: t("loans.form.subtype_prompt"), include_blank: t("loans.form.none") } %>
+ </div>
- <div class="space-y-2">
- <%= form.fields_for :accountable do |loan_form| %>
+ <%= render "shared/ruler", classes: "my-4" %>
+
+ <div class="space-y-2"
+ data-controller="loan-rate-changes"
+ data-loan-rate-changes-fixed-type-value="<%= Loan::FIXED_RATE_TYPE %>">
<div class="flex items-center gap-2">
<%= loan_form.money_field :initial_balance,
label: t("loans.form.initial_balance"),
@@ -18,22 +28,84 @@
placeholder: t("loans.form.interest_rate_placeholder"),
min: 0,
step: 0.005 %>
+ <%# A provider can write a rate type the form never offers ("arm"); it
+ stays in the list so saving the form keeps it rather than silently
+ replacing it with the first option. %>
<%= loan_form.select :rate_type,
- [[t("loans.form.rate_type_fixed"), "fixed"], [t("loans.form.rate_type_variable"), "variable"], [t("loans.form.rate_type_adjustable"), "adjustable"]],
- { label: t("loans.form.rate_type") } %>
+ loan_rate_type_options(account.loan),
+ { label: t("loans.form.rate_type") },
+ { data: { loan_rate_changes_target: "rateType",
+ action: "change->loan-rate-changes#toggle" } } %>
</div>
<div class="flex items-center gap-2">
+ <%= loan_form.date_field :start_date,
+ label: t("loans.form.start_date"),
+ max: Date.current %>
+ </div>
+ <p class="text-xs text-secondary"><%= t("loans.form.start_date_hint") %></p>
+
+ <div class="flex items-center gap-2">
+ <%# Bounded here rather than validated on Loan: PlaidAccount::Liabilities::StudentLoanProcessor
+ writes this column from provider dates, and a term the simulator will not walk is
+ answered tolerantly there (no schedule, as for an unknown rate type). %>
<%= loan_form.number_field :term_months,
label: t("loans.form.term_months"),
- placeholder: t("loans.form.term_months_placeholder") %>
+ placeholder: t("loans.form.term_months_placeholder"),
+ min: 1,
+ max: Loan::Simulator::MAX_PERIODS %>
</div>
- <div>
- <%= loan_form.select :subtype,
- Loan.subtype_options_for_select,
- { label: true, prompt: t("loans.form.subtype_prompt"), include_blank: t("loans.form.none") } %>
+ <%# 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,
+ not only by the Stimulus controller, so a save without JavaScript
+ behaves the same. A disabled input is not submitted, so a fixed loan
+ sends no rate_changes key and its recorded changes are retained
+ rather than cleared. Switching the select to variable enables and
+ reveals the retained rows, and the save resubmits them. The rows sit
+ in a disclosure that opens closed, as Additional details does. %>
+ <% rate_changes_disabled = !account.loan.variable_rate_type? %>
+ <div data-loan-rate-changes-target="section" <%= "hidden" if rate_changes_disabled %>>
+ <%= render DS::Disclosure.new(variant: :inline, body_class: "space-y-2 mt-2 pl-4 border-l border-primary") do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <span class="text-sm text-secondary hover:text-primary flex items-center gap-1 py-2">
+ <%= icon "chevron-right", size: "sm", class: "group-open:rotate-90 transition-transform" %>
+ <%= t("loans.form.rate_changes") %>
+ </span>
+ <% end %>
+
+ <p class="text-xs text-secondary"><%= t("loans.form.rate_changes_hint") %></p>
+
+ <%# Submitted whenever the section is enabled, so removing the last row
+ still sends the key and the writer is called to clear the schedule.
+ Without it, "remove them all" would send nothing and silently leave
+ them persisted. Disabled with the section: on a fixed loan this
+ input alone would otherwise submit and clear the retained rows. %>
+ <input type="hidden" name="account[accountable_attributes][rate_changes][]" value=""
+ <%= "disabled" if rate_changes_disabled %>>
+
+ <div data-loan-rate-changes-target="rows" class="space-y-2">
+ <% account.loan.rate_change_rows.each do |row| %>
+ <%= render "loans/rate_change_row",
+ effective_date: row[:effective_date], rate: row[:rate],
+ disabled: rate_changes_disabled %>
+ <% end %>
+ </div>
+
+ <p data-loan-rate-changes-target="empty" class="text-xs text-subdued"
+ <%= "hidden" if account.loan.rate_change_rows.any? %>>
+ <%= t("loans.form.rate_changes_empty") %>
+ </p>
+
+ <template data-loan-rate-changes-target="template">
+ <%= render "loans/rate_change_row", effective_date: nil, rate: nil %>
+ </template>
+
+ <%= render DS::Button.new(text: t("loans.form.rate_change_add"), icon: "plus", variant: "ghost", type: "button",
+ disabled: rate_changes_disabled, data: { action: "loan-rate-changes#add" }) %>
+ <% end %>
</div>
- <% end %>
- </div>
+ </div>
+ <% end %>
<% end %>
diff --git a/app/views/loans/_rate_change_field.html.erb b/app/views/loans/_rate_change_field.html.erb
new file mode 100644
index 0000000000..15baa64bb7
--- /dev/null
+++ b/app/views/loans/_rate_change_field.html.erb
@@ -0,0 +1,13 @@
+<%# locals: (label:, type:, name:, value:, disabled: false, attributes: {}) %>
+
+<%# The field shape StyledFormBuilder renders (.form-field, a label, the
+ input), written out because the builder labels through `for`/id and the
+ rate-change row is also the JS clone template, so an id would repeat on
+ every cloned row. The label wraps its input instead, which associates the
+ two without one. %>
+<div class="form-field">
+ <label class="form-field__body">
+ <span class="form-field__label"><%= label %></span>
+ <%= tag.input type: type, name: name, value: value, autocomplete: "off", class: "form-field__input", disabled: disabled, **attributes %>
+ </label>
+</div>
diff --git a/app/views/loans/_rate_change_row.html.erb b/app/views/loans/_rate_change_row.html.erb
new file mode 100644
index 0000000000..39132287f0
--- /dev/null
+++ b/app/views/loans/_rate_change_row.html.erb
@@ -0,0 +1,19 @@
+<%# locals: (effective_date:, rate:, disabled: false) %>
+
+<%# `disabled` is set server-side for a fixed loan so the row is not submitted
+ even without JavaScript; the Stimulus controller toggles it from there. %>
+<div class="flex items-center gap-2" data-rate-change-row>
+ <%= render "loans/rate_change_field",
+ label: t("loans.form.rate_change_effective_date"), type: "date",
+ name: "account[accountable_attributes][rate_changes][][effective_date]",
+ value: effective_date, disabled: disabled %>
+
+ <%= render "loans/rate_change_field",
+ label: t("loans.form.rate_change_rate"), type: "number",
+ name: "account[accountable_attributes][rate_changes][][rate]",
+ value: rate, disabled: disabled,
+ attributes: { step: "0.005", min: "0", max: "100" } %>
+
+ <%= render DS::Button.new(text: t("loans.form.rate_change_remove"), variant: "ghost", type: "button", class: "shrink-0",
+ disabled: disabled, data: { action: "loan-rate-changes#remove" }) %>
+</div>
diff --git a/app/views/loans/tabs/_overview.html.erb b/app/views/loans/tabs/_overview.html.erb
index 2c6d3810a6..ba574935fd 100644
--- a/app/views/loans/tabs/_overview.html.erb
+++ b/app/views/loans/tabs/_overview.html.erb
@@ -1,4 +1,9 @@
-<%# locals: (account:) %>
+<%# locals: (account:, as_of: Date.current) %>
+
+<%# ONE reference date for every figure on this tab, supplied by the caller
+ where it has one (the account page passes the same date to the Schedule
+ tab). %>
+<% today = as_of %>
<div class="grid grid-cols-3 gap-2">
<%= summary_card title: t(".original_principal") do %>
@@ -9,18 +14,29 @@
<%= format_money account.balance_money %>
<% end %>
+ <%# The rate in force today, not the one the loan was written at. On a
+ variable loan with a recorded change the Schedule tab beside this card
+ re-amortises at that change; quoting `interest_rate` here showed the
+ origination rate next to a schedule that no longer used it. For a fixed
+ loan, or before any change applies, this is the column unchanged. %>
<%= summary_card title: t(".interest_rate") do %>
- <% if account.loan.interest_rate.present? %>
- <%= number_to_percentage(account.loan.interest_rate, precision: 3) %>
+ <% current_rate = account.loan.current_variable_rate(today) %>
+ <% if current_rate.present? %>
+ <%= number_to_percentage(current_rate, precision: 3) %>
<% else %>
<%= t(".unknown") %>
<% end %>
<% end %>
+ <%# A fixed loan's contracted repayment. A variable loan has no single one, so
+ the card quotes the repayment in force today -- the next scheduled payment,
+ sized at every rate change recorded before it -- and N/A only when there
+ is no schedule or it has run out. %>
<%= summary_card title: t(".monthly_payment") do %>
- <% if account.loan.rate_type.present? && account.loan.rate_type != 'fixed' %>
- <%= t(".not_applicable") %>
- <% elsif account.loan.rate_type == 'fixed' && account.loan.monthly_payment.present? %>
+ <% if account.loan.variable_rate_type? %>
+ <% payment_in_force = account.loan.amortization_schedule&.payment_in_force(today) %>
+ <%= payment_in_force ? format_money(payment_in_force) : t(".not_applicable") %>
+ <% elsif account.loan.monthly_payment.present? %>
<%= format_money(account.loan.monthly_payment) %>
<% else %>
<%= t(".unknown") %>
@@ -39,6 +55,14 @@
<% end %>
<% end %>
+ <%# When the contract's last payment falls due. A variable loan keeps this
+ date through its rate changes -- the schedule resizes the repayment
+ instead -- so it is the loan's original payoff date either way. %>
+ <%= summary_card title: t(".original_payoff_date") do %>
+ <% original_payoff_date = account.loan.amortization_schedule&.payoff_date %>
+ <%= original_payoff_date ? l(original_payoff_date, format: :long) : t(".unknown") %>
+ <% end %>
+
<%= summary_card title: t(".type") do %>
<%= account.loan.rate_type&.titleize || t(".unknown") %>
<% end %>
diff --git a/app/views/loans/tabs/_schedule.html.erb b/app/views/loans/tabs/_schedule.html.erb
index aaaaa3330f..02ed316f37 100644
--- a/app/views/loans/tabs/_schedule.html.erb
+++ b/app/views/loans/tabs/_schedule.html.erb
@@ -5,8 +5,10 @@
<% today = Date.current %>
<div class="space-y-4">
- <div class="grid grid-cols-2 md:grid-cols-4 gap-2">
- <%= summary_card title: t(".monthly_payment") do %>
+ <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
+ <%# A re-amortising loan has no single monthly payment, so the card says
+ which one this is rather than implying the figure holds for the term. %>
+ <%= summary_card title: schedule.re_amortising? ? t(".opening_payment") : t(".monthly_payment") do %>
<%= format_money schedule.periodic_payment %>
<% end %>
@@ -17,16 +19,16 @@
<%= summary_card title: t(".total_cost") do %>
<%= format_money schedule.total_paid %>
<% end %>
-
- <%= summary_card title: t(".payoff_date") do %>
- <%= l schedule.payoff_date, format: :long %>
- <% end %>
</div>
<p class="text-sm text-secondary">
<%= t(".description", start_date: l(account.loan.origination_date, format: :long)) %>
</p>
+ <% if account.loan.variable_rate_type? %>
+ <p class="text-sm text-secondary"><%= t(".variable_rate_notice") %></p>
+ <% end %>
+
<div class="rounded-xl bg-container shadow-xs border border-alpha-black-25 overflow-hidden">
<div class="max-h-[32rem] overflow-y-auto overflow-x-auto">
<table class="w-full text-sm">
diff --git a/config/locales/models/loan/de.yml b/config/locales/models/loan/de.yml
new file mode 100644
index 0000000000..e4528e389a
--- /dev/null
+++ b/config/locales/models/loan/de.yml
@@ -0,0 +1,8 @@
+---
+de:
+ activerecord:
+ errors:
+ models:
+ loan:
+ invalid_rate_change: Jede Zinsänderung braucht einen Stichtag und einen Zinssatz.
+ rate_change_before_origination: Eine Zinsänderung kann nicht vor dem Beginn des Kredits wirksam werden.
diff --git a/config/locales/models/loan/en.yml b/config/locales/models/loan/en.yml
new file mode 100644
index 0000000000..0ab2f5360f
--- /dev/null
+++ b/config/locales/models/loan/en.yml
@@ -0,0 +1,8 @@
+---
+en:
+ activerecord:
+ errors:
+ models:
+ loan:
+ invalid_rate_change: Rate change rows need both an effective date and a rate.
+ rate_change_before_origination: A rate change cannot take effect before the loan originated.
diff --git a/config/locales/views/loans/de.yml b/config/locales/views/loans/de.yml
index 64cc4551dc..53ec2739c3 100644
--- a/config/locales/views/loans/de.yml
+++ b/config/locales/views/loans/de.yml
@@ -13,6 +13,15 @@ de:
rate_type_adjustable: Anpassbar
rate_type_fixed: Fest
rate_type_variable: Variabel
+ rate_changes: Zinsänderungen
+ rate_changes_hint: Jede Zeile legt den Zinssatz fest, der ab ihrem Stichtag bis zum nächsten gilt. Ein erneut eingegebener Stichtag ersetzt diese Zeile, statt eine zweite anzulegen.
+ rate_changes_empty: Keine Zinsänderungen erfasst. Der Kredit läuft mit dem oben angegebenen Zinssatz.
+ rate_change_effective_date: Stichtag
+ rate_change_rate: Zinssatz
+ rate_change_add: Zinsänderung hinzufügen
+ rate_change_remove: Entfernen
+ start_date: Auszahlungsdatum
+ start_date_hint: Wann der Kredit ausgezahlt wurde. Leer lassen, um das Eröffnungsdatum des Kontos zu verwenden.
none: Keine
subtype_none: Keine
subtype_prompt: Kreditart wählen
@@ -22,6 +31,7 @@ de:
interest_rate: Zinssatz
monthly_payment: Monatliche Zahlung
not_applicable: Nicht zutreffend
+ original_payoff_date: Ursprüngliches Ablösedatum
original_principal: Ursprünglicher Kreditbetrag
remaining_principal: Verbleibender Kreditbetrag
term: Laufzeit
@@ -30,12 +40,13 @@ de:
tabs:
schedule:
date: Datum
- description: Hochgerechnet aus ursprünglicher Kreditsumme, Zinssatz und Laufzeit, beginnend am %{start_date}. Sondertilgungen und Zinsänderungen sind nicht berücksichtigt.
+ description: Hochgerechnet aus ursprünglicher Kreditsumme, Zinssatz und Laufzeit, beginnend am %{start_date}. Sondertilgungen sind nicht berücksichtigt.
+ variable_rate_notice: Der Zinssatz dieses Kredits ändert sich im Laufe der Zeit. Der Tilgungsplan wird bei jeder erfassten Änderung neu berechnet; das ursprüngliche Ablösedatum bleibt, die Rate passt sich an. Eine noch nicht erfasste Änderung verschiebt diese Zahlen.
+ opening_payment: Anfangsrate
interest: Zinsen
monthly_payment: Monatsrate
number: "Nr."
payment: Rate
- payoff_date: Ablösedatum
principal: Tilgung
remaining_balance: Restschuld
total_cost: Gesamtkosten
@@ -45,6 +56,7 @@ de:
interest_rate: Zinssatz
monthly_payment: Monatsrate
not_applicable: "–"
+ original_payoff_date: Ursprüngliches Ablösedatum
original_principal: Ursprüngliche Kreditsumme
remaining_principal: Restschuld
term: Laufzeit
diff --git a/config/locales/views/loans/en.yml b/config/locales/views/loans/en.yml
index dccfe0c9f4..1df3da1169 100644
--- a/config/locales/views/loans/en.yml
+++ b/config/locales/views/loans/en.yml
@@ -16,26 +16,37 @@ en:
rate_type_adjustable: Adjustable
rate_type_fixed: Fixed
rate_type_variable: Variable
+ rate_changes: Rate changes
+ rate_changes_hint: Each row sets the rate that applies from its effective date until the next one. Re-entering a date replaces that row rather than adding a second.
+ rate_changes_empty: No rate changes recorded. The loan runs at its interest rate above.
+ rate_change_effective_date: Effective date
+ rate_change_rate: Rate
+ rate_change_add: Add rate change
+ 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.
new:
title: Enter loan details
overview:
interest_rate: Interest Rate
monthly_payment: Monthly Payment
not_applicable: N/A
- original_principal: Original Principal
- remaining_principal: Remaining Principal
+ original_payoff_date: Original Payoff Date
+ original_principal: Original Loan Amount
+ remaining_principal: Remaining Loan Amount
term: Term
type: Type
unknown: Unknown
tabs:
schedule:
date: Date
- description: Projected from the original balance, rate and term, starting %{start_date}. Extra payments and rate changes are not reflected.
+ description: Projected from the original balance, rate and term, starting %{start_date}. Extra payments are not reflected.
+ variable_rate_notice: This loan's rate changes over time. The schedule re-amortises at each recorded change, keeping the original payoff date and resizing the repayment; a change that has not been recorded yet will shift these figures.
+ opening_payment: Opening Payment
interest: Interest
monthly_payment: Monthly Payment
number: "#"
payment: Payment
- payoff_date: Payoff Date
principal: Principal
remaining_balance: Remaining Balance
total_cost: Total Cost
@@ -44,8 +55,9 @@ en:
interest_rate: Interest Rate
monthly_payment: Monthly Payment
not_applicable: N/A
- original_principal: Original Principal
- remaining_principal: Remaining Principal
+ original_payoff_date: Original Payoff Date
+ original_principal: Original Loan Amount
+ remaining_principal: Remaining Loan Amount
term: Term
type: Type
unknown: Unknown
diff --git a/db/migrate/20260908145118_add_variable_rate_tracking_to_loans.rb b/db/migrate/20260908145118_add_variable_rate_tracking_to_loans.rb
new file mode 100644
index 0000000000..eacacad149
--- /dev/null
+++ b/db/migrate/20260908145118_add_variable_rate_tracking_to_loans.rb
@@ -0,0 +1,13 @@
+class AddVariableRateTrackingToLoans < ActiveRecord::Migration[8.1]
+ def change
+ # Effective date => annual percentage, e.g. {"2026-04-01" => "6.15"}.
+ # A JSONB column rather than a table: a handful of rows per loan, always
+ # read together when a schedule is built, never queried across loans.
+ add_column :loans, :variable_rate_schedule, :jsonb, null: false, default: {}
+
+ # When the loan was drawn down. Optional -- origination otherwise comes
+ # from the account's first valuation, which is where it came from before
+ # this column existed and remains the answer for most loans.
+ add_column :loans, :start_date, :date
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 2e27333d2f..c6bca77a16 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1353,9 +1353,11 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_13_000000) do
t.decimal "interest_rate", precision: 10, scale: 3
t.jsonb "locked_attributes", default: {}
t.string "rate_type"
+ t.date "start_date"
t.string "subtype"
t.integer "term_months"
t.datetime "updated_at", null: false
+ t.jsonb "variable_rate_schedule", default: {}, null: false
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 5e433d639f..9c72aabc49 100644
--- a/test/controllers/loans_controller_test.rb
+++ b/test/controllers/loans_controller_test.rb
@@ -101,12 +101,476 @@ class LoansControllerTest < ActionDispatch::IntegrationTest
assert_match "Total Interest", response.body
end
+ # A variable loan IS amortizable since #104, and a provider's own rate type
+ # reads as variable since #100 decision 8, so the unamortizable case is now
+ # a loan with no rate type at all.
test "hides the schedule tab when the loan cannot be amortized" do
- @account.loan.update!(rate_type: "variable")
+ @account.loan.update!(rate_type: "")
get account_path(@account, tab: "schedule")
assert_response :success
assert_select "table tbody tr", count: 0
end
+
+ test "records rate changes and an origination date submitted through the form" do
+ patch loan_path(@account), params: {
+ account: {
+ accountable_attributes: {
+ id: @account.loan.id,
+ rate_type: "variable",
+ start_date: "2024-03-15",
+ rate_changes: [
+ { effective_date: "2026-04-01", rate: "7.25" },
+ { effective_date: "2026-10-01", rate: "6.5" },
+ { effective_date: "", rate: "" }
+ ]
+ }
+ }
+ }
+
+ @account.loan.reload
+ assert_equal({ "2026-04-01" => "7.25", "2026-10-01" => "6.5" }, @account.loan.variable_rate_schedule,
+ "the wholly blank sentinel row must be dropped rather than persisted or raising")
+ assert_equal Date.new(2024, 3, 15), @account.loan.start_date
+ assert_equal Date.new(2024, 3, 15), @account.loan.origination_date
+ end
+
+ test "the schedule tab reflects a recorded rate change" do
+ @account.loan.update!(rate_type: "variable", interest_rate: 6, term_months: 24)
+
+ get account_path(@account, tab: "schedule")
+ flat_body = response.body
+
+ # A year into the 24-month term, whatever today is. The fixture loan has no
+ # start_date, so its origination moves with the clock; a fixed date would
+ # fall before the first payment once the calendar passed it, and the
+ # schedule would stop re-amortising.
+ change_date = @account.loan.origination_date >> 12
+ @account.loan.update!(variable_rate_schedule: { change_date.iso8601 => "18.0" })
+ get account_path(@account, tab: "schedule")
+
+ assert_response :success
+ assert_not_equal flat_body, response.body,
+ "recording a rate change must change what the schedule tab renders"
+ # A substring free of characters ERB escapes -- the full string contains an
+ # apostrophe and renders as &#39;.
+ assert_match "re-amortises at each recorded change", response.body
+ assert_match I18n.t("loans.tabs.schedule.opening_payment"), response.body,
+ "a re-amortising schedule must not label its first payment as THE monthly payment"
+ end
+
+ # #100 decision 8: a provider writes rate types the form never offers. The
+ # select must still carry the loan's own value, or the browser submits the
+ # first option and saving any other field turns an "arm" loan into a fixed
+ # one without anyone choosing that.
+ test "the edit form keeps a provider-written rate type as the selected option" do
+ @account.loan.update!(rate_type: "arm")
+
+ get edit_loan_path(@account)
+
+ assert_response :success
+ assert_select "select[name='account[accountable_attributes][rate_type]'] option[value='arm'][selected]", { count: 1 },
+ "the provider's rate type must be the selected option"
+ assert_select "select[name='account[accountable_attributes][rate_type]'] option[value='fixed']", count: 1
+ assert_select "[data-loan-rate-changes-fixed-type-value='fixed']", count: 1
+ end
+
+ # A term the simulator will not walk leaves the loan without a schedule
+ # (see Loan#amortizable?). The model stays tolerant because a provider writes
+ # this column too; the form is where a person typing it is told the limit.
+ test "the term input declares the range a schedule can be built for" do
+ get edit_loan_path(@account)
+
+ assert_response :success
+ assert_select "input[name='account[accountable_attributes][term_months]'][min='1'][max='#{Loan::Simulator::MAX_PERIODS}']", count: 1
+ end
+
+ # A row with one half filled in is a typo, not a blank. Dropping it silently
+ # loses what the user typed between submit and redisplay and never tells them
+ # which row went.
+ test "a half-filled rate change is rejected rather than silently dropped" do
+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+
+ patch loan_path(@account), params: {
+ account: { accountable_attributes: {
+ id: @account.loan.id, rate_type: "variable",
+ rate_changes: [ { effective_date: "", rate: "9" } ]
+ } }
+ }
+
+ # Asserted on the response, not on a Loan rebuilt in the test: a redirect
+ # with the schedule untouched would otherwise pass.
+ assert_response :unprocessable_entity
+ assert_equal({ "2026-04-01" => "7.25" }, @account.loan.reload.variable_rate_schedule,
+ "a rejected submission must not alter the persisted schedule")
+ assert_select "input[name='account[accountable_attributes][rate_changes][][rate]'][value='9']", { count: 1 },
+ "the typed row comes back so the form can redisplay it"
+ end
+
+ # Removing every row must clear the schedule. Without the form's blank
+ # sentinel the PATCH carries no rate_changes key at all, nested assignment
+ # never calls the writer, and the removed rows stay persisted.
+ test "submitting only the blank sentinel clears the schedule" do
+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+
+ # The sentinel is a bare `rate_changes[]=` with no value, which Rack parses
+ # as "" and strong parameters drop, so the writer receives an empty array.
+ patch loan_path(@account), params: {
+ account: { accountable_attributes: {
+ id: @account.loan.id, rate_type: "variable", rate_changes: [ "" ]
+ } }
+ }
+
+ assert_empty @account.loan.reload.variable_rate_schedule
+ end
+
+ # The validation lives on Loan and is reached through nested attributes, which
+ # validate the nested record only when it has changes. Resubmitting the stored
+ # rows plus a typo'd one leaves the column equal to its stored value, so
+ # without `Loan#changed_for_autosave?` the account saved with a 302 and the
+ # typo'd row vanished.
+ test "an invalid row is rejected even when nothing else on the loan changed" do
+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+
+ patch loan_path(@account), params: { account: { accountable_attributes: {
+ id: @account.loan.id, rate_type: "variable",
+ rate_changes: [ "", { effective_date: "2026-04-01", rate: "7.25" }, { effective_date: "", rate: "9" } ]
+ } } }
+
+ assert_response :unprocessable_entity
+ assert_select "input[name='account[accountable_attributes][rate_changes][][rate]'][value='9']", { count: 1 },
+ "the typed row must come back for correction"
+ assert_equal({ "2026-04-01" => "7.25" }, @account.loan.reload.variable_rate_schedule)
+ end
+
+ # Retained rows are rendered for a fixed loan too, hidden and disabled, so
+ # switching the select to variable reveals them and a save keeps them.
+ # Before this, `rate_change_rows` was empty for a fixed loan, the revealed
+ # section was empty, and saving sent only the sentinel, which cleared them.
+ test "a fixed loan's retained rate changes survive switching to variable and saving" do
+ @account.loan.update!(rate_type: "fixed", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+
+ get edit_loan_path(@account)
+
+ assert_response :success
+ assert_select "[data-loan-rate-changes-target=rows] [data-rate-change-row]", count: 1
+ assert_select "[data-loan-rate-changes-target=rows] input[disabled][value='2026-04-01']", { count: 1 },
+ "retained rows are disabled while the loan is fixed, so they are not submitted"
+
+ # What the browser sends after the select is flipped to variable and the
+ # inputs are enabled: the sentinel and the row it rendered.
+ patch loan_path(@account), params: { account: { accountable_attributes: {
+ id: @account.loan.id, rate_type: "variable",
+ rate_changes: [ "", { effective_date: "2026-04-01", rate: "7.25" } ]
+ } } }
+
+ assert_equal({ "2026-04-01" => "7.25" }, @account.loan.reload.variable_rate_schedule)
+ assert_equal "variable", @account.loan.rate_type
+ end
+
+ # `disabled` used to be applied only by Stimulus, so without JavaScript the
+ # sentinel submitted and the writer read it as "remove them all".
+ test "the edit form of a fixed loan disables the whole rate-change section server-side" do
+ @account.loan.update!(rate_type: "fixed", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+
+ get edit_loan_path(@account)
+
+ assert_select "[data-loan-rate-changes-target=section][hidden]", count: 1
+ assert_select "[data-loan-rate-changes-target=section] input[name='account[accountable_attributes][rate_changes][]'][disabled]", { count: 1 },
+ "the sentinel must be disabled too, or a no-JS save clears the schedule"
+ # The <template> clone is inert and is left enabled; only rendered rows and
+ # the add button are submittable.
+ assert_select "[data-loan-rate-changes-target=rows] input:not([disabled])", count: 0
+ assert_select "[data-loan-rate-changes-target=rows] button:not([disabled])", count: 0
+ assert_select "[data-loan-rate-changes-target=section] button[data-action='loan-rate-changes#add']:not([disabled])", count: 0
+ end
+
+ test "a variable loan's edit form enables the rate-change section server-side" do
+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+
+ get edit_loan_path(@account)
+
+ assert_select "[data-loan-rate-changes-target=section][hidden]", count: 0
+ assert_select "[data-loan-rate-changes-target=rows] input[disabled]", count: 0
+ assert_select "[data-loan-rate-changes-target=section] input[name='account[accountable_attributes][rate_changes][]']:not([disabled])", count: 1
+ end
+
+ # Owner review of #3474: the rate changes open from a collapsed disclosure,
+ # as Additional details does, and the loan's fields keep the form's spacing
+ # instead of stacking flush against each other.
+ test "the rate changes sit in a collapsed disclosure and the loan fields are spaced" do
+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+
+ get edit_loan_path(@account)
+
+ assert_select "[data-loan-rate-changes-target=section] details:not([open]) > summary", text: /#{I18n.t("loans.form.rate_changes")}/
+ assert_select "[data-loan-rate-changes-target=section] details [data-loan-rate-changes-target=rows] input[name$='[rate]'][value='7.25']", count: 1
+ assert_select "[data-controller='loan-rate-changes'].space-y-2", count: 1
+ end
+
+ # Owner review of #3474: what kind of loan it is belongs with the account's
+ # own fields, straight after the balance, before the loan's terms.
+ test "the subtype sits under the balance, above the loan's terms" do
+ get edit_loan_path(@account)
+
+ body = response.body
+ balance = body.index('name="account[balance]"')
+ subtype = body.index('name="account[accountable_attributes][subtype]"')
+ terms = body.index('name="account[accountable_attributes][initial_balance]"')
+ assert balance && subtype && terms, "the balance, subtype and original balance fields must all render"
+ assert_operator balance, :<, subtype, "the subtype comes after the balance"
+ assert_operator subtype, :<, terms, "the subtype comes before the loan's terms"
+ end
+
+ # `Account.create_and_sync` saves with `save!`, and this is the first Loan
+ # validation a user can trip from the create form. Without a rescue the
+ # request ended on the generic 422 error page and the form was gone.
+ test "a half-filled rate change on create re-renders the form instead of the error page" do
+ assert_no_difference [ "Account.count", "Loan.count" ] do
+ post loans_path, params: { account: {
+ name: "Bad Loan", balance: 50_000, currency: "USD", accountable_type: "Loan",
+ accountable_attributes: {
+ rate_type: "variable", interest_rate: 6, term_months: 12, initial_balance: 50_000,
+ rate_changes: [ "", { effective_date: "", rate: "9" } ]
+ }
+ } }
+ end
+
+ assert_response :unprocessable_entity
+ assert_select "form[action='#{loans_path}']", count: 1, message: "the new-loan form comes back"
+ assert_select "input[name='account[accountable_attributes][rate_changes][][rate]'][value='9']", count: 1
+ assert_match "effective date and a rate", response.body
+ end
+
+ # The Overview tab quoted `loans.interest_rate`, the origination rate, while
+ # the Schedule tab beside it re-amortised at each recorded change.
+ test "the overview tab shows the rate in force, not the origination rate" do
+ # Drawn down two years ago, so the change a month ago re-sizes a repayment
+ # the loan was already making rather than setting its first one.
+ @account.loan.update!(rate_type: "variable", interest_rate: 6, start_date: Date.current - 2.years,
+ variable_rate_schedule: { (Date.current - 1.month).iso8601 => "7.25" })
+
+ get account_path(@account, tab: "overview")
+
+ assert_response :success
+ assert_select "h4", text: I18n.t("loans.tabs.overview.interest_rate")
+ assert_match "7.250%", response.body, "the recorded change is the rate in force"
+ assert_no_match "6.000%", response.body, "the origination rate is not what the loan is charging"
+
+ # Owner review of #3474: the repayment card quotes the scheduled repayment
+ # in force today -- the next payment on or after it, sized at the rates
+ # recorded so far -- rather than N/A.
+ schedule = @account.loan.amortization_schedule
+ in_force = schedule.payments.find { |payment| payment.date >= Date.current }.payment
+ assert_not_equal schedule.periodic_payment, in_force,
+ "the fixture must re-amortise before today, or this cannot tell today's repayment from the opening one"
+ # Scoped to the card: the Schedule tab's table on the same page lists every
+ # payment, so the figure turns up in the body whether or not the card has it.
+ card = css_select("h4").find { |title| title.text.strip == I18n.t("loans.tabs.overview.monthly_payment") }&.parent
+ assert card, "the overview has a monthly payment card"
+ assert_includes card.at_css("p").text,
+ ActiveSupport::NumberHelper.number_to_rounded(in_force.amount, precision: 2, delimiter: ","),
+ "the card quotes the repayment in force today"
+ assert_no_match I18n.t("loans.tabs.overview.not_applicable"), card.text
+ end
+
+ test "the overview tab of a fixed loan still shows its rate and monthly payment" do
+ @account.loan.update!(rate_type: "fixed", interest_rate: 6, term_months: 360)
+
+ get account_path(@account, tab: "overview")
+
+ assert_response :success
+ assert_match "6.000%", response.body
+ # 500,000 at 6% over 360 months, the fixture loan's contracted repayment.
+ assert_match "2,997.75", response.body
+ end
+
+ # Owner review of #3474: the Overview cards name the amounts as the loan
+ # amount rather than "principal".
+ test "the overview tab names the original and remaining loan amounts" do
+ get account_path(@account, tab: "overview")
+
+ assert_response :success
+ assert_select "h4", text: "Original Loan Amount", count: 1
+ assert_select "h4", text: "Remaining Loan Amount", count: 1
+ assert_select "h4", text: /Principal/, count: 0
+ end
+
+ # Owner review of #3474: the contract's payoff date is one of the loan's
+ # terms, so it sits with the others on Overview, named as the original date.
+ test "the overview tab shows the original payoff date and the schedule tab does not" do
+ payoff_date = @account.loan.amortization_schedule&.payoff_date
+ assert payoff_date, "the fixture loan must have a schedule, or there is no date to show"
+
+ get account_path(@account, tab: "overview")
+
+ assert_response :success
+ # Both tabs render into the page, so the card is found by its title and
+ # placed by the cards beside it.
+ card = css_select("h4").find { |title| title.text.strip == "Original Payoff Date" }&.parent
+ assert card, "the overview has an original payoff date card"
+ assert_equal I18n.l(payoff_date, format: :long), card.at_css("p").text.strip
+ assert card.parent.css("h4").any? { |title| title.text.strip == "Original Loan Amount" },
+ "the card sits among the Overview cards"
+ assert_select "h4", text: "Payoff Date", count: 0
+ end
+
+ # Codex on we-promise/sure#3473: `update` persisted the balance change (a
+ # valuation and the account's cached balance) before the loan's validation
+ # ran, so a rejected form had committed half of itself.
+ test "a rejected update does not persist the balance change submitted with it" do
+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+ balance_before = @account.reload.balance
+
+ assert_no_difference "Entry.count" do
+ patch loan_path(@account), params: { account: {
+ balance: balance_before - 10_000,
+ accountable_attributes: {
+ id: @account.loan.id, rate_type: "variable",
+ rate_changes: [ "", { effective_date: "2026-04-01", rate: "7.25" }, { effective_date: "", rate: "9" } ]
+ }
+ } }
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal balance_before, @account.reload.balance, "the balance half of a rejected form must not commit"
+ end
+
+ # CodeRabbit on we-promise/sure#3474: `lock_saved_attributes!` saves with
+ # `update!`. Run after the transaction had committed, a raise there left the
+ # balance change and the attribute update in place behind a failed request.
+ test "an update whose attribute lock fails commits neither the balance nor the attributes" do
+ balance_before = @account.reload.balance
+ name_before = @account.name
+ Account.any_instance.stubs(:lock_saved_attributes!).raises(ActiveRecord::RecordInvalid.new(@account))
+
+ assert_no_difference "Entry.count" do
+ patch loan_path(@account), params: { account: { name: "Renamed Loan", balance: balance_before - 10_000 } }
+ end
+
+ assert_response :unprocessable_entity
+ assert_select "form[action='#{loan_path(@account)}']", count: 1
+ assert_equal balance_before, @account.reload.balance, "the balance must roll back with the failed lock"
+ assert_equal name_before, @account.name, "the attribute update must roll back with the failed lock"
+ end
+
+ test "a successful balance update saves the other submitted values" do
+ balance_before = @account.reload.balance
+ updated_balance = balance_before - 10_000
+
+ patch loan_path(@account), params: { account: {
+ name: "Updated loan name",
+ balance: updated_balance,
+ accountable_attributes: { id: @account.loan.id, interest_rate: "7.25" }
+ } }
+
+ assert_redirected_to account_path(@account)
+ assert_equal updated_balance, @account.reload.balance
+ assert_equal "Updated loan name", @account.name
+ assert_equal BigDecimal("7.25"), @account.loan.reload.interest_rate
+ end
+
+ # CodeRabbit on we-promise/sure#3473: a failed balance result exits before
+ # the ordinary update path, so the 422 form must still receive the other
+ # values the user submitted.
+ test "a failed balance update keeps the other submitted values in the form" do
+ balance_before = @account.reload.balance
+ name_before = @account.name
+ rate_before = @account.loan.interest_rate
+ failed_balance = Account::CurrentBalanceManager::Result.new(
+ success?: false, changes_made?: false, error: "Balance update failed"
+ )
+ Account.any_instance.stubs(:set_current_balance).returns(failed_balance)
+
+ assert_no_difference "Entry.count" do
+ patch loan_path(@account), params: { account: {
+ name: "Unsaved loan name",
+ notes: "Unsaved loan notes",
+ balance: balance_before - 10_000,
+ accountable_attributes: { id: @account.loan.id, interest_rate: "7.25" }
+ } }
+ end
+
+ assert_response :unprocessable_entity
+ assert_select "input[name='account[name]'][value='Unsaved loan name']", count: 1
+ assert_select "input[name='account[accountable_attributes][interest_rate]'][value='7.25']", count: 1
+ assert_match "Balance update failed", response.body
+ assert_equal balance_before, @account.reload.balance
+ assert_equal name_before, @account.name
+ assert_equal rate_before, @account.loan.reload.interest_rate
+ end
+
+ # CodeRabbit on we-promise/sure#3473: `loans/new` renders the method
+ # selector when `step=method_select`, which reads `@provider_configs`; the
+ # rescue path must set it up as `new` does.
+ test "a rejected create with the method-select step still renders" do
+ post loans_path(step: "method_select"), params: { account: {
+ name: "Bad Loan", balance: 50_000, currency: "USD", accountable_type: "Loan",
+ accountable_attributes: { rate_type: "variable", interest_rate: 6, term_months: 12, initial_balance: 50_000,
+ rate_changes: [ "", { effective_date: "", rate: "9" } ] }
+ } }
+
+ assert_response :unprocessable_entity
+ end
+
+ test "the rate-change controls are design-system buttons" do
+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+
+ get edit_loan_path(@account)
+
+ assert_select "button[data-action='loan-rate-changes#add'] span", text: I18n.t("loans.form.rate_change_add")
+ assert_select "[data-rate-change-row] button[data-action='loan-rate-changes#remove'] span", text: I18n.t("loans.form.rate_change_remove")
+ end
+
+ # The design-system guide asks inputs to take the form's field shape. The rows
+ # were bare inputs outside any .form-field, so they rendered with no field
+ # border and no visible label. The partial is also the Stimulus clone
+ # template, so each label wraps its input rather than pointing at an id that
+ # every cloned row would repeat.
+ test "each rate-change input is a labelled form field without an id" do
+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "7.25" })
+
+ get edit_loan_path(@account)
+
+ assert_response :success
+ rows = "[data-loan-rate-changes-target=rows] [data-rate-change-row]"
+ assert_select "#{rows} .form-field label", count: 2
+ assert_select "#{rows} .form-field label input[type=date][value='2026-04-01']", count: 1
+ assert_select "#{rows} .form-field label input[type=number][value='7.25']", count: 1
+ assert_select "#{rows} .form-field__label", text: I18n.t("loans.form.rate_change_effective_date")
+ assert_select "#{rows} .form-field__label", text: I18n.t("loans.form.rate_change_rate")
+ # Unscoped on purpose: the <template> copy is the one every added row clones.
+ assert_select "[data-rate-change-row] input[id]", count: 0
+ end
+
+ # CodeRabbit on we-promise/sure#3473: `create_and_sync` can raise RecordInvalid
+ # from the opening valuation's `entries.create!` or from `lock_saved_attributes!`,
+ # and then `e.record` is an Entry or the accountable, not the account the form
+ # renders.
+ test "a create that fails on the opening valuation still re-renders the form" do
+ invalid_entry = Entry.new.tap(&:validate)
+ Account::OpeningBalanceManager.any_instance.stubs(:set_opening_balance)
+ .raises(ActiveRecord::RecordInvalid.new(invalid_entry))
+
+ assert_no_difference "Account.count" do
+ post loans_path, params: { account: {
+ name: "Loan With Bad Anchor", balance: 50_000, currency: "USD", accountable_type: "Loan",
+ accountable_attributes: { rate_type: "fixed", interest_rate: 6, term_months: 12, initial_balance: 50_000 }
+ } }
+ end
+
+ assert_response :unprocessable_entity
+ assert_select "form[action='#{loans_path}']", count: 1
+ end
end
diff --git a/test/models/account_test.rb b/test/models/account_test.rb
index 646e898e25..9d4f8d3cf2 100644
--- a/test/models/account_test.rb
+++ b/test/models/account_test.rb
@@ -21,6 +21,13 @@ class AccountTest < ActiveSupport::TestCase
admin = users(:empty)
super_admin = users(:sure_support_staff)
+ # Fixtures stamp every row with one `created_at`, and this family holds a
+ # second admin (`sso_only`), so "the earliest admin" is only meaningful
+ # once the timestamps differ. Without this the assertion below rides on
+ # whichever admin the query plan happens to return first.
+ family.users.update_all(created_at: 1.hour.ago)
+ admin.update!(created_at: 2.hours.ago)
+
Current.reset
account = family.accounts.create!(
@@ -34,6 +41,30 @@ class AccountTest < ActiveSupport::TestCase
assert_not_equal super_admin, account.owner
end
+ test "default owner is stable when two admins share a created_at" do
+ family = families(:empty)
+ family.users.where(role: "admin").update_all(created_at: 1.hour.ago)
+
+ Current.reset
+
+ owners = 2.times.map do |i|
+ family.accounts.create!(
+ name: "Unowned tie-break account #{i}",
+ balance: 0,
+ currency: "USD",
+ accountable: Depository.new
+ ).owner
+ end
+
+ # `id` breaks the tie, so the winner is the tied admin with the lowest id.
+ # Asserting only that the two calls agree would pass without the
+ # tie-breaker whenever the database returned the same tied row twice.
+ expected_owner = family.users.where(role: "admin").order(:id).first
+
+ assert_equal expected_owner, owners.first
+ assert_equal expected_owner, owners.last
+ end
+
test "create_and_sync calls sync_later by default" do
Account.any_instance.expects(:sync_later).once
diff --git a/test/models/demo/generator_test.rb b/test/models/demo/generator_test.rb
index 3cf99b4222..5c216bbc33 100644
--- a/test/models/demo/generator_test.rb
+++ b/test/models/demo/generator_test.rb
@@ -55,6 +55,65 @@ class Demo::GeneratorTest < ActiveSupport::TestCase
end
end
+ # The demo family's loans were bare Loan.new records -- no rate, no term, and
+ # the mortgage's principal a transaction rather than an opening valuation --
+ # so none of them had a schedule to show. The mortgage is adjustable with
+ # recorded changes, so the demo shows a schedule re-amortising; the other two
+ # are fixed.
+ test "demo loans carry the terms and principal a schedule is built from" do
+ @family.update!(currency: "USD")
+ generator = Demo::Generator.new(seed: 42)
+ generator.send(:create_realistic_categories!, @family)
+ generator.send(:create_realistic_accounts!, @family)
+ generator.send(:generate_major_purchases!)
+
+ mortgage = @family.accounts.find_by!(name: "Home Mortgage").loan
+ assert mortgage.variable_rate_type?, "the demo mortgage should be adjustable"
+ assert_equal BigDecimal("320000"), mortgage.original_balance.amount
+ assert_equal mortgage.start_date, mortgage.origination_date
+ assert mortgage.amortization_schedule.re_amortising?,
+ "a recorded rate change must move the demo mortgage's repayment"
+
+ [ "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"
+ assert loan.amortization_schedule&.payments&.any?, "#{name} should have a schedule"
+ end
+ end
+
+ # Owner review of #3474: the demo loans' figures must add up. Each loan pays
+ # its own schedule's principal and interest and nothing else moves its
+ # balance, so today it owes what its schedule says -- except the student
+ # loan, which made one extra payment (2,000, a year ago) and so is ahead of
+ # its schedule for a real reason.
+ test "demo loans owe what their own schedules say, the student loan ahead by its extra payment" do
+ @family.update!(currency: "USD")
+ generator = Demo::Generator.new(seed: 42)
+ generator.send(:create_realistic_categories!, @family)
+ generator.send(:create_realistic_accounts!, @family)
+ generator.send(:generate_housing_transactions!)
+ generator.send(:generate_transportation_transactions!)
+ generator.send(:generate_major_purchases!)
+ generator.send(:generate_loan_payments!)
+ checking = generator.instance_variable_get(:@chase_checking)
+ today = Date.current
+
+ { "Home Mortgage" => 0, "Car Loan" => 0, "Student Loan" => 2_000 }.each do |name, extra|
+ account = @family.accounts.find_by!(name: name)
+ Sync.create!(syncable: account).perform
+ due = account.reload.loan.amortization_schedule.payments.select { |payment| payment.date <= today }
+ assert due.any?, "#{name} must have payments due, or this asserts nothing"
+ assert_in_delta due.last.ending_balance.amount - extra, account.balance, 0.01,
+ "#{name} must owe its schedule's balance today#{" less its extra payment" if extra.positive?}"
+ end
+
+ student = @family.accounts.find_by!(name: "Student Loan").loan
+ due = student.amortization_schedule.payments.select { |payment| payment.date <= today }
+ booked_interest = checking.entries.where(name: "Student Loan Payment Interest").sum(:amount)
+ assert_in_delta due.sum { |payment| payment.interest.amount }, booked_interest, 0.01,
+ "the interest booked must be the schedule's interest, not a flat figure"
+ end
+
private
def create_user!(family, email)
family.users.create!(
diff --git a/test/models/loan/amortization_schedule_test.rb b/test/models/loan/amortization_schedule_test.rb
index fc9fc0647a..06ad2cd7c4 100644
--- a/test/models/loan/amortization_schedule_test.rb
+++ b/test/models/loan/amortization_schedule_test.rb
@@ -104,9 +104,30 @@ class Loan::AmortizationScheduleTest < ActiveSupport::TestCase
assert_equal BigDecimal("2245.22"), Loan::AmortizationSchedule.for(loan).periodic_payment.amount
end
- test "is not buildable for a variable rate loan" do
+ # Reversed by #104. A variable loan was excluded while a schedule could only
+ # be built off one rate; it now re-amortises at each recorded change, so the
+ # reason for the exclusion is gone.
+ test "is buildable for a variable rate loan" do
loan = loan_account(interest_rate: 3.5, term_months: 360, rate_type: "variable").loan
+ assert_not_nil Loan::AmortizationSchedule.for(loan)
+ end
+
+ # A rate type outside the form's vocabulary is still a rate type (#100
+ # decision 8). PlaidAccount::Liabilities::MortgageProcessor writes Plaid's
+ # raw `interest_rate.type` straight through, so this is reachable from a
+ # sync, not only from the form, and such a loan is variable rather than
+ # unknown.
+ test "is buildable for a provider's own rate type" do
+ loan = loan_account(interest_rate: 3.5, term_months: 360, rate_type: "teaser").loan
+
+ assert_not_nil Loan::AmortizationSchedule.for(loan)
+ end
+
+ # What is still not buildable: no rate type at all.
+ test "is not buildable for a blank rate type" do
+ loan = loan_account(interest_rate: 3.5, term_months: 360, rate_type: "").loan
+
assert_nil Loan::AmortizationSchedule.for(loan)
end
diff --git a/test/models/loan/simulator_test.rb b/test/models/loan/simulator_test.rb
new file mode 100644
index 0000000000..fc05f09815
--- /dev/null
+++ b/test/models/loan/simulator_test.rb
@@ -0,0 +1,229 @@
+require "test_helper"
+
+class Loan::SimulatorTest < ActiveSupport::TestCase
+ # 12 monthly payments through 2026.
+ SCHEDULE = (1..12).map { |n| Date.new(2026, 1, 1) >> n }.freeze
+
+ test "runs one payment per scheduled date and amortises to zero" do
+ result = run_simulation(starting_balance: 12_000, rate: 6)
+
+ assert_equal 12, result.payment_count
+ assert_equal BigDecimal("0"), result.payments.last[:ending_balance]
+ assert_equal Date.new(2027, 1, 1), result.payoff_date
+ end
+
+ test "principal payments sum to the starting balance" do
+ result = run_simulation(starting_balance: 12_000, rate: 6)
+
+ assert_equal BigDecimal("12000"),
+ result.payments.sum(BigDecimal("0")) { |p| p[:principal_payment] }
+ end
+
+ # Every run in this engine clears the balance: the level payment is sized
+ # from the balance and the periods remaining, and the final period settles
+ # exactly. Pinned so that a later change which CAN leave a balance
+ # outstanding -- a projection holding a contracted payment against a
+ # different balance -- has to confront this test rather than slip past it.
+ test "the final period settles the balance exactly, whatever the rounding" do
+ [ [ 12_000, 6 ], [ 10, 0 ], [ 999_999, 17.25 ], [ 1, 3.5 ] ].each do |balance, rate|
+ result = run_simulation(starting_balance: balance, rate: rate)
+
+ assert_equal BigDecimal("0"), result.payments.last[:ending_balance],
+ "#{balance} at #{rate}% left a balance outstanding"
+ assert_equal BigDecimal(balance.to_s),
+ result.payments.sum(BigDecimal("0")) { |p| p[:principal_payment] },
+ "#{balance} at #{rate}% did not repay its principal exactly"
+ end
+ end
+
+ test "a one-period loan at a positive rate settles principal and interest together" do
+ result = Loan::Simulator.new(
+ starting_balance: 1_000,
+ accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: [ Date.new(2026, 2, 1) ],
+ accrual_rate_for: ->(_date) { 12 },
+ currency_precision: 2
+ ).run
+
+ assert_equal BigDecimal("1010"), result.payments.first[:payment_amount]
+ assert_equal BigDecimal("0"), result.payments.first[:ending_balance]
+ end
+
+ test "a 360-period zero-rate loan remains outstanding before its final payment" do
+ schedule = (1..360).map { |month| Date.new(2026, 1, 1) >> month }
+ result = Loan::Simulator.new(
+ starting_balance: 360_000,
+ accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: schedule,
+ accrual_rate_for: ->(_date) { 0 },
+ currency_precision: 2
+ ).run
+
+ assert_equal BigDecimal("180000"), result.payments[179][:ending_balance],
+ "the 180th payment must not trigger early settlement at a zero rate"
+ assert_equal BigDecimal("0"), result.payments.last[:ending_balance]
+ assert_equal 360, result.payment_count
+ end
+
+ # THE behaviour this engine exists for, and the one #2984's single-rate loop
+ # cannot express. Asserted here rather than in #104 because it is a property
+ # of the simulator, not of how a Loan stores its rates.
+ #
+ # Interest for a period accrues at the rate in force when the period OPENED.
+ # A rate effective on the period's closing date belongs to the next window --
+ # the month being billed ran entirely at the old rate.
+ test "interest accrues at the rate in force when the period opened, not when it closed" do
+ change_date = Date.new(2026, 4, 1)
+ rate_for = ->(date) { date < change_date ? 6 : 24 }
+
+ result = Loan::Simulator.new(
+ starting_balance: 12_000,
+ accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: SCHEDULE,
+ accrual_rate_for: rate_for,
+ currency_precision: 2
+ ).run
+
+ # The period closing ON the change date (1 Mar -> 1 Apr) ran entirely at 6%.
+ closing_on_change = result.payments.find { |p| p[:payment_date] == change_date }
+ beginning = closing_on_change[:beginning_balance]
+ assert_equal (beginning * BigDecimal("6") / 100 / 12).round(2), closing_on_change[:interest_payment],
+ "the month ending on the rate change must be billed at the old rate"
+
+ # The next period (1 Apr -> 1 May) opened at 24% and is billed at it.
+ following = result.payments.find { |p| p[:payment_date] == Date.new(2026, 5, 1) }
+ assert_equal (following[:beginning_balance] * BigDecimal("24") / 100 / 12).round(2),
+ following[:interest_payment],
+ "the month opening on the rate change must be billed at the new rate"
+ end
+
+ test "reamortize resizes the payment when the rate moves; hold does not" do
+ change_date = Date.new(2026, 4, 1)
+ rate_for = ->(date) { date < change_date ? 6 : 24 }
+
+ reamortized, held = %i[reamortize hold].map do |strategy|
+ Loan::Simulator.new(
+ starting_balance: 12_000,
+ accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: SCHEDULE,
+ accrual_rate_for: rate_for,
+ currency_precision: 2,
+ payment_strategy: strategy
+ ).run
+ end
+
+ first_payment = ->(r) { r.payments.first[:payment_amount] }
+ after_change = ->(r) { r.payments.find { |p| p[:payment_date] == change_date }[:payment_amount] }
+
+ assert_operator after_change.call(reamortized), :>, first_payment.call(reamortized),
+ "a reamortising loan resizes its repayment upward when the rate rises"
+ assert_equal first_payment.call(held), after_change.call(held),
+ "a held loan keeps the contracted repayment through a rate change"
+ end
+
+ test "a re-amortisation event sizes the payment from its own effective date" do
+ result = Loan::Simulator.new(
+ starting_balance: 12_000,
+ accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: SCHEDULE,
+ accrual_rate_for: ->(_date) { 6 },
+ re_amortisation_events: ->(_from, _to) { [ { date: Date.new(2026, 7, 1), rate: 24 } ] },
+ currency_precision: 2
+ ).run
+
+ before = result.payments.find { |p| p[:payment_date] == Date.new(2026, 6, 1) }
+ on = result.payments.find { |p| p[:payment_date] == Date.new(2026, 7, 1) }
+
+ assert_operator on[:payment_amount], :>, before[:payment_amount]
+ # Two rates on the row that closes on the change: the period accrued at the
+ # old rate and the payment was sized at the new one. `interest_rate` is the
+ # one the interest column was computed with, so a reader who recomputes
+ # beginning_balance * rate / 12 gets the row's own figure.
+ assert_equal BigDecimal("24"), on[:sizing_rate]
+ assert_equal BigDecimal("6"), on[:interest_rate]
+ assert_equal (on[:beginning_balance] * on[:interest_rate] / 100 / 12).round(2), on[:interest_payment]
+ assert_equal BigDecimal("6"), before[:interest_rate]
+ # This run's accrual curve is flat at 6%; only the sizing events move, so
+ # the rows after the change still accrue at 6 and size at 24.
+ after = result.payments.find { |p| p[:payment_date] == Date.new(2026, 8, 1) }
+ assert_equal BigDecimal("6"), after[:interest_rate]
+ assert_equal BigDecimal("24"), after[:sizing_rate]
+ end
+
+ # A resized payment must stay level to maturity. The period that closes on a
+ # rate change accrued at the OLD rate, but the annuity formula assumes every
+ # remaining period, this one included, accrues at the new one; sized that
+ # way, the payment over-covers the first period and the final settlement
+ # becomes a discount of thousands. Codex's example on we-promise/sure#3473:
+ # 500,000 over 24 months, 6% to 18% at month six, level 24,394.64, final
+ # 19,156.02.
+ test "a resized payment stays level through the final settlement" do
+ change_date = Date.new(2026, 7, 1)
+ [ change_date, Date.new(2026, 6, 20) ].each do |effective|
+ result = Loan::Simulator.new(
+ starting_balance: 500_000,
+ accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: (1..24).map { |n| Date.new(2026, 1, 1) >> n },
+ accrual_rate_for: ->(date) { date < effective ? 6 : 18 },
+ re_amortisation_events: ->(_from, _to) { [ { date: effective, rate: 18 } ] },
+ currency_precision: 2
+ ).run
+
+ resized = result.payments.find { |p| p[:payment_date] >= effective }[:payment_amount]
+ assert_operator resized, :>, result.payments.first[:payment_amount]
+ assert_in_delta resized, result.payments.last[:payment_amount], 1.0,
+ "change effective #{effective}: the final payment must settle within rounding of the level payment"
+ assert_equal BigDecimal("500000"),
+ result.payments.sum(BigDecimal("0")) { |p| p[:principal_payment] }
+ end
+ end
+
+ test "refuses an empty payment schedule rather than inventing a run" do
+ error = assert_raises(ArgumentError) do
+ Loan::Simulator.new(
+ starting_balance: 1000, accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: [], accrual_rate_for: ->(_d) { 5 }, currency_precision: 2
+ )
+ end
+ assert_match(/must not be empty/, error.message)
+ end
+
+ test "refuses an unknown payment strategy" do
+ assert_raises(ArgumentError) do
+ Loan::Simulator.new(
+ starting_balance: 1000, accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: SCHEDULE, accrual_rate_for: ->(_d) { 5 },
+ currency_precision: 2, payment_strategy: :guess
+ )
+ end
+ end
+
+
+ # Truncating a longer schedule would return totals and a payoff date for a
+ # loan nobody asked for, and drop the remaining balance without saying so.
+ test "refuses a schedule longer than it will walk rather than truncating it" do
+ over = (1..(Loan::Simulator::MAX_PERIODS + 1)).map { |n| Date.new(2026, 1, 1) >> n }
+
+ error = assert_raises(ArgumentError) do
+ Loan::Simulator.new(
+ starting_balance: 100_000, accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: over, accrual_rate_for: ->(_d) { 5 }, currency_precision: 2
+ )
+ end
+ # The message carries the schedule it refused, so a report of it says
+ # which run tripped the guard rather than only restating the limit.
+ assert_match(/has 1201 periods \(2026-02-01 to 2126-02-01\), more than the 1200 allowed/, error.message)
+ end
+
+ private
+ def run_simulation(starting_balance:, rate:, **overrides)
+ Loan::Simulator.new(
+ starting_balance: starting_balance,
+ accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: SCHEDULE,
+ accrual_rate_for: ->(_date) { rate },
+ currency_precision: 2,
+ **overrides
+ ).run
+ end
+end
diff --git a/test/models/loan/variable_rate_schedule_test.rb b/test/models/loan/variable_rate_schedule_test.rb
new file mode 100644
index 0000000000..7276ac8cfe
--- /dev/null
+++ b/test/models/loan/variable_rate_schedule_test.rb
@@ -0,0 +1,344 @@
+require "test_helper"
+
+# The behaviour #104 exists for: a schedule that re-amortises at each recorded
+# rate change, and does so on the right dates.
+class Loan::VariableRateScheduleTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ end
+
+ test "a fixed loan is unaffected by this feature" do
+ fixed = build_loan(rate_type: "fixed")
+
+ # 500,000 at 6% over 360 months.
+ assert_equal BigDecimal("2997.75"), fixed.amortization_schedule.periodic_payment.amount
+ assert_equal 360, fixed.amortization_schedule.payments.count
+ assert_not fixed.amortization_schedule.re_amortising?
+ end
+
+ test "a variable loan with no recorded changes runs at its base rate" do
+ variable = build_loan(rate_type: "variable")
+ fixed = build_loan(rate_type: "fixed")
+
+ assert_not variable.amortization_schedule.re_amortising?
+ assert_equal fixed.amortization_schedule.total_interest,
+ variable.amortization_schedule.total_interest,
+ "a variable loan with no changes recorded is running at its base rate, and must cost the same"
+ end
+
+ test "a recorded rate change resizes the repayment from its effective date" do
+ loan = build_loan(
+ rate_type: "variable", term_months: 24, start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-07-01" => "18.0" }
+ )
+ payments = loan.amortization_schedule.payments
+
+ before = payments.find { |p| p.date == Date.new(2026, 6, 1) }
+ on_change = payments.find { |p| p.date == Date.new(2026, 7, 1) }
+
+ assert loan.amortization_schedule.re_amortising?
+ assert_operator on_change.payment.amount, :>, before.payment.amount
+ end
+
+ # C10. Accrual windows are half-open: a rate effective 1 July belongs to
+ # [Jul 1, Aug 1), not to the June that ran entirely at the old rate. Reading
+ # one rate for both accrual and payment sizing bills the month ENDING on the
+ # boundary at a rate that applied for none of it.
+ test "a rate change landing on a payment date does not re-rate the month before it" do
+ loan = build_loan(
+ rate_type: "variable", term_months: 24, start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-07-01" => "18.0" }
+ )
+ payments = loan.amortization_schedule.payments
+ closing_on_change = payments.find { |p| p.date == Date.new(2026, 7, 1) }
+
+ # 6% on the balance the June->July window opened with, not 18%.
+ expected = (closing_on_change.ending_balance.amount + closing_on_change.principal.amount) *
+ BigDecimal("6") / 100 / 12
+
+ assert_in_delta expected.to_f, closing_on_change.interest.amount.to_f, 0.01,
+ "the month ending on the rate change must still be billed at the old rate"
+ end
+
+ # Regression for we-promise/sure#3296's second blocking finding. A segment
+ # spanning a single 30-day month is `floor(30 / 30.44) == 0` payments under
+ # average-month arithmetic, and was silently skipped. This engine counts real
+ # payment dates, so the segment cannot vanish -- pinned end-to-end on the
+ # money, because a skipped segment leaves a well-formed schedule and raises
+ # nothing.
+ test "a rate spike confined to a single 30-day month is charged, not skipped" do
+ spiked = build_loan(
+ rate_type: "variable", term_months: 24, start_date: Date.new(2026, 1, 1),
+ variable_rate_schedule: { "2026-04-01" => "18.0", "2026-05-01" => "6.0" }
+ )
+ flat = build_loan(rate_type: "variable", term_months: 24, start_date: Date.new(2026, 1, 1))
+
+ assert_equal 30, (Date.new(2026, 5, 1) - Date.new(2026, 4, 1)).to_i,
+ "premise: the segment under test spans a 30-day month"
+
+ assert_operator spiked.amortization_schedule.total_interest.amount,
+ :>, flat.amortization_schedule.total_interest.amount,
+ "a rate spike confined to one 30-day month must change the interest charged"
+ end
+
+ test "current_variable_rate reads the change in force, and the base rate before any" do
+ loan = build_loan(
+ rate_type: "variable",
+ variable_rate_schedule: { "2026-04-01" => "18.0", "2026-07-01" => "9.5" }
+ )
+
+ assert_equal BigDecimal("6"), loan.current_variable_rate(Date.new(2026, 3, 31))
+ assert_equal BigDecimal("18.0"), loan.current_variable_rate(Date.new(2026, 4, 1))
+ assert_equal BigDecimal("18.0"), loan.current_variable_rate(Date.new(2026, 6, 30))
+ assert_equal BigDecimal("9.5"), loan.current_variable_rate(Date.new(2026, 7, 1))
+ end
+
+ test "a rate change before origination is rejected but one on origination is accepted" do
+ origination = Date.new(2026, 1, 1)
+ loan = build_loan(rate_type: "variable", start_date: origination)
+
+ loan.rate_changes = [ { effective_date: "2025-12-31", rate: "7.25" } ]
+
+ assert_not loan.valid?
+ assert loan.errors.of_kind?(:base, :rate_change_before_origination)
+ assert_equal [ { effective_date: "2025-12-31", rate: "7.25" } ], loan.rate_change_rows,
+ "the invalid row remains available to redisplay"
+
+ loan.errors.clear
+ loan.rate_changes = [ { effective_date: origination.iso8601, rate: "7.25" } ]
+
+ assert loan.valid?
+ assert_empty loan.errors
+ assert_equal BigDecimal("7.25"), loan.current_variable_rate(origination)
+ end
+
+ test "rate change validation uses the account's first valuation when start date is blank" do
+ origination = Date.new(2026, 1, 1)
+ loan = build_loan(rate_type: "variable")
+ loan.start_date = nil
+ loan.account.entries.create!(
+ name: "Opening balance", amount: 500_000, currency: "USD",
+ date: origination, entryable: Valuation.new(kind: "opening_anchor")
+ )
+ loan.account.reload
+
+ loan.rate_changes = [ { effective_date: "2025-12-31", rate: "7.25" } ]
+ assert_not loan.valid?, "a rate change before the account's first valuation is invalid"
+ assert loan.errors.of_kind?(:base, :rate_change_before_origination)
+
+ loan.errors.clear
+ loan.rate_changes = [ { effective_date: origination.iso8601, rate: "7.25" } ]
+ assert loan.valid?, "a rate change on the account's first valuation is valid"
+ end
+
+ # One reader of the column. `RateResolver` used to re-parse what
+ # `variable_rates` had already sorted by, so the two read paths returned
+ # different types for the same rows, and a parsing fix could land in one
+ # and not the other.
+ test "variable_rates is the one parsed reading of the column, dated and decimal" do
+ loan = build_loan(
+ rate_type: "variable",
+ variable_rate_schedule: { "2026-07-01" => "9.5", "2026-04-01" => "18.0" }
+ )
+
+ assert_equal [ [ Date.new(2026, 4, 1), BigDecimal("18.0") ], [ Date.new(2026, 7, 1), BigDecimal("9.5") ] ],
+ loan.variable_rates
+ assert_equal [ Date, BigDecimal ], loan.variable_rates.first.map(&:class)
+ assert_equal [ { effective_date: "2026-04-01", rate: "18.0" }, { effective_date: "2026-07-01", rate: "9.5" } ],
+ loan.rate_change_rows, "the form still renders what was stored"
+ end
+
+ test "a fixed loan ignores any rate changes recorded against it" do
+ loan = build_loan(rate_type: "fixed", variable_rate_schedule: { "2026-04-01" => "18.0" })
+
+ assert_equal BigDecimal("6"), loan.current_variable_rate(Date.new(2026, 12, 1))
+ assert_not loan.amortization_schedule.re_amortising?
+ end
+
+ test "re-entering an effective date replaces that row rather than adding a second" do
+ loan = build_loan(rate_type: "variable")
+
+ loan.rate_changes = [
+ { effective_date: "2026-04-01", rate: "7.5" },
+ { effective_date: "2026-04-01", rate: "8.25" }
+ ]
+
+ assert_equal({ "2026-04-01" => "8.25" }, loan.variable_rate_schedule)
+ end
+
+ test "incomplete and unparseable rows are captured while valid rows are parsed" do
+ loan = build_loan(rate_type: "variable")
+
+ loan.rate_changes = [
+ { effective_date: "", rate: "7.5" },
+ { effective_date: "2026-04-01", rate: "" },
+ { effective_date: "not a date", rate: "7.5" },
+ { effective_date: "2026-05-01", rate: "7.5" }
+ ]
+
+ assert_equal({ "2026-05-01" => "7.5" }, loan.variable_rate_schedule)
+ assert_equal [
+ { effective_date: "", rate: "7.5" },
+ { effective_date: "2026-04-01", rate: "" },
+ { effective_date: "not a date", rate: "7.5" }
+ ], loan.invalid_rate_changes
+ end
+
+ # The earlier version of this test never created a valuation, so
+ # `first_valuation` was nil and the first assertion compared the opening
+ # anchor with itself -- it passed without exercising the branch it named.
+ test "origination prefers a recorded start date over the account's first valuation" do
+ loan = build_loan(rate_type: "fixed")
+ loan.account.entries.create!(
+ name: "Opening balance", amount: 500_000, currency: "USD",
+ date: Date.new(2022, 6, 1), entryable: Valuation.new(kind: "opening_anchor")
+ )
+ loan.account.reload
+
+ assert_equal Date.new(2022, 6, 1), loan.reload.origination_date,
+ "with no start_date, origination is the account's first valuation"
+
+ loan.update!(start_date: Date.new(2020, 3, 15))
+ assert_equal Date.new(2020, 3, 15), loan.origination_date,
+ "a recorded start_date outranks the first valuation"
+ end
+
+
+ # `periodic_payment` used to re-derive the annuity from the loan's base rate.
+ # A change effective ON the first payment date already sizes that payment, so
+ # the card quoted a rate for a payment the borrower will never make.
+ test "the opening payment reflects a rate change effective on the first payment date" do
+ start_date = Date.new(2026, 1, 1)
+ first_payment = start_date >> 1
+
+ base = build_loan(rate_type: "variable", term_months: 24, start_date: start_date)
+ changed = build_loan(rate_type: "variable", term_months: 24, start_date: start_date,
+ variable_rate_schedule: { first_payment.iso8601 => "18.0" })
+
+ assert_equal changed.amortization_schedule.payments.first.payment,
+ changed.amortization_schedule.periodic_payment,
+ "the quoted opening payment must be the payment actually scheduled"
+ assert_operator changed.amortization_schedule.periodic_payment.amount, :>,
+ base.amortization_schedule.periodic_payment.amount
+ # Every payment is sized at the changed rate, so nothing re-amortises
+ # in-term and the card may call this figure THE monthly payment.
+ assert_not changed.amortization_schedule.re_amortising?,
+ "a change effective on the first payment resizes nothing in-term"
+ end
+
+ # CodeRabbit on we-promise/sure#3473: `re_amortising?` answered on event
+ # presence, so a recorded change that never moves the repayment (the same
+ # rate again, or one effective on the first payment) labelled a constant
+ # payment "Opening Payment".
+ test "re_amortising? is true only when the repayment actually moves in-term" do
+ start_date = Date.new(2026, 1, 1)
+ same_rate = build_loan(rate_type: "variable", term_months: 24, start_date: start_date,
+ variable_rate_schedule: { "2026-07-01" => "6.0" })
+ moved = build_loan(rate_type: "variable", term_months: 24, start_date: start_date,
+ variable_rate_schedule: { "2026-07-01" => "7.0" })
+
+ assert_not same_rate.amortization_schedule.re_amortising?, "the same rate again is not a resize"
+ assert moved.amortization_schedule.re_amortising?
+ end
+
+
+ # `first_valuation_amount` is decimal(19,4) against two-decimal USD, so an
+ # opening balance can carry sub-unit precision the schedule cannot represent.
+ # Left unrounded it vanished in the first period and the principal portions
+ # summed to less than the loan.
+ test "an opening balance with sub-unit precision is still repaid exactly" do
+ schedule = Loan::AmortizationSchedule.new(
+ principal: BigDecimal("1000.1234"), annual_rate: 0, term_months: 4,
+ start_date: Date.new(2026, 1, 1), currency: "USD"
+ )
+ repaid = schedule.payments.sum(BigDecimal("0")) { |p| p.principal.amount }
+
+ assert_equal schedule.principal, repaid
+ assert_equal BigDecimal("1000.12"), schedule.principal, "rounded to the currency at the door"
+ end
+
+ # A term the simulator refuses to walk must not reach it. `Simulator` raises
+ # rather than truncating -- correct for the simulator -- but `amortizable?`
+ # let such a loan through, so building the schedule for one raised
+ # ArgumentError straight out of an account page render.
+ #
+ # Treated exactly as an unrecognised rate_type is: no schedule, no tab. The
+ # tolerant answer matters because term_months is also written by
+ # PlaidAccount::Liabilities::StudentLoanProcessor, from provider dates this
+ # app does not control.
+ test "a term longer than the simulator will walk is not amortizable, rather than raising" do
+ loan = build_loan(rate_type: "fixed", term_months: Loan::Simulator::MAX_PERIODS + 1)
+
+ assert_not loan.amortizable?
+ assert_nil loan.amortization_schedule
+
+ at_limit = build_loan(rate_type: "fixed", term_months: Loan::Simulator::MAX_PERIODS)
+ assert at_limit.amortizable?, "the limit itself is still a schedulable loan"
+ assert at_limit.amortization_schedule.payments.any?
+ end
+
+ # The rate input declares min="0" max="100"; a crafted PATCH does not have to
+ # honour it. A rate outside that range parses fine and then silently drives
+ # the projection.
+ test "a rate outside the range the form declares is rejected, not persisted" do
+ loan = build_loan(rate_type: "variable")
+
+ [ "-1", "101", "1e1000" ].each do |bad|
+ loan.rate_changes = [ { effective_date: "2027-01-01", rate: bad } ]
+
+ assert_empty loan.variable_rate_schedule, "#{bad.inspect} should not have been stored"
+ assert_equal [ { effective_date: "2027-01-01", rate: bad } ], loan.invalid_rate_changes
+ assert_not loan.valid?, "#{bad.inspect} should fail validation so the form can redisplay it"
+ end
+ end
+
+ test "the bounds themselves are accepted" do
+ loan = build_loan(rate_type: "variable")
+ loan.rate_changes = [ { effective_date: "2027-01-01", rate: "0" },
+ { effective_date: "2028-01-01", rate: "100" } ]
+
+ assert_empty loan.invalid_rate_changes
+ assert_equal({ "2027-01-01" => "0.0", "2028-01-01" => "100.0" }, loan.variable_rate_schedule)
+ end
+
+ # CodeRabbit on we-promise/sure#3474: the schedule is memoised on the loan.
+ # Assigning any input it is built from must drop it, or a later read on the
+ # same instance answers with the old terms.
+ test "changing an input the schedule is built from rebuilds the schedule" do
+ loan = build_loan(rate_type: "variable", term_months: 24, start_date: Date.new(2026, 1, 1))
+ assert_not loan.amortization_schedule.re_amortising?
+
+ loan.rate_changes = [ { effective_date: "2026-07-01", rate: "18" } ]
+ assert loan.amortization_schedule.re_amortising?, "rate_changes= must drop the memoised schedule"
+
+ opening_payment = loan.amortization_schedule.periodic_payment.amount
+ loan.interest_rate = 9
+ assert_operator loan.amortization_schedule.periodic_payment.amount, :>, opening_payment,
+ "interest_rate= must drop the memoised schedule"
+
+ loan.term_months = 12
+ assert_equal 12, loan.amortization_schedule.payments.count, "term_months= must drop the memoised schedule"
+
+ loan.reload
+ assert_equal 24, loan.amortization_schedule.payments.count, "reload must drop the memoised schedule"
+ end
+
+ private
+ def build_loan(rate_type:, interest_rate: 6, term_months: 360, start_date: nil,
+ variable_rate_schedule: {})
+ Account.create!(
+ family: @family,
+ name: "Loan #{SecureRandom.hex(4)}",
+ balance: 500_000,
+ currency: "USD",
+ accountable: Loan.new(
+ subtype: "mortgage",
+ interest_rate: interest_rate,
+ term_months: term_months,
+ rate_type: rate_type,
+ start_date: start_date,
+ variable_rate_schedule: variable_rate_schedule
+ )
+ ).loan
+ end
+end
diff --git a/test/models/loan_test.rb b/test/models/loan_test.rb
index 438952e972..1d5d2fb985 100644
--- a/test/models/loan_test.rb
+++ b/test/models/loan_test.rb
@@ -41,9 +41,70 @@ class LoanTest < ActiveSupport::TestCase
assert_not loan_account.loan.amortizable?
end
- test "variable rate loans have no payment or schedule" do
- loan = Loan.new(interest_rate: 3.5, term_months: 360, rate_type: "variable")
+ # Reversed in part by #104: a variable loan now has a schedule. It still has
+ # no single monthly payment, because it does not have one -- quoting the
+ # payment it opened with would present a stale figure as a current one.
+ test "variable rate loans have a schedule but no single monthly payment" do
+ account = Account.create! \
+ family: families(:dylan_family),
+ name: "Variable Mortgage",
+ balance: 500000,
+ currency: "USD",
+ accountable: Loan.create!(subtype: "mortgage", interest_rate: 3.5, term_months: 360, rate_type: "variable")
+
+ assert_equal account, account.loan.account, "validating a Loan before attaching its Account must not cache a missing association"
+ assert account.loan.amortizable?
+ assert_not_nil account.loan.amortization_schedule
+ assert_nil account.loan.monthly_payment
+ end
+
+ # #100 decision 8: a provider writes its own vocabulary straight into
+ # rate_type (Plaid's mortgage payload says "arm", others capitalise), and a
+ # loan whose rate can move is variable whatever the word for it. Only a
+ # blank rate type says nothing at all.
+ test "any non-blank rate type other than fixed is a variable, amortizable loan" do
+ [ "arm", "Variable" ].each do |provider_rate_type|
+ account = Account.create! \
+ family: families(:dylan_family),
+ name: "Provider Mortgage",
+ balance: 500000,
+ currency: "USD",
+ accountable: Loan.create!(subtype: "mortgage", interest_rate: 3.5, term_months: 360, rate_type: provider_rate_type)
+
+ assert account.loan.variable_rate_type?, "#{provider_rate_type.inspect} should read as variable"
+ assert account.loan.amortizable?, "#{provider_rate_type.inspect} should amortize"
+ assert_nil account.loan.monthly_payment, "a variable loan has no single monthly payment"
+ end
+
+ [ nil, "" ].each do |blank|
+ account = Account.create! \
+ family: families(:dylan_family),
+ name: "Untyped Mortgage",
+ balance: 500000,
+ currency: "USD",
+ accountable: Loan.create!(subtype: "mortgage", interest_rate: 3.5, term_months: 360, rate_type: blank)
+
+ assert_not account.loan.variable_rate_type?, "#{blank.inspect} says nothing about the rate"
+ assert_not account.loan.amortizable?, "#{blank.inspect} must not amortize"
+ end
+ end
+
+ test "a loan with no account is not amortizable rather than raising" do
+ assert_not Loan.new(interest_rate: 3.5, term_months: 360, rate_type: "variable").amortizable?
+ assert_not Loan.new(interest_rate: 3.5, term_months: 360, rate_type: "fixed").amortizable?
+ end
+
+ test "a start date in the future is rejected, today and blank are not" do
+ loan = Loan.new(subtype: "mortgage", interest_rate: 6, term_months: 12, rate_type: "fixed")
+
+ loan.start_date = Date.current + 1
+ assert_not loan.valid?
+ assert loan.errors.of_kind?(:start_date, :less_than_or_equal_to)
+
+ loan.start_date = Date.current
+ assert loan.valid?
- assert_not loan.amortizable?
+ loan.start_date = nil
+ assert loan.valid?
end
end
diff --git a/test/models/plaid_account/liabilities/mortgage_processor_test.rb b/test/models/plaid_account/liabilities/mortgage_processor_test.rb
index cafa4efde4..65e9e27c15 100644
--- a/test/models/plaid_account/liabilities/mortgage_processor_test.rb
+++ b/test/models/plaid_account/liabilities/mortgage_processor_test.rb
@@ -30,6 +30,28 @@ class PlaidAccount::Liabilities::MortgageProcessorTest < ActiveSupport::TestCase
assert_equal 4.25, loan.interest_rate
end
+ # #100 decision 8: Plaid's own vocabulary ("arm") is written through as-is,
+ # and the loan it lands on must still get a schedule.
+ test "a Plaid rate type outside the form's vocabulary still yields a schedule" do
+ @plaid_account.current_account.update!(balance: 250_000, accountable: Loan.new(term_months: 360))
+ @plaid_account.update!(raw_liabilities_payload: {
+ mortgage: {
+ interest_rate: {
+ type: "arm",
+ percentage: 5.1
+ }
+ }
+ })
+
+ PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account).process
+
+ loan = @plaid_account.current_account.reload.loan
+
+ assert_equal "arm", loan.rate_type
+ assert loan.variable_rate_type?
+ assert_not_empty loan.amortization_schedule.payments
+ end
+
test "does nothing when mortgage data absent" do
@plaid_account.update!(raw_liabilities_payload: {})