diff --git a/src/app/(app)/credits/[id]/modifier/page.tsx b/src/app/(app)/credits/[id]/modifier/page.tsx
new file mode 100644
index 0000000..c9101ff
--- /dev/null
+++ b/src/app/(app)/credits/[id]/modifier/page.tsx
@@ -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 (
+
+
+
+ );
+}
diff --git a/src/app/(app)/credits/[id]/page.tsx b/src/app/(app)/credits/[id]/page.tsx
new file mode 100644
index 0000000..3499184
--- /dev/null
+++ b/src/app/(app)/credits/[id]/page.tsx
@@ -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 (
+
+
+
+
+ ‹
+
+
🏦 {loan.name}
+
+
+ Modifier
+
+
+
+
+ {tiles.map(([k, v]) => (
+
+ {k}
+ {v}
+
+ ))}
+
+
+
+ Remboursements affectés ce mois-ci
+ {allocated.length === 0 ? (
+ Aucun. Saisissez une entrée (ex. IK) et affectez-la à « {loan.name} ».
+ ) : (
+ <>
+ {allocated.map((o) => (
+
+
+ {o.label} · {formatDateFr(o.date)}
+
+ {formatEuro(o.amount, { sign: true })}
+
+ ))}
+
+ Coût net ce mois-ci
+ {formatEuro(s.payment + s.insurance - reimbursed)}
+
+ >
+ )}
+
+
+
+ Échéancier
+
+
+
+ | # |
+ Date |
+ Échéance |
+ Intérêts |
+ Capital |
+ Assurance |
+ Restant dû |
+
+
+
+ {rows.map((r, i) => (
+
+ | {r.n} |
+
+ {formatDateFr(r.date)}
+ {r.beforeTracking && avant suivi}
+ |
+ {formatEuro(r.payment)} |
+ {formatEuro(r.interest)} |
+ {formatEuro(r.principal)} |
+ {formatEuro(r.insurance)} |
+ {formatEuro(r.remaining)} |
+
+ ))}
+
+
+
+
+ );
+}
diff --git a/src/app/(app)/credits/nouveau/page.tsx b/src/app/(app)/credits/nouveau/page.tsx
new file mode 100644
index 0000000..e7cc570
--- /dev/null
+++ b/src/app/(app)/credits/nouveau/page.tsx
@@ -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 (
+
+
+
+ );
+}
diff --git a/src/app/(app)/credits/page.tsx b/src/app/(app)/credits/page.tsx
new file mode 100644
index 0000000..586fb7d
--- /dev/null
+++ b/src/app/(app)/credits/page.tsx
@@ -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 (
+
+
+
Crédits & charges
+
+ + Crédit
+
+
+
+ {loans.length === 0 && (
+
+ Aucun crédit. Ajoutez le crédit voiture, un prêt immobilier…
+
+ )}
+
+ {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 (
+
+
+
+
+
🏦 {loan.name}
+
{loan.lender ?? "—"}
+
+ {holder &&
{holder.firstName}}
+
+
+
+
Mensualité
+
{formatEuro(s.payment + s.insurance)}
+
+
+
Restant dû
+
{formatEuro(s.remaining)}
+
+
+
Fin
+
{formatDateFr(s.endDate)}
+
+
+
+ {Math.round(repaid * 100)} % remboursé
+
+
+ );
+ })}
+
+
+
+ Charges affectées ce mois-ci
+ {dashboard.netCharges.length === 0 ? (
+
+ 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 ».
+
+ ) : (
+ dashboard.netCharges.map((c) => (
+
+
+
{c.label}
+
+ {formatEuro(c.gross)} − {formatEuro(c.reimbursed)} remboursés
+
+
+
+
{formatEuro(c.net)}
+
+ couvert à {c.gross > 0 ? Math.round((c.reimbursed / c.gross) * 100) : 0} %
+
+
+
+ ))
+ )}
+
+
+ );
+}
diff --git a/src/components/credits/LoanForm.tsx b/src/components/credits/LoanForm.tsx
new file mode 100644
index 0000000..b184ce1
--- /dev/null
+++ b/src/components/credits/LoanForm.tsx
@@ -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(null);
+ const [f, setF] = useState(
+ 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: 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 (
+
+ );
+}
diff --git a/src/server/actions/loans.ts b/src/server/actions/loans.ts
new file mode 100644
index 0000000..f0e890d
--- /dev/null
+++ b/src/server/actions/loans.ts
@@ -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;
+}
diff --git a/src/server/services/loans.ts b/src/server/services/loans.ts
new file mode 100644
index 0000000..6ef6ba7
--- /dev/null
+++ b/src/server/services/loans.ts
@@ -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> {
+ 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 {
+ 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 };
+}
diff --git a/tests/server/loans.test.ts b/tests/server/loans.test.ts
new file mode 100644
index 0000000..160cb2c
--- /dev/null
+++ b/tests/server/loans.test.ts
@@ -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);
+ });
+});