Repository Public
1// Calculateur hypothécaire : versement, bilan du terme, intérêts totaux,2// comparaison de deux scénarios et tableau d'amortissement repliable.3// Le calcul se fait dans le navigateur (mortgage.ts) ; le taux proposé par4// défaut est le meilleur taux observé pour le type et le terme choisis.56import { useEffect, useId, useMemo, useState, type ReactNode } from "react";7import { ChevronDown } from "lucide-react";8import { fmtRate, termLabel, TERMS, type MortgageMarket } from "@/lib/api.marche";9import { cn } from "@/lib/cn";10import { fmtInt, fmtMoney } from "@/lib/format";11import { Collapse, Ticker } from "@/lib/motion";12import { Segmented } from "@/ui/primitives";13import { Lines, SERIES_COLORS } from "./charts";14import { Nature } from "./layout";15import { compute, FREQUENCIES, MAX_INSURABLE_PRICE, STRESS_BUFFER, STRESS_FLOOR, type Frequency, type Result, type Scenario } from "./mortgage";1617const money2 = (n: number) => `${n.toLocaleString("fr-CA", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} $`;18const money0 = (n: number) => fmtMoney(Math.round(n));19const pct1 = (n: number) => `${n.toLocaleString("fr-CA", { maximumFractionDigits: 2 })} %`;2021function Field({ label, children, hint }: { label: string; children: ReactNode; hint?: ReactNode }) {22 return (23 <label className="block min-w-0">24 <span className="mb-1.5 flex items-baseline justify-between gap-3 text-[0.84rem] text-ink-3">25 <span>{label}</span>26 {hint && <span className="num text-ink-2">{hint}</span>}27 </span>28 {children}29 </label>30 );31}3233function NumberInput({ value, onChange, min, max, step, suffix, label }: { value: number; onChange: (n: number) => void; min: number; max: number; step: number; suffix: string; label: string }) {34 const [draft, setDraft] = useState<string | null>(null);35 return (36 <span className="relative block">37 <input38 type="text"39 inputMode="decimal"40 aria-label={label}41 value={draft ?? value.toLocaleString("fr-CA", { maximumFractionDigits: 2 })}42 onFocus={(e) => {43 setDraft(String(value).replace(".", ","));44 requestAnimationFrame(() => e.target.select());45 }}46 onChange={(e) => {47 setDraft(e.target.value);48 const n = Number.parseFloat(e.target.value.replace(/[\s ]/g, "").replace(",", "."));49 if (Number.isFinite(n)) onChange(Math.min(max, Math.max(min, n)));50 }}51 onBlur={() => setDraft(null)}52 className="field num h-11 w-full pr-9"53 />54 <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-[0.86rem] text-ink-3">{suffix}</span>55 <span className="sr-only">56 de {min} à {max}, par pas de {step}57 </span>58 </span>59 );60}6162function Range({ value, onChange, min, max, step, label }: { value: number; onChange: (n: number) => void; min: number; max: number; step: number; label: string }) {63 return (64 <input65 type="range"66 aria-label={label}67 min={min}68 max={max}69 step={step}70 value={Math.min(max, Math.max(min, value))}71 onChange={(e) => onChange(Number(e.target.value))}72 className="mt-1 h-8 w-full cursor-pointer accent-[var(--brand)]"73 />74 );75}7677const selectClass = "field h-11 w-full";7879function ScenarioForm({ s, set, compact, bestFor }: { s: Scenario; set: (patch: Partial<Scenario>) => void; compact?: boolean; bestFor: (fixed: boolean, term: number) => MortgageMarket | undefined }) {80 const best = bestFor(s.fixed, s.termMonths);81 return (82 <div className="grid grid-cols-2 gap-x-5 gap-y-4">83 {!compact && (84 <div className="col-span-2">85 <Field label="Prix de la propriété">86 <NumberInput label="Prix de la propriété" value={s.price} onChange={(price) => set({ price })} min={20_000} max={10_000_000} step={5000} suffix="$" />87 </Field>88 <Range label="Prix de la propriété, curseur" value={s.price} onChange={(price) => set({ price })} min={100_000} max={2_000_000} step={5000} />89 </div>90 )}91 <div className="col-span-2">92 <Field label="Mise de fonds" hint={money0((s.price * s.downPct) / 100)}>93 <NumberInput label="Mise de fonds en pourcentage" value={s.downPct} onChange={(downPct) => set({ downPct })} min={0} max={95} step={0.5} suffix="%" />94 </Field>95 <Range label="Mise de fonds, curseur" value={s.downPct} onChange={(downPct) => set({ downPct })} min={5} max={60} step={0.5} />96 </div>97 <Field label="Type de taux">98 <select className={selectClass} value={s.fixed ? "fixed" : "variable"} onChange={(e) => set({ fixed: e.target.value === "fixed", termMonths: e.target.value === "fixed" ? s.termMonths : 60 })}>99 <option value="fixed">Fixe</option>100 <option value="variable">Variable</option>101 </select>102 </Field>103 <Field label="Terme">104 <select className={selectClass} value={s.termMonths} onChange={(e) => set({ termMonths: Number(e.target.value) })}>105 {TERMS.map((t) => (106 <option key={t.months} value={t.months}>107 {t.label}108 </option>109 ))}110 </select>111 </Field>112 <div className="col-span-2">113 <Field label="Taux d'intérêt annuel">114 <NumberInput label="Taux d'intérêt annuel" value={s.rate} onChange={(rate) => set({ rate })} min={0.5} max={15} step={0.05} suffix="%" />115 </Field>116 <Range label="Taux d'intérêt, curseur" value={s.rate} onChange={(rate) => set({ rate })} min={2} max={9} step={0.05} />117 {best ? (118 <p className="text-[0.8rem] leading-relaxed text-ink-3">119 Meilleur taux observé, {s.fixed ? "fixe" : "variable"} {termLabel(s.termMonths)} : <span className="num text-ink-2">{fmtRate(best.best)}</span> ({best.best_institution}).{" "}120 {Math.abs(best.best - s.rate) > 0.001 && (121 <button type="button" onClick={() => set({ rate: best.best })} className="font-medium text-brand underline-offset-[3px] hover:underline">122 Utiliser ce taux123 </button>124 )}125 </p>126 ) : (127 <p className="text-[0.8rem] text-ink-3">Aucun taux observé pour ce produit : entrez le vôtre.</p>128 )}129 </div>130 <div className="col-span-2">131 <span className="mb-1.5 block text-[0.84rem] text-ink-3">Amortissement</span>132 <Segmented133 label="Amortissement"134 value={String(s.amortYears)}135 onChange={(v) => set({ amortYears: Number(v) })}136 options={[15, 20, 25, 30].map((y) => ({ value: String(y), label: `${y} ans` }))}137 />138 </div>139 {!compact && (140 <div className="col-span-2">141 <Field label="Fréquence des versements">142 <select className={selectClass} value={s.frequency} onChange={(e) => set({ frequency: e.target.value as Frequency })}>143 {FREQUENCIES.map((f) => (144 <option key={f.value} value={f.value}>145 {f.label}146 </option>147 ))}148 </select>149 </Field>150 </div>151 )}152 </div>153 );154}155156function Notes({ s, r }: { s: Scenario; r: Result }) {157 const notes: ReactNode[] = [];158 if (!r.valid) notes.push("Entrez un prix, une mise de fonds inférieure au prix et un taux pour lancer le calcul.");159 if (r.valid && r.down < r.minDown - 0.01)160 notes.push(161 <>162 Mise de fonds minimale estimée pour ce prix : <span className="num font-medium">{money0(r.minDown)}</span> ({pct1((r.minDown / s.price) * 100)}).163 </>,164 );165 if (r.insurance.required && r.insurance.eligible)166 notes.push(167 <>168 Avec moins de 20 % de mise de fonds, le prêt doit être assuré. Prime estimée : <span className="num font-medium">{money0(r.insurance.premium)}</span> ({pct1(r.insurance.premiumRate * 100)} du prêt), ajoutée au prêt. Taxe du Québec sur la169 prime, payable à la signature : environ <span className="num font-medium">{money0(r.insurance.tax)}</span>.170 </>,171 );172 r.insurance.issues.forEach((i) => notes.push(i));173 if (!r.insurance.required && s.price >= MAX_INSURABLE_PRICE && s.downPct < 20) notes.push("À 1 500 000 $ et plus, la mise de fonds doit atteindre 20 %.");174 if (!notes.length) return null;175 return (176 <ul className="mt-5 space-y-2 border-l-2 border-high/50 pl-4 text-[0.86rem] leading-relaxed text-ink-2">177 {notes.map((n, i) => (178 <li key={i}>{n}</li>179 ))}180 </ul>181 );182}183184export function Calculator({ products }: { products: MortgageMarket[] }) {185 const id = useId();186 const bestFor = (fixed: boolean, term: number) => products.find((p) => p.rate_type === (fixed ? "fixed" : "variable") && p.term_months === term);187 const [a, setA] = useState<Scenario>({ price: 500_000, downPct: 20, rate: 5, fixed: true, termMonths: 60, amortYears: 25, frequency: "monthly" });188 const [b, setB] = useState<Scenario | null>(null);189 const [table, setTable] = useState(false);190 const [touched, setTouched] = useState(false);191192 // taux par défaut : le meilleur taux observé, tant que la personne n'a rien saisi193 const best5 = products.find((p) => p.rate_type === "fixed" && p.term_months === 60)?.best;194 useEffect(() => {195 if (best5 != null && !touched) setA((s) => ({ ...s, rate: best5 }));196 }, [best5, touched]);197198 const patchA = (patch: Partial<Scenario>) => {199 if (patch.rate != null) setTouched(true);200 setA((s) => {201 const next = { ...s, ...patch };202 // changer de produit propose le meilleur taux de ce produit203 if ((patch.fixed != null || patch.termMonths != null) && patch.rate == null) {204 const p = bestFor(next.fixed, next.termMonths);205 if (p) next.rate = p.best;206 }207 return next;208 });209 };210 const patchB = (patch: Partial<Scenario>) =>211 setB((s) => {212 if (!s) return s;213 const next = { ...s, ...patch };214 if ((patch.fixed != null || patch.termMonths != null) && patch.rate == null) {215 const p = bestFor(next.fixed, next.termMonths);216 if (p) next.rate = p.best;217 }218 return next;219 });220221 const ra = useMemo(() => compute(a), [a]);222 const sb = useMemo(() => (b ? { ...b, price: a.price, frequency: a.frequency } : null), [b, a.price, a.frequency]);223 const rb = useMemo(() => (sb ? compute(sb) : null), [sb]);224 const freqLabel = FREQUENCIES.find((f) => f.value === a.frequency)!.label.toLowerCase();225226 const rows: { label: string; hint?: string; get: (r: Result, s: Scenario) => string; num?: (r: Result) => number; lowerIsBetter?: boolean }[] = [227 { label: "Versement", hint: freqLabel, get: (r) => money2(r.payment), num: (r) => r.payment, lowerIsBetter: true },228 { label: "Montant emprunté", hint: "prime d'assurance comprise", get: (r) => money0(r.principal) },229 { label: "Taux", get: (_r, s) => `${fmtRate(s.rate)} ${s.fixed ? "fixe" : "variable"}, ${termLabel(s.termMonths)}` },230 { label: "Intérêts pendant le terme", get: (r) => money0(r.termInterest), num: (r) => r.termInterest, lowerIsBetter: true },231 { label: "Capital remboursé pendant le terme", get: (r) => money0(r.termPrincipal), num: (r) => r.termPrincipal },232 { label: "Solde à la fin du terme", get: (r) => money0(r.termBalance), num: (r) => r.termBalance, lowerIsBetter: true },233 { label: "Intérêts sur toute la durée", hint: "si le taux ne changeait jamais", get: (r) => money0(r.totalInterest), num: (r) => r.totalInterest, lowerIsBetter: true },234 { label: "Coût total du prêt", hint: "capital et intérêts", get: (r) => money0(r.totalPaid), num: (r) => r.totalPaid, lowerIsBetter: true },235 { label: "Prêt remboursé en", get: (r, s) => `${(Math.abs(r.payoffYears - s.amortYears) < 0.2 ? s.amortYears : r.payoffYears).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} ans` },236 { label: "Versement au taux du test de résistance", get: (r) => `${money2(r.qualifyingPayment)} à ${fmtRate(r.qualifyingRate)}`.replace(/ /g, "\u00a0") },237 ];238239 const balance = (r: Result) => [{ x: 0, y: r.principal }, ...r.years.map((y) => ({ x: y.year, y: y.balance }))];240 const cell = "border-b border-line py-2.5 align-baseline";241242 return (243 <div className="grid grid-cols-1 gap-x-12 gap-y-10 lg:grid-cols-[minmax(0,22rem)_minmax(0,1fr)]">244 <div className="min-w-0">245 <ScenarioForm s={a} set={patchA} bestFor={bestFor} />246 <div className="mt-6 border-t border-line">247 <button248 type="button"249 aria-expanded={!!b}250 aria-controls={`${id}-b`}251 onClick={() => setB((s) => (s ? null : { ...a, amortYears: a.amortYears === 30 ? 25 : 30 }))}252 className="flex min-h-12 w-full items-center justify-between gap-4 py-3 text-left text-[0.95rem] font-medium"253 >254 {b ? "Retirer le second scénario" : "Comparer avec un second scénario"}255 <ChevronDown className={cn("size-4 shrink-0 text-ink-3 transition-transform duration-200", b && "rotate-180")} />256 </button>257 <Collapse open={!!b}>258 <div id={`${id}-b`} className="pb-2 pt-1">259 <p className="mb-4 text-[0.84rem] leading-relaxed text-ink-3">Même propriété, mêmes versements ({freqLabel}) : changez la mise de fonds, le taux, le terme ou l'amortissement.</p>260 {b && <ScenarioForm compact s={{ ...b, price: a.price }} set={patchB} bestFor={bestFor} />}261 </div>262 </Collapse>263 </div>264 </div>265266 <div className="min-w-0">267 <div className="flex flex-wrap items-end justify-between gap-x-8 gap-y-3 border-t border-line pt-6">268 <div>269 <p className="text-[0.84rem] text-ink-3">Versement estimé, {freqLabel}</p>270 <p className="num mt-1 text-[2rem] font-semibold leading-none sm:text-[2.3rem]">271 <Ticker value={Math.round(ra.payment)} format={(n) => fmtMoney(n)} />272 </p>273 {a.frequency !== "monthly" && <p className="num mt-1.5 text-[0.82rem] text-ink-3">soit {money0(ra.monthlyEquivalent)} par mois pour un versement mensuel</p>}274 </div>275 <Nature kind="estime" />276 </div>277 <Notes s={a} r={ra} />278279 <table className="num mt-6 w-full border-collapse text-[0.9rem]">280 {rb && (281 <thead>282 <tr>283 <th className="border-b border-line-2 pb-2" />284 <th className="border-b border-line-2 pb-2 text-right text-[0.76rem] font-medium text-ink-3">285 <span className="mr-1.5 inline-block h-0.5 w-3 rounded align-middle" style={{ background: SERIES_COLORS[0] }} />286 Scénario 1287 </th>288 <th className="border-b border-line-2 pb-2 text-right text-[0.76rem] font-medium text-ink-3">289 <span className="mr-1.5 inline-block h-0.5 w-3 rounded align-middle" style={{ background: SERIES_COLORS[1] }} />290 Scénario 2291 </th>292 </tr>293 </thead>294 )}295 <tbody>296 {rows.map((row) => {297 const va = row.num?.(ra);298 const vb = rb && row.num ? row.num(rb) : undefined;299 const diff = va != null && vb != null ? vb - va : null;300 return (301 <tr key={row.label}>302 <th scope="row" className={cn(cell, "pr-3 text-left font-sans font-normal text-ink-2")}>303 {row.label}304 {row.hint && <span className="block text-[0.76rem] text-ink-3">{row.hint}</span>}305 </th>306 <td className={cn(cell, "text-right font-medium text-ink")}>{row.get(ra, a)}</td>307 {rb && sb && (308 <td className={cn(cell, "pl-3 text-right font-medium text-ink")}>309 {row.get(rb, sb)}310 {diff != null && Math.abs(diff) >= 1 && (311 <span className="block text-[0.76rem] font-normal text-ink-3">312 {diff > 0 ? "+" : "−"}313 {fmtInt(Math.abs(Math.round(diff)))} $314 </span>315 )}316 </td>317 )}318 </tr>319 );320 })}321 </tbody>322 </table>323324 {ra.valid && ra.years.length > 1 && (325 <div className="mt-8">326 <h4 className="font-sans text-[0.95rem] font-medium tracking-normal">Solde du prêt, année après année</h4>327 <div className="mt-3">328 <Lines329 label="Solde du prêt par année"330 height={200}331 zero332 idle="Survolez ou touchez la courbe pour lire le solde d'une année."333 fmtY={(v) => fmtMoney(Math.round(v))}334 fmtX={(x) => (Math.round(x) === 0 ? "Départ" : `Année ${Math.round(x)}`)}335 series={[336 { key: "a", label: "Scénario 1", area: !rb, points: balance(ra) },337 ...(rb?.valid ? [{ key: "b", label: "Scénario 2", points: balance(rb) }] : []),338 ]}339 />340 </div>341 </div>342 )}343344 <div className="mt-6 border-y border-line">345 <button type="button" aria-expanded={table} onClick={() => setTable((v) => !v)} className="flex min-h-12 w-full items-center justify-between gap-4 py-3 text-left text-[0.95rem] font-medium">346 Tableau d'amortissement347 <ChevronDown className={cn("size-4 shrink-0 text-ink-3 transition-transform duration-200", table && "rotate-180")} />348 </button>349 <Collapse open={table}>350 <div className="pb-5">351 <table className="num w-full border-collapse text-[0.88rem]">352 <thead>353 <tr>354 {["Année", "Intérêts", "Capital", "Solde"].map((h, i) => (355 <th key={h} className={cn("border-b border-line-2 pb-2 text-[0.76rem] font-medium text-ink-3", i ? "text-right" : "text-left")}>356 {h}357 </th>358 ))}359 </tr>360 </thead>361 <tbody>362 {ra.years.map((y) => (363 <tr key={y.year} className={y.year * 12 === a.termMonths ? "bg-surface-2" : undefined}>364 <td className="border-b border-line py-2 text-ink-2">365 {y.year}366 {y.year * 12 === a.termMonths && <span className="ml-2 font-sans text-[0.74rem] text-ink-3">fin du terme</span>}367 </td>368 <td className="border-b border-line py-2 text-right text-ink-2">{fmtInt(Math.round(y.interest))} $</td>369 <td className="border-b border-line py-2 text-right text-ink-2">{fmtInt(Math.round(y.principal))} $</td>370 <td className="border-b border-line py-2 text-right font-medium text-ink">{fmtInt(Math.round(y.balance))} $</td>371 </tr>372 ))}373 </tbody>374 </table>375 <p className="mt-3 text-[0.8rem] leading-relaxed text-ink-3">Scénario 1, en supposant le même taux jusqu'au dernier versement. En réalité, le taux est renégocié à chaque fin de terme.</p>376 </div>377 </Collapse>378 </div>379380 <p className="mt-4 text-[0.8rem] leading-relaxed text-ink-3">381 Estimations indicatives. Taux fixe composé semestriellement, taux variable composé mensuellement. Test de résistance : le plus élevé du taux du contrat plus {STRESS_BUFFER} points et de{" "}382 {STRESS_FLOOR.toLocaleString("fr-CA")} %. Les règles et leurs sources sont détaillées plus bas. Ce calcul n'est ni une offre de financement ni une préautorisation.383 </p>384 </div>385 </div>386 );387}388