import { beforeEach, describe, expect, it } from "vitest"; import { fromIsoDate } from "@/lib/dates"; import { prisma } from "@/server/db"; import { syncRecurrings } from "@/server/sync"; import { categoryId, makeUsers, resetDb } from "./helpers"; async function makeRent() { const { h, c } = await makeUsers(); const rent = await prisma.recurring.create({ data: { kind: "EXPENSE", amount: "1000.00", label: "Loyer", categoryId: await categoryId("Logement"), accountUserId: h.id, frequency: "MONTHLY", dayOfMonth: 5, startDate: fromIsoDate("2026-01-05"), splits: { create: [{ userId: h.id, basisPoints: 5000 }, { userId: c.id, basisPoints: 5000 }] }, }, }); return { h, c, rent }; } describe("syncRecurrings", () => { beforeEach(resetDb); it("creates 12 months of planned occurrences with splits, idempotently", async () => { const { rent } = await makeRent(); expect(await syncRecurrings("2026-10-27")).toBe(12); expect(await syncRecurrings("2026-10-27")).toBe(0); const first = await prisma.operation.findFirstOrThrow({ where: { recurringId: rent.id }, orderBy: { date: "asc" }, include: { splits: true }, }); expect(first.date.toISOString().slice(0, 10)).toBe("2026-10-05"); expect(first.status).toBe("PLANNED"); expect(first.splits.map((s) => s.basisPoints)).toEqual([5000, 5000]); }); it("recreates deleted occurrences but never skipped ones", async () => { const { rent } = await makeRent(); await syncRecurrings("2026-10-27"); await prisma.operation.updateMany({ where: { recurringId: rent.id, date: fromIsoDate("2026-10-05") }, data: { status: "SKIPPED" }, }); await prisma.operation.deleteMany({ where: { recurringId: rent.id, date: fromIsoDate("2026-11-05") } }); expect(await syncRecurrings("2026-10-27")).toBe(1); const october = await prisma.operation.findFirstOrThrow({ where: { recurringId: rent.id, date: fromIsoDate("2026-10-05") } }); expect(october.status).toBe("SKIPPED"); }); it("keeps actual history when the recurring template is deleted", async () => { const { rent } = await makeRent(); await syncRecurrings("2026-10-27"); const october = await prisma.operation.findFirstOrThrow({ where: { recurringId: rent.id, date: fromIsoDate("2026-10-05") } }); await prisma.operation.update({ where: { id: october.id }, data: { status: "ACTUAL" } }); await prisma.operation.deleteMany({ where: { recurringId: rent.id, status: "PLANNED" } }); await prisma.recurring.delete({ where: { id: rent.id } }); const kept = await prisma.operation.findUniqueOrThrow({ where: { id: october.id } }); expect(kept.recurringId).toBeNull(); expect(kept.status).toBe("ACTUAL"); }); });