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

+100
View File
@@ -0,0 +1,100 @@
import Link from "next/link";
import { BudgetHistoryChart } from "@/components/budgets/BudgetHistoryChart";
import { BudgetInput } from "@/components/budgets/BudgetInput";
import { Card, CardLabel } from "@/components/ui/Card";
import { MonthSwitcher } from "@/components/ui/MonthSwitcher";
import { centsFromDecimal, decimalFromCents, formatEuro } from "@/domain/money";
import { budgetForMonth, budgetStatus } from "@/domain/monthly";
import { currentMonthParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { prisma } from "@/server/db";
import { getCategories, getOpsForMonth } from "@/server/repo";
import { budgetHistory } from "@/server/services/budgets";
export default async function BudgetsPage({ searchParams }: { searchParams: Promise<{ m?: string; cat?: string }> }) {
await requireUser();
const sp = await searchParams;
const month = sp.m && /^\d{4}-(0[1-9]|1[0-2])$/.test(sp.m) ? sp.m : currentMonthParis();
const [categories, ops, rows] = await Promise.all([getCategories("EXPENSE"), getOpsForMonth(month), prisma.budget.findMany()]);
const active = budgetForMonth(rows.map((b) => ({ ...b, monthlyAmount: centsFromDecimal(b.monthlyAmount) })), month);
const amountOf = new Map(active.map((b) => [b.categoryId, b.amount]));
const status = new Map(
budgetStatus(ops, month, categories.map((c) => ({ categoryId: c.id, amount: amountOf.get(c.id) ?? 0 }))).map((s) => [s.categoryId, s]),
);
const selected = categories.find((c) => c.id === sp.cat) ?? categories.find((c) => amountOf.has(c.id)) ?? categories[0];
const history = selected ? await budgetHistory(selected.id, 6, month) : [];
const totalBudget = active.reduce((t, b) => t + b.amount, 0);
const totalActual = categories.filter((c) => amountOf.has(c.id)).reduce((t, c) => t + (status.get(c.id)?.actual ?? 0), 0);
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<MonthSwitcher month={month} basePath="/budgets" params={{ cat: sp.cat }} />
{totalBudget > 0 && (
<div className="text-[13px] text-muted">
Budgété <b className="tabular text-ink">{formatEuro(totalBudget)}</b> · dépensé{" "}
<b className={`tabular ${totalActual > totalBudget ? "text-neg" : "text-ink"}`}>{formatEuro(totalActual)}</b>
</div>
)}
</div>
<Card>
<div className="mb-2 flex items-baseline justify-between gap-3">
<CardLabel>Budgets mensuels par catégorie</CardLabel>
<span className="text-right text-xs text-muted">Un montant saisi s&apos;applique à partir de ce mois</span>
</div>
<div className="divide-y divide-line-soft">
{categories.map((c) => {
const budget = amountOf.get(c.id);
const s = status.get(c.id)!;
const over = budget !== undefined && s.over;
const pct = budget ? Math.min(100, (s.actual / budget) * 100) : 0;
return (
<div key={c.id} className="flex items-center gap-3 py-2.5">
<Link href={`/budgets?m=${month}&cat=${c.id}`} className="w-36 shrink-0 truncate font-medium hover:text-accent md:w-44">
{c.emoji} {c.name}
</Link>
<div className="hidden min-w-0 flex-1 md:block">
{budget ? (
<div className="h-2 overflow-hidden rounded-full bg-line-soft">
<div className={`h-full rounded-full ${over ? "bg-neg" : "bg-accent"}`} style={{ width: `${pct}%` }} />
</div>
) : null}
</div>
<div className="tabular min-w-0 flex-1 text-right text-[13px] md:w-56 md:flex-none">
<span className={over ? "font-semibold text-neg" : ""}>{formatEuro(s.actual)}</span>
{s.plannedRemaining > 0 && <span className="text-warn"> + {formatEuro(s.plannedRemaining)} prévus</span>}
</div>
<BudgetInput
key={`${c.id}-${month}-${budget ?? 0}`}
categoryId={c.id}
month={month}
initial={budget ? decimalFromCents(budget).replace(".", ",").replace(",00", "") : ""}
/>
</div>
);
})}
</div>
</Card>
{selected && (
<Card>
<div className="mb-3 flex flex-wrap items-baseline justify-between gap-2">
<CardLabel>
{selected.emoji} {selected.name} · 6 derniers mois
</CardLabel>
<span className="flex items-center gap-3 text-xs text-muted">
<span className="flex items-center gap-1.5">
<span className="inline-block h-2.5 w-2.5 rounded-sm bg-accent" /> Réel
</span>
<span className="flex items-center gap-1.5">
<span className="inline-block w-4 border-t-2 border-dashed border-muted" /> Budget
</span>
</span>
</div>
<BudgetHistoryChart data={history} />
</Card>
)}
</div>
);
}
@@ -0,0 +1,51 @@
"use client";
import { Bar, CartesianGrid, Cell, ComposedChart, Line, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { formatEuro } from "@/domain/money";
const ACCENT = "#4f46e5";
const OVER = "#dc2626";
const MUTED = "#6b7280";
const SHORT = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."];
/** Réel (barres) face au budget (ligne en escalier pointillée), sur une catégorie. */
export function BudgetHistoryChart({ data }: { data: { month: string; budget: number | null; actual: number }[] }) {
const rows = data.map((d) => ({
month: d.month,
label: `${SHORT[Number(d.month.slice(5, 7)) - 1]} ${d.month.slice(2, 4)}`,
actual: d.actual / 100,
budget: d.budget === null ? null : d.budget / 100,
over: d.budget !== null && d.actual > d.budget,
}));
return (
<div className="h-64 w-full">
<ResponsiveContainer>
<ComposedChart data={rows} margin={{ top: 8, right: 8, bottom: 0, left: 0 }} barCategoryGap="35%">
<CartesianGrid vertical={false} stroke="#f1f2f5" />
<XAxis dataKey="label" tickLine={false} axisLine={{ stroke: "#e5e7eb" }} tick={{ fill: MUTED, fontSize: 12 }} />
<YAxis
width={56}
tickLine={false}
axisLine={false}
tick={{ fill: MUTED, fontSize: 12 }}
tickFormatter={(v: number) => `${Math.round(v)} €`}
/>
<Tooltip
cursor={{ fill: "#f5f6fa" }}
formatter={(value, name) => [
value === null || value === undefined ? "—" : formatEuro(Math.round(Number(value) * 100)),
name === "actual" ? "Réel" : "Budget",
]}
contentStyle={{ borderRadius: 10, border: "1px solid #e5e7eb", fontSize: 13 }}
/>
<Bar dataKey="actual" radius={[4, 4, 0, 0]} maxBarSize={36}>
{rows.map((r) => (
<Cell key={r.month} fill={r.over ? OVER : ACCENT} />
))}
</Bar>
<Line dataKey="budget" type="stepAfter" stroke={MUTED} strokeWidth={2} strokeDasharray="5 4" dot={{ r: 4, fill: MUTED, stroke: "#fff", strokeWidth: 2 }} connectNulls={false} />
</ComposedChart>
</ResponsiveContainer>
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
"use client";
import { useState, useTransition } from "react";
import { setBudgetAction } from "@/server/actions/budgets";
/** Montant du budget, enregistré à la sortie du champ, applicable à partir du mois affiché. */
export function BudgetInput({ categoryId, month, initial }: { categoryId: string; month: string; initial: string }) {
const [value, setValue] = useState(initial);
const [saved, setSaved] = useState(initial);
const [error, setError] = useState<string | null>(null);
const [pending, start] = useTransition();
const save = () => {
if (value.trim() === saved.trim()) return;
start(async () => {
const r = await setBudgetAction(categoryId, value, month);
if (!r.ok) return setError(r.error);
setError(null);
setSaved(value);
});
};
return (
<span className="inline-flex flex-col items-end">
<span className="relative">
<input
aria-label="Budget mensuel"
inputMode="decimal"
placeholder="—"
value={value}
onChange={(e) => setValue(e.target.value)}
onBlur={save}
onKeyDown={(e) => e.key === "Enter" && (e.currentTarget as HTMLInputElement).blur()}
className={`w-28 rounded-[10px] border bg-white py-1.5 pl-3 pr-7 text-right text-sm outline-none focus:border-accent focus:ring-2 focus:ring-accent/20 ${
error ? "border-neg" : "border-line"
} ${pending ? "opacity-60" : ""}`}
/>
<span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-muted">€</span>
</span>
{error && <span className="text-xs text-neg">{error}</span>}
</span>
);
}
+12
View File
@@ -0,0 +1,12 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireUser } from "@/server/auth";
import { setBudget } from "@/server/services/budgets";
export async function setBudgetAction(categoryId: string, amount: string, fromMonth: string) {
await requireUser();
const result = await setBudget(categoryId, amount, fromMonth);
if (result.ok) revalidatePath("/", "layout");
return result;
}
+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 };
});
}
+61
View File
@@ -0,0 +1,61 @@
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 });
});
});