From 9fb4aab887122f10264952c4382c2ae0db2088e8 Mon Sep 17 00:00:00 2001 From: Yugonito Date: Tue, 27 Oct 2026 18:00:07 +0100 Subject: [PATCH] feat(domain): loan amortization schedule Co-Authored-By: Claude Opus 5.5 --- src/domain/loan.ts | 133 ++++++++++++++++++++++++++++++++++++++ tests/domain/loan.test.ts | 95 +++++++++++++++++++++++++++ 2 files changed, 228 insertions(+) create mode 100644 src/domain/loan.ts create mode 100644 tests/domain/loan.test.ts diff --git a/src/domain/loan.ts b/src/domain/loan.ts new file mode 100644 index 0000000..29b0318 --- /dev/null +++ b/src/domain/loan.ts @@ -0,0 +1,133 @@ +import { addMonths, dateInMonth, monthOf } from "@/lib/dates"; +import type { Cents } from "./types"; + +export interface LoanInput { + principal: Cents; + annualRatePct: number; + durationMonths: number; + startDate: string; + insuranceMonthly: Cents; + paymentOverride: Cents | null; + referenceDate: string | null; + referenceRemainingCapital: Cents | null; +} + +export interface ScheduleRow { + n: number; + date: string; + payment: Cents; + interest: Cents; + principal: Cents; + insurance: Cents; + remaining: Cents; + /** Échéance antérieure au capital de référence saisi (affichée « avant suivi »). */ + beforeTracking: boolean; +} + +export interface LoanSummary { + payment: Cents; + insurance: Cents; + endDate: string; + remaining: Cents; + interestPaid: Cents; + interestLeft: Cents; +} + +const MAX_ROWS = 1200; + +/** Mensualité constante hors assurance (amortissement à la française). */ +export function monthlyPayment(principal: Cents, annualRatePct: number, months: number): Cents { + if (months <= 0) return principal; + const r = annualRatePct / 100 / 12; + if (r === 0) return Math.round(principal / months); + return Math.round((principal * r) / (1 - Math.pow(1 + r, -months))); +} + +function rowDate(startDate: string, n: number): string { + return dateInMonth(addMonths(monthOf(startDate), n - 1), Number(startDate.slice(8, 10))); +} + +/** + * Lignes d'amortissement à partir de `remaining`. Si `lastN` est fourni, la ligne `lastN` + * solde le capital ; sinon on continue jusqu'à remboursement complet. + */ +function amortize( + l: LoanInput, + firstN: number, + remaining: Cents, + payment: Cents, + lastN: number | null, +): ScheduleRow[] { + const rows: ScheduleRow[] = []; + const rate = l.annualRatePct / 100 / 12; + for (let n = firstN; remaining > 0 && rows.length < MAX_ROWS; n++) { + const interest = Math.round(remaining * rate); + let principal = payment - interest; + if (principal <= 0) throw new Error("Mensualité insuffisante pour couvrir les intérêts"); + if (principal >= remaining || n === lastN) principal = remaining; + remaining -= principal; + rows.push({ + n, + date: rowDate(l.startDate, n), + payment: principal + interest, + interest, + principal, + insurance: l.insuranceMonthly, + remaining, + beforeTracking: false, + }); + } + return rows; +} + +export function buildSchedule(l: LoanInput): ScheduleRow[] { + const standardPayment = l.paymentOverride ?? monthlyPayment(l.principal, l.annualRatePct, l.durationMonths); + if (l.referenceDate === null || l.referenceRemainingCapital === null) { + return amortize(l, 1, l.principal, standardPayment, l.paymentOverride === null ? l.durationMonths : null); + } + + // Crédit en cours : l'historique théorique sert seulement à l'affichage, + // le suivi repart du capital constaté à la date de référence. + const original = amortize( + l, + 1, + l.principal, + monthlyPayment(l.principal, l.annualRatePct, l.durationMonths), + l.durationMonths, + ); + const before = original + .filter((r) => r.date <= l.referenceDate!) + .map((r) => ({ ...r, beforeTracking: true })); + const payment = + l.paymentOverride ?? + monthlyPayment(l.referenceRemainingCapital, l.annualRatePct, l.durationMonths - before.length); + const after = amortize( + l, + before.length + 1, + l.referenceRemainingCapital, + payment, + l.paymentOverride === null ? l.durationMonths : null, + ); + return [...before, ...after]; +} + +/** Capital restant dû après la dernière échéance passée à `date`. */ +export function remainingAt(rows: ScheduleRow[], date: string): Cents { + let remaining: Cents | null = null; + for (const r of rows) if (r.date <= date) remaining = r.remaining; + if (remaining !== null) return remaining; + const first = rows[0]; + return first ? first.remaining + first.principal : 0; +} + +export function loanSummary(rows: ScheduleRow[], today: string): LoanSummary { + const tracked = rows.filter((r) => !r.beforeTracking); + return { + payment: tracked[0]?.payment ?? 0, + insurance: rows[0]?.insurance ?? 0, + endDate: rows[rows.length - 1]?.date ?? "", + remaining: remainingAt(rows, today), + interestPaid: rows.filter((r) => r.date <= today).reduce((t, r) => t + r.interest, 0), + interestLeft: rows.filter((r) => r.date > today).reduce((t, r) => t + r.interest, 0), + }; +} diff --git a/tests/domain/loan.test.ts b/tests/domain/loan.test.ts new file mode 100644 index 0000000..cdc34ba --- /dev/null +++ b/tests/domain/loan.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "vitest"; +import { buildSchedule, loanSummary, monthlyPayment, remainingAt, type LoanInput } from "@/domain/loan"; + +const base: LoanInput = { + principal: 2000000, + annualRatePct: 4, + durationMonths: 48, + startDate: "2026-01-05", + insuranceMonthly: 1500, + paymentOverride: null, + referenceDate: null, + referenceRemainingCapital: null, +}; + +describe("monthlyPayment", () => { + it("uses the French constant-payment formula", () => { + expect(monthlyPayment(2000000, 4, 48)).toBe(45158); + }); + + it("divides evenly at zero rate", () => { + expect(monthlyPayment(1200000, 0, 12)).toBe(100000); + }); +}); + +describe("buildSchedule", () => { + const rows = buildSchedule(base); + + it("produces one row per month with interest and principal", () => { + expect(rows).toHaveLength(48); + expect(rows[0]).toMatchObject({ + n: 1, + date: "2026-01-05", + payment: 45158, + interest: 6667, + principal: 38491, + insurance: 1500, + remaining: 1961509, + beforeTracking: false, + }); + }); + + it("lets the last payment absorb the rounding residue", () => { + const last = rows[rows.length - 1]; + expect(last.remaining).toBe(0); + expect(last.principal).toBe(rows[rows.length - 2].remaining); + expect(last.date).toBe("2029-12-05"); + expect(rows.reduce((t, r) => t + r.principal, 0)).toBe(2000000); + }); + + it("clamps day 31 to the end of shorter months", () => { + const r = buildSchedule({ ...base, startDate: "2026-01-31" }); + expect(r[1].date).toBe("2026-02-28"); + expect(r[2].date).toBe("2026-03-31"); + }); + + it("restarts from the bank's remaining capital and real payment in reference mode", () => { + const r = buildSchedule({ + ...base, + referenceDate: "2026-06-10", + referenceRemainingCapital: 1800000, + paymentOverride: 46000, + }); + const before = r.filter((x) => x.beforeTracking); + expect(before.map((x) => x.date)).toEqual([ + "2026-01-05", "2026-02-05", "2026-03-05", "2026-04-05", "2026-05-05", "2026-06-05", + ]); + const first = r.find((x) => !x.beforeTracking)!; + expect(first).toMatchObject({ date: "2026-07-05", payment: 46000, interest: 6000, principal: 40000, remaining: 1760000 }); + const last = r[r.length - 1]; + expect(last.remaining).toBe(0); + expect(last.payment).toBeLessThanOrEqual(46000); + }); + + it("refuses a payment that does not cover the interest", () => { + expect(() => buildSchedule({ ...base, referenceDate: "2026-06-10", referenceRemainingCapital: 1800000, paymentOverride: 5000 })).toThrow( + "Mensualité insuffisante pour couvrir les intérêts", + ); + }); +}); + +describe("remainingAt / loanSummary", () => { + const rows = buildSchedule(base); + + it("returns the capital after the last payment on or before the date", () => { + expect(remainingAt(rows, "2026-01-04")).toBe(2000000); + expect(remainingAt(rows, "2026-01-05")).toBe(1961509); + }); + + it("summarises the loan at a date", () => { + const s = loanSummary(rows, "2026-01-05"); + expect(s).toMatchObject({ payment: 45158, insurance: 1500, endDate: "2029-12-05", remaining: 1961509, interestPaid: 6667 }); + const totalInterest = rows.reduce((t, r) => t + r.interest, 0); + expect(s.interestPaid + s.interestLeft).toBe(totalInterest); + }); +});