diff --git a/src/app/(app)/reglages/page.tsx b/src/app/(app)/reglages/page.tsx
new file mode 100644
index 0000000..2798366
--- /dev/null
+++ b/src/app/(app)/reglages/page.tsx
@@ -0,0 +1,48 @@
+import { CategoriesCard, DefaultSplitCard, PersonCard } from "@/components/settings/SettingsForms";
+import { Card, CardLabel } from "@/components/ui/Card";
+import { addMonths, currentMonthParis } from "@/lib/dates";
+import { requireUser } from "@/server/auth";
+import { prisma } from "@/server/db";
+import { getCategories, getDefaultSplit } from "@/server/repo";
+
+export default async function SettingsPage() {
+ const me = await requireUser();
+ const [users, categories, defaultSplit] = await Promise.all([
+ prisma.user.findMany({ select: { id: true, firstName: true, login: true, color: true }, orderBy: { createdAt: "asc" } }),
+ getCategories(undefined, true),
+ getDefaultSplit(),
+ ]);
+ const month = currentMonthParis();
+
+ return (
+
+
Réglages
+
+ {users.map((u) => (
+
+ ))}
+
+
+
+
+
+ Export CSV
+ Toutes les opérations de la période, au format Excel (séparateur « ; »).
+
+
+
+
({ id: c.id, name: c.name, emoji: c.emoji, kind: c.kind, archived: c.archived }))} />
+
+
+ );
+}
diff --git a/src/app/api/export/route.ts b/src/app/api/export/route.ts
new file mode 100644
index 0000000..6129c09
--- /dev/null
+++ b/src/app/api/export/route.ts
@@ -0,0 +1,42 @@
+import { NextResponse, type NextRequest } from "next/server";
+import { addMonths, currentMonthParis, fromIsoDate } from "@/lib/dates";
+import { getSession } from "@/server/auth";
+import { opsToCsv } from "@/server/csv";
+import { prisma } from "@/server/db";
+import { toOp } from "@/server/mappers";
+import { getCategories, getUsers } from "@/server/repo";
+
+const MONTH = /^\d{4}-(0[1-9]|1[0-2])$/;
+
+export async function GET(req: NextRequest) {
+ const session = await getSession();
+ if (!session.userId || !(await prisma.user.findUnique({ where: { id: session.userId } }))) {
+ return NextResponse.json({ error: "Non connecté" }, { status: 401 });
+ }
+ const now = currentMonthParis();
+ let from = req.nextUrl.searchParams.get("from") ?? now;
+ let to = req.nextUrl.searchParams.get("to") ?? now;
+ if (!MONTH.test(from) || !MONTH.test(to)) return NextResponse.json({ error: "Mois invalide" }, { status: 400 });
+ if (from > to) [from, to] = [to, from];
+
+ const [rows, users, categories, recurrings] = await Promise.all([
+ prisma.operation.findMany({
+ where: { date: { gte: fromIsoDate(`${from}-01`), lt: fromIsoDate(`${addMonths(to, 1)}-01`) } },
+ include: { splits: true },
+ orderBy: [{ date: "asc" }, { createdAt: "asc" }],
+ }),
+ getUsers(),
+ getCategories(undefined, true),
+ prisma.recurring.findMany({ select: { id: true, label: true } }),
+ ]);
+ const ops = rows.map((r) => ({ ...toOp(r), note: r.note }));
+ const chargeLabels = Object.fromEntries([...recurrings.map((r) => [r.id, r.label]), ...rows.map((r) => [r.id, r.label])]);
+ const csv = opsToCsv(ops, users, Object.fromEntries(categories.map((c) => [c.id, { name: c.name }])), chargeLabels);
+
+ return new NextResponse(csv, {
+ headers: {
+ "Content-Type": "text/csv; charset=utf-8",
+ "Content-Disposition": `attachment; filename="finances-${from}_${to}.csv"`,
+ },
+ });
+}
diff --git a/src/components/settings/SettingsForms.tsx b/src/components/settings/SettingsForms.tsx
new file mode 100644
index 0000000..815825a
--- /dev/null
+++ b/src/components/settings/SettingsForms.tsx
@@ -0,0 +1,193 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import type { OpKind, Split } from "@/domain/types";
+import {
+ archiveCategoryAction,
+ changePasswordAction,
+ saveCategoryAction,
+ setDefaultSplitAction,
+ updateUserAction,
+} from "@/server/actions/settings";
+import { SplitPicker } from "../SplitPicker";
+import { Button } from "../ui/Button";
+import { Card, CardLabel } from "../ui/Card";
+import { Field, Input } from "../ui/Field";
+
+function Feedback({ msg }: { msg: { ok: boolean; text: string } | null }) {
+ if (!msg) return null;
+ return {msg.text};
+}
+
+function useSave() {
+ const [pending, start] = useTransition();
+ const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
+ const run = (fn: () => Promise<{ ok: boolean; error?: string }>, success = "Enregistré ✓") =>
+ start(async () => {
+ const r = await fn();
+ setMsg(r.ok ? { ok: true, text: success } : { ok: false, text: r.error ?? "Erreur" });
+ });
+ return { pending, msg, run };
+}
+
+export function PersonCard({ user, isMe }: { user: { id: string; firstName: string; login: string; color: string }; isMe: boolean }) {
+ const [f, setF] = useState(user);
+ const profile = useSave();
+ const password = useSave();
+ const [current, setCurrent] = useState("");
+ const [next, setNext] = useState("");
+
+ return (
+
+ {isMe ? `${user.firstName} (vous)` : user.firstName}
+
+
+ setF({ ...f, firstName: e.target.value })} />
+
+
+ setF({ ...f, color: e.target.value })} className="h-[42px] w-16 p-1" />
+
+
+
+ setF({ ...f, login: e.target.value })} />
+
+
+
+
+
+ {isMe && (
+
+
Changer mon mot de passe
+
setCurrent(e.target.value)} />
+
setNext(e.target.value)} />
+
+
+
+
+
+ )}
+
+ );
+}
+
+export function DefaultSplitCard({ users, split }: { users: { id: string; firstName: string }[]; split: Split }) {
+ const [value, setValue] = useState(split);
+ const save = useSave();
+ return (
+
+ Répartition par défaut des dépenses
+ Proposée à chaque nouvelle dépense. Les entrées restent à 100 % pour la personne qui les reçoit.
+
+
+
+
+
+
+ );
+}
+
+interface Cat {
+ id: string;
+ name: string;
+ emoji: string;
+ kind: OpKind;
+ archived: boolean;
+}
+
+function CategoryRow({ cat }: { cat: Cat }) {
+ const [name, setName] = useState(cat.name);
+ const [emoji, setEmoji] = useState(cat.emoji);
+ const save = useSave();
+ const dirty = name !== cat.name || emoji !== cat.emoji;
+ return (
+
+ setEmoji(e.target.value)} />
+ setName(e.target.value)} />
+ {dirty && (
+
+ )}
+
+ {save.msg && !save.msg.ok && }
+
+ );
+}
+
+export function CategoriesCard({ categories }: { categories: Cat[] }) {
+ const [kind, setKind] = useState("EXPENSE");
+ const [name, setName] = useState("");
+ const [emoji, setEmoji] = useState("");
+ const add = useSave();
+ return (
+
+
+
Catégories
+
+ {(["EXPENSE", "INCOME"] as const).map((k) => (
+
+ ))}
+
+
+
+ {categories
+ .filter((c) => c.kind === kind)
+ .map((c) => (
+
+ ))}
+
+
+ setEmoji(e.target.value)} />
+ setName(e.target.value)} />
+
+
+
+
+ );
+}
diff --git a/src/server/actions/settings.ts b/src/server/actions/settings.ts
new file mode 100644
index 0000000..e3bf4ce
--- /dev/null
+++ b/src/server/actions/settings.ts
@@ -0,0 +1,42 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import type { OpKind, Split } from "@/domain/types";
+import { requireUser } from "@/server/auth";
+import * as settings from "@/server/services/settings";
+
+const refresh = () => revalidatePath("/", "layout");
+
+export async function updateUserAction(id: string, input: { firstName: string; color: string; login: string }) {
+ await requireUser();
+ const r = await settings.updateUser(id, input);
+ if (r.ok) refresh();
+ return r;
+}
+
+/** On ne change que son propre mot de passe (l'autre passe par le script de réinitialisation). */
+export async function changePasswordAction(current: string, next: string) {
+ const user = await requireUser();
+ return settings.changePassword(user.id, current, next);
+}
+
+export async function setDefaultSplitAction(split: Split) {
+ await requireUser();
+ const r = await settings.setDefaultSplit(split);
+ if (r.ok) refresh();
+ return r;
+}
+
+export async function saveCategoryAction(input: { id?: string; name: string; emoji: string; kind: OpKind }) {
+ await requireUser();
+ const r = await settings.saveCategory(input);
+ if (r.ok) refresh();
+ return r;
+}
+
+export async function archiveCategoryAction(id: string, archived: boolean) {
+ await requireUser();
+ const r = await settings.archiveCategory(id, archived);
+ refresh();
+ return r;
+}
diff --git a/src/server/csv.ts b/src/server/csv.ts
new file mode 100644
index 0000000..e9611d5
--- /dev/null
+++ b/src/server/csv.ts
@@ -0,0 +1,53 @@
+import { bpToPercentLabel } from "@/domain/money";
+import type { Op } from "@/domain/types";
+import { formatDateFr } from "@/lib/dates";
+
+const field = (v: string) => (/[;"\r\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v);
+
+/** "-86,40" : virgule décimale, signe selon le type, pas de séparateur de milliers (pour Excel). */
+const amount = (o: Op) => {
+ const cents = o.amount;
+ const text = `${Math.floor(cents / 100)},${String(cents % 100).padStart(2, "0")}`;
+ return o.kind === "EXPENSE" ? `-${text}` : text;
+};
+
+/** Export CSV pour Excel : UTF-8 avec BOM, séparateur « ; », fins de ligne CRLF. */
+export function opsToCsv(
+ ops: (Op & { note?: string | null })[],
+ users: { id: string; firstName: string }[],
+ categories: Record,
+ chargeLabels: Record,
+): string {
+ const header = [
+ "Date",
+ "Type",
+ "Libellé",
+ "Catégorie",
+ "Montant",
+ "Payé par",
+ "Statut",
+ ...users.map((u) => `Part ${u.firstName} %`),
+ "Affecté à",
+ "Note",
+ ];
+ const lines = ops
+ .filter((o) => o.status !== "SKIPPED")
+ .map((o) => {
+ const target = o.allocatedToRecurringId ?? o.allocatedToOperationId;
+ return [
+ formatDateFr(o.date),
+ o.kind === "EXPENSE" ? "Dépense" : "Entrée",
+ o.label,
+ categories[o.categoryId]?.name ?? "",
+ amount(o),
+ users.find((u) => u.id === o.accountUserId)?.firstName ?? "",
+ o.status === "PLANNED" ? "Prévu" : "Réel",
+ ...users.map((u) => bpToPercentLabel(o.split[u.id] ?? 0)),
+ target ? (chargeLabels[target] ?? "") : "",
+ o.note ?? "",
+ ]
+ .map(field)
+ .join(";");
+ });
+ return "" + [header.map(field).join(";"), ...lines].join("\r\n") + "\r\n";
+}
diff --git a/src/server/services/settings.ts b/src/server/services/settings.ts
new file mode 100644
index 0000000..155c8fe
--- /dev/null
+++ b/src/server/services/settings.ts
@@ -0,0 +1,62 @@
+import { Prisma } from "@prisma/client";
+import { validateSplit } from "@/domain/money";
+import type { OpKind, Split } from "@/domain/types";
+import { hashPassword, validatePassword, verifyPassword } from "../auth";
+import { prisma } from "../db";
+import type { Result } from "./operations";
+
+const isUniqueViolation = (e: unknown) => e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002";
+
+export async function updateUser(id: string, input: { firstName: string; color: string; login: string }): Promise {
+ const firstName = input.firstName.trim();
+ const login = input.login.trim().toLowerCase();
+ if (!firstName) return { ok: false, error: "Le prénom est obligatoire." };
+ if (!/^[a-z0-9._-]+$/.test(login)) return { ok: false, error: "Identifiant invalide (lettres, chiffres, . _ -)." };
+ if (!/^#[0-9a-f]{6}$/i.test(input.color)) return { ok: false, error: "Couleur invalide." };
+ try {
+ await prisma.user.update({ where: { id }, data: { firstName, login, color: input.color } });
+ } catch (e) {
+ if (isUniqueViolation(e)) return { ok: false, error: "Cet identifiant est déjà utilisé." };
+ throw e;
+ }
+ return { ok: true };
+}
+
+export async function changePassword(id: string, current: string, next: string): Promise {
+ const user = await prisma.user.findUniqueOrThrow({ where: { id } });
+ if (!(await verifyPassword(current, user.passwordHash))) return { ok: false, error: "Mot de passe actuel incorrect." };
+ const error = validatePassword(next, next);
+ if (error) return { ok: false, error };
+ await prisma.user.update({ where: { id }, data: { passwordHash: await hashPassword(next) } });
+ return { ok: true };
+}
+
+export async function setDefaultSplit(split: Split): Promise {
+ const error = validateSplit(split);
+ if (error) return { ok: false, error };
+ await prisma.setting.upsert({ where: { id: 1 }, update: { defaultSplit: split }, create: { id: 1, defaultSplit: split } });
+ return { ok: true };
+}
+
+export async function saveCategory(input: { id?: string; name: string; emoji: string; kind: OpKind }): Promise> {
+ const name = input.name.trim();
+ if (!name) return { ok: false, error: "Le nom est obligatoire." };
+ const data = { name, emoji: input.emoji.trim() || "•", kind: input.kind };
+ try {
+ if (input.id) {
+ await prisma.category.update({ where: { id: input.id }, data });
+ return { ok: true, id: input.id };
+ }
+ const last = await prisma.category.aggregate({ _max: { sortOrder: true } });
+ const created = await prisma.category.create({ data: { ...data, sortOrder: (last._max.sortOrder ?? 0) + 1 } });
+ return { ok: true, id: created.id };
+ } catch (e) {
+ if (isUniqueViolation(e)) return { ok: false, error: "Cette catégorie existe déjà." };
+ throw e;
+ }
+}
+
+export async function archiveCategory(id: string, archived: boolean): Promise {
+ await prisma.category.update({ where: { id }, data: { archived } });
+ return { ok: true };
+}
diff --git a/tests/domain/csv.test.ts b/tests/domain/csv.test.ts
new file mode 100644
index 0000000..683f337
--- /dev/null
+++ b/tests/domain/csv.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import { opsToCsv } from "@/server/csv";
+import { op } from "./fixtures";
+
+const users = [
+ { id: "H", firstName: "H" },
+ { id: "C", firstName: "C" },
+];
+const categories = { courses: { name: "Courses" }, salaire: { name: "Salaire" } };
+
+describe("opsToCsv", () => {
+ const groceries = op({ kind: "EXPENSE", amount: 8640, accountUserId: "C", label: "Carrefour; Bio", categoryId: "courses", date: "2026-10-27" });
+
+ it("starts with a BOM and a French header", () => {
+ const csv = opsToCsv([groceries], users, categories, {});
+ expect(csv.startsWith("\uFEFFDate;Type;Libellé;Catégorie;Montant;Payé par;Statut;Part H %;Part C %;Affecté à;Note\r\n")).toBe(true);
+ });
+
+ it("quotes fields with separators and uses comma decimals", () => {
+ const lines = opsToCsv([groceries], users, categories, {}).split("\r\n");
+ expect(lines[1]).toBe('27/10/2026;Dépense;"Carrefour; Bio";Courses;-86,40;C;Réel;50;50;;');
+ });
+
+ it("writes incomes positive, planned status, allocation label and escaped notes", () => {
+ const refund = {
+ ...op({ kind: "INCOME" as const, amount: 20000, accountUserId: "H", label: "Employeur", categoryId: "salaire", status: "PLANNED" as const, allocatedToRecurringId: "rent", date: "2026-10-05" }),
+ note: 'part "loyer"',
+ };
+ const lines = opsToCsv([refund], users, categories, { rent: "Loyer" }).split("\r\n");
+ expect(lines[1]).toBe('05/10/2026;Entrée;Employeur;Salaire;200,00;H;Prévu;50;50;Loyer;"part ""loyer"""');
+ });
+
+ it("excludes skipped operations", () => {
+ const skipped = op({ kind: "EXPENSE", amount: 100, accountUserId: "H", status: "SKIPPED" });
+ expect(opsToCsv([skipped], users, categories, {}).split("\r\n").filter(Boolean)).toHaveLength(1);
+ });
+});
diff --git a/tests/server/settings.test.ts b/tests/server/settings.test.ts
new file mode 100644
index 0000000..55f2995
--- /dev/null
+++ b/tests/server/settings.test.ts
@@ -0,0 +1,51 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { hashPassword, verifyPassword } from "@/server/auth";
+import { prisma } from "@/server/db";
+import { archiveCategory, changePassword, saveCategory, setDefaultSplit, updateUser } from "@/server/services/settings";
+import { makeUsers, resetDb } from "./helpers";
+
+let H: string;
+let C: string;
+
+beforeEach(async () => {
+ await resetDb();
+ const u = await makeUsers();
+ H = u.h.id;
+ C = u.c.id;
+});
+
+describe("settings", () => {
+ it("renames a person and rejects a login already taken", async () => {
+ expect(await updateUser(H, { firstName: "Hugues", color: "#111111", login: "hugues" })).toEqual({ ok: true });
+ expect((await prisma.user.findUniqueOrThrow({ where: { id: H } })).firstName).toBe("Hugues");
+ expect(await updateUser(C, { firstName: "Léa", color: "#db2777", login: "hugues" })).toEqual({
+ ok: false,
+ error: "Cet identifiant est déjà utilisé.",
+ });
+ });
+
+ it("changes a password only with the current one", async () => {
+ await prisma.user.update({ where: { id: H }, data: { passwordHash: await hashPassword("ancien-mdp") } });
+ expect(await changePassword(H, "faux", "nouveau-mdp")).toEqual({ ok: false, error: "Mot de passe actuel incorrect." });
+ expect(await changePassword(H, "ancien-mdp", "court")).toEqual({ ok: false, error: "Le mot de passe doit faire au moins 8 caractères." });
+ expect(await changePassword(H, "ancien-mdp", "nouveau-mdp")).toEqual({ ok: true });
+ const user = await prisma.user.findUniqueOrThrow({ where: { id: H } });
+ expect(await verifyPassword("nouveau-mdp", user.passwordHash)).toBe(true);
+ });
+
+ it("stores a valid default split only", async () => {
+ expect(await setDefaultSplit({ [H]: 6000, [C]: 4000 })).toEqual({ ok: true });
+ expect((await prisma.setting.findUniqueOrThrow({ where: { id: 1 } })).defaultSplit).toEqual({ [H]: 6000, [C]: 4000 });
+ expect(await setDefaultSplit({ [H]: 6000, [C]: 3000 })).toEqual({ ok: false, error: "La répartition doit totaliser 100 %." });
+ });
+
+ it("creates, renames and archives categories", async () => {
+ const r = await saveCategory({ name: "Animaux", emoji: "🐶", kind: "EXPENSE" });
+ if (!r.ok) throw new Error(r.error);
+ await saveCategory({ id: r.id, name: "Chat", emoji: "🐱", kind: "EXPENSE" });
+ await archiveCategory(r.id, true);
+ const cat = await prisma.category.findUniqueOrThrow({ where: { id: r.id } });
+ expect([cat.name, cat.emoji, cat.archived]).toEqual(["Chat", "🐱", true]);
+ expect(await saveCategory({ name: "Courses", emoji: "🛒", kind: "EXPENSE" })).toEqual({ ok: false, error: "Cette catégorie existe déjà." });
+ });
+});