diff --git a/src/app/(app)/budgets/page.tsx b/src/app/(app)/budgets/page.tsx
new file mode 100644
index 0000000..91fa9dd
--- /dev/null
+++ b/src/app/(app)/budgets/page.tsx
@@ -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 (
+
+
+
+ {totalBudget > 0 && (
+
+ Budgété {formatEuro(totalBudget)} · dépensé{" "}
+ totalBudget ? "text-neg" : "text-ink"}`}>{formatEuro(totalActual)}
+
+ )}
+
+
+
+
+ Budgets mensuels par catégorie
+ Un montant saisi s'applique à partir de ce mois
+
+
+ {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 (
+
+
+ {c.emoji} {c.name}
+
+
+ {budget ? (
+
+ ) : null}
+
+
+ {formatEuro(s.actual)}
+ {s.plannedRemaining > 0 && + {formatEuro(s.plannedRemaining)} prévus}
+
+
+
+ );
+ })}
+
+
+
+ {selected && (
+
+
+
+ {selected.emoji} {selected.name} · 6 derniers mois
+
+
+
+ Réel
+
+
+ Budget
+
+
+
+
+
+ )}
+
+ );
+}
diff --git a/src/components/budgets/BudgetHistoryChart.tsx b/src/components/budgets/BudgetHistoryChart.tsx
new file mode 100644
index 0000000..a366433
--- /dev/null
+++ b/src/components/budgets/BudgetHistoryChart.tsx
@@ -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 (
+
+
+
+
+
+ `${Math.round(v)} €`}
+ />
+ [
+ value === null || value === undefined ? "—" : formatEuro(Math.round(Number(value) * 100)),
+ name === "actual" ? "Réel" : "Budget",
+ ]}
+ contentStyle={{ borderRadius: 10, border: "1px solid #e5e7eb", fontSize: 13 }}
+ />
+
+ {rows.map((r) => (
+ |
+ ))}
+
+
+
+
+
+ );
+}
diff --git a/src/components/budgets/BudgetInput.tsx b/src/components/budgets/BudgetInput.tsx
new file mode 100644
index 0000000..41d941e
--- /dev/null
+++ b/src/components/budgets/BudgetInput.tsx
@@ -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(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 (
+
+
+ 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" : ""}`}
+ />
+ €
+
+ {error && {error}}
+
+ );
+}
diff --git a/src/server/actions/budgets.ts b/src/server/actions/budgets.ts
new file mode 100644
index 0000000..52bc259
--- /dev/null
+++ b/src/server/actions/budgets.ts
@@ -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;
+}
diff --git a/src/server/services/budgets.ts b/src/server/services/budgets.ts
new file mode 100644
index 0000000..f0df15e
--- /dev/null
+++ b/src/server/services/budgets.ts
@@ -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 {
+ 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 };
+ });
+}
diff --git a/tests/server/budgets.test.ts b/tests/server/budgets.test.ts
new file mode 100644
index 0000000..7e014b7
--- /dev/null
+++ b/tests/server/budgets.test.ts
@@ -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 });
+ });
+});