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à." }); }); });