50 lines
2.2 KiB
TypeScript
50 lines
2.2 KiB
TypeScript
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 };
|
|
});
|
|
}
|