feat: monthly budgets per category with history

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
YugonitoandClaude Opus 5.5 committed 2026-10-27 18:28:00 +01:00
1 parent bfaa38510b
commit 0b9c6a11d3
6 files changed
+316

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
import { centsFromDecimal, decimalFromCents, parseEuro } from "@/domain/money";
import { budgetForMonth } from "@/domain/monthly";
import { addMonths } from "@/lib/dates";
import { prisma } from "../db";
import { getOpsBetween } from "../repo";
import type { Result } from "./operations";
/**
* Fixe le budget d'une catégorie à partir d'un mois (et pour la suite).
* Montant vide ou nul : plus de budget à partir de ce mois.
*/
export async function setBudget(categoryId: string, amount: string, fromMonth: string): Promise<Result> {
const blank = amount.trim() === "" || /^0+([,.]0*)?$/.test(amount.trim());
const cents = blank ? 0 : parseEuro(amount);
if (cents === null) return { ok: false, error: "Montant invalide." };
await prisma.$transaction(async (tx) => {
// Le nouveau budget remplace ceux qui démarraient à ce mois ou plus tard.
await tx.budget.deleteMany({ where: { categoryId, startMonth: { gte: fromMonth } } });
await tx.budget.updateMany({
where: { categoryId, startMonth: { lt: fromMonth }, OR: [{ endMonth: null }, { endMonth: { gte: fromMonth } }] },
data: { endMonth: addMonths(fromMonth, -1) },
});
if (cents > 0) {
await tx.budget.create({ data: { categoryId, monthlyAmount: decimalFromCents(cents), startMonth: fromMonth } });
}
});
return { ok: true };
}
export async function budgetHistory(
categoryId: string,
months: number,
untilMonth: string,
): Promise<{ month: string; budget: number | null; actual: number }[]> {
const first = addMonths(untilMonth, -(months - 1));
const [rows, ops] = await Promise.all([
prisma.budget.findMany({ where: { categoryId } }),
getOpsBetween(`${first}-01`, `${addMonths(untilMonth, 1)}-01`),
]);
const budgets = rows.map((b) => ({ ...b, monthlyAmount: centsFromDecimal(b.monthlyAmount) }));
return Array.from({ length: months }, (_, i) => {
const month = addMonths(first, i);
const actual = ops
.filter((o) => o.categoryId === categoryId && o.kind === "EXPENSE" && o.status === "ACTUAL" && o.date.startsWith(month))
.reduce((t, o) => t + o.amount, 0);
return { month, budget: budgetForMonth(budgets, month)[0]?.amount ?? null, actual };
});
}