feat(loans): amortisation engine and variable-rate loans
Fixes #3295
Built on #2984. This is the first of two pull requests: #3474 (the loan balance chart with a payoff projection, for #3332) is stacked on this commit and can be reviewed after it, or folded in here if maintainers would rather review one change. It replaces #3296, which grew to 8,900 lines and was reviewed down; everything here is roughly 1,500 lines, and the two regressions that review found are carried as tests.
What this does
Two slices, one commit:
The calculation loop is replaced. #2984 sizes one level payment up front and loops the term at a single annual_rate; there is no seam a rate change can enter through. The loop becomes Loan::Simulator, fed by callables, with Loan::AmortizationMath (the annuity formula and one period's split) and Loan::SimulationResult. The public API of Loan::AmortizationSchedule is unchanged: payments, periodic_payment, total_interest, total_paid, payoff_date, payment_for and the Payment Data type are exactly as reviewed, and #2984's own test file passes byte-unmodified against the new engine (git diff on test/models/loan/amortization_schedule_test.rb between the two is empty). That was the acceptance criterion for the swap.
Variable-rate loans. One migration adds loans.variable_rate_schedule (jsonb, effective date to annual percentage) and loans.start_date. Loan::RateResolver reads the recorded changes. The loan form gains a rate-change editor: plain array-named inputs, so it works without JavaScript, and a Stimulus controller adds and removes rows and hides the section for fixed loans. The Schedule tab re-amortises at each recorded change and labels the first figure "Opening Payment" when the repayment moves. The Overview tab shows the rate in force today, the original principal and the original payoff date. amortizable? widens to any loan with a non-blank rate type, so the Schedule tab appears for variable and adjustable loans, and for a provider's own vocabulary (PlaidAccount::Liabilities::MortgageProcessor writes Plaid's raw interest_rate.type straight through). A blank rate type is still not schedulable. monthly_payment stays nil for a variable loan: it has a schedule now, but not a single monthly payment, and quoting the one it opened with would present a stale figure as current.
A rate change dated before the loan's origination (its start date, or its first valuation when there is none) is rejected, and so is a future start date.
Two rates, not one
A period is bounded by two dates, and on a variable loan they can sit either side of a change.
- Interest for
[previous payment date, this payment date)accrues at the rate in force when the period opened. - Payment sizing uses the rate in force on the payment date.
Reading one rate for both re-rates the month ending on the boundary, billing a rate that applied for none of it. This is also why #3296's second blocking finding is unreachable here: nothing counts days into payments (segments are real payment dates), so a segment spanning a 30-day month cannot round to zero payments and vanish. Pinned end-to-end on charged interest, because a skipped segment leaves a well-formed schedule and raises nothing.
Deliberately not here
Daily accrual, offset accounts, extra repayments, scenarios, day-count conventions, a persisted schedule cache and its rebuild pipeline. Two expectations in #3295 are declined rather than omitted silently: monthly accrual applies a mid-period rate change from the next period (a property of monthly accrual, documented on Loan::Simulator where it happens; splitting periods at change dates is daily accrual), and there is no Rails.cache layer in this slice. Measured on an M-series laptop: a 360-month fixed schedule builds in 8 ms, a 360-month variable schedule with five changes in 63 ms, a 1,200-month schedule in 21 ms.
Demo data
Demo::Generator gives the demo family's three loans real terms, so each has a schedule:
- Home Mortgage: adjustable, 320,000 at 6.25% over 30 years, with two recorded rate changes (5.5% two years in, 6.75% two years after that), so the demo shows a schedule re-amortising.
- Car Loan: fixed, 24,000 at 6.9% over 5 years.
- Student Loan: fixed, 42,000 at 5.5% over 10 years, with one extra payment a year ago.
Each loan opens at its principal and is paid from its own schedule, so its balance today is what the schedule says (less the student loan's extra payment). test/models/demo/generator_test.rb asserts the terms and the balances.
Screenshots
From the demo family's Home Mortgage (adjustable, with two recorded rate changes). Taken on this pull request's previous revision (33687b9b8); the latest revision changes only a test, so every pictured screen is the same.
Schedule tab. The first card reads Opening Payment rather than Monthly Payment, because the repayment changes at each recorded rate change.


Overview tab. The rate in force today, the original loan amount and the original payoff date.


Loan form. The recorded rate changes, with the origination date.


Migration notes
One additive migration, 20260908145118_add_variable_rate_tracking_to_loans:
loans.variable_rate_schedule:jsonb,default: {},null: false.loans.start_date:date, nullable.
Existing loans are not rewritten: they get an empty rate schedule and no start date, and behave as before; a loan without a start date takes its origination from its first valuation. Nothing to run after deploy.
Blast radius
amortizable? is read by the account page's tabs, AmortizationSchedule.for and Loan#monthly_payment. The Schedule tab now appears on variable and adjustable loans; monthly_payment is unchanged. amortizable? also requires an account, which #2984's rate_type == "fixed" guard happened to short-circuit before. A term longer than 1,200 months is not amortizable rather than raising; term_months is also written by PlaidAccount::Liabilities::StudentLoanProcessor from provider dates, so a hard validation would turn one bad date into a failed sync.
AccountableResource#update, the edit action every account type shares, now runs the balance change and the attribute update in one transaction, so a rejected edit no longer persists half of itself. Every account type's controller test runs against it.
Carried, unrelated to loans: Account#assign_default_owner orders its candidates by created_at, id. Two admin fixtures share a timestamp, so the default owner depended on the query plan and flaked CI. It is one line and can be dropped if you would rather take it separately.
Verification
All new behaviour is covered by tests that were observed to fail before the change they pin, including: interest accrues at the opening rate and the repayment resizes on the payment date; a change landing on a payment date does not re-rate the month before it; a one-month rate spike in a 30-day month is charged; a fixed loan's schedule is byte-identical to #2984's; a provider rate type outside the form's vocabulary still yields a schedule; invalid rate-change rows are rejected with a 422 and redisplayed even when nothing else on the loan changed; a rate change before origination is rejected; a fixed loan's retained rate changes survive a switch to variable and back; a half-filled row on the new-loan form re-renders the form rather than the error page; a future start_date is rejected; a rejected update does not persist the balance change submitted with it; the Overview tab shows the rate in force.
Locally, on this commit with #3474's on top, over main at ca4a6b4a0:
- The loan, account, account-type controller, account chart component, period picker and i18n tests: 375 runs, 0 failures (4 skipped: the i18n key checks
mainalso skips). test/system/loan_payoff_chart_test.rbin headless Chrome: 6 runs, 0 failures.bin/rubocopon the changed Ruby files,biome linton the changed controller andbin/brakeman: clean. No ERB has changed since the last fullerb_lint --lint-all.- Full
bin/rails test: 9,050 runs, 0 failures, 1 error (RecurringTransaction::PipelineTest, whose ownPG.connectfails auth on this machine on any branch).
GitHub checks on this commit, including the unit and system test jobs, are green.
History
Squashed from jaysbeekay/sure#109, where the full review history lives: three rounds of cubic, CodeRabbit and Codacy, and an independent review whose blocking, should-fix and minor findings are all addressed on the branch. The fork's plan for this delivery is docs/plans/loan-chart-upstream-delivery.md.