Loans: split payments into principal and interest

Merged
DA
24d ago
+1610-61

Problem

A loan payment currently reduces principal by its full amount. For an amortising loan most of an early payment services interest, so the tracked balance falls faster than the real one and net worth drifts optimistic. The workaround is to split every payment by hand against the lender's schedule.

Refs #1804.

What changed

  • One accrual engine. The day-count calculation now lives in Loan::AmortizationMath; Loan::Simulator delegates to it, so the schedule and the ledger replay charge a period the same way. A full scheduled 30/360 period stays bit-identical; a period cut short by a valuation now charges its own 30/360 days.
  • New Loan::PrincipalPayments replay. One interest charge per scheduled period, on the principal the period opened with, using the loan's day-count convention and RateResolver. A payment reduces principal by only the part left after interest. Unpaid interest carries.
  • Classification. Every unlinked positive row adds principal, so a refund, redraw or reversal raises the balance. A linked transfer is a full payment by default. A loan can opt in to principal-only transfers; then a linked transfer never takes interest out of principal, because the borrower records the interest separately.
  • Late payments. A payment up to five days after its due date still reduces the principal the new period charges interest on, so a weekend slip matches the schedule.
  • Premium. Allocation is interest, then premium, then principal. The premium is tracked per instalment, so an underpayment cannot turn unpaid premium into principal.
  • Overpayments. A payment above the remaining principal leaves a credit instead of being dropped.
  • Eligibility. Only manual loans whose opening anchor is their real origination and whose recorded principal matches are replayed. Provider-owned loans are untouched.
  • Preview gate. Balance::BaseCalculator checks Family#preview_features_enabled?; syncs run without Current.user. A change to the family preview flag now enqueues a sync for the family's manual loans. The flag is the family rollup, so it also changes when a member joins or leaves, not only when the current user toggles preview.
  • Input changes. Saving the principal-only toggle, a schedule input, initial_balance or the insurance terms queues an account sync, so the stored rows do not wait for the next scheduled run.
  • Read path. Balance::SyncCache memoises the replay. The report_missing_rates option is not in this PR; #4471 adds it with the read path that uses it.

Migration

  • loans.principal_only_transfers (boolean, default false), with a matching toggle on the loan form. No data backfill is needed.
  • syncs.full_resync_requested (boolean, default false). A loan edit marks a running sync so it queues a full follow-up. Sync#queue_full_resync runs after each sync and adds one primary-key lookup for the flag, even though only loan edits set it.

Expected behaviour

  • Paying the scheduled EMI matches the schedule row for row and ends at zero, including when paid a few days late.
  • A loan with principal_only_transfers on treats linked transfers as principal only. The borrower records interest separately.
  • A loan without the opt-in treats a linked transfer as a full payment and splits interest first.
  • An unlinked positive row raises the balance instead of paying interest.
  • A payment above interest reduces principal by the excess; a payment below interest does not reduce principal.
  • A payment above the remaining principal leaves a credit.
  • Existing balances are recalculated on the next sync. Some loans will show a higher outstanding balance; that is the expected correction, not a regression.
  • With preview off, balances behave exactly as before.

Review follow-ups

  • jjmata: a deferred period keeps nil period interest; the premium waterfall is interest, premium, principal; report_missing_rates moved to #4471.
  • jaysbeekay: late-payment grace window; unlinked positives add principal; principal-only is a per-loan choice; 30/360 stubs; the reverse hook is removed; overpayments are not capped; full-term and regression tests added.
  • jaysbeekay (second pass): auto-matched principal-only loans re-sync from the transfer date; a full-resync request survives a stale or cancelled sync; a split payment inside the grace window charges the period once.

Follow-up: interest expense

#1804 is a feature request, not a PR. The replayed interest is not an expense line in this PR. A follow-up PR stacked on this one will split each linked payment into a principal transfer and an interest expense, with a per-loan interest category. The principal leg will stop counting as an expense; only the interest leg will.

Relationship to #4453

The only shared file is Balance::SyncCache, on different lines. The AmortizationMath change is additive and behaviour-preserving; #4453's Loan::AmortizationSchedule use is unaffected.

Validation

  • Full Rails suite: 13,719 runs, 62,887 assertions, 0 failures, 0 errors, 37 skips
  • RuboCop: changed files clean
  • ERB lint: 806 files, no errors
  • Brakeman: 0 warnings, 0 errors
  • System tests: not run; no views, components, JavaScript or user-flow changes

Summary by CodeRabbit

  • New Features
    • Preview-enabled manual amortized loans with a matching opening balance now reflect principal and interest separately in balance projections.
    • Loan settings include an option for linked transfers that record principal only, with guidance available in English and French.
  • Improvements
    • Changing the preview-feature setting synchronizes eligible manual loans.
    • Changes to loan terms and balance-related details refresh loan balances, including when a sync is already in progress.
    • Loan interest calculations now account for the selected day-count convention and period length.