Files
hcl-finances-manager/tests/server/budgets.test.ts
T
2026-10-27 18:28:00 +01:00

62 lines
2.6 KiB
TypeScript

import { beforeEach, describe, expect, it } from "vitest";
import { budgetForMonth } from "@/domain/monthly";
import { centsFromDecimal } from "@/domain/money";
import { prisma } from "@/server/db";
import { budgetHistory, setBudget } from "@/server/services/budgets";
import { saveOperation } from "@/server/services/operations";
import { categoryId, makeUsers, resetDb } from "./helpers";
let courses: string;
const active = async (month: string) => {
const rows = await prisma.budget.findMany();
return budgetForMonth(rows.map((b) => ({ ...b, monthlyAmount: centsFromDecimal(b.monthlyAmount) })), month);
};
beforeEach(async () => {
await resetDb();
courses = await categoryId("Courses");
});
describe("setBudget", () => {
it("starts a new budget from a month and keeps the previous one before it", async () => {
await setBudget(courses, "400", "2026-10");
await setBudget(courses, "450", "2027-01");
expect(await active("2026-12")).toEqual([{ categoryId: courses, amount: 40000 }]);
expect(await active("2027-01")).toEqual([{ categoryId: courses, amount: 45000 }]);
});
it("updates in place when the start month is the same", async () => {
await setBudget(courses, "400", "2026-10");
await setBudget(courses, "420", "2026-10");
expect(await prisma.budget.count()).toBe(1);
expect(await active("2026-10")).toEqual([{ categoryId: courses, amount: 42000 }]);
});
it("closes the budget with an empty or zero amount", async () => {
await setBudget(courses, "400", "2026-10");
await setBudget(courses, "0", "2027-03");
expect(await active("2027-03")).toEqual([]);
expect(await active("2027-02")).toEqual([{ categoryId: courses, amount: 40000 }]);
});
it("rejects an invalid amount", async () => {
expect(await setBudget(courses, "abc", "2026-10")).toEqual({ ok: false, error: "Montant invalide." });
});
});
describe("budgetHistory", () => {
it("returns budget and actual spending month by month, oldest first", async () => {
const { h, c } = await makeUsers();
await setBudget(courses, "400", "2026-09");
await saveOperation(
{ kind: "EXPENSE", amount: "100", label: "Courses", categoryId: courses, date: "2026-10-03", accountUserId: h.id, status: "ACTUAL", split: { [h.id]: 5000, [c.id]: 5000 } },
h.id,
);
const hist = await budgetHistory(courses, 6, "2026-10");
expect(hist.map((x) => x.month)).toEqual(["2026-05", "2026-06", "2026-07", "2026-08", "2026-09", "2026-10"]);
expect(hist[3]).toEqual({ month: "2026-08", budget: null, actual: 0 });
expect(hist[5]).toEqual({ month: "2026-10", budget: 40000, actual: 10000 });
});
});