import { beforeEach, describe, expect, it } from "vitest"; import { computeBalances, describeBalance } from "@/domain/balance"; import { createHousehold, hashPassword, verifyPassword } from "@/server/auth"; import { toSettlement } from "@/server/mappers"; import { prisma } from "@/server/db"; import { resetDb } from "./helpers"; const person = (firstName: string, login: string, color: string) => ({ firstName, login, password: "motdepasse", passwordConfirm: "motdepasse", color, }); describe("passwords", () => { it("verifies the right password and rejects a wrong one", async () => { const hash = await hashPassword("secret-123"); expect(await verifyPassword("secret-123", hash)).toBe(true); expect(await verifyPassword("nope", hash)).toBe(false); }); }); describe("createHousehold", () => { beforeEach(resetDb); it("creates both people, the default split and an opening balance", async () => { const { users } = await createHousehold({ people: [person("Hugues", "hugues", "#4f46e5"), person("Léa", "lea", "#db2777")], defaultPercentFirst: "60", openingAmount: "150", openingDirection: "second-owes-first", }); expect(await prisma.user.count()).toBe(2); const setting = await prisma.setting.findUniqueOrThrow({ where: { id: 1 } }); expect(setting.defaultSplit).toEqual({ [users[0].id]: 6000, [users[1].id]: 4000 }); const s = await prisma.settlement.findFirstOrThrow(); expect(s.amount.toString()).toBe("150"); // « La personne 2 doit à la personne 1 » : le tableau de bord doit l'afficher ainsi. const ids = users.map((u) => u.id); expect(describeBalance(computeBalances([], [toSettlement(s)], ids))).toEqual({ debtor: users[1].id, creditor: users[0].id, amount: 15000, }); }); it("skips the opening balance when empty", async () => { await createHousehold({ people: [person("A", "a", "#4f46e5"), person("B", "b", "#db2777")], defaultPercentFirst: "50", openingAmount: "", openingDirection: "second-owes-first", }); expect(await prisma.settlement.count()).toBe(0); }); it("refuses to run twice", async () => { const input = { people: [person("A", "a", "#4f46e5"), person("B", "b", "#db2777")] as [ReturnType, ReturnType], defaultPercentFirst: "50", openingAmount: "", openingDirection: "second-owes-first" as const, }; await createHousehold(input); await expect(createHousehold(input)).rejects.toThrow("Installation déjà effectuée"); }); it("validates passwords and logins", async () => { await expect( createHousehold({ people: [{ ...person("A", "a", "#4f46e5"), password: "court", passwordConfirm: "court" }, person("B", "b", "#db2777")], defaultPercentFirst: "50", openingAmount: "", openingDirection: "second-owes-first", }), ).rejects.toThrow("Le mot de passe doit faire au moins 8 caractères."); await expect( createHousehold({ people: [person("A", "same", "#4f46e5"), person("B", "same", "#db2777")], defaultPercentFirst: "50", openingAmount: "", openingDirection: "second-owes-first", }), ).rejects.toThrow("Les deux identifiants doivent être différents."); }); });