feat: loans with amortization schedule and net charges
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0b9c6a11d3
commit
9cb7fe8c81
8 files changed
+682
No files matched your search
@@ -0,0 +1,47 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { FormPage } from "@/components/FormPage";
|
||||
import { LoanForm } from "@/components/credits/LoanForm";
|
||||
import { centsFromDecimal, decimalFromCents } from "@/domain/money";
|
||||
import { todayParis, toIsoDate } from "@/lib/dates";
|
||||
import { requireUser } from "@/server/auth";
|
||||
import { prisma } from "@/server/db";
|
||||
import { splitOf } from "@/server/mappers";
|
||||
import { getDefaultSplit, getUsers } from "@/server/repo";
|
||||
|
||||
const euro = (d: { toString(): string } | null) => (d === null ? "" : decimalFromCents(centsFromDecimal(d)).replace(".", ","));
|
||||
|
||||
export default async function EditLoanPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { id } = await params;
|
||||
const [loan, users, defaultSplit] = await Promise.all([
|
||||
prisma.loan.findUnique({ where: { id }, include: { splits: true } }),
|
||||
getUsers(),
|
||||
getDefaultSplit(),
|
||||
]);
|
||||
if (!loan) notFound();
|
||||
return (
|
||||
<FormPage title={`Modifier « ${loan.name} »`} back={`/credits/${loan.id}`}>
|
||||
<LoanForm
|
||||
users={users}
|
||||
defaultSplit={defaultSplit}
|
||||
currentUserId={user.id}
|
||||
today={todayParis()}
|
||||
initial={{
|
||||
id: loan.id,
|
||||
name: loan.name,
|
||||
lender: loan.lender ?? "",
|
||||
principal: euro(loan.principal),
|
||||
annualRate: loan.annualRate.toString().replace(".", ","),
|
||||
durationMonths: loan.durationMonths,
|
||||
startDate: toIsoDate(loan.startDate),
|
||||
insuranceMonthly: euro(loan.insuranceMonthly),
|
||||
accountUserId: loan.accountUserId,
|
||||
split: splitOf(loan.splits),
|
||||
paymentOverride: euro(loan.paymentOverride),
|
||||
referenceDate: loan.referenceDate ? toIsoDate(loan.referenceDate) : "",
|
||||
referenceRemainingCapital: euro(loan.referenceRemainingCapital),
|
||||
}}
|
||||
/>
|
||||
</FormPage>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Card, CardLabel } from "@/components/ui/Card";
|
||||
import { buildSchedule, loanSummary } from "@/domain/loan";
|
||||
import { formatEuro } from "@/domain/money";
|
||||
import { formatDateFr, fromIsoDate, monthOf, todayParis } from "@/lib/dates";
|
||||
import { requireUser } from "@/server/auth";
|
||||
import { prisma } from "@/server/db";
|
||||
import { toOp } from "@/server/mappers";
|
||||
import { toLoanInput } from "@/server/services/loans";
|
||||
|
||||
export default async function LoanDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
await requireUser();
|
||||
const { id } = await params;
|
||||
const loan = await prisma.loan.findUnique({ where: { id }, include: { recurring: true } });
|
||||
if (!loan) notFound();
|
||||
const today = todayParis();
|
||||
const rows = buildSchedule(toLoanInput(loan));
|
||||
const s = loanSummary(rows, today);
|
||||
const currentIndex = rows.findIndex((r) => r.date >= today);
|
||||
const month = monthOf(today);
|
||||
const allocated = loan.recurring
|
||||
? (
|
||||
await prisma.operation.findMany({
|
||||
where: {
|
||||
allocatedToRecurringId: loan.recurring.id,
|
||||
status: { not: "SKIPPED" },
|
||||
date: { gte: fromIsoDate(`${month}-01`) },
|
||||
},
|
||||
include: { splits: true },
|
||||
orderBy: { date: "asc" },
|
||||
})
|
||||
)
|
||||
.map(toOp)
|
||||
.filter((o) => monthOf(o.date) === month)
|
||||
: [];
|
||||
const reimbursed = allocated.reduce((t, o) => t + o.amount, 0);
|
||||
const tiles: [string, string][] = [
|
||||
["Mensualité", formatEuro(s.payment)],
|
||||
["Assurance", formatEuro(s.insurance)],
|
||||
["Capital restant dû", formatEuro(s.remaining)],
|
||||
["Intérêts payés", formatEuro(s.interestPaid)],
|
||||
["Intérêts restants", formatEuro(s.interestLeft)],
|
||||
["Fin", formatDateFr(s.endDate)],
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link href="/credits" className="grid h-[30px] w-[30px] place-items-center rounded-lg border border-line bg-white text-muted" aria-label="Retour">
|
||||
‹
|
||||
</Link>
|
||||
<h1 className="text-xl font-bold md:text-[22px]">🏦 {loan.name}</h1>
|
||||
</div>
|
||||
<Link href={`/credits/${loan.id}/modifier`} className="rounded-[10px] border border-line bg-white px-4 py-2.5 font-semibold">
|
||||
Modifier
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-6">
|
||||
{tiles.map(([k, v]) => (
|
||||
<Card key={k} className="p-4">
|
||||
<div className="text-xs text-muted">{k}</div>
|
||||
<b className="tabular mt-1 block text-base">{v}</b>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardLabel className="mb-1.5">Remboursements affectés ce mois-ci</CardLabel>
|
||||
{allocated.length === 0 ? (
|
||||
<p className="py-2 text-muted">Aucun. Saisissez une entrée (ex. IK) et affectez-la à « {loan.name} ».</p>
|
||||
) : (
|
||||
<>
|
||||
{allocated.map((o) => (
|
||||
<div key={o.id} className="flex justify-between border-b border-line-soft py-2">
|
||||
<span>
|
||||
{o.label} <span className="text-muted">· {formatDateFr(o.date)}</span>
|
||||
</span>
|
||||
<b className="tabular text-pos">{formatEuro(o.amount, { sign: true })}</b>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex justify-between pt-2.5">
|
||||
<b>Coût net ce mois-ci</b>
|
||||
<b className="tabular">{formatEuro(s.payment + s.insurance - reimbursed)}</b>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card className="overflow-x-auto p-0">
|
||||
<CardLabel className="px-[18px] pt-[18px]">Échéancier</CardLabel>
|
||||
<table className="tabular mt-2 w-full min-w-[560px] text-right text-[13px]">
|
||||
<thead className="text-xs text-muted">
|
||||
<tr className="border-b border-line">
|
||||
<th className="px-3 py-2 text-left font-semibold">#</th>
|
||||
<th className="px-3 py-2 text-left font-semibold">Date</th>
|
||||
<th className="px-3 py-2 font-semibold">Échéance</th>
|
||||
<th className="px-3 py-2 font-semibold">Intérêts</th>
|
||||
<th className="px-3 py-2 font-semibold">Capital</th>
|
||||
<th className="px-3 py-2 font-semibold">Assurance</th>
|
||||
<th className="px-3 py-2 font-semibold">Restant dû</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r, i) => (
|
||||
<tr
|
||||
key={r.n}
|
||||
className={`border-b border-line-soft last:border-0 ${r.beforeTracking ? "text-gray-400" : ""} ${
|
||||
i === currentIndex ? "bg-accent-soft font-semibold text-accent" : ""
|
||||
}`}
|
||||
>
|
||||
<td className="px-3 py-1.5 text-left">{r.n}</td>
|
||||
<td className="px-3 py-1.5 text-left">
|
||||
{formatDateFr(r.date)}
|
||||
{r.beforeTracking && <span className="ml-1 text-[11px]">avant suivi</span>}
|
||||
</td>
|
||||
<td className="px-3 py-1.5">{formatEuro(r.payment)}</td>
|
||||
<td className="px-3 py-1.5">{formatEuro(r.interest)}</td>
|
||||
<td className="px-3 py-1.5">{formatEuro(r.principal)}</td>
|
||||
<td className="px-3 py-1.5">{formatEuro(r.insurance)}</td>
|
||||
<td className="px-3 py-1.5">{formatEuro(r.remaining)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { FormPage } from "@/components/FormPage";
|
||||
import { LoanForm } from "@/components/credits/LoanForm";
|
||||
import { todayParis } from "@/lib/dates";
|
||||
import { requireUser } from "@/server/auth";
|
||||
import { getDefaultSplit, getUsers } from "@/server/repo";
|
||||
|
||||
export default async function NewLoanPage() {
|
||||
const user = await requireUser();
|
||||
const [users, defaultSplit] = await Promise.all([getUsers(), getDefaultSplit()]);
|
||||
return (
|
||||
<FormPage title="Nouveau crédit" back="/credits">
|
||||
<LoanForm users={users} defaultSplit={defaultSplit} currentUserId={user.id} today={todayParis()} />
|
||||
</FormPage>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import Link from "next/link";
|
||||
import { Card, CardLabel } from "@/components/ui/Card";
|
||||
import { Chip } from "@/components/ui/Chip";
|
||||
import { buildSchedule, loanSummary } from "@/domain/loan";
|
||||
import { formatEuro } from "@/domain/money";
|
||||
import { currentMonthParis, formatDateFr, todayParis } from "@/lib/dates";
|
||||
import { requireUser } from "@/server/auth";
|
||||
import { loadDashboard } from "@/server/dashboard";
|
||||
import { prisma } from "@/server/db";
|
||||
import { getUsers } from "@/server/repo";
|
||||
import { toLoanInput } from "@/server/services/loans";
|
||||
|
||||
export default async function CreditsPage() {
|
||||
const user = await requireUser();
|
||||
const today = todayParis();
|
||||
const [loans, users, dashboard] = await Promise.all([
|
||||
prisma.loan.findMany({ orderBy: { createdAt: "asc" } }),
|
||||
getUsers(),
|
||||
loadDashboard(currentMonthParis(), user.id, today),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-xl font-bold md:text-[22px]">Crédits & charges</h1>
|
||||
<Link href="/credits/nouveau" className="rounded-[10px] bg-accent px-4 py-2.5 font-semibold text-white hover:bg-indigo-700">
|
||||
+ Crédit
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{loans.length === 0 && (
|
||||
<Card>
|
||||
<p className="text-muted">Aucun crédit. Ajoutez le crédit voiture, un prêt immobilier…</p>
|
||||
</Card>
|
||||
)}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{loans.map((loan) => {
|
||||
const input = toLoanInput(loan);
|
||||
const rows = buildSchedule(input);
|
||||
const s = loanSummary(rows, today);
|
||||
const repaid = input.principal > 0 ? 1 - s.remaining / input.principal : 1;
|
||||
const holder = users.find((u) => u.id === loan.accountUserId);
|
||||
return (
|
||||
<Link key={loan.id} href={`/credits/${loan.id}`} className="block">
|
||||
<Card className="h-full transition hover:border-accent/40">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<b className="text-base">🏦 {loan.name}</b>
|
||||
<div className="text-[13px] text-muted">{loan.lender ?? "—"}</div>
|
||||
</div>
|
||||
{holder && <Chip color={holder.color}>{holder.firstName}</Chip>}
|
||||
</div>
|
||||
<div className="mt-4 grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<div className="text-xs text-muted">Mensualité</div>
|
||||
<b className="tabular">{formatEuro(s.payment + s.insurance)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted">Restant dû</div>
|
||||
<b className="tabular">{formatEuro(s.remaining)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted">Fin</div>
|
||||
<b>{formatDateFr(s.endDate)}</b>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 h-2 overflow-hidden rounded-full bg-line-soft">
|
||||
<div className="h-full rounded-full bg-accent" style={{ width: `${Math.max(0, Math.min(100, repaid * 100))}%` }} />
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-muted">{Math.round(repaid * 100)} % remboursé</div>
|
||||
</Card>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardLabel className="mb-1.5">Charges affectées ce mois-ci</CardLabel>
|
||||
{dashboard.netCharges.length === 0 ? (
|
||||
<p className="py-2 text-muted">
|
||||
Aucune entrée affectée ce mois-ci. Lors de la saisie d'une entrée (IK, part de loyer employeur…), utilisez « Affecter à une charge ».
|
||||
</p>
|
||||
) : (
|
||||
dashboard.netCharges.map((c) => (
|
||||
<div key={c.id} className="flex items-center justify-between border-b border-line-soft py-2.5 last:border-0">
|
||||
<div>
|
||||
<b>{c.label}</b>
|
||||
<div className="tabular text-[13px] text-muted">
|
||||
{formatEuro(c.gross)} − {formatEuro(c.reimbursed)} remboursés
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<b className="tabular">{formatEuro(c.net)}</b>
|
||||
<div className="text-xs text-muted">
|
||||
couvert à {c.gross > 0 ? Math.round((c.reimbursed / c.gross) * 100) : 0} %
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
import type { Split } from "@/domain/types";
|
||||
import { deleteLoanAction, saveLoanAction } from "@/server/actions/loans";
|
||||
import type { LoanFormInput } from "@/server/services/loans";
|
||||
import { SplitPicker } from "../SplitPicker";
|
||||
import { Button } from "../ui/Button";
|
||||
import { Field, FormError, Input } from "../ui/Field";
|
||||
import { Pills } from "../ui/Pills";
|
||||
|
||||
export function LoanForm({
|
||||
users,
|
||||
defaultSplit,
|
||||
currentUserId,
|
||||
today,
|
||||
initial,
|
||||
}: {
|
||||
users: { id: string; firstName: string }[];
|
||||
defaultSplit: Split;
|
||||
currentUserId: string;
|
||||
today: string;
|
||||
initial?: LoanFormInput & { id: string };
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [pending, start] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [f, setF] = useState<LoanFormInput>(
|
||||
initial ?? {
|
||||
name: "",
|
||||
lender: "",
|
||||
principal: "",
|
||||
annualRate: "",
|
||||
durationMonths: 60,
|
||||
startDate: today,
|
||||
insuranceMonthly: "",
|
||||
accountUserId: currentUserId,
|
||||
split: Object.fromEntries(users.map((u) => [u.id, u.id === currentUserId ? 10000 : 0])),
|
||||
paymentOverride: "",
|
||||
referenceDate: "",
|
||||
referenceRemainingCapital: "",
|
||||
},
|
||||
);
|
||||
const [running, setRunning] = useState(Boolean(initial?.referenceDate || initial?.paymentOverride));
|
||||
const set = <K extends keyof LoanFormInput>(k: K, v: LoanFormInput[K]) => setF((prev) => ({ ...prev, [k]: v }));
|
||||
|
||||
const submit = () =>
|
||||
start(async () => {
|
||||
const payload = running ? f : { ...f, paymentOverride: "", referenceDate: "", referenceRemainingCapital: "" };
|
||||
const r = await saveLoanAction(payload);
|
||||
if (!r.ok) return setError(r.error);
|
||||
router.push(`/credits/${r.id}`);
|
||||
});
|
||||
|
||||
const remove = () => {
|
||||
if (!initial || !confirm("Supprimer ce crédit ? Les mensualités déjà passées restent dans l'historique.")) return;
|
||||
start(async () => {
|
||||
await deleteLoanAction(initial.id);
|
||||
router.push("/credits");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label="Nom">
|
||||
<Input value={f.name} onChange={(e) => set("name", e.target.value)} placeholder="Crédit voiture" />
|
||||
</Field>
|
||||
<Field label="Organisme (facultatif)">
|
||||
<Input value={f.lender} onChange={(e) => set("lender", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Capital emprunté (€)">
|
||||
<Input inputMode="decimal" value={f.principal} onChange={(e) => set("principal", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Taux annuel (%)">
|
||||
<Input inputMode="decimal" value={f.annualRate} onChange={(e) => set("annualRate", e.target.value)} placeholder="3,45" />
|
||||
</Field>
|
||||
<Field label="Durée (mois)">
|
||||
<Input type="number" min={1} max={600} value={f.durationMonths} onChange={(e) => set("durationMonths", Number(e.target.value))} />
|
||||
</Field>
|
||||
<Field label="Première échéance">
|
||||
<Input type="date" value={f.startDate} onChange={(e) => set("startDate", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Assurance mensuelle (€)">
|
||||
<Input inputMode="decimal" value={f.insuranceMonthly} onChange={(e) => set("insuranceMonthly", e.target.value)} placeholder="0" />
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold text-muted">Titulaire (compte débité)</div>
|
||||
<Pills options={users.map((u) => ({ value: u.id, label: u.firstName }))} value={f.accountUserId} onChange={(v) => set("accountUserId", v)} />
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold text-muted">Répartition de la mensualité</div>
|
||||
<SplitPicker users={users} defaultSplit={defaultSplit} value={f.split} onChange={(s) => set("split", s)} />
|
||||
</div>
|
||||
|
||||
<div className="rounded-card border border-line p-4">
|
||||
<label className="flex items-center gap-2 font-medium">
|
||||
<input type="checkbox" checked={running} onChange={(e) => setRunning(e.target.checked)} className="h-4 w-4 accent-accent" />
|
||||
Crédit déjà en cours : utiliser les chiffres de la banque
|
||||
</label>
|
||||
{running && (
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-3">
|
||||
<Field label="Mensualité réelle hors assurance (€)">
|
||||
<Input inputMode="decimal" value={f.paymentOverride} onChange={(e) => set("paymentOverride", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Capital restant dû (€)">
|
||||
<Input inputMode="decimal" value={f.referenceRemainingCapital} onChange={(e) => set("referenceRemainingCapital", e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Au (date)">
|
||||
<Input type="date" value={f.referenceDate} onChange={(e) => set("referenceDate", e.target.value)} />
|
||||
</Field>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<FormError message={error} />
|
||||
<div className="flex gap-3">
|
||||
{initial && (
|
||||
<Button type="button" variant="danger" onClick={remove} disabled={pending}>
|
||||
Supprimer
|
||||
</Button>
|
||||
)}
|
||||
<Button type="submit" className="flex-1 py-3" disabled={pending}>
|
||||
{pending ? "Enregistrement…" : "Enregistrer"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { requireUser } from "@/server/auth";
|
||||
import * as loans from "@/server/services/loans";
|
||||
|
||||
export async function saveLoanAction(input: loans.LoanFormInput) {
|
||||
await requireUser();
|
||||
const result = await loans.saveLoan(input);
|
||||
if (result.ok) revalidatePath("/", "layout");
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function deleteLoanAction(id: string) {
|
||||
await requireUser();
|
||||
const result = await loans.deleteLoan(id);
|
||||
revalidatePath("/", "layout");
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import type { Loan, LoanSplit } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { buildSchedule, type LoanInput } from "@/domain/loan";
|
||||
import { centsFromDecimal, decimalFromCents, parseEuro, validateSplit } from "@/domain/money";
|
||||
import type { Split } from "@/domain/types";
|
||||
import { fromIsoDate, todayParis, toIsoDate } from "@/lib/dates";
|
||||
import { prisma } from "../db";
|
||||
import { splitRows } from "../mappers";
|
||||
import { syncRecurrings } from "../sync";
|
||||
import type { Result } from "./operations";
|
||||
|
||||
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date invalide.");
|
||||
|
||||
export interface LoanFormInput {
|
||||
id?: string;
|
||||
name: string;
|
||||
lender: string;
|
||||
principal: string;
|
||||
annualRate: string;
|
||||
durationMonths: number;
|
||||
startDate: string;
|
||||
insuranceMonthly: string;
|
||||
accountUserId: string;
|
||||
split: Split;
|
||||
paymentOverride: string;
|
||||
referenceDate: string;
|
||||
referenceRemainingCapital: string;
|
||||
}
|
||||
|
||||
export function toLoanInput(row: Loan): LoanInput {
|
||||
return {
|
||||
principal: centsFromDecimal(row.principal),
|
||||
annualRatePct: Number(row.annualRate.toString()),
|
||||
durationMonths: row.durationMonths,
|
||||
startDate: toIsoDate(row.startDate),
|
||||
insuranceMonthly: centsFromDecimal(row.insuranceMonthly),
|
||||
paymentOverride: row.paymentOverride ? centsFromDecimal(row.paymentOverride) : null,
|
||||
referenceDate: row.referenceDate ? toIsoDate(row.referenceDate) : null,
|
||||
referenceRemainingCapital: row.referenceRemainingCapital ? centsFromDecimal(row.referenceRemainingCapital) : null,
|
||||
};
|
||||
}
|
||||
|
||||
export type LoanWithSplits = Loan & { splits: LoanSplit[] };
|
||||
|
||||
/** Montant facultatif : vide → null ; invalide → undefined. */
|
||||
const optionalEuro = (s: string) => (s.trim() === "" ? null : (parseEuro(s) ?? undefined));
|
||||
|
||||
/** Création ou modification d'un crédit et de son récurrent de mensualité. */
|
||||
export async function saveLoan(input: LoanFormInput, today: string = todayParis()): Promise<Result<{ id: string }>> {
|
||||
if (!input.name.trim()) return { ok: false, error: "Le nom est obligatoire." };
|
||||
const principal = parseEuro(input.principal);
|
||||
if (principal === null) return { ok: false, error: "Capital invalide." };
|
||||
const rateText = input.annualRate.trim().replace(",", ".");
|
||||
const rate = /^\d+(\.\d{1,3})?$/.test(rateText) ? Number(rateText) : NaN;
|
||||
if (!(rate >= 0 && rate < 100)) return { ok: false, error: "Taux invalide." };
|
||||
if (!Number.isInteger(input.durationMonths) || input.durationMonths < 1 || input.durationMonths > 600) {
|
||||
return { ok: false, error: "Durée invalide (en mois)." };
|
||||
}
|
||||
if (!isoDate.safeParse(input.startDate).success) return { ok: false, error: "Date de première échéance invalide." };
|
||||
const insurance = input.insuranceMonthly.trim() === "" ? 0 : parseEuro(input.insuranceMonthly);
|
||||
if (insurance === null) return { ok: false, error: "Assurance invalide." };
|
||||
const paymentOverride = optionalEuro(input.paymentOverride);
|
||||
const refCapital = optionalEuro(input.referenceRemainingCapital);
|
||||
if (paymentOverride === undefined) return { ok: false, error: "Mensualité invalide." };
|
||||
if (refCapital === undefined) return { ok: false, error: "Capital restant dû invalide." };
|
||||
const refDate = input.referenceDate.trim() || null;
|
||||
if (refDate && !isoDate.safeParse(refDate).success) return { ok: false, error: "Date de référence invalide." };
|
||||
if ((refDate === null) !== (refCapital === null)) {
|
||||
return { ok: false, error: "Renseignez à la fois le capital restant dû et sa date." };
|
||||
}
|
||||
const splitError = validateSplit(input.split);
|
||||
if (splitError) return { ok: false, error: splitError };
|
||||
|
||||
const loanInput: LoanInput = {
|
||||
principal,
|
||||
annualRatePct: rate,
|
||||
durationMonths: input.durationMonths,
|
||||
startDate: input.startDate,
|
||||
insuranceMonthly: insurance,
|
||||
paymentOverride,
|
||||
referenceDate: refDate,
|
||||
referenceRemainingCapital: refCapital,
|
||||
};
|
||||
let schedule;
|
||||
try {
|
||||
schedule = buildSchedule(loanInput);
|
||||
} catch (e) {
|
||||
return { ok: false, error: e instanceof Error ? e.message : "Échéancier impossible." };
|
||||
}
|
||||
const tracked = schedule.filter((r) => !r.beforeTracking);
|
||||
if (tracked.length === 0) return { ok: false, error: "Ce crédit est déjà entièrement remboursé." };
|
||||
|
||||
const category =
|
||||
(await prisma.category.findFirst({ where: { name: "Crédit", kind: "EXPENSE" } })) ??
|
||||
(await prisma.category.findFirstOrThrow({ where: { kind: "EXPENSE" }, orderBy: { sortOrder: "asc" } }));
|
||||
|
||||
const loanData = {
|
||||
name: input.name.trim(),
|
||||
lender: input.lender.trim() || null,
|
||||
principal: decimalFromCents(principal),
|
||||
annualRate: rateText,
|
||||
durationMonths: input.durationMonths,
|
||||
startDate: fromIsoDate(input.startDate),
|
||||
insuranceMonthly: decimalFromCents(insurance),
|
||||
accountUserId: input.accountUserId,
|
||||
paymentOverride: paymentOverride === null ? null : decimalFromCents(paymentOverride),
|
||||
referenceDate: refDate ? fromIsoDate(refDate) : null,
|
||||
referenceRemainingCapital: refCapital === null ? null : decimalFromCents(refCapital),
|
||||
};
|
||||
const recurringData = {
|
||||
kind: "EXPENSE" as const,
|
||||
amount: decimalFromCents(tracked[0].payment + insurance),
|
||||
label: loanData.name,
|
||||
categoryId: category.id,
|
||||
accountUserId: input.accountUserId,
|
||||
frequency: "MONTHLY" as const,
|
||||
dayOfMonth: Number(input.startDate.slice(8, 10)),
|
||||
startDate: fromIsoDate(tracked[0].date),
|
||||
endDate: fromIsoDate(schedule[schedule.length - 1].date),
|
||||
};
|
||||
|
||||
const { loanId, recurringId } = await prisma.$transaction(async (tx) => {
|
||||
let loanId = input.id;
|
||||
if (loanId) {
|
||||
await tx.loanSplit.deleteMany({ where: { loanId } });
|
||||
await tx.loan.update({ where: { id: loanId }, data: { ...loanData, splits: { create: splitRows(input.split) } } });
|
||||
} else {
|
||||
loanId = (await tx.loan.create({ data: { ...loanData, splits: { create: splitRows(input.split) } } })).id;
|
||||
}
|
||||
const existing = await tx.recurring.findUnique({ where: { loanId } });
|
||||
if (existing) {
|
||||
await tx.recurringSplit.deleteMany({ where: { recurringId: existing.id } });
|
||||
await tx.recurring.update({ where: { id: existing.id }, data: { ...recurringData, splits: { create: splitRows(input.split) } } });
|
||||
return { loanId, recurringId: existing.id };
|
||||
}
|
||||
const rec = await tx.recurring.create({ data: { ...recurringData, loanId, splits: { create: splitRows(input.split) } } });
|
||||
return { loanId, recurringId: rec.id };
|
||||
});
|
||||
|
||||
await prisma.operation.deleteMany({ where: { recurringId, status: "PLANNED", date: { gte: fromIsoDate(today) } } });
|
||||
await syncRecurrings(today);
|
||||
return { ok: true, id: loanId };
|
||||
}
|
||||
|
||||
export async function deleteLoan(id: string, today: string = todayParis()): Promise<Result> {
|
||||
const rec = await prisma.recurring.findUnique({ where: { loanId: id } });
|
||||
if (rec) await prisma.operation.deleteMany({ where: { recurringId: rec.id, status: "PLANNED", date: { gte: fromIsoDate(today) } } });
|
||||
await prisma.loan.delete({ where: { id } });
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { prisma } from "@/server/db";
|
||||
import { deleteLoan, saveLoan, type LoanFormInput } from "@/server/services/loans";
|
||||
import { makeUsers, resetDb } from "./helpers";
|
||||
|
||||
const TODAY = "2026-10-27";
|
||||
let input: LoanFormInput;
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetDb();
|
||||
const { h, c } = await makeUsers();
|
||||
input = {
|
||||
name: "Crédit voiture",
|
||||
lender: "Banque",
|
||||
principal: "20000",
|
||||
annualRate: "4",
|
||||
durationMonths: 48,
|
||||
startDate: "2026-01-05",
|
||||
insuranceMonthly: "15",
|
||||
accountUserId: h.id,
|
||||
split: { [h.id]: 10000, [c.id]: 0 },
|
||||
paymentOverride: "",
|
||||
referenceDate: "",
|
||||
referenceRemainingCapital: "",
|
||||
};
|
||||
});
|
||||
|
||||
describe("saveLoan", () => {
|
||||
it("creates the loan's monthly recurring, without retroactive occurrences", async () => {
|
||||
const r = await saveLoan(input, TODAY);
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
const rec = await prisma.recurring.findFirstOrThrow({ where: { loanId: r.id }, include: { category: true } });
|
||||
expect(rec.amount.toString()).toBe("466.58");
|
||||
expect(rec.endDate?.toISOString().slice(0, 10)).toBe("2029-12-05");
|
||||
expect(rec.category.name).toBe("Crédit");
|
||||
const first = await prisma.operation.findFirstOrThrow({ where: { recurringId: rec.id }, orderBy: { date: "asc" } });
|
||||
expect(first.date.toISOString().slice(0, 10)).toBe("2026-10-05");
|
||||
});
|
||||
|
||||
it("follows the bank's figures for a loan already running", async () => {
|
||||
const r = await saveLoan(input, TODAY);
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
await saveLoan(
|
||||
{ ...input, id: r.id, referenceDate: "2026-06-10", referenceRemainingCapital: "18000", paymentOverride: "460" },
|
||||
TODAY,
|
||||
);
|
||||
const rec = await prisma.recurring.findFirstOrThrow({ where: { loanId: r.id } });
|
||||
expect(rec.amount.toString()).toBe("475");
|
||||
const future = await prisma.operation.findMany({
|
||||
where: { recurringId: rec.id, status: "PLANNED", date: { gte: new Date("2026-10-27T00:00:00Z") } },
|
||||
});
|
||||
expect(future.length).toBeGreaterThan(0);
|
||||
expect(future.every((o) => o.amount.toString() === "475")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a payment that cannot cover the interest", async () => {
|
||||
const r = await saveLoan({ ...input, referenceDate: "2026-06-10", referenceRemainingCapital: "18000", paymentOverride: "50" }, TODAY);
|
||||
expect(r).toEqual({ ok: false, error: "Mensualité insuffisante pour couvrir les intérêts" });
|
||||
});
|
||||
|
||||
it("validates the rate and the capital", async () => {
|
||||
expect(await saveLoan({ ...input, annualRate: "abc" }, TODAY)).toEqual({ ok: false, error: "Taux invalide." });
|
||||
expect(await saveLoan({ ...input, principal: "0" }, TODAY)).toEqual({ ok: false, error: "Capital invalide." });
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteLoan", () => {
|
||||
it("removes the loan and its recurring but keeps actual history", async () => {
|
||||
const r = await saveLoan(input, TODAY);
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
await prisma.operation.updateMany({ where: { date: new Date("2026-10-05T00:00:00Z") }, data: { status: "ACTUAL" } });
|
||||
await deleteLoan(r.id, TODAY);
|
||||
expect(await prisma.loan.count()).toBe(0);
|
||||
expect(await prisma.recurring.count()).toBe(0);
|
||||
expect(await prisma.operation.count({ where: { status: "ACTUAL" } })).toBe(1);
|
||||
expect(await prisma.operation.count({ where: { status: "PLANNED", date: { gte: new Date("2026-10-27T00:00:00Z") } } })).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user