feat: settings and CSV export
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9cb7fe8c81
commit
8201496bb6
8 files changed
+528
No files matched your search
@@ -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 (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-xl font-bold md:text-[22px]">Réglages</h1>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{users.map((u) => (
|
||||
<PersonCard key={u.id} user={u} isMe={u.id === me.id} />
|
||||
))}
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-4">
|
||||
<DefaultSplitCard users={users} split={defaultSplit} />
|
||||
<Card className="space-y-3">
|
||||
<CardLabel>Export CSV</CardLabel>
|
||||
<p className="text-[13px] text-muted">Toutes les opérations de la période, au format Excel (séparateur « ; »).</p>
|
||||
<form action="/api/export" method="get" className="flex flex-wrap items-end gap-2">
|
||||
<label className="block">
|
||||
<span className="mb-1.5 block text-xs font-semibold text-muted">Du mois</span>
|
||||
<input type="month" name="from" defaultValue={addMonths(month, -11)} className="rounded-[10px] border border-line px-3 py-2" />
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="mb-1.5 block text-xs font-semibold text-muted">Au mois</span>
|
||||
<input type="month" name="to" defaultValue={month} className="rounded-[10px] border border-line px-3 py-2" />
|
||||
</label>
|
||||
<button className="rounded-[10px] bg-accent px-4 py-2.5 font-semibold text-white hover:bg-indigo-700">Télécharger</button>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
<CategoriesCard categories={categories.map((c) => ({ id: c.id, name: c.name, emoji: c.emoji, kind: c.kind, archived: c.archived }))} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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 <span className={`text-[13px] font-medium ${msg.ok ? "text-pos" : "text-neg"}`}>{msg.text}</span>;
|
||||
}
|
||||
|
||||
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 (
|
||||
<Card className="space-y-4">
|
||||
<CardLabel>{isMe ? `${user.firstName} (vous)` : user.firstName}</CardLabel>
|
||||
<div className="flex gap-3">
|
||||
<Field label="Prénom">
|
||||
<Input value={f.firstName} onChange={(e) => setF({ ...f, firstName: e.target.value })} />
|
||||
</Field>
|
||||
<Field label="Couleur">
|
||||
<Input type="color" value={f.color} onChange={(e) => setF({ ...f, color: e.target.value })} className="h-[42px] w-16 p-1" />
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="Identifiant">
|
||||
<Input value={f.login} autoCapitalize="none" onChange={(e) => setF({ ...f, login: e.target.value })} />
|
||||
</Field>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button disabled={profile.pending} onClick={() => profile.run(() => updateUserAction(user.id, f))}>
|
||||
Enregistrer
|
||||
</Button>
|
||||
<Feedback msg={profile.msg} />
|
||||
</div>
|
||||
{isMe && (
|
||||
<div className="space-y-3 border-t border-line pt-4">
|
||||
<CardLabel>Changer mon mot de passe</CardLabel>
|
||||
<Input type="password" placeholder="Mot de passe actuel" autoComplete="current-password" value={current} onChange={(e) => setCurrent(e.target.value)} />
|
||||
<Input type="password" placeholder="Nouveau mot de passe (8 caractères min.)" autoComplete="new-password" value={next} onChange={(e) => setNext(e.target.value)} />
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
disabled={password.pending}
|
||||
onClick={() =>
|
||||
password.run(async () => {
|
||||
const r = await changePasswordAction(current, next);
|
||||
if (r.ok) {
|
||||
setCurrent("");
|
||||
setNext("");
|
||||
}
|
||||
return r;
|
||||
}, "Mot de passe modifié ✓")
|
||||
}
|
||||
>
|
||||
Changer
|
||||
</Button>
|
||||
<Feedback msg={password.msg} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function DefaultSplitCard({ users, split }: { users: { id: string; firstName: string }[]; split: Split }) {
|
||||
const [value, setValue] = useState(split);
|
||||
const save = useSave();
|
||||
return (
|
||||
<Card className="space-y-3">
|
||||
<CardLabel>Répartition par défaut des dépenses</CardLabel>
|
||||
<p className="text-[13px] text-muted">Proposée à chaque nouvelle dépense. Les entrées restent à 100 % pour la personne qui les reçoit.</p>
|
||||
<SplitPicker users={users} defaultSplit={split} value={value} onChange={setValue} />
|
||||
<div className="flex items-center gap-3">
|
||||
<Button disabled={save.pending} onClick={() => save.run(() => setDefaultSplitAction(value))}>
|
||||
Enregistrer
|
||||
</Button>
|
||||
<Feedback msg={save.msg} />
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className={`flex items-center gap-2 py-1.5 ${cat.archived ? "opacity-50" : ""}`}>
|
||||
<Input aria-label="Emoji" className="w-14 text-center" value={emoji} onChange={(e) => setEmoji(e.target.value)} />
|
||||
<Input aria-label="Nom" className="min-w-0 flex-1" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
{dirty && (
|
||||
<Button className="px-3" disabled={save.pending} onClick={() => save.run(() => saveCategoryAction({ id: cat.id, name, emoji, kind: cat.kind }))}>
|
||||
OK
|
||||
</Button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="w-20 shrink-0 text-[13px] font-semibold text-muted hover:text-ink"
|
||||
onClick={() => save.run(() => archiveCategoryAction(cat.id, !cat.archived), cat.archived ? "Réactivée" : "Archivée")}
|
||||
>
|
||||
{cat.archived ? "Réactiver" : "Archiver"}
|
||||
</button>
|
||||
{save.msg && !save.msg.ok && <Feedback msg={save.msg} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CategoriesCard({ categories }: { categories: Cat[] }) {
|
||||
const [kind, setKind] = useState<OpKind>("EXPENSE");
|
||||
const [name, setName] = useState("");
|
||||
const [emoji, setEmoji] = useState("");
|
||||
const add = useSave();
|
||||
return (
|
||||
<Card className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<CardLabel>Catégories</CardLabel>
|
||||
<div className="flex rounded-[10px] bg-gray-100 p-1 text-[13px]">
|
||||
{(["EXPENSE", "INCOME"] as const).map((k) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
onClick={() => setKind(k)}
|
||||
className={`rounded-lg px-3 py-1 font-semibold ${kind === k ? "bg-white shadow-sm" : "text-muted"}`}
|
||||
>
|
||||
{k === "EXPENSE" ? "Dépenses" : "Entrées"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="divide-y divide-line-soft">
|
||||
{categories
|
||||
.filter((c) => c.kind === kind)
|
||||
.map((c) => (
|
||||
<CategoryRow key={`${c.id}-${c.name}-${c.emoji}-${c.archived}`} cat={c} />
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 border-t border-line pt-3">
|
||||
<Input aria-label="Emoji" placeholder="🙂" className="w-14 text-center" value={emoji} onChange={(e) => setEmoji(e.target.value)} />
|
||||
<Input aria-label="Nouvelle catégorie" placeholder="Nouvelle catégorie" className="min-w-0 flex-1" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<Button
|
||||
disabled={add.pending || !name.trim()}
|
||||
onClick={() =>
|
||||
add.run(async () => {
|
||||
const r = await saveCategoryAction({ name, emoji, kind });
|
||||
if (r.ok) {
|
||||
setName("");
|
||||
setEmoji("");
|
||||
}
|
||||
return r;
|
||||
}, "Ajoutée ✓")
|
||||
}
|
||||
>
|
||||
Ajouter
|
||||
</Button>
|
||||
</div>
|
||||
<Feedback msg={add.msg} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<string, { name: string }>,
|
||||
chargeLabels: Record<string, string>,
|
||||
): 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";
|
||||
}
|
||||
@@ -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<Result> {
|
||||
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<Result> {
|
||||
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<Result> {
|
||||
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<Result<{ id: string }>> {
|
||||
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<Result> {
|
||||
await prisma.category.update({ where: { id }, data: { archived } });
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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à." });
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user