Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Loans: split payments into principal and interest (#4470)

Shibu M01066a51c9ed
diff --git a/app/controllers/loans_controller.rb b/app/controllers/loans_controller.rb
index 2ff6844db0..8d3a4be985 100644
--- a/app/controllers/loans_controller.rb
+++ b/app/controllers/loans_controller.rb
@@ -4,6 +4,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, :day_count_convention,
+ :principal_only_transfers,
{ rate_changes: [ :effective_date, :rate ] }
)
end
diff --git a/app/controllers/settings/preferences_controller.rb b/app/controllers/settings/preferences_controller.rb
index 4b846780c4..afe0726424 100644
--- a/app/controllers/settings/preferences_controller.rb
+++ b/app/controllers/settings/preferences_controller.rb
@@ -14,13 +14,25 @@ class Settings::PreferencesController < ApplicationController
def update
@user = Current.user
user_params = params.permit(user: [ :preview_features_enabled ]).fetch(:user, {})
+ preview_changed = false
@user.with_locked_preferences do |updated_prefs|
if user_params.key?(:preview_features_enabled)
- updated_prefs["preview_features_enabled"] =
- ActiveModel::Type::Boolean.new.cast(user_params[:preview_features_enabled])
+ enabled = ActiveModel::Type::Boolean.new.cast(user_params[:preview_features_enabled])
+ preview_changed = updated_prefs["preview_features_enabled"] != enabled
+ updated_prefs["preview_features_enabled"] = enabled
end
end
+
+ sync_manual_loans if preview_changed
redirect_to settings_preferences_path
end
+
+ private
+ # The loan replay is gated on the family flag, and its result is stored in
+ # the shared balance rows. Re-sync the manual loans so the toggle takes
+ # effect now rather than at the next scheduled sync.
+ def sync_manual_loans
+ Current.family.accounts.manual.where(accountable_type: "Loan").find_each(&:sync_later)
+ end
end
diff --git a/app/models/balance/base_calculator.rb b/app/models/balance/base_calculator.rb
index 76002b3cfe..d599f1eb7b 100644
--- a/app/models/balance/base_calculator.rb
+++ b/app/models/balance/base_calculator.rb
@@ -47,6 +47,26 @@ class Balance::BaseCalculator
@sync_cache ||= Balance::SyncCache.new(account)
end
+ def loan_principal_change(date)
+ loan_principal_payments&.change_for(date)
+ end
+
+ # The balance change a loan's payment actually makes when interest is
+ # taken out first. A sync is background work with no `Current.user`, so the
+ # family rollup is the right preview check: one opted-in member enables the
+ # recalculated balance for the shared account. The guide reserves the
+ # per-user check for UI.
+ def loan_principal_payments
+ return @loan_principal_payments if defined?(@loan_principal_payments)
+
+ @loan_principal_payments = if account.loan? &&
+ account.loan.amortizable? &&
+ account.has_opening_anchor? &&
+ account.family.preview_features_enabled?
+ sync_cache.loan_principal_payments(account.loan)
+ end
+ end
+
def holdings_value_for_date(date)
sync_cache.get_holdings_value(date)
end
@@ -117,8 +137,13 @@ class Balance::BaseCalculator
income_outflow_sum = income_trades.select { |e| e.amount >= 0 }.sum(&:amount)
if account.balance_type == :non_cash && account.accountable_type == "Loan"
- non_cash_inflows = txn_inflow_sum.abs
- non_cash_outflows = txn_outflow_sum
+ if (change = loan_principal_change(date))
+ non_cash_inflows = change.principal_paid
+ non_cash_outflows = change.principal_added
+ else
+ non_cash_inflows = txn_inflow_sum.abs
+ non_cash_outflows = txn_outflow_sum
+ end
elsif account.balance_type != :non_cash
cash_inflows = txn_inflow_sum.abs + trade_cash_inflow_sum.abs + income_inflow_sum.abs
cash_outflows = txn_outflow_sum + trade_cash_outflow_sum + income_outflow_sum
diff --git a/app/models/balance/forward_calculator.rb b/app/models/balance/forward_calculator.rb
index 45c5e5fd2f..e4d52a130d 100644
--- a/app/models/balance/forward_calculator.rb
+++ b/app/models/balance/forward_calculator.rb
@@ -151,6 +151,10 @@ class Balance::ForwardCalculator < Balance::BaseCalculator
# Positive entries amount on an "asset" account means, "account value has decreased"
# Positive entries amount on a "liability" account means, "account debt has increased"
def signed_entry_flows(entries)
+ if account.loan? && entries.any? && (change = loan_principal_change(entries.first.date))
+ return change.net
+ end
+
entry_flows = entries.sum(&:amount)
account.asset? ? -entry_flows : entry_flows
end
diff --git a/app/models/balance/sync_cache.rb b/app/models/balance/sync_cache.rb
index 0819f22b3b..c3c98664b0 100644
--- a/app/models/balance/sync_cache.rb
+++ b/app/models/balance/sync_cache.rb
@@ -41,6 +41,18 @@ class Balance::SyncCache
entries_by_date[date]&.select { |e| e.transaction? || e.trade? } || []
end
+ # Every entry converted to the account currency, in date order.
+ def entries
+ converted_entries
+ end
+
+ # One replay per loan per cache, so a calculator that asks twice does not
+ # walk the ledger twice.
+ def loan_principal_payments(loan)
+ @loan_principal_payments ||= {}
+ @loan_principal_payments[loan.id] ||= Loan::PrincipalPayments.for(loan, entries: entries)
+ end
+
private
attr_reader :account
diff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rb
index 30cdea60b6..a253058d39 100644
--- a/app/models/family/auto_transfer_matchable.rb
+++ b/app/models/family/auto_transfer_matchable.rb
@@ -139,6 +139,7 @@ module Family::AutoTransferMatchable
# Track which transactions we've already matched to avoid duplicates
used_transaction_ids = Set.new
+ created_transfers = []
Transfer.transaction do
candidates_scope.each do |match|
@@ -149,15 +150,36 @@ module Family::AutoTransferMatchable
# (a concurrent sync claimed one of the transactions for a different pairing).
# A created transfer stays pending and leaves the transaction kinds untouched
# until the user confirms it (Transfer#confirm!).
- next unless find_or_create_transfer!(match)
+ transfer = find_or_create_transfer!(match)
+ next unless transfer
+ created_transfers << transfer if transfer.previously_new_record?
used_transaction_ids << match.inflow_transaction_id
used_transaction_ids << match.outflow_transaction_id
end
end
+
+ sync_principal_only_loan_accounts(created_transfers)
end
private
+ # A principal-only loan replays a linked transfer as principal. The balance
+ # was materialized before this match existed, so re-sync from the transfer's
+ # entry dates.
+ def sync_principal_only_loan_accounts(transfers)
+ transfers.each do |transfer|
+ next unless principal_only_loan_transfer?(transfer)
+
+ transfer.sync_account_later
+ end
+ end
+
+ def principal_only_loan_transfer?(transfer)
+ [ transfer.from_account, transfer.to_account ].compact.any? do |account|
+ account.loan? && account.loan.amortizable? && account.loan.principal_only_transfers?
+ end
+ end
+
# The hint's candidate pairs for `transactions`: the narrower hint window and
# tolerance, no rejected pairs, both legs in the same category (or both
# uncategorized, since a categorized purchase against an income is not a
diff --git a/app/models/loan.rb b/app/models/loan.rb
index 0363317c8f..f39f212245 100644
--- a/app/models/loan.rb
+++ b/app/models/loan.rb
@@ -313,6 +313,48 @@ class Loan < ApplicationRecord
end
end
+ # The balance replay reads these columns. A save without a sync leaves the
+ # stored rows on the old calculation until the next scheduled sync.
+ BALANCE_INPUTS = (SCHEDULE_INPUTS + INSURANCE_INPUTS + %i[initial_balance principal_only_transfers]).freeze
+
+ # `lock_saved_attributes!` saves the loan a second time in the same
+ # transaction. A commit condition that reads saved changes would see only
+ # that second save, so remember the input change until the commit runs.
+ after_update :remember_balance_input_change
+ after_update_commit :sync_balance_after_change, if: :balance_inputs_changed?
+ after_rollback :forget_balance_input_change
+
+ private def remember_balance_input_change
+ return unless BALANCE_INPUTS.any? { |input| saved_change_to_attribute?(input) }
+
+ @balance_inputs_changed = true
+ end
+
+ private def balance_inputs_changed?
+ @balance_inputs_changed == true
+ end
+
+ private def sync_balance_after_change
+ @balance_inputs_changed = false
+ return unless account
+
+ # A running sync cannot widen its window, so reusing it would keep the
+ # balance seeded from the old window. Mark it for a full sync after it
+ # finishes.
+ if (sync = account.syncs.visible.where(status: "syncing").first)
+ sync.update!(full_resync_requested: true)
+ # The sync can finish between the lookup and the update. Its own
+ # completion check may already have run, so queue the full sync here.
+ account.sync_later unless sync.reload.syncing?
+ else
+ account.sync_later
+ end
+ end
+
+ private def forget_balance_input_change
+ @balance_inputs_changed = false
+ end
+
def reload(*)
@amortization_schedule = nil
@insurance = nil
diff --git a/app/models/loan/amortization_math.rb b/app/models/loan/amortization_math.rb
index af206a596f..acb64380b1 100644
--- a/app/models/loan/amortization_math.rb
+++ b/app/models/loan/amortization_math.rb
@@ -5,8 +5,83 @@ class Loan
# re-amortisation part-way through sizes them from the balance then
# outstanding over the periods still remaining. Two callers, one formula.
module AmortizationMath
+ PERCENT = BigDecimal("100")
+ MONTHS_PER_YEAR = BigDecimal("12")
+ DAYS_PER_YEAR = BigDecimal("365")
+ DAYS_PER_LEAP_YEAR = BigDecimal("366")
+
module_function
+ # `annual_percentage` is whatever the caller's rate source returned -- an
+ # Integer in tests, a BigDecimal from RateResolver -- so the coercion at
+ # this boundary stays. The two-step division is kept so results match the
+ # schedules this product has always produced.
+ def monthly_rate(annual_percentage)
+ (BigDecimal(annual_percentage.to_s) / PERCENT) / MONTHS_PER_YEAR
+ end
+
+ # How much of a year one period charges, under the loan's day-count
+ # convention.
+ #
+ # Under 30/360 a full scheduled period is a flat twelfth. A period cut
+ # short by a valuation is not a full month, so it charges its own 30/360
+ # days. `full_period` keeps the contracted schedule bit-identical while
+ # letting a partial period charge the days it actually covers.
+ def accrual_factor(annual_percentage:, period_start:, period_end:, day_count_convention:, full_period: true)
+ 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.to_sym == :thirty_360
+ return monthly_rate(annual_percentage) if full_period
+
+ return rate * thirty_360_year_fraction(period_start, period_end)
+ end
+
+ if day_count_convention.to_sym == :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
+
+ # US 30/360 day fraction for a part-month period. The month-end rules keep
+ # the common cases consistent: a 31st start counts as the 30th, and a 31st
+ # end does too when the start is already the 30th.
+ def thirty_360_year_fraction(period_start, period_end)
+ start_day = period_start.day
+ end_day = period_end.day
+ start_day = 30 if start_day == 31
+ end_day = 30 if end_day == 31 && start_day == 30
+
+ days = 360 * (period_end.year - period_start.year) +
+ 30 * (period_end.month - period_start.month) +
+ (end_day - start_day)
+
+ BigDecimal(days.to_s) / 360
+ 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.
+ 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
+
# 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.
diff --git a/app/models/loan/principal_payments.rb b/app/models/loan/principal_payments.rb
new file mode 100644
index 0000000000..0d56349d50
--- /dev/null
+++ b/app/models/loan/principal_payments.rb
@@ -0,0 +1,421 @@
+class Loan
+ # Replays a loan's ledger into the principal and interest each payment
+ # actually paid.
+ #
+ # Interest is charged once per scheduled period, on the principal the period
+ # opened with, using the loan's own day-count convention. A payment therefore
+ # reduces principal by only the part left after interest. This is the same
+ # engine the schedule uses, so a borrower who pays the schedule matches it
+ # row for row.
+ #
+ # A linked transfer is a full payment unless the loan opts in to
+ # principal-only transfers. The opt-in covers the workflow from #1804: the
+ # borrower transfers only principal and records the interest separately.
+ #
+ # Only a manual loan whose opening anchor is its real origination is
+ # replayed. A provider-owned loan's anchor is a current balance dated into
+ # the past, so charging interest on it would invent a history.
+ class PrincipalPayments
+ # A payment made a few days after the due date still belongs to that
+ # period. Without this window, a weekend slip would charge the next period
+ # on a principal the borrower had already repaid.
+ PAYMENT_GRACE_DAYS = 5
+
+ Change = Data.define(:principal_paid, :principal_added, :interest_paid) do
+ def net
+ principal_added - principal_paid
+ end
+ end
+
+ # The replay walks scheduled dates and entry dates in one ordered stream.
+ # `period_interest` is nil until the open period has been charged; a nil
+ # amount is different from a genuine zero-rate charge.
+ State = Struct.new(
+ :principal,
+ :carried_interest,
+ :period_interest,
+ :period_start,
+ :period_principal,
+ :payment_index,
+ keyword_init: true
+ )
+
+ def self.for(loan, entries:)
+ account = loan&.account
+ return nil unless loan&.amortizable? && account&.manual?
+ return nil unless account.has_opening_anchor? && account.opening_anchor_balance.to_d.positive?
+ return nil unless loan.initial_balance.present? && loan.initial_balance.to_d.positive?
+ return nil unless anchor_matches_origination?(loan, account)
+
+ new(loan, entries: entries)
+ end
+
+ def self.anchor_matches_origination?(loan, account)
+ return false unless account.opening_anchor_date == loan.origination_date
+
+ precision = Money::Currency.new(account.currency).default_precision || 2
+ account.opening_anchor_balance.to_d.round(precision) ==
+ loan.original_balance.amount.round(precision)
+ end
+ private_class_method :anchor_matches_origination?
+
+ def initialize(loan, entries:)
+ @loan = loan
+ @account = loan.account
+ @entries = entries
+ @premium_remaining = {}
+ @changes = build_changes
+ end
+
+ def change_for(date)
+ @changes[date]
+ end
+
+ def changes
+ @changes
+ end
+
+ private
+ attr_reader :loan, :account, :entries
+
+ def build_changes
+ return {} if schedule.nil?
+
+ state = State.new(
+ principal: opening_balance,
+ carried_interest: BigDecimal("0"),
+ period_interest: nil,
+ period_start: anchor_date,
+ period_principal: opening_balance,
+ payment_index: 0
+ )
+
+ changes = {}
+
+ timeline.each do |date|
+ next if date < anchor_date
+
+ advance_closed_periods(state, date)
+ charge_period(state) if charge_period_for_date?(state, date)
+
+ transactions = transactions_on(date)
+ change = process_transactions(state, date, transactions) if transactions.any?
+
+ if (valuation = valuation_on(date))
+ apply_valuation(state, valuation)
+ # A valuation-only day still needs an entry so callers can see the
+ # reset. A payment on the same day keeps its own change: the
+ # valuation resets the balance, but the payment still happened.
+ changes[date] = change || zero_change
+ elsif change
+ changes[date] = change
+ end
+
+ close_period(state, date) if due_date?(state, date)
+ end
+
+ changes
+ end
+
+ # Close every scheduled period that ended before this date. A period
+ # with no payment still accrues its charge; it is carried, not lost.
+ # A period already charged by an early payment is not charged again.
+ def advance_closed_periods(state, date)
+ while (payment = schedule.payments[state.payment_index]) && payment.date < date
+ charge_period(state) if state.period_interest.nil?
+ close_period(state, payment.date)
+ end
+ end
+
+ def charge_period_for_date?(state, date)
+ return false unless state.period_interest.nil?
+ return true if due_date?(state, date)
+ # A payment between due dates pays interest already carried before it
+ # pays the next period's charge.
+ return false if state.carried_interest.positive?
+ # A payment inside the grace window can still lower the principal the
+ # new period charges. Wait for the window to close.
+ return false if grace_window?(state, date)
+
+ transactions_on(date).any?
+ end
+
+ def charge_period(state)
+ payment = schedule.payments[state.payment_index]
+ return if payment.nil? || payment.date <= state.period_start
+
+ if state.period_principal <= 0
+ state.period_interest = BigDecimal("0")
+ return
+ end
+
+ factor = AmortizationMath.accrual_factor(
+ annual_percentage: rate_resolver.accrual_rate_for(state.period_start),
+ period_start: state.period_start,
+ period_end: payment.date,
+ day_count_convention: day_count_convention,
+ full_period: scheduled_period_start?(state.period_start)
+ )
+
+ state.period_interest = (state.period_principal * factor).round(precision)
+ end
+
+ def close_period(state, date)
+ payment = schedule.payments[state.payment_index]
+ return unless payment && payment.date == date
+
+ state.carried_interest += period_interest(state)
+ state.period_interest = nil
+ state.period_start = date
+ state.period_principal = state.principal
+ state.payment_index += 1
+ end
+
+ def process_transactions(state, date, transactions)
+ linked, unlinked = transactions.partition { |entry| linked?(entry) }
+
+ added = transactions.sum(BigDecimal("0")) do |entry|
+ entry.amount.positive? ? entry.amount : BigDecimal("0")
+ end.round(precision)
+ state.principal += added
+
+ payment = instalment_for(state, date)
+ principal_paid = BigDecimal("0")
+ interest_paid = BigDecimal("0")
+
+ linked_negative = linked.select { |entry| entry.amount.negative? }
+ unlinked_negative = unlinked.select { |entry| entry.amount.negative? }
+
+ principal_only, full_linked = if loan.principal_only_transfers?
+ [ linked_negative, [] ]
+ else
+ [ [], linked_negative ]
+ end
+
+ principal_only.each do |entry|
+ # No cap: an overpayment beyond the remaining principal leaves a
+ # credit instead of being dropped.
+ applied = (-entry.amount).round(precision)
+ state.principal -= applied
+ principal_paid += applied
+ apply_grace_principal(state, date, applied)
+
+ # The borrower records the instalment's interest separately. Count
+ # it once; it never reduces principal again.
+ interest_paid += principal_only_interest(state)
+ end
+
+ full_amount = (full_linked + unlinked_negative).sum(BigDecimal("0")) { |entry| -entry.amount }.round(precision)
+
+ if full_amount.positive?
+ paid_interest = apply_interest(state, full_amount)
+
+ remaining = full_amount - paid_interest
+ remaining = apply_premium(remaining, payment)
+ # No cap: an overpayment beyond the remaining principal leaves a
+ # credit instead of being dropped.
+ applied = remaining
+ state.principal -= applied
+ principal_paid += applied
+ apply_grace_principal(state, date, applied)
+ interest_paid += paid_interest
+ end
+
+ Change.new(
+ principal_paid: principal_paid.round(precision),
+ principal_added: added.round(precision),
+ interest_paid: interest_paid.round(precision)
+ )
+ end
+
+ # A payment a few days after the due date still reduces the principal
+ # the new period charges interest on. Beyond the window, the period keeps
+ # the principal it opened with.
+ def apply_grace_principal(state, date, applied)
+ return unless applied.positive?
+ return unless grace_window?(state, date)
+
+ state.period_principal -= applied
+ end
+
+ # A payment made a few days after the period opens still belongs to that
+ # period. This is the same window apply_grace_principal uses.
+ def grace_window?(state, date)
+ return false unless scheduled_period_start?(state.period_start)
+
+ days = (date - state.period_start).to_i
+ days.positive? && days <= PAYMENT_GRACE_DAYS
+ end
+
+ # Apply a payment to carried interest first, then to the open period's
+ # charge. A deferred period stays nil: deferred is not the same as a
+ # genuine zero-rate charge.
+ def apply_interest(state, amount)
+ from_carried = [ amount, state.carried_interest ].min
+ state.carried_interest -= from_carried
+
+ from_period = BigDecimal("0")
+ unless state.period_interest.nil?
+ from_period = [ amount - from_carried, state.period_interest ].min
+ state.period_interest -= from_period
+ end
+
+ from_carried + from_period
+ end
+
+ # The premium is charged alongside the instalment and is senior to
+ # principal. Track its remaining amount per instalment so a payment in
+ # two halves does not charge it twice and an underpayment cannot turn it
+ # into principal.
+ def apply_premium(remaining, payment)
+ return remaining if payment.nil?
+
+ due = premium_remaining(payment)
+ return remaining unless due.positive?
+
+ paid = [ remaining, due ].min
+ @premium_remaining[payment.number] = due - paid
+ remaining - paid
+ end
+
+ def premium_remaining(payment)
+ @premium_remaining[payment.number] ||= premium_for(payment)
+ end
+
+ # A late principal-only transfer belongs to the period it missed; an
+ # early one belongs to the period it is paying into.
+ def instalment_for(state, date)
+ return schedule.payments[state.payment_index] if due_date?(state, date)
+ if state.carried_interest.positive? && state.payment_index.positive?
+ return schedule.payments[state.payment_index - 1]
+ end
+
+ schedule.payments[state.payment_index] || schedule.payments.last
+ end
+
+ def principal_only_interest(state)
+ paid = state.carried_interest
+ state.carried_interest = BigDecimal("0")
+
+ if state.period_interest&.positive?
+ paid += state.period_interest
+ state.period_interest = BigDecimal("0")
+ end
+
+ paid
+ end
+
+ def apply_valuation(state, valuation)
+ state.principal = valuation.amount.to_d.round(precision)
+ state.carried_interest = BigDecimal("0")
+ state.period_interest = nil
+ state.period_start = valuation.date
+ state.period_principal = state.principal
+
+ # Periods whose due date is on or before the valuation are behind the
+ # reset; the next period starts from the valuation.
+ while (payment = schedule.payments[state.payment_index]) && payment.date <= valuation.date
+ state.payment_index += 1
+ end
+ end
+
+ def transactions_on(date)
+ entries_by_date[date]&.select(&:transaction?) || []
+ end
+
+ def valuation_on(date)
+ entries_by_date[date]&.find(&:valuation?)
+ end
+
+ def entries_by_date
+ @entries_by_date ||= entries.group_by(&:date)
+ end
+
+ def timeline
+ @timeline ||= begin
+ entry_dates = entries.map(&:date)
+ last_entry_date = entry_dates.max
+ # Nothing after the last entry can change a balance, so future
+ # instalments are not walked.
+ due_dates = schedule.payments.map(&:date).select { |date| last_entry_date && date <= last_entry_date }
+
+ (due_dates + entry_dates).uniq.sort
+ end
+ end
+
+ def due_date?(state, date)
+ schedule.payments[state.payment_index]&.date == date
+ end
+
+ # A period opened on a scheduled date is a full period for the day-count
+ # convention. A period opened by a mid-period valuation is a stub.
+ def scheduled_period_start?(date)
+ scheduled_dates.include?(date)
+ end
+
+ def scheduled_dates
+ @scheduled_dates ||= (schedule.payments.map(&:date) << anchor_date).to_set
+ end
+
+ def linked?(entry)
+ linked_transaction_ids.include?(entry.entryable_id)
+ end
+
+ def linked_transaction_ids
+ @linked_transaction_ids ||= begin
+ ids = entries.select(&:transaction?).map(&:entryable_id)
+ if ids.empty?
+ Set.new
+ else
+ Transfer.where("inflow_transaction_id IN (?) OR outflow_transaction_id IN (?)", ids, ids)
+ .pluck(:inflow_transaction_id, :outflow_transaction_id)
+ .flatten
+ .to_set
+ end
+ end
+ end
+
+ def rate_resolver
+ @rate_resolver ||= Loan::RateResolver.for(loan)
+ end
+
+ def schedule
+ @schedule ||= loan.amortization_schedule
+ end
+
+ def premium_for(payment)
+ return BigDecimal("0") if payment.nil?
+
+ premium = loan.insurance&.premium_for(payment.number)
+ premium ? premium.amount.amount : BigDecimal("0")
+ end
+
+ def period_interest(state)
+ state.period_interest || BigDecimal("0")
+ end
+
+ def opening_balance
+ @opening_balance ||= account.opening_anchor_balance.to_d.round(precision)
+ end
+
+ def anchor_date
+ @anchor_date ||= account.opening_anchor_date
+ end
+
+ def day_count_convention
+ @day_count_convention ||= (loan.day_count_convention.presence || Loan::DEFAULT_DAY_COUNT_CONVENTION).to_sym
+ end
+
+ def precision
+ @precision ||= Money::Currency.new(account.currency).default_precision || 2
+ end
+
+ def zero_change
+ Change.new(
+ principal_paid: BigDecimal("0"),
+ principal_added: BigDecimal("0"),
+ interest_paid: BigDecimal("0")
+ )
+ end
+ end
+end
diff --git a/app/models/loan/simulator.rb b/app/models/loan/simulator.rb
index 4362827497..d4fba5b039 100644
--- a/app/models/loan/simulator.rb
+++ b/app/models/loan/simulator.rb
@@ -53,12 +53,6 @@ class Loan
# instead of being re-sized back onto the original maturity
PAYMENT_STRATEGIES = %i[reamortize hold scheduled].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")
-
# 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
@@ -69,8 +63,6 @@ class Loan
# 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:,
@@ -254,52 +246,19 @@ class Loan
.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.
- # 30/360 keeps the original two-step division untouched, so a default
- # loan's figures are bit-identical rather than merely close.
+ # The day-count definition lives in AmortizationMath so the schedule and
+ # the ledger replay cannot charge a period differently.
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
+ AmortizationMath.accrual_factor(
+ annual_percentage: annual_percentage,
+ period_start: period_start,
+ period_end: period_end,
+ day_count_convention: @day_count_convention
+ )
end
def monthly_rate(annual_percentage)
- (BigDecimal(annual_percentage.to_s) / PERCENT) / MONTHS_PER_YEAR
+ AmortizationMath.monthly_rate(annual_percentage)
end
def callable!(value, name)
diff --git a/app/models/sync.rb b/app/models/sync.rb
index 66079a2a4e..2ab28b6ab8 100644
--- a/app/models/sync.rb
+++ b/app/models/sync.rb
@@ -50,7 +50,7 @@ class Sync < ApplicationRecord
end
# Marks a sync that never completed within the expected time window
- event :mark_stale do
+ event :mark_stale, after_commit: :handle_stale_transition do
transitions from: %i[pending syncing], to: :stale
end
end
@@ -353,6 +353,30 @@ class Sync < ApplicationRecord
rescue => e
Rails.logger.error("Error performing post-sync for #{syncable_type} (#{syncable.id}): #{e.message}")
report_error(e)
+ ensure
+ # A resync request outlives a post-sync failure.
+ queue_full_resync
+ end
+
+ # A loan input can change while this sync runs. The running sync cannot
+ # widen its own window, so run a fresh full sync now that this one is done.
+ def queue_full_resync
+ # A fresh read sees a request the web process wrote after this sync
+ # loaded its own row.
+ return unless Sync.where(id: id).pick(:full_resync_requested)
+
+ # Another partial sync can already be running. Mark it instead of
+ # reusing it through sync_later, which cannot widen a running window.
+ if (running = syncable.syncs.visible.where(status: "syncing").first)
+ running.update!(full_resync_requested: true)
+ else
+ syncable.sync_later
+ end
+
+ update_column(:full_resync_requested, false)
+ rescue => e
+ Rails.logger.error("Error queueing full resync for #{syncable_type} (#{syncable_id}): #{e.message}")
+ report_error(e)
end
def report_error(error)
@@ -384,6 +408,11 @@ class Sync < ApplicationRecord
family.touch(:latest_sync_completed_at)
end
+ # A stale sync skips post-sync, so a resync request must be processed here.
+ def handle_stale_transition
+ queue_full_resync
+ end
+
def window_valid
if window_start_date && window_end_date && window_start_date > window_end_date
errors.add(:window_end_date, "must be greater than window_start_date")
diff --git a/app/views/loans/_form.html.erb b/app/views/loans/_form.html.erb
index c4ac2b838c..4f6a0a7204 100644
--- a/app/views/loans/_form.html.erb
+++ b/app/views/loans/_form.html.erb
@@ -91,6 +91,15 @@
</div>
<p class="text-xs text-secondary"><%= t("loans.form.insurance_rate_hint") %></p>
+ <div class="flex items-center justify-between gap-4">
+ <div class="space-y-1">
+ <p class="text-sm" id="principal_only_transfers_label"><%= t("loans.form.principal_only_transfers") %></p>
+ <p class="text-secondary text-sm"><%= t("loans.form.principal_only_transfers_hint") %></p>
+ </div>
+ <%= loan_form.toggle :principal_only_transfers,
+ "aria-labelledby": "principal_only_transfers_label" %>
+ </div>
+
<%# Rate changes only mean something for a loan whose rate can move. The
section is rendered for every rate type, retained rows included, and
for fixed it is hidden AND its inputs disabled -- here, server-side,
diff --git a/config/locales/views/loans/en.yml b/config/locales/views/loans/en.yml
index d1fc2c186b..abfd82f0b6 100644
--- a/config/locales/views/loans/en.yml
+++ b/config/locales/views/loans/en.yml
@@ -40,6 +40,8 @@ en:
insurance_rate_type: Insurance type
insurance_rate_type_decreasing_life: Decreasing
insurance_rate_type_level_term: Level term
+ principal_only_transfers: Linked transfers are principal only
+ principal_only_transfers_hint: Turn this on when you transfer only the principal and record the interest separately. Leave it off when the linked transfer is the full payment.
new:
title: Enter loan details
overview:
diff --git a/config/locales/views/loans/fr.yml b/config/locales/views/loans/fr.yml
index e275cc88e4..6c9fd55a0a 100644
--- a/config/locales/views/loans/fr.yml
+++ b/config/locales/views/loans/fr.yml
@@ -19,6 +19,8 @@ fr:
insurance_rate_type: Type d'assurance
insurance_rate_type_decreasing_life: Dégressive
insurance_rate_type_level_term: Constante
+ principal_only_transfers: Les virements liés portent uniquement sur le capital
+ principal_only_transfers_hint: Activez cette option si vous virez uniquement le capital et enregistrez les intérêts séparément. Laissez-la désactivée si le virement lié correspond au paiement complet.
subtype_none: Aucun
subtype_prompt: Sélectionner le type de prêt
term_months: Durée (mois)
diff --git a/db/migrate/20261025090000_add_principal_only_transfers_to_loans.rb b/db/migrate/20261025090000_add_principal_only_transfers_to_loans.rb
new file mode 100644
index 0000000000..fad67e6c4c
--- /dev/null
+++ b/db/migrate/20261025090000_add_principal_only_transfers_to_loans.rb
@@ -0,0 +1,8 @@
+class AddPrincipalOnlyTransfersToLoans < ActiveRecord::Migration[8.1]
+ # A linked transfer can be the principal part of a payment whose interest is
+ # recorded separately. No ledger marker reliably says so, so the borrower
+ # sets the behaviour per loan instead of the replay guessing from an amount.
+ def change
+ add_column :loans, :principal_only_transfers, :boolean, default: false, null: false
+ end
+end
diff --git a/db/migrate/20261028090000_add_full_resync_requested_to_syncs.rb b/db/migrate/20261028090000_add_full_resync_requested_to_syncs.rb
new file mode 100644
index 0000000000..634eaf8970
--- /dev/null
+++ b/db/migrate/20261028090000_add_full_resync_requested_to_syncs.rb
@@ -0,0 +1,7 @@
+class AddFullResyncRequestedToSyncs < ActiveRecord::Migration[8.1]
+ # A running sync cannot widen its window. A loan input change during that
+ # sync marks it here so a full sync runs after the current one finishes.
+ def change
+ add_column :syncs, :full_resync_requested, :boolean, default: false, null: false
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 1031552662..39a6d184c8 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1604,6 +1604,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_11_080000) do
t.string "insurance_rate_type"
t.decimal "interest_rate", precision: 10, scale: 3
t.jsonb "locked_attributes", default: {}
+ t.boolean "principal_only_transfers", default: false, null: false
t.string "rate_type"
t.date "start_date"
t.string "subtype"
@@ -2718,6 +2719,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_11_080000) do
t.jsonb "data"
t.string "error"
t.datetime "failed_at"
+ t.boolean "full_resync_requested", default: false, null: false
t.uuid "parent_id"
t.datetime "pending_at"
t.string "status", default: "pending"
diff --git a/test/controllers/loans_controller_test.rb b/test/controllers/loans_controller_test.rb
index 06589217c6..afe33675ee 100644
--- a/test/controllers/loans_controller_test.rb
+++ b/test/controllers/loans_controller_test.rb
@@ -222,6 +222,26 @@ class LoansControllerTest < ActionDispatch::IntegrationTest
"the controller filtered out the convention the user chose"
end
+ test "saving principal_only_transfers queues a balance sync" do
+ patch loan_path(@account), params: {
+ account: {
+ accountable_attributes: {
+ id: @account.accountable_id,
+ principal_only_transfers: "1"
+ }
+ }
+ }
+
+ assert @account.loan.reload.principal_only_transfers?
+ assert_enqueued_jobs 1, only: SyncJob
+ end
+
+ test "saving an unrelated loan field does not queue a balance sync" do
+ assert_no_enqueued_jobs(only: SyncJob) do
+ patch loan_path(@account), params: { account: { name: "Renamed Loan" } }
+ end
+ 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/controllers/settings/preferences_controller_test.rb b/test/controllers/settings/preferences_controller_test.rb
index d83e18b7ae..c9a1a1db25 100644
--- a/test/controllers/settings/preferences_controller_test.rb
+++ b/test/controllers/settings/preferences_controller_test.rb
@@ -68,6 +68,15 @@ class Settings::PreferencesControllerTest < ActionDispatch::IntegrationTest
assert user.reload.preview_features_enabled?
end
+ test "changing preview features syncs the manual loans" do
+ loan_account = accounts(:loan)
+ assert loan_account.manual?
+
+ assert_difference -> { loan_account.syncs.count }, 1 do
+ patch settings_preferences_url, params: { user: { preview_features_enabled: "1" } }
+ end
+ end
+
test "update toggles preview_features_enabled off" do
user = users(:family_admin)
user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => true))
diff --git a/test/models/balance/forward_calculator_test.rb b/test/models/balance/forward_calculator_test.rb
index 430fb7715a..7689da96a1 100644
--- a/test/models/balance/forward_calculator_test.rb
+++ b/test/models/balance/forward_calculator_test.rb
@@ -1003,6 +1003,42 @@ class Balance::ForwardCalculatorTest < ActiveSupport::TestCase
)
end
+ test "a preview loan payment reduces principal by only the post-interest part" do
+ account = create_loan_account(
+ initial_balance: 12_000,
+ term_months: 12,
+ entries: [
+ { type: "opening_anchor", date: Date.new(2026, 1, 1), balance: 12_000 },
+ { type: "transaction", date: Date.new(2026, 2, 1), amount: -1_066.19 }
+ ]
+ )
+ enable_preview_features_for_family!(account.family)
+
+ calculated = Balance::ForwardCalculator.new(account).calculate
+ row = calculated.find { |balance| balance.date == Date.new(2026, 2, 1) }
+
+ assert_equal BigDecimal("11053.81"), row.balance
+ assert_equal BigDecimal("946.19"), row.non_cash_inflows
+ assert_equal BigDecimal("0"), row.non_cash_outflows
+ end
+
+ test "a loan payment is all principal when preview is off" do
+ account = create_loan_account(
+ initial_balance: 12_000,
+ term_months: 12,
+ entries: [
+ { type: "opening_anchor", date: Date.new(2026, 1, 1), balance: 12_000 },
+ { type: "transaction", date: Date.new(2026, 2, 1), amount: -1_066.19 }
+ ]
+ )
+
+ calculated = Balance::ForwardCalculator.new(account).calculate
+ row = calculated.find { |balance| balance.date == Date.new(2026, 2, 1) }
+
+ assert_equal BigDecimal("10933.81"), row.balance
+ assert_equal BigDecimal("1066.19"), row.non_cash_inflows
+ end
+
private
def assert_balances(calculated_data:, expected_balances:)
# Sort calculated data by date to ensure consistent ordering
diff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rb
index a8f9671302..08b7fbd2fa 100644
--- a/test/models/family/auto_transfer_matchable_test.rb
+++ b/test/models/family/auto_transfer_matchable_test.rb
@@ -2,6 +2,7 @@ require "test_helper"
class Family::AutoTransferMatchableTest < ActiveSupport::TestCase
include EntriesTestHelper
+ include LedgerTestingHelper
setup do
@family = families(:dylan_family)
@@ -918,6 +919,63 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCase
assert_equal "funds_movement", inflow_entry.entryable.kind
end
+ test "auto-matching a principal-only loan payment re-syncs the loan" do
+ @loan.loan.update_column(:principal_only_transfers, true)
+ create_transaction(date: Date.current, account: @depository, amount: 500)
+ create_transaction(date: Date.current, account: @loan, amount: -500)
+
+ assert_difference -> { Sync.where(syncable: @loan).count }, 1 do
+ @family.auto_match_transfers!
+ end
+
+ sync = Sync.where(syncable: @loan).order(:created_at).last
+ assert_equal Date.current, sync.window_start_date
+ end
+
+ test "auto-matching a principal-only loan payment corrects the stored balance" do
+ account = create_loan_account(
+ initial_balance: 12_000,
+ term_months: 12,
+ entries: [
+ { type: "opening_anchor", date: Date.new(2026, 1, 1), balance: 12_000 },
+ { type: "transaction", date: Date.new(2026, 2, 1), amount: -946.19 }
+ ]
+ )
+ enable_preview_features_for_family!(account.family)
+ checking = create_checking_account(account)
+ checking.entries.create!(
+ name: "Payment",
+ date: Date.new(2026, 2, 1),
+ amount: 946.19,
+ currency: checking.currency,
+ entryable: Transaction.new
+ )
+
+ Balance::Materializer.new(account, strategy: :forward).materialize_balances
+ assert_equal BigDecimal("11173.81"), account.balances.find_by(date: Date.new(2026, 2, 1)).balance,
+ "the unlinked replay takes the interest out of principal"
+
+ account.loan.update_column(:principal_only_transfers, true)
+ Sync.where(syncable: account).delete_all
+ account.family.auto_match_transfers!
+
+ sync = Sync.where(syncable: account).order(:created_at).last
+ assert_equal Date.new(2026, 2, 1), sync.window_start_date
+
+ Balance::Materializer.new(account, strategy: :forward, window_start_date: sync.window_start_date).materialize_balances
+ assert_equal BigDecimal("11053.81"), account.balances.find_by(date: Date.new(2026, 2, 1)).balance,
+ "the follow-up sync replays the new transfer as principal only"
+ end
+
+ test "auto-matching a loan payment without the opt-in does not re-sync the loan" do
+ create_transaction(date: Date.current, account: @depository, amount: 500)
+ create_transaction(date: Date.current, account: @loan, amount: -500)
+
+ assert_no_difference -> { Sync.where(syncable: @loan).count } do
+ @family.auto_match_transfers!
+ end
+ end
+
test "loan disbursement (loan to cash) assigns funds_movement kind to outflow" do
# Loan → Cash: outflow from loan, inflow to depository
outflow_entry = create_transaction(date: Date.current, account: @loan, amount: 500)
diff --git a/test/models/loan/day_count_convention_test.rb b/test/models/loan/day_count_convention_test.rb
index ea2255270c..5a65c88dcb 100644
--- a/test/models/loan/day_count_convention_test.rb
+++ b/test/models/loan/day_count_convention_test.rb
@@ -43,6 +43,31 @@ class Loan::DayCountConventionTest < ActiveSupport::TestCase
end
end
+ test "30/360 charges a partial period by its own days" do
+ factor = Loan::AmortizationMath.accrual_factor(
+ annual_percentage: RATE,
+ period_start: Date.new(2026, 2, 15),
+ period_end: Date.new(2026, 3, 1),
+ day_count_convention: :thirty_360,
+ full_period: false
+ )
+
+ assert_equal (BigDecimal(RATE.to_s) / 100) * (BigDecimal("16") / 360), factor,
+ "15 February to 1 March is 16 thirty-360 days"
+ end
+
+ test "30/360 keeps a scheduled period at a flat twelfth" do
+ factor = Loan::AmortizationMath.accrual_factor(
+ annual_percentage: RATE,
+ period_start: Date.new(2026, 2, 15),
+ period_end: Date.new(2026, 3, 1),
+ day_count_convention: :thirty_360,
+ full_period: true
+ )
+
+ assert_equal BigDecimal(RATE.to_s) / 100 / 12, factor
+ end
+
test "an unspecified convention is the default one" do
from = Date.new(2026, 2, 1)
diff --git a/test/models/loan/principal_payments_test.rb b/test/models/loan/principal_payments_test.rb
new file mode 100644
index 0000000000..6b6864b784
--- /dev/null
+++ b/test/models/loan/principal_payments_test.rb
@@ -0,0 +1,557 @@
+require "test_helper"
+
+class Loan::PrincipalPaymentsTest < ActiveSupport::TestCase
+ include LedgerTestingHelper
+
+ OPENING_DATE = Date.new(2026, 1, 1)
+ PAYMENT_DATE = Date.new(2026, 2, 1)
+
+ test "an unlinked payment pays interest before principal" do
+ account = create_loan_account(entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -2_000 }
+ ])
+
+ change = principal_payments(account).change_for(PAYMENT_DATE)
+
+ assert_equal BigDecimal("1800"), change.principal_paid
+ assert_equal BigDecimal("200"), change.interest_paid
+ assert_equal BigDecimal("0"), change.principal_added
+ assert_equal BigDecimal("-1800"), change.net
+ end
+
+ test "a payment below accrued interest does not reduce principal" do
+ account = create_loan_account(entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -100 }
+ ])
+
+ change = principal_payments(account).change_for(PAYMENT_DATE)
+
+ assert_equal BigDecimal("0"), change.principal_paid
+ assert_equal BigDecimal("100"), change.interest_paid
+ assert_equal BigDecimal("0"), change.net
+ end
+
+ test "a payment above interest reduces principal by the excess" do
+ account = create_loan_account(entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -5_000 }
+ ])
+
+ change = principal_payments(account).change_for(PAYMENT_DATE)
+
+ assert_equal BigDecimal("4800"), change.principal_paid
+ assert_equal BigDecimal("200"), change.interest_paid
+ end
+
+ test "later payments accrue interest on the reduced principal" do
+ account = create_loan_account(entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -10_000 },
+ { type: "transaction", date: Date.new(2026, 3, 2), amount: -2_000 }
+ ])
+
+ payments = principal_payments(account)
+
+ assert_equal BigDecimal("9800"), payments.change_for(PAYMENT_DATE).principal_paid
+ assert_equal BigDecimal("1898"), payments.change_for(Date.new(2026, 3, 2)).principal_paid
+ assert_equal BigDecimal("102"), payments.change_for(Date.new(2026, 3, 2)).interest_paid
+ end
+
+ test "unpaid interest carries into the next payment" do
+ account = create_loan_account(entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -100 },
+ { type: "transaction", date: Date.new(2026, 3, 2), amount: -2_000 }
+ ])
+
+ payments = principal_payments(account)
+
+ assert_equal BigDecimal("0"), payments.change_for(PAYMENT_DATE).principal_paid
+ assert_equal BigDecimal("100"), payments.change_for(PAYMENT_DATE).interest_paid
+ assert_equal BigDecimal("1700"), payments.change_for(Date.new(2026, 3, 2)).principal_paid
+ assert_equal BigDecimal("300"), payments.change_for(Date.new(2026, 3, 2)).interest_paid
+ end
+
+ test "uses the loan's day-count convention" do
+ account = create_loan_account(day_count_convention: "actual_365", entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -2_000 }
+ ])
+
+ change = principal_payments(account).change_for(PAYMENT_DATE)
+
+ assert_equal BigDecimal("203.84"), change.interest_paid
+ assert_equal BigDecimal("1796.16"), change.principal_paid
+ end
+
+ test "a positive line adds principal instead of paying interest" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: 100 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -1_066.19 }
+ ])
+
+ change = principal_payments(account).change_for(PAYMENT_DATE)
+
+ assert_equal BigDecimal("100"), change.principal_added, "a positive row is a charge or a refund, never interest"
+ assert_equal BigDecimal("120"), change.interest_paid
+ assert_equal BigDecimal("946.19"), change.principal_paid
+ end
+
+ test "a refund raises the balance and does not become interest" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -1_066.19 },
+ { type: "transaction", date: Date.new(2026, 2, 15), amount: 500 },
+ { type: "transaction", date: Date.new(2026, 3, 1), amount: -1_066.19 }
+ ])
+
+ payments = principal_payments(account)
+ refund = payments.change_for(Date.new(2026, 2, 15))
+ next_payment = payments.change_for(Date.new(2026, 3, 1))
+
+ assert_equal BigDecimal("500"), refund.principal_added
+ assert_equal BigDecimal("0"), refund.interest_paid
+ assert_equal BigDecimal("110.54"), next_payment.interest_paid,
+ "the next period charges interest on the period's opening principal, not the refund"
+ assert_equal BigDecimal("955.65"), next_payment.principal_paid
+ end
+
+ test "a late principal-only transfer pays the period it missed" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000,
+ principal_only_transfers: true, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ])
+ instalment = account.loan.amortization_schedule.payments.first
+
+ create_linked_loan_payment(account, instalment.principal.amount, instalment.date + 4.days)
+ account.reload
+
+ change = principal_payments(account).change_for(instalment.date + 4.days)
+
+ assert_equal BigDecimal("946.19"), change.principal_paid
+ assert_equal BigDecimal("120"), change.interest_paid
+ end
+
+ test "an early full payment pays the coming period's interest" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ])
+ instalment = account.loan.amortization_schedule.payments.first
+
+ account.entries.create!(name: "Payment", date: instalment.date - 10.days,
+ amount: -instalment.payment.amount,
+ currency: account.currency, entryable: Transaction.new)
+ account.reload
+
+ change = principal_payments(account).change_for(instalment.date - 10.days)
+
+ assert_equal BigDecimal("946.19"), change.principal_paid
+ assert_equal BigDecimal("120"), change.interest_paid
+ end
+
+ test "a payment above the remaining principal leaves a credit" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -20_000 }
+ ])
+
+ change = principal_payments(account).change_for(PAYMENT_DATE)
+
+ assert_equal BigDecimal("19_880"), change.principal_paid
+ assert_equal BigDecimal("120"), change.interest_paid
+ assert_equal BigDecimal("-19_880"), change.net
+ assert_equal BigDecimal("-7_880"), BigDecimal("12_000") + change.net
+ end
+
+ test "a linked transfer is a payment, not interest" do
+ account = create_loan_account(entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 }
+ ])
+
+ create_linked_loan_payment(account, 2_000, PAYMENT_DATE)
+ account.reload
+
+ change = principal_payments(account).change_for(PAYMENT_DATE)
+
+ assert_equal BigDecimal("1800"), change.principal_paid, "a transfer that is not the scheduled principal is split"
+ assert_equal BigDecimal("200"), change.interest_paid
+ end
+
+ test "a linked transfer equal to the scheduled principal is a full payment without the opt-in" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ])
+ instalment = account.loan.amortization_schedule.payments.first
+
+ create_linked_loan_payment(account, instalment.principal.amount, instalment.date)
+ account.reload
+
+ change = principal_payments(account).change_for(instalment.date)
+
+ assert_equal BigDecimal("826.19"), change.principal_paid,
+ "without the opt-in the transfer pays the period's interest first"
+ assert_equal BigDecimal("120"), change.interest_paid
+ end
+
+ test "a linked transfer is principal-only when the loan opts in" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000,
+ principal_only_transfers: true, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ])
+ instalment = account.loan.amortization_schedule.payments.first
+
+ create_linked_loan_payment(account, instalment.principal.amount - BigDecimal("0.01"), instalment.date)
+ account.reload
+
+ change = principal_payments(account).change_for(instalment.date)
+
+ assert_equal BigDecimal("946.18"), change.principal_paid,
+ "a cent away from the scheduled principal is still principal-only"
+ assert_equal BigDecimal("120"), change.interest_paid, "the interest was paid as a separate expense"
+ end
+
+ test "a linked full EMI is split into interest and principal" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ])
+ instalment = account.loan.amortization_schedule.payments.first
+
+ create_linked_loan_payment(account, instalment.payment.amount, instalment.date)
+ account.reload
+
+ change = principal_payments(account).change_for(instalment.date)
+
+ assert_equal BigDecimal("946.19"), change.principal_paid
+ assert_equal BigDecimal("120"), change.interest_paid
+ end
+
+ test "paying the scheduled EMI matches the schedule row for row" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ])
+ schedule = account.loan.amortization_schedule
+ instalments = schedule.payments.first(3)
+
+ instalments.each do |instalment|
+ account.entries.create!(name: "Payment", date: instalment.date,
+ amount: -instalment.payment.amount,
+ currency: account.currency, entryable: Transaction.new)
+ end
+ account.reload
+
+ payments = principal_payments(account)
+ principal_paid = payments.changes.values.sum(BigDecimal("0"), &:principal_paid)
+ interest_paid = payments.changes.values.sum(BigDecimal("0"), &:interest_paid)
+
+ assert_equal instalments.sum(BigDecimal("0")) { |payment| payment.principal.amount }, principal_paid
+ assert_equal instalments.sum(BigDecimal("0")) { |payment| payment.interest.amount }, interest_paid
+ assert_equal instalments.last.ending_balance.amount, BigDecimal("12_000") - principal_paid
+ end
+
+ test "an unlinked redraw raises principal for later interest" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -1_066.19 },
+ { type: "transaction", date: Date.new(2026, 2, 15), amount: 5_000 },
+ { type: "transaction", date: Date.new(2026, 3, 1), amount: -2_000 }
+ ])
+
+ payments = principal_payments(account)
+
+ assert_equal BigDecimal("5000"), payments.change_for(Date.new(2026, 2, 15)).principal_added
+ assert_equal BigDecimal("0"), payments.change_for(Date.new(2026, 2, 15)).interest_paid
+ assert_equal BigDecimal("110.54"), payments.change_for(Date.new(2026, 3, 1)).interest_paid
+ assert_equal BigDecimal("1889.46"), payments.change_for(Date.new(2026, 3, 1)).principal_paid
+ end
+
+ test "a linked drawdown increases principal for later interest" do
+ account = create_loan_account(
+ subtype: "line_of_credit",
+ entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -200 }
+ ]
+ )
+
+ create_linked_loan_drawdown(account, 5_000, PAYMENT_DATE)
+ account.entries.create!(name: "Payment", date: Date.new(2026, 3, 2), amount: -2_000,
+ currency: account.currency, entryable: Transaction.new)
+ account.reload
+
+ payments = principal_payments(account)
+
+ assert_equal BigDecimal("5000"), payments.change_for(PAYMENT_DATE).principal_added
+ assert_equal BigDecimal("0"), payments.change_for(PAYMENT_DATE).principal_paid
+ assert_equal BigDecimal("1750"), payments.change_for(Date.new(2026, 3, 2)).principal_paid
+ assert_equal BigDecimal("250"), payments.change_for(Date.new(2026, 3, 2)).interest_paid
+ end
+
+ test "a reconciliation resets principal and clears carried interest" do
+ account = create_loan_account(entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -100 },
+ { type: "reconciliation", date: Date.new(2026, 2, 15), balance: 19_000 },
+ { type: "transaction", date: Date.new(2026, 3, 2), amount: -2_000 }
+ ])
+
+ payments = principal_payments(account)
+
+ assert_equal BigDecimal("0"), payments.change_for(Date.new(2026, 2, 15)).net
+ assert_equal BigDecimal("1898.67"), payments.change_for(Date.new(2026, 3, 2)).principal_paid,
+ "interest on the reconciliation balance for the 16-day 30/360 stub"
+ assert_equal BigDecimal("101.33"), payments.change_for(Date.new(2026, 3, 2)).interest_paid
+ end
+
+ test "a payment on a reconciliation day is counted and the reset applies to later interest" do
+ account = create_loan_account(entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 },
+ { type: "reconciliation", date: PAYMENT_DATE, balance: 18_000 },
+ { type: "transaction", date: PAYMENT_DATE, amount: -2_000 },
+ { type: "transaction", date: Date.new(2026, 3, 1), amount: -2_000 }
+ ])
+
+ payments = principal_payments(account)
+ reset_day = payments.change_for(PAYMENT_DATE)
+ next_day = payments.change_for(Date.new(2026, 3, 1))
+
+ assert_equal BigDecimal("1800"), reset_day.principal_paid
+ assert_equal BigDecimal("200"), reset_day.interest_paid
+ assert_equal BigDecimal("1820"), next_day.principal_paid, "interest accrues on the reconciliation balance"
+ assert_equal BigDecimal("180"), next_day.interest_paid
+ end
+
+ test "an insurance premium never reduces principal" do
+ account = create_loan_account(
+ term_months: 12,
+ initial_balance: 12_000,
+ insurance_rate: 1.2,
+ insurance_rate_type: "level_term",
+ entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ]
+ )
+ instalment = account.loan.amortization_schedule.payments.first
+ premium = account.loan.insurance.premium_for(instalment.number).amount.amount
+
+ account.entries.create!(name: "Payment", date: instalment.date,
+ amount: -(instalment.payment.amount + premium),
+ currency: account.currency, entryable: Transaction.new)
+ account.reload
+
+ change = principal_payments(account).change_for(instalment.date)
+
+ assert_equal BigDecimal("946.19"), change.principal_paid
+ assert_equal BigDecimal("120"), change.interest_paid
+ end
+
+ test "an underpaid insurance premium does not reduce principal" do
+ account = create_loan_account(
+ term_months: 12,
+ initial_balance: 12_000,
+ insurance_rate: 1.2,
+ insurance_rate_type: "level_term",
+ entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ]
+ )
+ instalment = account.loan.amortization_schedule.payments.first
+ premium = account.loan.insurance.premium_for(instalment.number).amount.amount
+
+ account.entries.create!(name: "Payment", date: instalment.date,
+ amount: -(instalment.payment.amount + premium - BigDecimal("6.19")),
+ currency: account.currency, entryable: Transaction.new)
+ account.reload
+
+ change = principal_payments(account).change_for(instalment.date)
+
+ assert_equal BigDecimal("940"), change.principal_paid,
+ "the unpaid part of the premium comes out of principal, not the whole premium"
+ assert_equal BigDecimal("120"), change.interest_paid
+ end
+
+ test "two half payments cover the insurance premium once" do
+ account = create_loan_account(
+ term_months: 12,
+ initial_balance: 12_000,
+ insurance_rate: 1.2,
+ insurance_rate_type: "level_term",
+ entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ]
+ )
+ instalment = account.loan.amortization_schedule.payments.first
+ premium = account.loan.insurance.premium_for(instalment.number).amount.amount
+ total = instalment.payment.amount + premium
+ first_half = (total / 2).round(2)
+ second_half = total - first_half
+
+ account.entries.create!(name: "Payment 1", date: instalment.date,
+ amount: -first_half, currency: account.currency, entryable: Transaction.new)
+ account.entries.create!(name: "Payment 2", date: instalment.date,
+ amount: -second_half, currency: account.currency, entryable: Transaction.new)
+ account.reload
+
+ change = principal_payments(account).change_for(instalment.date)
+
+ assert_equal BigDecimal("946.19"), change.principal_paid
+ assert_equal BigDecimal("120"), change.interest_paid
+ end
+
+ test "a deferred period charge is not lost after a late payment" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 },
+ { type: "transaction", date: Date.new(2026, 3, 15), amount: -1_066.19 },
+ { type: "transaction", date: Date.new(2026, 4, 1), amount: -1_066.19 }
+ ])
+
+ payments = principal_payments(account)
+
+ assert_equal BigDecimal("240"), payments.change_for(Date.new(2026, 3, 15)).interest_paid,
+ "two missed instalments carry 240 of interest"
+ assert_equal BigDecimal("826.19"), payments.change_for(Date.new(2026, 3, 15)).principal_paid
+ assert_equal BigDecimal("120"), payments.change_for(Date.new(2026, 4, 1)).interest_paid,
+ "the deferred period is still charged on the next due date"
+ assert_equal BigDecimal("946.19"), payments.change_for(Date.new(2026, 4, 1)).principal_paid
+ end
+
+ test "a payment two days late still matches the schedule for the whole term" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ])
+ schedule = account.loan.amortization_schedule
+
+ schedule.payments.each do |instalment|
+ account.entries.create!(name: "Payment", date: instalment.date + 2.days,
+ amount: -instalment.payment.amount,
+ currency: account.currency, entryable: Transaction.new)
+ end
+ account.reload
+
+ payments = principal_payments(account)
+ total_principal = payments.changes.values.sum(BigDecimal("0"), &:principal_paid)
+ total_interest = payments.changes.values.sum(BigDecimal("0"), &:interest_paid)
+
+ assert_equal schedule.payments.sum(BigDecimal("0")) { |instalment| instalment.interest.amount }, total_interest
+ assert_equal BigDecimal("12_000"), total_principal
+ end
+
+ test "an instalment paid in two parts inside the grace window charges the period once" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 },
+ { type: "transaction", date: Date.new(2026, 2, 1), amount: -600 },
+ { type: "transaction", date: Date.new(2026, 2, 2), amount: -466.19 },
+ { type: "transaction", date: Date.new(2026, 3, 1), amount: -1_066.19 }
+ ])
+
+ payments = principal_payments(account)
+
+ assert_equal BigDecimal("120"), payments.change_for(Date.new(2026, 2, 1)).interest_paid
+ assert_equal BigDecimal("480"), payments.change_for(Date.new(2026, 2, 1)).principal_paid
+ assert_equal BigDecimal("0"), payments.change_for(Date.new(2026, 2, 2)).interest_paid,
+ "the second part must not pay the next period in advance"
+ assert_equal BigDecimal("466.19"), payments.change_for(Date.new(2026, 2, 2)).principal_paid
+ assert_equal BigDecimal("110.54"), payments.change_for(Date.new(2026, 3, 1)).interest_paid
+ assert_equal BigDecimal("955.65"), payments.change_for(Date.new(2026, 3, 1)).principal_paid
+ end
+
+ test "a rate change takes effect from the period that opens on the new rate" do
+ account = create_loan_account(
+ term_months: 12,
+ initial_balance: 12_000,
+ rate_type: "variable",
+ variable_rate_schedule: { "2026-02-15" => "24.0" },
+ entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 },
+ { type: "transaction", date: Date.new(2026, 4, 1), amount: -2_000 }
+ ]
+ )
+
+ change = principal_payments(account).change_for(Date.new(2026, 4, 1))
+
+ assert_equal BigDecimal("480"), change.interest_paid,
+ "Jan and Feb charge 12%, then the period opening 1 March charges 24%"
+ assert_equal BigDecimal("1520"), change.principal_paid
+ end
+
+ test "a loan whose opening anchor differs from its initial balance is left alone" do
+ account = create_loan_account(
+ term_months: 12,
+ initial_balance: 12_000,
+ entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 19_999 }
+ ]
+ )
+
+ assert_nil principal_payments(account)
+ end
+
+ test "paying the schedule for the full term ends at zero" do
+ account = create_loan_account(term_months: 12, initial_balance: 12_000, entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 12_000 }
+ ])
+ schedule = account.loan.amortization_schedule
+
+ schedule.payments.each do |instalment|
+ account.entries.create!(name: "Payment", date: instalment.date,
+ amount: -instalment.payment.amount,
+ currency: account.currency, entryable: Transaction.new)
+ end
+ account.reload
+
+ payments = principal_payments(account)
+ total_principal = payments.changes.values.sum(BigDecimal("0"), &:principal_paid)
+ total_interest = payments.changes.values.sum(BigDecimal("0"), &:interest_paid)
+
+ assert_equal BigDecimal("12_000"), total_principal
+ assert_equal schedule.payments.sum(BigDecimal("0")) { |instalment| instalment.interest.amount }, total_interest
+ assert_equal BigDecimal("0"), BigDecimal("12_000") - total_principal
+ end
+
+ test "a provider loan is left alone" do
+ account = create_loan_account(entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 }
+ ])
+
+ Account.any_instance.stubs(:manual?).returns(false)
+
+ assert_nil Loan::PrincipalPayments.for(account.loan, entries: Balance::SyncCache.new(account).entries)
+ end
+
+ test "a loan whose anchor is not its origination is left alone" do
+ account = create_loan_account(
+ start_date: OPENING_DATE - 1.year,
+ entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 }
+ ]
+ )
+
+ assert_nil Loan::PrincipalPayments.for(account.loan, entries: Balance::SyncCache.new(account).entries)
+ end
+
+ test "a loan without an opening anchor is left alone" do
+ account = create_loan_account(entries: [
+ { type: "current_anchor", date: Date.current, balance: 20_000 }
+ ])
+
+ assert_nil principal_payments(account)
+ end
+
+ test "a loan without terms is left alone" do
+ account = create_account_with_ledger(
+ account: { type: Loan, currency: "USD" },
+ entries: [
+ { type: "opening_anchor", date: OPENING_DATE, balance: 20_000 }
+ ]
+ )
+
+ assert_nil Loan::PrincipalPayments.for(account.loan, entries: Balance::SyncCache.new(account).entries)
+ end
+
+ private
+ def principal_payments(account)
+ Loan::PrincipalPayments.for(account.loan, entries: Balance::SyncCache.new(account).entries)
+ end
+end
diff --git a/test/models/loan_test.rb b/test/models/loan_test.rb
index 60cb636753..79873fb6e4 100644
--- a/test/models/loan_test.rb
+++ b/test/models/loan_test.rb
@@ -347,6 +347,47 @@ class LoanTest < ActiveSupport::TestCase
loan.variable_rate_update_for(Loan::MAX_INTEREST_RATE, as_of: as_of)[:variable_rate_schedule])
end
+ test "a balance input change during a running sync requests a full follow-up" do
+ account = build_loan_account(balance: 80_000, down_payment: 20_000)
+ sync = Sync.create!(syncable: account, status: :syncing)
+
+ assert_no_difference -> { Sync.where(syncable: account).count } do
+ account.loan.update!(principal_only_transfers: true)
+ end
+
+ assert sync.reload.full_resync_requested?
+ end
+
+ test "a balance input change with no running sync starts a sync" do
+ account = build_loan_account(balance: 80_000, down_payment: 20_000)
+
+ assert_difference -> { Sync.where(syncable: account).count }, 1 do
+ account.loan.update!(principal_only_transfers: true)
+ end
+ end
+
+ test "a balance input change ignores a syncing sync outside the visible window" do
+ account = build_loan_account(balance: 80_000, down_payment: 20_000)
+ sync = Sync.create!(syncable: account, status: :syncing, created_at: Sync::VISIBLE_FOR.ago - 1.minute)
+
+ assert_difference -> { Sync.where(syncable: account).count }, 1 do
+ account.loan.update!(principal_only_transfers: true)
+ end
+
+ assert_not sync.reload.full_resync_requested?
+ end
+
+ test "a balance input change ignores a cancel-requested sync" do
+ account = build_loan_account(balance: 80_000, down_payment: 20_000)
+ sync = Sync.create!(syncable: account, status: :syncing, cancel_requested_at: Time.current)
+
+ assert_difference -> { Sync.where(syncable: account).count }, 1 do
+ account.loan.update!(principal_only_transfers: true)
+ end
+
+ assert_not sync.reload.full_resync_requested?
+ end
+
private
# A loan imported part way through its life: the principal it was written
# for is recorded, and the only valuation the account carries is the
diff --git a/test/models/sync_test.rb b/test/models/sync_test.rb
index 9b9b892d2a..c3078fbc9a 100644
--- a/test/models/sync_test.rb
+++ b/test/models/sync_test.rb
@@ -482,4 +482,99 @@ class SyncTest < ActiveSupport::TestCase
assert_equal new_start, sync.window_start_date
assert_equal new_end, sync.window_end_date
end
+
+ test "a completed sync queues a full follow-up when requested" do
+ account = accounts(:loan)
+ sync = Sync.create!(syncable: account, full_resync_requested: true)
+
+ account.expects(:perform_sync).with(sync).once
+ # The sync reloads its syncable, so these run on a different instance.
+ Account.any_instance.expects(:perform_post_sync).once
+ Account.any_instance.expects(:broadcast_sync_complete).once
+
+ assert_difference -> { Sync.where(syncable: account).count }, 1 do
+ sync.perform
+ end
+
+ assert sync.reload.completed?
+ assert_not sync.full_resync_requested?
+
+ follow_up = Sync.where(syncable: account).order(:created_at).last
+ assert_nil follow_up.window_start_date
+ assert_nil follow_up.window_end_date
+ assert_equal "pending", follow_up.status
+ assert_enqueued_with(job: SyncJob)
+ end
+
+ test "a post-sync failure still queues the full follow-up" do
+ account = accounts(:loan)
+ sync = Sync.create!(syncable: account, full_resync_requested: true)
+
+ account.expects(:perform_sync).with(sync).once
+ Account.any_instance.expects(:perform_post_sync).raises(StandardError.new("post-sync failed"))
+ Account.any_instance.expects(:broadcast_sync_complete).never
+
+ assert_difference -> { Sync.where(syncable: account).count }, 1 do
+ sync.perform
+ end
+
+ assert sync.reload.completed?
+ assert_not sync.full_resync_requested?
+ assert_enqueued_with(job: SyncJob)
+ end
+
+ test "a follow-up marks a running partial sync instead of reusing it" do
+ account = accounts(:loan)
+ sync = Sync.create!(syncable: account, full_resync_requested: true)
+ running = Sync.create!(syncable: account, status: :syncing)
+
+ account.expects(:perform_sync).with(sync).once
+ Account.any_instance.expects(:perform_post_sync).once
+ Account.any_instance.expects(:broadcast_sync_complete).once
+
+ assert_no_difference -> { Sync.where(syncable: account).count } do
+ sync.perform
+ end
+
+ assert sync.reload.completed?
+ assert_not sync.full_resync_requested?
+ assert running.reload.full_resync_requested?
+ assert_equal "syncing", running.status
+ end
+
+ test "a stale sync still queues the full follow-up" do
+ account = accounts(:loan)
+ sync = Sync.create!(syncable: account, status: :syncing, full_resync_requested: true)
+
+ assert_difference -> { Sync.where(syncable: account).count }, 1 do
+ sync.mark_stale!
+ end
+
+ assert sync.reload.stale?
+ assert_not sync.full_resync_requested?
+ assert_enqueued_with(job: SyncJob)
+ end
+
+ test "a cancelled sync still queues the full follow-up" do
+ account = accounts(:loan)
+ sync = Sync.create!(syncable: account, status: :syncing, full_resync_requested: true)
+ sync.update!(cancel_requested_at: Time.current)
+
+ assert_difference -> { Sync.where(syncable: account).count }, 1 do
+ sync.finalize_if_all_children_finalized
+ end
+
+ assert sync.reload.stale?
+ assert_not sync.full_resync_requested?
+ assert_enqueued_with(job: SyncJob)
+ end
+
+ test "a stale sync without a request queues nothing" do
+ account = accounts(:loan)
+ sync = Sync.create!(syncable: account, status: :syncing)
+
+ assert_no_difference -> { Sync.where(syncable: account).count } do
+ sync.mark_stale!
+ end
+ end
end
diff --git a/test/support/ledger_testing_helper.rb b/test/support/ledger_testing_helper.rb
index 8194979a08..2c27cbe527 100644
--- a/test/support/ledger_testing_helper.rb
+++ b/test/support/ledger_testing_helper.rb
@@ -135,6 +135,63 @@ module LedgerTestingHelper
created_account
end
+ # A manual loan whose opening anchor is its origination: the shape the
+ # principal replay is allowed to run for.
+ def create_loan_account(entries:, **loan_attrs)
+ currency = loan_attrs.delete(:currency) || "USD"
+ account = create_account_with_ledger(
+ account: { type: Loan, currency: currency },
+ entries: entries
+ )
+ account.loan.update!(
+ {
+ subtype: "mortgage",
+ interest_rate: 12,
+ term_months: 360,
+ rate_type: "fixed",
+ start_date: Date.new(2026, 1, 1),
+ initial_balance: 20_000
+ }.merge(loan_attrs)
+ )
+ account.reload
+ end
+
+ def create_checking_account(account)
+ @checking_accounts ||= {}
+ @checking_accounts[account.family_id] ||= account.family.accounts.create!(
+ name: "Checking",
+ balance: 10_000,
+ currency: account.currency,
+ accountable: Depository.new
+ )
+ end
+
+ def create_linked_loan_payment(account, amount, date)
+ Transfer::Creator.new(
+ family: account.family,
+ source_account_id: create_checking_account(account).id,
+ destination_account_id: account.id,
+ date: date,
+ amount: amount
+ ).create
+ end
+
+ def create_linked_loan_drawdown(account, amount, date)
+ Transfer::Creator.new(
+ family: account.family,
+ source_account_id: account.id,
+ destination_account_id: create_checking_account(account).id,
+ date: date,
+ amount: amount
+ ).create
+ end
+
+ def enable_preview_features_for_family!(family)
+ family.users.each do |user|
+ user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => true))
+ end
+ end
+
def assert_calculated_ledger_balances(calculated_data:, expected_data:)
# Convert expected data to a hash for easier lookup
# Structure: [ { date:, legacy_balances: { balance:, cash_balance: }, balances: { start:, start_cash:, etc... }, flows: { ... }, adjustments: { ... } } ]
diff --git a/test/system/accounts_test.rb b/test/system/accounts_test.rb
index d07fe854a5..4c93682e70 100644
--- a/test/system/accounts_test.rb
+++ b/test/system/accounts_test.rb
@@ -195,11 +195,7 @@ class AccountsTest < ApplicationSystemTestCase
click_button "Create Account"
- within_testid("account-sidebar-tabs") do
- click_on "All"
- find("details", text: Accountable.from_type(accountable_type).display_name).click
- assert_text account_name
- end
+ assert_account_in_sidebar(accountable_type, account_name)
visit accounts_url
assert_text account_name
@@ -231,6 +227,29 @@ class AccountsTest < ApplicationSystemTestCase
assert_equal updated_notes, created_account[:notes]
end
+ # The account page issues a Turbo morph refresh shortly after it loads.
+ # Reading the sidebar while that refresh is in flight can detach the node
+ # ("Node with given id does not belong to the document"), which Capybara
+ # does not retry. Retry until the account appears in the sidebar.
+ def assert_account_in_sidebar(accountable_type, account_name)
+ 3.times do
+ begin
+ within_testid("account-sidebar-tabs") do
+ click_on "All"
+ details = find("details", text: Accountable.from_type(accountable_type).display_name)
+ details.click unless details[:open]
+ assert_text account_name
+ end
+ return
+ rescue Selenium::WebDriver::Error::WebDriverError => e
+ raise unless e.message.match?(
+ /does not belong to the document|stale element reference/i,
+ )
+ end
+ end
+ assert_text account_name
+ end
+
# Fill + submit the account edit dialog, retrying when a Turbo morph
# detaches nodes mid-interaction (Chrome: "Node with given id does not
# belong to the document"). Mirrors open_account_edit_dialog.