The personal finance app for everyone (by everyone)
Ruby
Add native amortization schedules for loan accounts (#2984)
Igor Oliveira6c1c8eeec547
diff --git a/app/components/UI/account_page.rb b/app/components/UI/account_page.rbindex 36be3c2b24..10e3b3223f 100644--- a/app/components/UI/account_page.rb+++ b/app/components/UI/account_page.rb@@ -46,7 +46,9 @@ class UI::AccountPage < ApplicationComponentbase_tabs = case account.accountable_typewhen "Investment", "Crypto"[ :activity, :holdings ]- when "Property", "Vehicle", "Loan"+ when "Loan"+ account.loan.amortizable? ? [ :activity, :overview, :schedule ] : [ :activity, :overview ]+ when "Property", "Vehicle"[ :activity, :overview ]else[ :activity ]@@ -76,7 +78,7 @@ class UI::AccountPage < ApplicationComponentcase tabwhen :activityactivity_feed- when :holdings, :overview+ when :holdings, :overview, :schedule# Accountable is responsible for implementing the partial in the correct folderrender "#{account.accountable_type.downcase.pluralize}/tabs/#{tab}", account: accountwhen :statementsdiff --git a/app/models/loan.rb b/app/models/loan.rbindex 4b6b88ccaf..87547517c7 100644--- a/app/models/loan.rb+++ b/app/models/loan.rb@@ -15,18 +15,31 @@ class Loan < ApplicationRecorddef monthly_paymentreturn nil if term_months.nil? || interest_rate.nil? || rate_type.nil? || rate_type != "fixed"- return Money.new(0, account.currency) if account.loan.original_balance.amount.zero? || term_months.zero?+ # 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- annual_rate = interest_rate / 100.0- monthly_rate = annual_rate / 12.0+ amortization_schedule&.periodic_payment+ end- if monthly_rate.zero?- payment = account.loan.original_balance.amount / term_months- else- payment = (account.loan.original_balance.amount * monthly_rate * (1 + monthly_rate)**term_months) / ((1 + monthly_rate)**term_months - 1)- 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.+ def amortizable?+ rate_type == "fixed" &&+ interest_rate.present? &&+ term_months.to_i.positive? &&+ original_balance.amount.positive?+ end++ def amortization_schedule+ @amortization_schedule ||= AmortizationSchedule.for(self)+ end- Money.new(payment.round, account.currency)+ # 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.+ def origination_date+ account.first_valuation&.date || account.opening_anchor_dateenddef original_balancediff --git a/app/models/loan/amortization_schedule.rb b/app/models/loan/amortization_schedule.rbnew file mode 100644index 0000000000..483db06cfb--- /dev/null+++ b/app/models/loan/amortization_schedule.rb@@ -0,0 +1,146 @@+# Builds a constant-payment ("French") amortization schedule for a fixed-rate loan.+#+# Each period charges interest on the outstanding principal and applies the+# remainder of the fixed 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.+class Loan::AmortizationSchedule+ Payment = Data.define(:number, :date, :payment, :principal, :interest, :ending_balance)++ attr_reader :principal, :annual_rate, :term_months, :start_date, :currency++ class << self+ # Returns a schedule for the loan, or nil when the loan isn't amortizable+ # (variable rate, or missing rate/term/principal).+ def for(loan)+ return nil unless loan.amortizable?++ new(+ principal: loan.original_balance.amount,+ annual_rate: loan.interest_rate,+ term_months: loan.term_months,+ start_date: loan.origination_date,+ currency: loan.account.currency+ )+ end+ end++ def initialize(principal:, annual_rate:, term_months:, start_date:, currency:)+ @principal = BigDecimal(principal.to_s)+ @annual_rate = BigDecimal(annual_rate.to_s)+ @term_months = term_months.to_i+ @start_date = start_date+ @currency = currency+ end++ # Every scheduled payment, oldest first. Empty when there is nothing to+ # amortize; shorter than the term when rounding clears the balance early.+ def payments+ @payments ||= build_payments+ 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.+ def periodic_payment+ return money(0) unless schedulable?++ money(raw_periodic_payment)+ 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 })+ end++ # Principal plus total_interest — everything the borrower pays.+ def total_paid+ money(payments.sum(BigDecimal(0)) { |payment| payment.payment.amount })+ end++ # The date of the final payment, or nil when there's nothing to amortize.+ def payoff_date+ payments.last&.date+ end++ # The scheduled payment falling in the same calendar month as `date`, if any.+ # Callers use this to reconcile a real bank payment against the schedule.+ def payment_for(date)+ 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++ # 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+ 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)+ )+ 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++ def money(value)+ Money.new(value, currency)+ end+enddiff --git a/app/views/loans/tabs/_schedule.html.erb b/app/views/loans/tabs/_schedule.html.erbnew file mode 100644index 0000000000..aaaaa3330f--- /dev/null+++ b/app/views/loans/tabs/_schedule.html.erb@@ -0,0 +1,58 @@+<%# locals: (account:) %>++<% schedule = account.loan.amortization_schedule %>+<% payments = schedule.payments %>+<% today = Date.current %>++<div class="space-y-4">+ <div class="grid grid-cols-2 md:grid-cols-4 gap-2">+ <%= summary_card title: t(".monthly_payment") do %>+ <%= format_money schedule.periodic_payment %>+ <% end %>++ <%= summary_card title: t(".total_interest") do %>+ <%= format_money schedule.total_interest %>+ <% end %>++ <%= 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>++ <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">+ <thead class="sticky top-0 bg-container border-b border-alpha-black-25">+ <tr class="text-secondary text-left">+ <th scope="col" class="font-medium px-4 py-3"><%= t(".number") %></th>+ <th scope="col" class="font-medium px-4 py-3"><%= t(".date") %></th>+ <th scope="col" class="font-medium px-4 py-3 text-right"><%= t(".payment") %></th>+ <th scope="col" class="font-medium px-4 py-3 text-right"><%= t(".principal") %></th>+ <th scope="col" class="font-medium px-4 py-3 text-right"><%= t(".interest") %></th>+ <th scope="col" class="font-medium px-4 py-3 text-right"><%= t(".remaining_balance") %></th>+ </tr>+ </thead>+ <tbody>+ <% payments.each do |payment| %>+ <tr class="border-b border-alpha-black-25 last:border-0 <%= "bg-container-inset" if payment.date <= today %>">+ <td class="px-4 py-3 text-secondary tabular-nums"><%= payment.number %></td>+ <td class="px-4 py-3 text-primary"><%= l payment.date, format: :long %></td>+ <td class="px-4 py-3 text-right text-primary tabular-nums privacy-sensitive"><%= format_money payment.payment %></td>+ <td class="px-4 py-3 text-right text-primary tabular-nums privacy-sensitive"><%= format_money payment.principal %></td>+ <td class="px-4 py-3 text-right text-secondary tabular-nums privacy-sensitive"><%= format_money payment.interest %></td>+ <td class="px-4 py-3 text-right text-primary tabular-nums privacy-sensitive"><%= format_money payment.ending_balance %></td>+ </tr>+ <% end %>+ </tbody>+ </table>+ </div>+ </div>+</div>diff --git a/config/locales/views/accounts/de.yml b/config/locales/views/accounts/de.ymlindex db85eb6bce..df2ea96325 100644--- a/config/locales/views/accounts/de.yml+++ b/config/locales/views/accounts/de.yml@@ -119,6 +119,7 @@ de:activity: Aktivitätholdings: Beständeoverview: Übersicht+ schedule: Tilgungsplanstatements: Auszügeupdate:success: "%{type}-Konto aktualisiert"diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.ymlindex 51d289c992..02a68aea9e 100644--- a/config/locales/views/accounts/en.yml+++ b/config/locales/views/accounts/en.yml@@ -84,6 +84,7 @@ en:activity: Activityholdings: Holdingsoverview: Overview+ schedule: Schedulestatements: Statementsactivity:amount: Amountdiff --git a/config/locales/views/loans/de.yml b/config/locales/views/loans/de.ymlindex b3890f8754..64cc4551dc 100644--- a/config/locales/views/loans/de.yml+++ b/config/locales/views/loans/de.yml@@ -28,6 +28,18 @@ de:type: Typunknown: Unbekannttabs:+ schedule:+ date: Datum+ description: Hochgerechnet aus ursprünglicher Kreditsumme, Zinssatz und Laufzeit, beginnend am %{start_date}. Sondertilgungen und Zinsänderungen sind nicht berücksichtigt.+ interest: Zinsen+ monthly_payment: Monatsrate+ number: "Nr."+ payment: Rate+ payoff_date: Ablösedatum+ principal: Tilgung+ remaining_balance: Restschuld+ total_cost: Gesamtkosten+ total_interest: Zinsen gesamtoverview:edit_loan_details: Kreditdaten bearbeiteninterest_rate: Zinssatzdiff --git a/config/locales/views/loans/en.yml b/config/locales/views/loans/en.ymlindex b133b9886a..dccfe0c9f4 100644--- a/config/locales/views/loans/en.yml+++ b/config/locales/views/loans/en.yml@@ -28,6 +28,18 @@ en:type: Typeunknown: Unknowntabs:+ schedule:+ date: Date+ description: Projected from the original balance, rate and term, starting %{start_date}. Extra payments and rate changes are not reflected.+ interest: Interest+ monthly_payment: Monthly Payment+ number: "#"+ payment: Payment+ payoff_date: Payoff Date+ principal: Principal+ remaining_balance: Remaining Balance+ total_cost: Total Cost+ total_interest: Total Interestoverview:interest_rate: Interest Ratemonthly_payment: Monthly Paymentdiff --git a/test/controllers/loans_controller_test.rb b/test/controllers/loans_controller_test.rbindex 67fff1859d..5e433d639f 100644--- a/test/controllers/loans_controller_test.rb+++ b/test/controllers/loans_controller_test.rb@@ -92,4 +92,21 @@ class LoansControllerTest < ActionDispatch::IntegrationTestassert_equal "Loan account updated", flash[:notice]assert_enqueued_with(job: SyncJob)end++ test "renders the amortization schedule tab for a fixed rate loan" do+ get account_path(@account, tab: "schedule")++ assert_response :success+ assert_select "table tbody tr", count: @account.loan.term_months+ assert_match "Total Interest", response.body+ end++ test "hides the schedule tab when the loan cannot be amortized" do+ @account.loan.update!(rate_type: "variable")++ get account_path(@account, tab: "schedule")++ assert_response :success+ assert_select "table tbody tr", count: 0+ endenddiff --git a/test/models/loan/amortization_schedule_test.rb b/test/models/loan/amortization_schedule_test.rbnew file mode 100644index 0000000000..fc9fc0647a--- /dev/null+++ b/test/models/loan/amortization_schedule_test.rb@@ -0,0 +1,133 @@+require "test_helper"++class Loan::AmortizationScheduleTest < ActiveSupport::TestCase+ test "builds one payment per month of the term" do+ schedule = build_schedule++ assert_equal 360, schedule.payments.count+ assert_equal 1, schedule.payments.first.number+ assert_equal 360, schedule.payments.last.number+ end++ test "level payment matches the standard amortization formula" do+ assert_equal BigDecimal("2245.22"), build_schedule.periodic_payment.amount+ end++ test "first payment is mostly interest and last payment is mostly principal" do+ schedule = build_schedule+ first = schedule.payments.first+ last = schedule.payments.last++ # 500,000 at 3.5% => 1,458.33 of interest in month one.+ assert_equal BigDecimal("1458.33"), first.interest.amount+ assert_equal BigDecimal("786.89"), first.principal.amount+ assert first.interest.amount > first.principal.amount+ assert last.principal.amount > last.interest.amount+ end++ test "amortizes down to exactly zero" do+ assert_equal BigDecimal("0"), build_schedule.payments.last.ending_balance.amount+ end++ test "principal portions sum to the original principal" do+ schedule = build_schedule+ total_principal = schedule.payments.sum(BigDecimal(0)) { |payment| payment.principal.amount }++ assert_equal BigDecimal("500000"), total_principal+ end++ test "total paid is principal plus total interest" do+ schedule = build_schedule++ # Slightly above the naive payment*term figure because interest is rounded+ # to cents every month, exactly as a lender's table does.+ assert_equal BigDecimal("308281.36"), schedule.total_interest.amount+ assert_equal schedule.principal + schedule.total_interest.amount, schedule.total_paid.amount+ end++ test "payment dates step monthly from origination" do+ schedule = build_schedule(start_date: Date.new(2026, 1, 31))++ assert_equal Date.new(2026, 2, 28), schedule.payments.first.date+ assert_equal Date.new(2026, 3, 31), schedule.payments.second.date+ end++ test "payoff date is the last payment date" do+ schedule = build_schedule(start_date: Date.new(2026, 1, 1), term_months: 12)++ assert_equal Date.new(2027, 1, 1), schedule.payoff_date+ end++ test "handles a zero-interest loan with straight-line principal" do+ schedule = build_schedule(annual_rate: 0, term_months: 10, principal: 1000)++ assert_equal BigDecimal("100"), schedule.periodic_payment.amount+ assert schedule.payments.all? { |payment| payment.interest.amount.zero? }+ assert_equal BigDecimal("0"), schedule.total_interest.amount+ assert_equal BigDecimal("0"), schedule.payments.last.ending_balance.amount+ end++ test "rounds to whole units for a currency without minor units" do+ schedule = build_schedule(currency: "JPY", principal: 1_000_000, annual_rate: 2, term_months: 12)++ assert schedule.payments.all? { |payment| payment.payment.amount.frac.zero? }+ assert_equal BigDecimal("0"), schedule.payments.last.ending_balance.amount+ end++ test "returns no payments when the term is zero" do+ assert_empty build_schedule(term_months: 0).payments+ assert_nil build_schedule(term_months: 0).payoff_date+ assert_equal BigDecimal("0"), build_schedule(term_months: 0).periodic_payment.amount+ assert_equal BigDecimal("0"), build_schedule(principal: 0).periodic_payment.amount+ end++ test "keeps the periods it built when rounding clears the balance early" do+ # 10 over 51 months rounds to a 0.20 payment, which pays the loan off in 50.+ schedule = build_schedule(principal: 10, annual_rate: 0, term_months: 51)++ assert_equal 50, schedule.payments.count+ assert_equal BigDecimal("0"), schedule.payments.last.ending_balance.amount+ assert_equal BigDecimal("10"), schedule.total_paid.amount+ assert_equal schedule.payments.last.date, schedule.payoff_date+ end++ test "payment_for finds the payment landing in a given month" do+ schedule = build_schedule(start_date: Date.new(2026, 1, 1), term_months: 12)++ assert_equal 3, schedule.payment_for(Date.new(2026, 4, 17)).number+ assert_nil schedule.payment_for(Date.new(2030, 1, 1))+ end++ test "builds from a loan record" do+ loan = loan_account(interest_rate: 3.5, term_months: 360, rate_type: "fixed").loan++ assert_equal BigDecimal("2245.22"), Loan::AmortizationSchedule.for(loan).periodic_payment.amount+ end++ test "is not buildable for a variable rate loan" do+ loan = loan_account(interest_rate: 3.5, term_months: 360, rate_type: "variable").loan++ assert_nil Loan::AmortizationSchedule.for(loan)+ end++ private+ def build_schedule(principal: 500_000, annual_rate: 3.5, term_months: 360,+ start_date: Date.new(2026, 1, 1), currency: "USD")+ Loan::AmortizationSchedule.new(+ principal: principal,+ annual_rate: annual_rate,+ term_months: term_months,+ start_date: start_date,+ currency: currency+ )+ end++ def loan_account(**loan_attrs)+ Account.create! \+ family: families(:dylan_family),+ name: "Mortgage Loan",+ balance: 500_000,+ currency: "USD",+ accountable: Loan.create!(subtype: "mortgage", **loan_attrs)+ end+enddiff --git a/test/models/loan_test.rb b/test/models/loan_test.rbindex 05ce9fa05a..438952e972 100644--- a/test/models/loan_test.rb+++ b/test/models/loan_test.rb@@ -21,6 +21,29 @@ class LoanTest < ActiveSupport::TestCaserate_type: "fixed")- assert_equal 2245, loan_account.loan.monthly_payment.amount+ assert_equal BigDecimal("2245.22"), loan_account.loan.monthly_payment.amount+ end++ test "monthly payment is zero for a non-positive term" do+ loan_account = Account.create! \+ family: families(:dylan_family),+ name: "Backwards Loan",+ balance: 500000,+ currency: "USD",+ accountable: Loan.create!(+ subtype: "mortgage",+ interest_rate: 3.5,+ term_months: -360,+ rate_type: "fixed"+ )++ assert_equal 0, loan_account.loan.monthly_payment.amount+ 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")++ assert_not loan.amortizable?endend