Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Loans: let interest accrue on the basis the lender actually uses (#3639)

jaysbeekayd647b0430958
diff --git a/app/controllers/loans_controller.rb b/app/controllers/loans_controller.rb
index e1b687567a..2ff6844db0 100644
--- a/app/controllers/loans_controller.rb
+++ b/app/controllers/loans_controller.rb
@@ -3,7 +3,7 @@ class LoansController < ApplicationController
permitted_accountable_attributes(
:id, :subtype, :rate_type, :interest_rate, :term_months, :initial_balance, :start_date,
- :down_payment, :insurance_rate, :insurance_rate_type,
+ :down_payment, :insurance_rate, :insurance_rate_type, :day_count_convention,
{ rate_changes: [ :effective_date, :rate ] }
)
end
diff --git a/app/helpers/loans_helper.rb b/app/helpers/loans_helper.rb
index 3fdc353662..52f97b9c07 100644
--- a/app/helpers/loans_helper.rb
+++ b/app/helpers/loans_helper.rb
@@ -32,4 +32,18 @@ module LoansHelper
options << [ loan.rate_type.titleize, loan.rate_type ]
end
+
+ # Built from the model constant rather than listed here, so a convention the
+ # engine gains cannot be offered without a label. `raise: true` is what makes
+ # that true: `config.i18n.raise_on_missing_translations` is not enabled in
+ # development or test, and `config.i18n.fallbacks` is, so without it a key
+ # missing in every locale would quietly render the literal "translation
+ # missing" string instead of failing. A key missing only in the current
+ # locale still falls back to English first, so a locale that has not
+ # translated these labels yet shows the English ones rather than an error.
+ def loan_day_count_convention_options
+ Loan::DAY_COUNT_CONVENTIONS.map do |convention|
+ [ t("loans.form.day_count_convention_#{convention}", raise: true), convention ]
+ end
+ end
end
diff --git a/app/models/loan.rb b/app/models/loan.rb
index 1bc1ba447d..179a9c58a2 100644
--- a/app/models/loan.rb
+++ b/app/models/loan.rb
@@ -239,10 +239,17 @@ class Loan < ApplicationRecord
@amortization_schedule ||= AmortizationSchedule.for(self)
end
+ # Mirrored from the engine so the model and the simulator cannot drift: the
+ # engine owns what the conventions mean, the model owns what a user may store.
+ DAY_COUNT_CONVENTIONS = Simulator::DAY_COUNT_CONVENTIONS.map(&:to_s).freeze
+ DEFAULT_DAY_COUNT_CONVENTION = Simulator::DEFAULT_DAY_COUNT_CONVENTION.to_s
+
# 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 = %i[interest_rate term_months rate_type start_date variable_rate_schedule day_count_convention].freeze
+
+ validates :day_count_convention, inclusion: { in: DAY_COUNT_CONVENTIONS }
SCHEDULE_INPUTS.each do |input|
define_method(:"#{input}=") do |value|
diff --git a/app/models/loan/amortization_schedule.rb b/app/models/loan/amortization_schedule.rb
index 88843070ac..3b55967627 100644
--- a/app/models/loan/amortization_schedule.rb
+++ b/app/models/loan/amortization_schedule.rb
@@ -29,7 +29,8 @@ class Loan::AmortizationSchedule
term_months: loan.term_months,
start_date: loan.origination_date,
currency: loan.account.currency,
- rate_resolver: (Loan::RateResolver.for(loan) if loan.variable_rate_type?)
+ rate_resolver: (Loan::RateResolver.for(loan) if loan.variable_rate_type?),
+ day_count_convention: loan.day_count_convention
)
end
end
@@ -37,7 +38,8 @@ class Loan::AmortizationSchedule
# `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)
+ def initialize(principal:, annual_rate:, term_months:, start_date:, currency:, rate_resolver: nil,
+ day_count_convention: Loan::Simulator::DEFAULT_DAY_COUNT_CONVENTION)
@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)
@@ -50,6 +52,7 @@ class Loan::AmortizationSchedule
@term_months = term_months.to_i
@start_date = start_date
@rate_resolver = rate_resolver
+ @day_count_convention = day_count_convention
end
# True when this schedule re-amortises part-way through, i.e. the repayment
@@ -142,7 +145,8 @@ class Loan::AmortizationSchedule
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
+ currency_precision: currency_precision,
+ day_count_convention: @day_count_convention
).run
else
Loan::SimulationResult.new(payments: [], currency_precision: currency_precision)
diff --git a/app/models/loan/payoff_projection.rb b/app/models/loan/payoff_projection.rb
index 8c0b563b21..c6fee05623 100644
--- a/app/models/loan/payoff_projection.rb
+++ b/app/models/loan/payoff_projection.rb
@@ -163,7 +163,13 @@ class Loan
# A projection that cannot clear the balance must SAY so. Settling the
# final payment regardless would manufacture a payoff date for a loan
# the contract no longer pays off.
- settle_at_schedule_end: false
+ settle_at_schedule_end: false,
+ # Charged on the same basis as the schedule it is compared with. Left
+ # to the simulator's default, a loan on actual/365 would be projected
+ # on a flat twelfth beside a schedule that is not, and a borrower
+ # exactly on contract would be quoted interest saved or lost that
+ # only the difference in basis produced.
+ day_count_convention: loan.day_count_convention
).run
end
diff --git a/app/models/loan/simulator.rb b/app/models/loan/simulator.rb
index 756edf40e7..4362827497 100644
--- a/app/models/loan/simulator.rb
+++ b/app/models/loan/simulator.rb
@@ -59,6 +59,19 @@ class Loan
PERCENT = BigDecimal("100")
MONTHS_PER_YEAR = BigDecimal("12")
+ # How a period's interest is measured against a year.
+ #
+ # `thirty_360` is the default because it IS the flat 1/12 this engine has
+ # always charged -- 30/360 reduces to 1/12 exactly -- so a loan that does
+ # not choose a convention produces the schedule it produced before, row for
+ # row. `actual_actual` is NOT a substitute for that: it charges 31/365 in
+ # January and 28/365 in February, and only reaches 1/12 when a whole
+ # calendar year is summed.
+ DAY_COUNT_CONVENTIONS = %i[thirty_360 actual_365 actual_actual].freeze
+ DEFAULT_DAY_COUNT_CONVENTION = :thirty_360
+ DAYS_PER_YEAR = BigDecimal("365")
+ DAYS_PER_LEAP_YEAR = BigDecimal("366")
+
def initialize(
starting_balance:,
accrual_start_date:,
@@ -68,7 +81,8 @@ class Loan
re_amortisation_events: nil,
payment_strategy: :reamortize,
payment_amount: nil,
- settle_at_schedule_end: true
+ settle_at_schedule_end: true,
+ day_count_convention: DEFAULT_DAY_COUNT_CONVENTION
)
@starting_balance = BigDecimal(starting_balance.to_s)
@accrual_start_date = accrual_start_date
@@ -88,6 +102,7 @@ class Loan
else BigDecimal(payment_amount.to_s)
end
@settle_at_schedule_end = settle_at_schedule_end
+ @day_count_convention = (day_count_convention || DEFAULT_DAY_COUNT_CONVENTION).to_sym
raise ArgumentError, "payment schedule must not be empty" if @payment_schedule.empty?
if @payment_schedule.length > MAX_PERIODS
@@ -101,6 +116,11 @@ class Loan
if (@payment_strategy == :scheduled) != @payment_amount.respond_to?(:call)
raise ArgumentError, ":scheduled takes a callable payment_amount; the other strategies take a number"
end
+ unless DAY_COUNT_CONVENTIONS.include?(@day_count_convention)
+ raise ArgumentError,
+ "unsupported day-count convention: #{@day_count_convention.inspect} " \
+ "(expected one of #{DAY_COUNT_CONVENTIONS.join(', ')})"
+ end
end
def run
@@ -116,7 +136,15 @@ class Loan
# See the class comment: opening rate charges the period, closing rate
# sizes the payment.
- accrual_rate = monthly_rate(@accrual_rate_for.call(period_start))
+ #
+ # The day count applies to the charge, not to the sizing. `level_payment`
+ # is an annuity formula and assumes ONE constant periodic rate; a factor
+ # that moves with the length of the month would differ every period, so
+ # under :reamortize the payment would be recomputed every month and stop
+ # being level. Sizing therefore stays on the nominal monthly rate, which
+ # is also what the borrower's contracted payment is set from.
+ accrual_annual = @accrual_rate_for.call(period_start)
+ accrual_rate = accrual_factor(period_start, payment_date, accrual_annual)
sizing_rate = monthly_rate(rate_on(payment_date))
# Interest first, on the balance the period OPENED with: one charge per
@@ -163,7 +191,11 @@ class Loan
monthly_rate: sizing_rate,
remaining_payments: @payment_schedule.length - index,
currency_precision: @currency_precision,
- first_period_interest: (interest if sizing_rate != accrual_rate)
+ # "Did the rate move mid-period?", asked of the rates themselves.
+ # Comparing the derived factors would answer "yes" every month once
+ # a day count is in play, because January and February differ by
+ # length rather than by rate.
+ first_period_interest: (interest if sizing_rate != monthly_rate(accrual_annual))
)
end
end
@@ -183,7 +215,9 @@ class Loan
# 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;
+ # recomputes the charge from beginning_balance, this rate and the
+ # period's day count (a flat twelfth under thirty_360) 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 << {
@@ -223,6 +257,47 @@ class Loan
# `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.
+ # 30/360 keeps the original two-step division untouched, so a default
+ # loan's figures are bit-identical rather than merely close.
+ def accrual_factor(period_start, period_end, annual_percentage)
+ return monthly_rate(annual_percentage) if @day_count_convention == :thirty_360
+
+ # After the 30/360 return, so the default path stays bit-identical.
+ if period_end < period_start
+ raise ArgumentError, "period ends (#{period_end}) before it starts (#{period_start})"
+ end
+
+ rate = BigDecimal(annual_percentage.to_s) / PERCENT
+
+ if @day_count_convention == :actual_365
+ return (rate * BigDecimal((period_end - period_start).to_i.to_s)) / DAYS_PER_YEAR
+ end
+
+ rate * actual_actual_year_fraction(period_start, period_end)
+ end
+
+ # actual/actual measures each calendar year's days against THAT year's
+ # own length, so a period crossing New Year is two fractions rather than
+ # one. Taking the opening year's denominator for the whole period would
+ # charge the days after 1 January at the wrong rate -- 15 December 2027
+ # to 15 January 2028 would put the 2028 days over 365 instead of 366.
+ def actual_actual_year_fraction(period_start, period_end)
+ fraction = BigDecimal("0")
+ cursor = period_start
+
+ while cursor < period_end
+ next_year_start = Date.new(cursor.year + 1, 1, 1)
+ segment_end = [ next_year_start, period_end ].min
+ days = BigDecimal((segment_end - cursor).to_i.to_s)
+ denominator = Date.leap?(cursor.year) ? DAYS_PER_LEAP_YEAR : DAYS_PER_YEAR
+
+ fraction += days / denominator
+ cursor = segment_end
+ end
+
+ fraction
+ end
+
def monthly_rate(annual_percentage)
(BigDecimal(annual_percentage.to_s) / PERCENT) / MONTHS_PER_YEAR
end
diff --git a/app/views/loans/_form.html.erb b/app/views/loans/_form.html.erb
index 8fb490c01e..c4ac2b838c 100644
--- a/app/views/loans/_form.html.erb
+++ b/app/views/loans/_form.html.erb
@@ -65,6 +65,16 @@
max: Loan::Simulator::MAX_PERIODS %>
</div>
+ <div class="flex items-center gap-2">
+ <%# How the lender measures a period against a year. The default charges
+ a flat twelfth, which is what every existing loan was built on, so
+ leaving this alone changes nothing about the schedule. %>
+ <%= loan_form.select :day_count_convention,
+ loan_day_count_convention_options,
+ { label: t("loans.form.day_count_convention") } %>
+ </div>
+ <p class="text-xs text-secondary"><%= t("loans.form.day_count_convention_hint") %></p>
+
<div class="flex items-center gap-2">
<%# The premium many lenders quote beside the instalment. Charged
alongside it rather than inside it, so it moves the loan's total
diff --git a/config/locales/views/loans/de.yml b/config/locales/views/loans/de.yml
index e4ea44612d..9fe684d3f8 100644
--- a/config/locales/views/loans/de.yml
+++ b/config/locales/views/loans/de.yml
@@ -7,6 +7,14 @@ de:
interest_rate: Zinssatz
interest_rate_placeholder: '5,25'
initial_balance: Ursprünglicher Kreditbetrag
+ day_count_convention: Zinsberechnungsmethode
+ day_count_convention_actual_365: Taggenau/365
+ day_count_convention_actual_actual: Taggenau/taggenau
+ day_count_convention_hint: Wie Ihr Kreditgeber jede Periode gegen ein Jahr
+ misst. Taggenau/365 berechnet nach der Länge des Monats und ist bei
+ britischen und australischen Hypotheken üblich. 30/360 berechnet ein
+ glattes Zwölftel, die Grundlage, die Sure bisher immer verwendet hat.
+ day_count_convention_thirty_360: 30/360 (glattes Zwölftel)
rate_type: Zinssatztyp
term_months: Laufzeit (Monate)
term_months_placeholder: '360'
diff --git a/config/locales/views/loans/en.yml b/config/locales/views/loans/en.yml
index 5554bee34b..504995c9fa 100644
--- a/config/locales/views/loans/en.yml
+++ b/config/locales/views/loans/en.yml
@@ -7,6 +7,14 @@ en:
interest_rate: Interest rate
interest_rate_placeholder: '5.25'
initial_balance: Original loan balance
+ day_count_convention: Interest basis
+ day_count_convention_actual_365: Actual/365
+ day_count_convention_actual_actual: Actual/actual
+ day_count_convention_hint: How your lender measures each period against a year.
+ Actual/365 charges by the length of the month and is standard for UK and
+ Australian mortgages. 30/360 charges a flat twelfth, the basis Sure has
+ always used.
+ day_count_convention_thirty_360: 30/360 (a flat twelfth)
rate_type: Rate type
term_months: Term (months)
term_months_placeholder: '360'
diff --git a/db/migrate/20260918210000_add_day_count_convention_to_loans.rb b/db/migrate/20260918210000_add_day_count_convention_to_loans.rb
new file mode 100644
index 0000000000..74f8965098
--- /dev/null
+++ b/db/migrate/20260918210000_add_day_count_convention_to_loans.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+# How a loan's interest is measured against a year.
+#
+# The default is `thirty_360` because it IS what the engine already charges:
+# 30/360 reduces to a flat 1/12 exactly, so every existing loan keeps the
+# schedule it had, row for row. `actual/actual` would NOT have done -- it
+# charges 31/365 in January and 28/365 in February, and only reaches 1/12 when
+# a whole calendar year is summed -- so choosing it as the default would have
+# silently restated every schedule in the product.
+#
+# A plain string with a check constraint, matching `securities.kind`
+# (`chk_securities_kind`): adding a convention later is a constraint swap, not
+# a type change.
+class AddDayCountConventionToLoans < ActiveRecord::Migration[8.1]
+ CONVENTIONS = %w[thirty_360 actual_365 actual_actual].freeze
+ CONSTRAINT = "chk_loans_day_count_convention"
+
+ def change
+ add_column :loans, :day_count_convention, :string,
+ null: false, default: "thirty_360"
+
+ add_check_constraint :loans,
+ "day_count_convention IN (#{CONVENTIONS.map { |v| "'#{v}'" }.join(', ')})",
+ name: CONSTRAINT
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 79d72e07db..c0963b4c06 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1584,6 +1584,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_20_090000) do
create_table "loans", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.datetime "created_at", null: false
+ t.string "day_count_convention", default: "thirty_360", null: false
t.decimal "down_payment", precision: 19, scale: 4
t.decimal "initial_balance", precision: 19, scale: 4
t.decimal "insurance_rate", precision: 8, scale: 4
@@ -1596,6 +1597,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_20_090000) do
t.integer "term_months"
t.datetime "updated_at", null: false
t.jsonb "variable_rate_schedule", default: {}, null: false
+ t.check_constraint "day_count_convention::text = ANY (ARRAY['thirty_360'::character varying, 'actual_365'::character varying, 'actual_actual'::character varying]::text[])", name: "chk_loans_day_count_convention"
t.check_constraint "down_payment IS NULL OR down_payment >= 0::numeric", name: "chk_loans_down_payment_non_negative"
t.check_constraint "insurance_rate IS NULL OR insurance_rate >= 0::numeric", name: "chk_loans_insurance_rate_non_negative"
t.check_constraint "insurance_rate_type IS NULL OR (insurance_rate_type::text = ANY (ARRAY['level_term'::character varying::text, 'decreasing_life'::character varying::text]))", name: "chk_loans_insurance_rate_type"
diff --git a/test/controllers/loans_controller_test.rb b/test/controllers/loans_controller_test.rb
index 44934f0c01..df974b5686 100644
--- a/test/controllers/loans_controller_test.rb
+++ b/test/controllers/loans_controller_test.rb
@@ -179,6 +179,49 @@ class LoansControllerTest < ActionDispatch::IntegrationTest
assert_enqueued_with(job: SyncJob)
end
+ # The form offers a day-count convention, and a select is worth nothing if the
+ # controller drops the value. This is the end-to-end path the model and engine
+ # tests do not cover: without `:day_count_convention` in
+ # `permitted_accountable_attributes` the parameter is filtered out, the loan
+ # keeps its old convention, and every future schedule ignores the choice.
+ test "the day-count convention chosen on create is saved" do
+ post loans_path, params: {
+ account: {
+ name: "Tracker",
+ balance: 50000,
+ currency: "USD",
+ accountable_type: "Loan",
+ accountable_attributes: {
+ subtype: "mortgage",
+ interest_rate: 5.5,
+ term_months: 60,
+ rate_type: "fixed",
+ initial_balance: 50000,
+ day_count_convention: "actual_actual"
+ }
+ }
+ }
+
+ assert_equal "actual_actual", Loan.order(:created_at).last.day_count_convention,
+ "the controller filtered the convention out of create"
+ end
+
+ test "the day-count convention chosen on the form is saved" do
+ assert_equal "thirty_360", @account.loan.day_count_convention
+
+ patch loan_path(@account), params: {
+ account: {
+ accountable_attributes: {
+ id: @account.accountable_id,
+ day_count_convention: "actual_365"
+ }
+ }
+ }
+
+ assert_equal "actual_365", @account.loan.reload.day_count_convention,
+ "the controller filtered out the convention the user chose"
+ end
+
# #3383: the opening anchor holds the original principal, so
# it belongs on the day the loan was drawn down, not on the form's separate
# opening balance date (which defaults to today minus two years).
diff --git a/test/helpers/loans_helper_test.rb b/test/helpers/loans_helper_test.rb
new file mode 100644
index 0000000000..638130ca7f
--- /dev/null
+++ b/test/helpers/loans_helper_test.rb
@@ -0,0 +1,48 @@
+require "test_helper"
+
+class LoansHelperTest < ActionView::TestCase
+ include LoansHelper
+
+ test "every day-count convention the engine offers has a label" do
+ options = loan_day_count_convention_options
+
+ assert_equal Loan::DAY_COUNT_CONVENTIONS.length, options.length
+ options.each do |label, value|
+ assert_includes Loan::DAY_COUNT_CONVENTIONS, value
+ assert label.present?, "#{value} has no label"
+ assert_no_match(/translation missing/, label)
+ end
+ end
+
+ # The helper is built from the model constant precisely so a convention the
+ # engine gains cannot be offered without a label. That promise rests on
+ # `raise: true`: `raise_on_missing_translations` is not enabled in
+ # development or test, and `config.i18n.fallbacks` is on, so without it a
+ # missing key renders the English label or the literal "translation missing"
+ # string and the form ships a nonsense option instead of failing.
+ test "a convention with no label fails loudly rather than rendering a fallback" do
+ original = Loan::DAY_COUNT_CONVENTIONS
+ Loan.send(:remove_const, :DAY_COUNT_CONVENTIONS)
+ Loan.const_set(:DAY_COUNT_CONVENTIONS, original + [ "convention_with_no_label" ])
+
+ assert_raises(I18n::MissingTranslationData) { loan_day_count_convention_options }
+ ensure
+ Loan.send(:remove_const, :DAY_COUNT_CONVENTIONS)
+ Loan.const_set(:DAY_COUNT_CONVENTIONS, original)
+ end
+
+ # `raise: true` must not turn a missing TRANSLATION into a failure: only en
+ # and de carry these labels, and a Spanish user editing a loan must get the
+ # English labels through the configured fallbacks, not an error page. The
+ # raise is for a key missing in every locale, which the test above covers.
+ test "a locale without its own labels falls back to English rather than failing" do
+ key = "loans.form.day_count_convention_actual_365"
+ assert_nil I18n.t(key, locale: :es, fallback: false, default: nil),
+ "the precondition is a locale that does not carry the label itself"
+
+ english = I18n.with_locale(:en) { loan_day_count_convention_options }
+ spanish = I18n.with_locale(:es) { loan_day_count_convention_options }
+
+ assert_equal english, spanish
+ end
+end
diff --git a/test/migrations/add_day_count_convention_to_loans_migration_test.rb b/test/migrations/add_day_count_convention_to_loans_migration_test.rb
new file mode 100644
index 0000000000..88d10606f8
--- /dev/null
+++ b/test/migrations/add_day_count_convention_to_loans_migration_test.rb
@@ -0,0 +1,95 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require Rails.root.join("db/migrate/20260918210000_add_day_count_convention_to_loans")
+
+# The migration owns exactly one column and one check constraint. `down` must
+# remove those and nothing else, `up` must put them back as they were, and `up`
+# must not quietly adopt a column it did not create -- a rollback would then
+# drop that column and every loan's basis with it. The schema changes roll back
+# with the test's transaction.
+class AddDayCountConventionToLoansMigrationTest < ActiveSupport::TestCase
+ COLUMN = "day_count_convention"
+ CONSTRAINT = AddDayCountConventionToLoans::CONSTRAINT
+
+ teardown { Loan.reset_column_information }
+
+ test "down then up restores the column, its default and its constraint" do
+ before = shape
+
+ migrate(:down)
+ migrate(:up)
+
+ assert_equal before, shape
+ assert_equal "thirty_360", before[:default]
+ assert_equal false, before[:null]
+ assert_equal AddDayCountConventionToLoans::CONVENTIONS, before[:permitted]
+ end
+
+ test "down removes exactly the column and constraint that up adds" do
+ columns_up = column_names
+ constraints_up = constraint_names
+
+ migrate(:down)
+ columns_down = column_names
+ constraints_down = constraint_names
+
+ migrate(:up)
+
+ assert_equal [ COLUMN ], columns_up - columns_down
+ assert_equal [ CONSTRAINT ], constraints_up - constraints_down
+ assert_empty columns_down - columns_up
+ assert_empty constraints_down - constraints_up
+ assert_equal columns_up.sort, column_names.sort
+ assert_equal constraints_up.sort, constraint_names.sort
+ end
+
+ test "up refuses a column it did not create rather than adopting it" do
+ before = shape
+
+ error = assert_raises(ActiveRecord::StatementInvalid) do
+ Loan.transaction(requires_new: true) { migrate(:up) }
+ end
+
+ assert_match(/column "#{COLUMN}" of relation "loans" already exists/, error.message)
+ assert_equal before, shape
+ end
+
+ private
+ def connection = ActiveRecord::Base.connection
+
+ def migrate(direction)
+ ActiveRecord::Migration.suppress_messages { AddDayCountConventionToLoans.new.migrate(direction) }
+ Loan.reset_column_information
+ end
+
+ def column_names
+ connection.columns(:loans).map(&:name)
+ end
+
+ def constraint_names
+ connection.check_constraints(:loans).map(&:name)
+ end
+
+ def shape
+ column = connection.columns(:loans).find { |c| c.name == COLUMN }
+ {
+ type: column&.sql_type,
+ default: column&.default,
+ null: column&.null,
+ permitted: permitted_values
+ }
+ end
+
+ # The values the constraint admits, read back from the catalog. Compared as
+ # a list rather than as the rendered predicate: a constraint loaded from
+ # schema.rb and one created by `add_check_constraint` print the same check
+ # with different casts.
+ def permitted_values
+ definition = connection.select_value(
+ "SELECT pg_get_constraintdef(oid) FROM pg_constraint " \
+ "WHERE conname = #{connection.quote(CONSTRAINT)}"
+ )
+ definition&.scan(/'([^']+)'/)&.flatten
+ end
+end
diff --git a/test/models/loan/day_count_convention_test.rb b/test/models/loan/day_count_convention_test.rb
new file mode 100644
index 0000000000..ea2255270c
--- /dev/null
+++ b/test/models/loan/day_count_convention_test.rb
@@ -0,0 +1,397 @@
+require "test_helper"
+
+# A lender accrues interest on a stated basis, and `actual/365` -- standard for
+# UK and Australian mortgages -- charges by the length of the month. Charging
+# every period as a flat 1/12 cannot express that, so a borrower's statement
+# and the app disagree on every row.
+#
+# The load-bearing test here is not any of the `actual/365` figures. It is that
+# the DEFAULT still charges exactly what it charged before: this engine is the
+# single accrual point for every loan figure in the product, so a default that
+# moved would silently restate every schedule.
+class Loan::DayCountConventionTest < ActiveSupport::TestCase
+ BALANCE = 300_000
+ RATE = 6
+
+ # 300,000 at 6% is 18,000 a year, so each figure below is 18,000 x days/denominator.
+ # Computed by hand from the convention, not read back out of the engine.
+ test "actual/365 charges by the length of the month" do
+ assert_equal BigDecimal("1528.77"), interest_for(Date.new(2026, 1, 1), Date.new(2026, 2, 1), :actual_365),
+ "January is 31 days: 18000 x 31/365"
+ assert_equal BigDecimal("1380.82"), interest_for(Date.new(2026, 2, 1), Date.new(2026, 3, 1), :actual_365),
+ "February is 28 days: 18000 x 28/365"
+ assert_equal BigDecimal("1479.45"), interest_for(Date.new(2026, 4, 1), Date.new(2026, 5, 1), :actual_365),
+ "April is 30 days: 18000 x 30/365"
+ end
+
+ # The leap day is the residue that does not cancel over a year, and the two
+ # actual conventions part company on it: actual/365 charges a 366th day at
+ # the same daily rate, actual/actual spreads the year over 366.
+ test "the two actual conventions differ on a leap February" do
+ assert_equal BigDecimal("1430.14"), interest_for(Date.new(2028, 2, 1), Date.new(2028, 3, 1), :actual_365),
+ "29 days over 365"
+ assert_equal BigDecimal("1426.23"), interest_for(Date.new(2028, 2, 1), Date.new(2028, 3, 1), :actual_actual),
+ "29 days over 366"
+ end
+
+ # 30/360 reduces to 1/12 exactly, which is the whole reason it is the default.
+ test "the default charges a flat twelfth, whatever the month holds" do
+ %w[2026-01-01 2026-02-01 2026-04-01 2028-02-01].each do |iso|
+ from = Date.parse(iso)
+ assert_equal BigDecimal("1500"), interest_for(from, from >> 1, :thirty_360),
+ "#{iso} should charge 18000/12 regardless of month length"
+ end
+ end
+
+ test "an unspecified convention is the default one" do
+ from = Date.new(2026, 2, 1)
+
+ assert_equal interest_for(from, from >> 1, :thirty_360), interest_for(from, from >> 1, nil)
+ end
+
+ # The negative test the whole change rests on. `Loan::Simulator` is the single
+ # accrual point upstream -- `Loan::AmortizationSchedule` runs through it -- so
+ # a default that charged anything other than a flat 1/12 would restate every
+ # existing schedule. Row for row, not merely in total.
+ test "a default loan produces the schedule it produced before, row for row" do
+ schedule = (1..12).map { |n| Date.new(2026, 1, 1) >> n }
+
+ baseline = simulate(schedule: schedule, convention: nil)
+ explicit = simulate(schedule: schedule, convention: :thirty_360)
+
+ assert_equal 12, baseline.payments.length
+ baseline.payments.zip(explicit.payments).each_with_index do |(was, now), index|
+ assert_equal was, now, "period #{index + 1} moved between the implicit and explicit default"
+ end
+
+ # And against the arithmetic itself, so the test does not merely compare the
+ # engine with itself: every period is the flat twelfth on its opening balance.
+ baseline.payments.each_with_index do |payment, index|
+ opening = index.zero? ? BigDecimal(BALANCE.to_s) : baseline.payments[index - 1][:ending_balance]
+ assert_equal (opening * BigDecimal(RATE.to_s) / 100 / 12).round(2), payment[:interest_payment],
+ "period #{index + 1} is not a flat twelfth of the opening balance"
+ end
+ end
+
+ # A rate change INSIDE a period, on a day count: the period accrues at the
+ # opening rate for its actual days and the payment is re-sized at the new
+ # rate, told what that period really charged. Every other row keeps its
+ # payment -- the day count varies the charge, never the sizing.
+ test "a rate change inside a period re-sizes once, on the period's day-counted charge" do
+ schedule = (1..120).map { |n| Date.new(2026, 1, 1) >> n }
+ change = Date.new(2026, 6, 15)
+ result = Loan::Simulator.new(
+ starting_balance: BALANCE,
+ accrual_start_date: Date.new(2026, 1, 1),
+ payment_schedule: schedule,
+ accrual_rate_for: ->(date) { date < change ? RATE : 8 },
+ currency_precision: 2,
+ day_count_convention: :actual_365
+ ).run
+ rows = result.payments
+ straddle = rows.index { |row| row[:payment_date] == Date.new(2026, 7, 1) }
+ opening = rows[straddle][:beginning_balance]
+
+ assert_equal Loan::AmortizationMath.level_payment(balance: BigDecimal(BALANCE.to_s), monthly_rate: BigDecimal(RATE.to_s) / 100 / 12,
+ remaining_payments: 120, currency_precision: 2),
+ rows.first[:payment_amount], "the opening payment is the plain level payment: no rate moved in period 1"
+ assert_equal (opening * BigDecimal(RATE.to_s) / 100 * 30 / 365).round(2), rows[straddle][:interest_payment],
+ "June accrues 30 days at the opening 6%, on actual/365"
+ assert_equal Loan::AmortizationMath.level_payment(balance: opening, monthly_rate: BigDecimal("8") / 100 / 12,
+ remaining_payments: 120 - straddle, currency_precision: 2,
+ first_period_interest: rows[straddle][:interest_payment]),
+ rows[straddle][:payment_amount], "the re-sized payment covers what June actually charged"
+ assert_equal [ rows.first[:payment_amount] ], rows[0...straddle].map { |row| row[:payment_amount] }.uniq,
+ "no row before the change is re-sized"
+ assert_equal [ rows[straddle][:payment_amount] ], rows[straddle...-1].map { |row| row[:payment_amount] }.uniq,
+ "no row after the change is re-sized again"
+ end
+
+ # A decreasing-life premium is charged on each period's opening balance, so it
+ # follows the schedule's day count. Reassigning the convention must restate it
+ # at once, as it restates the schedule -- not answer from a memo built on the
+ # old basis.
+ test "changing the convention restates a decreasing premium without a reload" do
+ loan = insured_loan(:actual_365)
+ on_actual = loan.total_insurance
+
+ loan.day_count_convention = "thirty_360"
+
+ assert_equal insured_loan(:thirty_360).total_insurance, loan.total_insurance
+ assert_not_equal on_actual, loan.total_insurance, "the two conventions should charge different premiums on this loan"
+ end
+
+ # A period that ends before it starts is a caller's mistake. Under an actual
+ # convention it would charge negative interest, so it is refused instead.
+ test "a period that ends before it starts is refused on an actual convention" do
+ assert_raises(ArgumentError) { interest_for(Date.new(2026, 2, 1), Date.new(2026, 1, 1), :actual_365) }
+ assert_raises(ArgumentError) { interest_for(Date.new(2026, 2, 1), Date.new(2026, 1, 1), :actual_actual) }
+ end
+
+ # The design decision that keeps the payment level. `level_payment` is an
+ # annuity formula over one constant periodic rate; if the day count reached
+ # the sizing, the rate would differ every month and :reamortize would rebuild
+ # the payment every period. The charge varies, the contracted payment does not.
+ test "a varying day count does not resize the payment every period" do
+ schedule = (1..12).map { |n| Date.new(2026, 1, 1) >> n }
+
+ result = simulate(schedule: schedule, convention: :actual_365)
+ # The final period settles the balance, so its amount legitimately differs;
+ # every period before it is the contracted payment.
+ contracted = result.payments[0...-1].map { |p| p[:payment_amount] }.uniq
+
+ assert_equal 1, contracted.length,
+ "the payment was resized as the month length changed: #{contracted.inspect}"
+
+ # And it is the SAME payment the default sizes, because sizing never sees
+ # the day count. If the straddle correction (`first_period_interest`) were
+ # keyed on the derived factors rather than on the rates, a constant-rate
+ # loan would look like a rate change every month and this would move.
+ default_payment = simulate(schedule: schedule, convention: :thirty_360).payments.first[:payment_amount]
+ assert_equal default_payment, contracted.first,
+ "the day count reached the payment sizing"
+ end
+
+ test "an unsupported convention is refused rather than silently defaulted" do
+ error = assert_raises(ArgumentError) do
+ simulate(schedule: [ Date.new(2026, 2, 1) ], convention: :actual_360)
+ end
+
+ assert_match(/unsupported day-count convention/, error.message)
+ end
+
+ # The column is worthless if it does not reach the engine. This walks the
+ # whole path a real loan takes -- Loan -> AmortizationSchedule.for ->
+ # Simulator -- rather than constructing the engine directly, because the
+ # wiring between them is the part that can silently not be done.
+ test "a loan's stored convention reaches the schedule it produces" do
+ loan = loans(:one)
+ loan.account.update!(currency: "USD")
+ loan.update!(day_count_convention: "thirty_360")
+
+ default_first = loan.amortization_schedule.payments.first.interest.amount
+
+ loan.update!(day_count_convention: "actual_365")
+ actual_first = loan.amortization_schedule.payments.first.interest.amount
+
+ assert_not_equal default_first, actual_first,
+ "changing the loan's convention did not change its schedule"
+ end
+
+ test "the column refuses a convention the engine does not implement" do
+ loan = loans(:one)
+
+ loan.day_count_convention = "actual_360"
+ assert_not loan.valid?
+ assert_includes loan.errors[:day_count_convention], "is not included in the list"
+ end
+
+ test "a loan defaults to the convention that preserves today's arithmetic" do
+ assert_equal "thirty_360", Loan.new.day_count_convention
+ assert_equal "thirty_360", Loan::DEFAULT_DAY_COUNT_CONVENTION
+ end
+
+ # actual/actual measures each calendar year against its own length, so a
+ # period crossing New Year is two fractions. 15 Dec 2027 to 15 Jan 2028 is
+ # 17 days of 2027 over 365 plus 14 days of 2028 over 366 -- taking the
+ # opening year's denominator for all 31 would put the 2028 days over 365.
+ test "an actual/actual period crossing New Year uses each year's own denominator" do
+ from = Date.new(2027, 12, 15)
+ to = Date.new(2028, 1, 15)
+
+ expected = (BigDecimal("300000") * BigDecimal("0.06") *
+ ((BigDecimal("17") / 365) + (BigDecimal("14") / 366))).round(2)
+ naive = (BigDecimal("300000") * BigDecimal("0.06") * BigDecimal("31") / 365).round(2)
+
+ assert_not_equal naive, expected, "the two approaches must differ, or this test proves nothing"
+ assert_equal expected, interest_for(from, to, :actual_actual)
+ end
+
+ # The same period on actual/365 is unaffected: that convention has one
+ # denominator by definition, so the year boundary is not a boundary for it.
+ test "actual/365 is indifferent to the year boundary" do
+ expected = (BigDecimal("300000") * BigDecimal("0.06") * BigDecimal("31") / 365).round(2)
+
+ assert_equal expected, interest_for(Date.new(2027, 12, 15), Date.new(2028, 1, 15), :actual_365)
+ end
+
+ # The same boundary with the leap year on the OPENING side: 15 Dec 2028 to
+ # 15 Jan 2029 is 17 days of 2028 over 366 plus 14 days of 2029 over 365. The
+ # test above has the leap year closing the period; this one catches an
+ # implementation that takes either end's denominator for the whole span.
+ test "an actual/actual period leaving a leap year uses each year's own denominator" do
+ from = Date.new(2028, 12, 15)
+ to = Date.new(2029, 1, 15)
+
+ expected = (BigDecimal("300000") * BigDecimal("0.06") *
+ ((BigDecimal("17") / 366) + (BigDecimal("14") / 365))).round(2)
+ opening_year_only = (BigDecimal("300000") * BigDecimal("0.06") * BigDecimal("31") / 366).round(2)
+ closing_year_only = (BigDecimal("300000") * BigDecimal("0.06") * BigDecimal("31") / 365).round(2)
+
+ assert_not_equal opening_year_only, expected, "must differ from the opening year's denominator alone"
+ assert_not_equal closing_year_only, expected, "must differ from the closing year's denominator alone"
+ assert_equal expected, interest_for(from, to, :actual_actual)
+ end
+
+ # The payment is sized on the nominal monthly rate, so on actual/365 the
+ # periods charge a little more or a little less than that sizing assumed and
+ # the last row absorbs the difference. Both directions are pinned: February
+ # and March (59 days) charge less than two flat twelfths, so the final
+ # payment falls BELOW the contracted one; December and January (62 days)
+ # charge more, so it rises ABOVE it. Either way the loan closes at zero.
+ test "the settling row absorbs an actual/365 shortfall below the contracted payment" do
+ result = simulate(schedule: [ Date.new(2026, 3, 1), Date.new(2026, 4, 1) ], convention: :actual_365,
+ accrual_start: Date.new(2026, 2, 1))
+ contracted, final = result.payments.map { |p| p[:payment_amount] }
+
+ assert_operator final, :<, contracted, "59 days of actual/365 charge less than two flat twelfths"
+ assert_final_row_settles(result)
+ end
+
+ test "the settling row absorbs an actual/365 excess above the contracted payment" do
+ result = simulate(schedule: [ Date.new(2026, 1, 1), Date.new(2026, 2, 1) ], convention: :actual_365,
+ accrual_start: Date.new(2025, 12, 1))
+ contracted, final = result.payments.map { |p| p[:payment_amount] }
+
+ assert_operator final, :>, contracted, "62 days of actual/365 charge more than two flat twelfths"
+ assert_final_row_settles(result)
+ end
+
+ # The stored-loan test above walks actual/365 only, which would pass if the
+ # column reached the engine as "any actual convention". A leap January is
+ # where the two actual conventions part, so the first row names which one ran.
+ test "a loan stored on actual/actual is scheduled on actual/actual" do
+ loan = Account.create!(
+ family: families(:dylan_family), name: "Actual/actual #{SecureRandom.hex(3)}", balance: BALANCE, currency: "USD",
+ accountable: Loan.create!(subtype: "mortgage", interest_rate: RATE, term_months: 12, rate_type: "fixed",
+ start_date: Date.new(2024, 1, 1), initial_balance: BALANCE,
+ day_count_convention: "actual_actual")
+ ).loan
+ stored = Loan.find(loan.id)
+
+ first = stored.amortization_schedule.payments.first.interest.amount
+
+ assert_equal "actual_actual", stored.day_count_convention
+ assert_equal BigDecimal("1524.59"), first, "January 2024 is 31 days over 366: 18000 x 31/366"
+ assert_not_equal BigDecimal("1528.77"), first, "31/365 would mean the loan ran on actual/365"
+ assert_not_equal BigDecimal("1500"), first, "a flat twelfth would mean the convention never arrived"
+ end
+
+ # A loan written on the last day of January pays on each month's last day,
+ # because the schedule steps every date from the start: 29 February, then
+ # 31 March, not 29 March. Under an actual convention those clamped dates ARE
+ # the charge, so each row must count the days between its own two dates.
+ test "a schedule from the last day of January charges each month's own days" do
+ schedule = Loan::AmortizationSchedule.new(
+ principal: BALANCE, annual_rate: RATE, term_months: 4, start_date: Date.new(2028, 1, 31),
+ currency: "USD", day_count_convention: :actual_365
+ )
+ rows = schedule.payments
+
+ assert_equal [ Date.new(2028, 2, 29), Date.new(2028, 3, 31), Date.new(2028, 4, 30), Date.new(2028, 5, 31) ],
+ rows.map(&:date)
+
+ opening = BigDecimal(BALANCE.to_s)
+ [ 29, 31, 30, 31 ].zip(rows).each do |days, row|
+ assert_equal (opening * BigDecimal(RATE.to_s) / 100 * days / 365).round(2), row.interest.amount,
+ "the period ending #{row.date} should charge #{days} days over 365"
+ opening = row.ending_balance.amount
+ end
+ end
+
+ # :hold and :scheduled take their payment from the caller, not from sizing,
+ # so a day count reaching them is a separate path from :reamortize. Each row
+ # must still be charged its own days while the payment stays what was asked.
+ test ":hold keeps its seeded repayment while actual/365 varies the charge" do
+ rows = simulate_strategy(:hold, BigDecimal("2000")).payments
+
+ assert_equal [ BigDecimal("2000") ], rows[0...-1].map { |row| row[:payment_amount] }.uniq,
+ "the seeded repayment was re-sized"
+ assert_day_counted(rows)
+ end
+
+ test ":scheduled pays what it is asked each period while actual/365 varies the charge" do
+ asked = ->(index:, **) { BigDecimal("2000") + index }
+ rows = simulate_strategy(:scheduled, asked).payments
+
+ assert_equal rows[0...-1].each_index.map { |index| BigDecimal("2000") + index },
+ rows[0...-1].map { |row| row[:payment_amount] },
+ "a period paid something other than what the callable asked"
+ assert_day_counted(rows)
+ end
+
+ private
+ def simulate_strategy(strategy, payment_amount)
+ Loan::Simulator.new(
+ starting_balance: BALANCE,
+ accrual_start_date: Date.new(2025, 12, 1),
+ payment_schedule: (1..12).map { |n| Date.new(2025, 12, 1) >> n },
+ accrual_rate_for: ->(_date) { RATE },
+ currency_precision: 2,
+ payment_strategy: strategy,
+ payment_amount: payment_amount,
+ day_count_convention: :actual_365
+ ).run
+ end
+
+ # Every row charges its opening balance for the days since the previous
+ # payment over 365, and February (28 days) charges less than a flat
+ # twelfth would -- so a run that fell back to 1/12 cannot pass.
+ def assert_day_counted(rows)
+ previous = Date.new(2025, 12, 1)
+ rows.each do |row|
+ days = (row[:payment_date] - previous).to_i
+ assert_equal (row[:beginning_balance] * BigDecimal(RATE.to_s) / 100 * days / 365).round(2), row[:interest_payment],
+ "the period ending #{row[:payment_date]} should charge #{days} days over 365"
+ previous = row[:payment_date]
+ end
+
+ february = rows.find { |row| row[:payment_date] == Date.new(2026, 3, 1) }
+ assert_operator february[:interest_payment], :<, (february[:beginning_balance] * BigDecimal(RATE.to_s) / 1200).round(2)
+ end
+
+ def insured_loan(convention)
+ Account.create!(
+ family: families(:dylan_family), name: "Insured #{SecureRandom.hex(3)}", balance: BALANCE, currency: "USD",
+ accountable: Loan.create!(subtype: "mortgage", interest_rate: RATE, term_months: 360, rate_type: "fixed",
+ start_date: Date.new(2026, 1, 1), insurance_rate: 1.2,
+ insurance_rate_type: "decreasing_life", day_count_convention: convention.to_s)
+ ).loan
+ end
+
+ def simulate(schedule:, convention:, balance: BALANCE, rate: RATE, accrual_start: schedule.first - 31)
+ Loan::Simulator.new(
+ starting_balance: balance,
+ accrual_start_date: accrual_start,
+ payment_schedule: schedule,
+ accrual_rate_for: ->(_date) { rate },
+ currency_precision: 2,
+ day_count_convention: convention
+ ).run
+ end
+
+ # The final row pays exactly its opening balance plus its own charge, hand
+ # computed on actual/365 from the row's own dates, and leaves nothing owing.
+ def assert_final_row_settles(result)
+ assert result.converged?
+ final = result.payments.last
+ days = (final[:payment_date] - result.payments[-2][:payment_date]).to_i
+ charge = (final[:beginning_balance] * BigDecimal(RATE.to_s) / 100 * days / 365).round(2)
+
+ assert_equal charge, final[:interest_payment]
+ assert_equal final[:beginning_balance] + charge, final[:payment_amount]
+ assert_equal BigDecimal("0"), final[:ending_balance]
+ end
+
+ # One period, so the figure asserted is the charge for exactly that span.
+ def interest_for(from, to, convention)
+ Loan::Simulator.new(
+ starting_balance: BALANCE,
+ accrual_start_date: from,
+ payment_schedule: [ to ],
+ accrual_rate_for: ->(_date) { RATE },
+ currency_precision: 2,
+ day_count_convention: convention
+ ).run.payments.first[:interest_payment]
+ end
+end
diff --git a/test/models/loan/default_convention_baseline_test.rb b/test/models/loan/default_convention_baseline_test.rb
new file mode 100644
index 0000000000..be94ee0cf1
--- /dev/null
+++ b/test/models/loan/default_convention_baseline_test.rb
@@ -0,0 +1,134 @@
+require "test_helper"
+require "digest"
+
+# The default convention must charge exactly what the engine charged before
+# day-count conventions existed, on every path that reaches Loan::Simulator.
+#
+# Each expected figure below was captured from we-promise/sure `main` at
+# 20352e1a0, whose engine has no day-count convention, by running this file
+# with BASELINE_CAPTURE=1. They are not read back out of the patched engine, so
+# a default that moved by a cent on any row fails here.
+#
+# A digest covers every row of a scenario; the spot figures beside it say which
+# part moved when the digest fails.
+class Loan::DefaultConventionBaselineTest < ActiveSupport::TestCase
+ AS_OF = Date.new(2027, 1, 15)
+ START = Date.new(2026, 1, 1)
+
+ EXPECTED = {
+ "fixed_360" => "579580c8f4df4a01fd6b316d80bdfe097e966afb0d7796d244392679d6e901d2",
+ "straddle_reamortize" => "9e61e14f16ee016da4b4089d01af1c9e4db4108f8fdb115612f1eb2f0bc1a58e",
+ "on_payment_date" => "f035430d4e3eaec3053a37325c80bb55b171cf8dbfd58f20700b1d8e58b2fadd",
+ "hold" => "12397dbaaa26b929587379965730b592947f394c8e1b1339bc3f8f3127d893e7",
+ "loan_schedule" => "5026346a0b7ad4b3b832a09db1566efcc109d776cc6b5b270121245c06887eb1",
+ "projection_on_contract" => "8e3a7b3abc0155a01546489433d0390d895eb1f29b69094a4b2b2709468fe218",
+ "projection_ahead" => "dee43f46f7da315bfc9a8f2d7bfb9200e20122337930f6fd7259dff9534651e7",
+ "projection_behind" => "407c0810c113d44f61fc0a9c1e0dda76f2e330c1f97609ebfcaae34f549f931c",
+ "totals" => "dea5348c982598b060dd2951f650251b38ffa6498308f1a8ccdbae6f527c558b"
+ }.freeze
+
+ setup do
+ @family = families(:dylan_family)
+ end
+
+ test "a fixed-rate loan charges what it charged before, over its whole term" do
+ check "fixed_360", simulate(rate_for: ->(_date) { 6 }, periods: 360)
+ end
+
+ test "a rate change inside a period sizes and charges what it did before" do
+ check "straddle_reamortize", simulate(rate_for: ->(date) { date < Date.new(2026, 6, 15) ? 6 : 8 }, periods: 120)
+ end
+
+ test "a rate change on a payment date sizes and charges what it did before" do
+ check "on_payment_date", simulate(rate_for: ->(date) { date < Date.new(2026, 6, 1) ? 6 : 8 }, periods: 120)
+ end
+
+ test "a held payment through a rate change charges what it did before" do
+ check "hold", simulate(rate_for: ->(date) { date < Date.new(2026, 6, 15) ? 6 : 8 }, periods: 120, payment_strategy: :hold)
+ end
+
+ test "a stored loan's schedule is what it was before" do
+ loan = build_loan(variable_rate_schedule: { "2026-06-15" => "8.0" })
+
+ check "loan_schedule", loan.amortization_schedule.payments.map { |payment| canonical_payment(payment) }
+ end
+
+ test "a projection on contract, ahead of it and behind it is what it was before" do
+ { "on_contract" => 0, "ahead" => -25_000, "behind" => 5_000 }.each do |position, offset|
+ loan = build_loan
+ scheduled = loan.amortization_schedule.payments.select { |p| p.date <= AS_OF }.last.ending_balance.amount
+ loan.account.update!(balance: scheduled + offset)
+
+ projection = loan.payoff_projection(as_of: AS_OF)
+ check "projection_#{position}", [
+ projection.payments.map { |row| canonical_row(row) },
+ projection.payoff_date&.iso8601,
+ projection.total_interest.to_s,
+ projection.converged?,
+ projection.balloon_amount.to_s
+ ]
+ end
+ end
+
+ test "a loan's total cost and decreasing-life insurance are what they were before" do
+ loan = build_loan(insurance_rate: 1.2, insurance_rate_type: "decreasing_life")
+
+ check "totals", [ loan.total_cost.to_s, loan.total_insurance.to_s ]
+ end
+
+ private
+ def simulate(rate_for:, periods:, payment_strategy: :reamortize)
+ Loan::Simulator.new(
+ starting_balance: 300_000,
+ accrual_start_date: START,
+ payment_schedule: (1..periods).map { |n| START >> n },
+ accrual_rate_for: rate_for,
+ currency_precision: 2,
+ payment_strategy: payment_strategy
+ ).run.then { |result| [ result.payments.map { |row| canonical_row(row) }, result.converged?, result.balloon_amount.to_s ] }
+ end
+
+ def build_loan(variable_rate_schedule: {}, insurance_rate: nil, insurance_rate_type: nil)
+ account = Account.create!(
+ family: @family, name: "Baseline #{SecureRandom.hex(4)}", balance: 300_000, currency: "USD",
+ accountable: Loan.new(subtype: "mortgage", interest_rate: 6, term_months: 360,
+ rate_type: variable_rate_schedule.empty? ? "fixed" : "variable",
+ start_date: START, variable_rate_schedule: variable_rate_schedule,
+ insurance_rate: insurance_rate, insurance_rate_type: insurance_rate_type)
+ )
+ account.entries.create!(date: START, name: "Opening balance", amount: 300_000, currency: "USD",
+ entryable: Valuation.new(kind: "opening_anchor"))
+ account.loan
+ end
+
+ # Every key, in a fixed order, with BigDecimals in plain notation, so the
+ # digest cannot depend on hash ordering or on how a number prints.
+ def canonical_row(row)
+ row.sort_by { |key, _| key.to_s }.map { |key, value| "#{key}=#{scalar(value)}" }.join(";")
+ end
+
+ def canonical_payment(payment)
+ payment.to_h.sort_by { |key, _| key.to_s }.map { |key, value| "#{key}=#{scalar(value)}" }.join(";")
+ end
+
+ def scalar(value)
+ case value
+ when BigDecimal then value.to_s("F")
+ when Money then "#{value.amount.to_s("F")} #{value.currency.iso_code}"
+ when Date then value.iso8601
+ else value.to_s
+ end
+ end
+
+ def check(name, figures)
+ digest = Digest::SHA256.hexdigest(figures.inspect)
+
+ if ENV["BASELINE_CAPTURE"]
+ puts "BASELINE #{name.inspect} => #{digest.inspect},"
+ return
+ end
+
+ assert EXPECTED.key?(name), "no baseline captured for #{name}"
+ assert_equal EXPECTED.fetch(name), digest, "#{name} no longer matches the engine before day-count conventions"
+ end
+end
diff --git a/test/models/loan/payoff_projection_test.rb b/test/models/loan/payoff_projection_test.rb
index d0ced4b9e7..7a8ef5b9ba 100644
--- a/test/models/loan/payoff_projection_test.rb
+++ b/test/models/loan/payoff_projection_test.rb
@@ -217,18 +217,46 @@ class Loan::PayoffProjectionTest < ActiveSupport::TestCase
"on contract, the projection must charge the running month what the schedule charges it"
end
+ # The projection is the second caller of Loan::Simulator, and it builds its
+ # own. A loan on actual/365 must be projected on actual/365: otherwise the
+ # schedule reconciles to the lender's statement while the projection beside
+ # it charges a flat twelfth, and a borrower exactly on contract is told they
+ # are saving (or losing) interest they are not.
+ test "a loan on actual/365 is projected on the basis its schedule charges" do
+ loan = build_loan(term_months: 24, day_count_convention: "actual_365")
+ next_row = loan.amortization_schedule.payments.find { |p| p.date > @today }
+ on_date = next_row.date
+ following = loan.amortization_schedule.payments.find { |p| p.date > on_date }
+ loan.account.update!(balance: next_row.ending_balance.amount)
+
+ days = (following.date - on_date).to_i
+ opening = next_row.ending_balance.amount
+ actual_365 = (opening * BigDecimal("0.06") * days / 365).round(2)
+ flat = (opening * BigDecimal("0.06") / 12).round(2)
+ assert_not_equal flat, actual_365, "the period must be one where the two bases disagree"
+ assert_equal actual_365, following.interest.amount, "the schedule charges actual/365"
+
+ projection = Loan.find(loan.id).payoff_projection(as_of: on_date)
+
+ assert_equal following.interest.amount, projection.payments.first[:interest_payment],
+ "the projection's first period must charge what the schedule charges it"
+ assert_equal BigDecimal("0"), projection.interest_saved.amount,
+ "on contract, the projection must save nothing against its own schedule"
+ end
+
private
# Built the way the account form builds one: with an opening valuation for
# the amount borrowed. `Loan#original_balance` reads it; without it the
# principal follows whatever the current balance is later set to, and a
# schedule read after a balance update would amortise a different loan.
- def build_loan(term_months:, rate_type: "fixed", interest_rate: 6)
+ def build_loan(term_months:, rate_type: "fixed", interest_rate: 6, day_count_convention: "thirty_360")
account = 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: Date.new(2026, 1, 1))
+ start_date: Date.new(2026, 1, 1),
+ day_count_convention: day_count_convention)
)
account.entries.create!(
date: Date.new(2026, 1, 1), name: "Opening balance", amount: 500_000, currency: "USD",