feat: monthly dashboard

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
YugonitoandClaude Opus 5.5 committed 2026-10-27 18:20:24 +01:00
1 parent 2860f2f776
commit 1e91f38fd3
5 files changed
+529 -3

No files matched your search

+190 -3
View File
@@ -1,6 +1,193 @@
import Link from "next/link";
import { OpList } from "@/components/OpList";
import { SettlementDialog } from "@/components/dashboard/SettlementDialog";
import { Avatar } from "@/components/ui/Avatar";
import { Card, CardLabel } from "@/components/ui/Card";
import { Chip } from "@/components/ui/Chip";
import { MonthSwitcher } from "@/components/ui/MonthSwitcher";
import { formatEuro } from "@/domain/money";
import { currentMonthParis, formatDateFr, todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth"; import { requireUser } from "@/server/auth";
import { loadDashboard } from "@/server/dashboard";
export default async function DashboardPage() { const validMonth = (m?: string) => (m && /^\d{4}-(0[1-9]|1[0-2])$/.test(m) ? m : currentMonthParis());
const user = await requireUser();
return <p>Bonjour {user.firstName}</p>; function Row({ k, v, strong, className = "" }: { k: string; v: React.ReactNode; strong?: boolean; className?: string }) {
return (
<div className={`flex justify-between border-b border-line-soft py-[7px] last:border-0 ${strong ? "pt-2.5" : ""} ${className}`}>
<span className={strong ? "font-semibold" : "text-muted"}>{k}</span>
<span className="tabular font-semibold">{v}</span>
</div>
);
} }
export default async function DashboardPage({ searchParams }: { searchParams: Promise<{ m?: string }> }) {
const user = await requireUser();
const month = validMonth((await searchParams).m);
const today = todayParis();
const d = await loadDashboard(month, user.id, today);
const returnTo = `/?m=${month}`;
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<MonthSwitcher month={month} basePath="/" />
<div className="flex items-center gap-2">
{d.toConfirmCount > 0 && (
<Link href="/recurrents" className="rounded-full bg-warn-soft px-3 py-1.5 text-xs font-semibold text-warn">
{d.toConfirmCount} à confirmer
</Link>
)}
<Link
href={`/nouvelle?retour=${encodeURIComponent(returnTo)}`}
className="hidden rounded-[10px] bg-accent px-4 py-2.5 font-semibold text-white hover:bg-indigo-700 md:inline-block"
>
+ Nouvelle opération
</Link>
</div>
</div>
<div className="grid gap-4 md:grid-cols-3">
<Card>
<CardLabel>Entrées du foyer</CardLabel>
<div className="tabular mt-1.5 text-[28px] font-bold tracking-tight text-pos">{formatEuro(d.totals.income, { sign: true })}</div>
<div className="mt-1 text-[13px] text-muted">
{d.totals.allocatedIncome > 0
? `dont ${formatEuro(d.totals.allocatedIncome)} remboursés par l'employeur`
: d.totals.plannedIncome > 0
? `dont ${formatEuro(d.totals.plannedIncome)} prévus`
: " "}
</div>
</Card>
<Card>
<CardLabel>Sorties du foyer</CardLabel>
<div className="tabular mt-1.5 text-[28px] font-bold tracking-tight text-neg">{formatEuro(-d.totals.expense)}</div>
<div className="mt-1 text-[13px] text-muted">
{d.totals.plannedExpense > 0 ? `dont ${formatEuro(d.totals.plannedExpense)} prévus, pas encore passés` : " "}
</div>
</Card>
<Card>
<CardLabel>Reste</CardLabel>
<div className="tabular mt-1.5 text-[28px] font-bold tracking-tight">{formatEuro(d.totals.remaining, { sign: true })}</div>
<div className="mt-1 text-[13px] text-muted">après les dépenses prévues</div>
</Card>
</div>
{d.balance && (
<div className="flex flex-col gap-3 rounded-card border border-warn-line bg-warn-soft px-[18px] py-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<b className="text-base">{d.balance.text}</b>
<div className="mt-1 text-[13px] text-amber-800">
Cumul des dépenses partagées
{d.lastSettlementDate ? ` depuis le dernier remboursement (${formatDateFr(d.lastSettlementDate).slice(0, 5)})` : ""}
</div>
</div>
<SettlementDialog
users={d.users}
debtorId={d.balance.debtorId}
creditorId={d.balance.creditorId}
amount={d.balance.amount}
today={today}
/>
</div>
)}
<div className="grid gap-4 md:grid-cols-2">
{d.persons.map(({ user: u, flows }) => (
<Card key={u.id}>
<div className="mb-3.5 flex items-center gap-2.5">
<Avatar user={u} />
<b>{u.firstName}</b>
</div>
<Row k="Entrées" v={<span className="text-pos">{formatEuro(flows.income, { sign: true })}</span>} />
<Row k="Payé de sa poche" v={formatEuro(-flows.paidOut)} />
<Row k="Part réelle des charges" v={formatEuro(-flows.chargesShare)} />
<Row
k="Reste"
strong
v={<span className={flows.remaining >= 0 ? "text-pos" : "text-neg"}>{formatEuro(flows.remaining, { sign: true })}</span>}
/>
</Card>
))}
</div>
<div className={`grid gap-4 ${d.netCharges.length > 0 ? "md:grid-cols-2" : ""}`}>
<Card>
<CardLabel className="mb-3.5">Budgets du mois</CardLabel>
{d.budgets.length === 0 ? (
<p className="text-muted">
Aucun budget défini.{" "}
<Link href="/budgets" className="font-semibold text-accent">
Définir des budgets
</Link>
</p>
) : (
<div className="space-y-3.5">
{d.budgets.map((b) => (
<div key={b.categoryId}>
<div className="flex justify-between font-medium">
<span>
{b.emoji} {b.name}
</span>
<span className={`tabular ${b.over ? "text-neg" : "text-muted"}`}>
{formatEuro(b.actual)} / {formatEuro(b.budget)}
</span>
</div>
<div className="mt-1.5 h-2 overflow-hidden rounded-full bg-line-soft">
<div
className={`h-full rounded-full ${b.over ? "bg-neg" : "bg-accent"}`}
style={{ width: `${Math.min(100, b.budget ? (b.actual / b.budget) * 100 : 100)}%` }}
/>
</div>
</div>
))}
</div>
)}
</Card>
{d.netCharges.length > 0 && (
<Card>
<CardLabel className="mb-1.5">Charges nettes</CardLabel>
{d.netCharges.map((c) => {
const full = d.users.find((u) => c.split[u.id] === 10000);
return (
<div key={c.id} className="flex items-center justify-between border-b border-line-soft py-2.5 last:border-0">
<div>
<b>{c.label}</b>
<div className="tabular mt-0.5 text-[13px] text-muted">
{formatEuro(c.gross)} − {formatEuro(c.reimbursed)} remboursés
</div>
</div>
<div className="text-right">
<b className="tabular">{formatEuro(c.net)}</b>
<div>
{full ? (
<Chip color={full.color}>{full.firstName} 100 %</Chip>
) : (
<Chip tone="split">{d.users.map((u) => formatEuro(Math.round((c.net * (c.split[u.id] ?? 0)) / 10000))).join(" / ")}</Chip>
)}
</div>
</div>
</div>
);
})}
</Card>
)}
</div>
<Card>
<div className="mb-1.5 flex items-center justify-between">
<CardLabel>Dernières opérations</CardLabel>
<Link href={`/operations?m=${month}`} className="text-[13px] font-semibold text-accent">
Tout voir
</Link>
</div>
{d.recent.length === 0 ? (
<p className="py-4 text-muted">Aucune opération ce mois-ci.</p>
) : (
<OpList ops={d.recent} ctx={d} returnTo={returnTo} />
)}
</Card>
</div>
);
}
+74
View File
@@ -0,0 +1,74 @@
import Link from "next/link";
import { bpToPercentLabel } from "@/domain/money";
import type { Op } from "@/domain/types";
import { formatDateFr } from "@/lib/dates";
import { Amount } from "./ui/Amount";
import { Chip } from "./ui/Chip";
export interface OpListContext {
users: { id: string; firstName: string; color: string }[];
categories: Record<string, { name: string; emoji: string }>;
chargeLabels: Record<string, string>;
}
function splitLabel(op: Op, users: OpListContext["users"]) {
const full = users.find((u) => op.split[u.id] === 10000);
if (full) return null;
return users.map((u) => bpToPercentLabel(op.split[u.id] ?? 0)).join("/");
}
function Chips({ op, ctx }: { op: Op; ctx: OpListContext }) {
const account = ctx.users.find((u) => u.id === op.accountUserId);
const fullUser = ctx.users.find((u) => op.split[u.id] === 10000);
const split = splitLabel(op, ctx.users);
const target = op.allocatedToRecurringId ?? op.allocatedToOperationId;
return (
<div className="flex flex-wrap gap-1">
{op.status === "PLANNED" && <Chip tone="planned">prévue</Chip>}
{account && (
<Chip color={account.color}>
{op.kind === "EXPENSE" ? "payé par" : "reçu par"} {account.firstName}
</Chip>
)}
{split && <Chip tone="split">{split}</Chip>}
{!split && fullUser && fullUser.id !== op.accountUserId && <Chip color={fullUser.color}>pour {fullUser.firstName}</Chip>}
{target && <Chip tone="link">↳ {ctx.chargeLabels[target] ?? "charge"}</Chip>}
</div>
);
}
/** Liste d'opérations : tableau sur ordinateur, cartes sur mobile. Chaque ligne ouvre l'édition. */
export function OpList({ ops, ctx, returnTo }: { ops: Op[]; ctx: OpListContext; returnTo: string }) {
const href = (op: Op) => `/operations/${op.id}?retour=${encodeURIComponent(returnTo)}`;
return (
<div className="divide-y divide-line-soft">
{ops.map((op) => {
const cat = ctx.categories[op.categoryId];
return (
<Link
key={op.id}
href={href(op)}
className={`flex items-center gap-3 py-2.5 hover:bg-page/60 ${op.status === "PLANNED" ? "opacity-65" : ""}`}
>
<span className="hidden w-12 shrink-0 text-muted md:block">{formatDateFr(op.date).slice(0, 5)}</span>
<span className="grid h-[30px] w-[30px] shrink-0 place-items-center rounded-lg bg-gray-100 text-[15px]">{cat?.emoji}</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold">{op.label}</span>
<span className="block text-[13px] text-muted">
<span className="md:hidden">{formatDateFr(op.date).slice(0, 5)} · </span>
{cat?.name}
</span>
<span className="mt-1 block md:hidden">
<Chips op={op} ctx={ctx} />
</span>
</span>
<span className="hidden md:block">
<Chips op={op} ctx={ctx} />
</span>
<Amount cents={op.amount} kind={op.kind} className="w-28 shrink-0 text-right" />
</Link>
);
})}
</div>
);
}
@@ -0,0 +1,87 @@
"use client";
import { useState, useTransition } from "react";
import { decimalFromCents } from "@/domain/money";
import { saveSettlementAction } from "@/server/actions/operations";
import { Button } from "../ui/Button";
import { Card } from "../ui/Card";
import { Field, FormError, Input, Select } from "../ui/Field";
export function SettlementDialog({
users,
debtorId,
creditorId,
amount,
today,
}: {
users: { id: string; firstName: string }[];
debtorId?: string;
creditorId?: string;
amount?: number;
today: string;
}) {
const [open, setOpen] = useState(false);
const [from, setFrom] = useState(debtorId ?? users[1]?.id ?? "");
const [to, setTo] = useState(creditorId ?? users[0]?.id ?? "");
const [value, setValue] = useState(amount ? decimalFromCents(amount).replace(".", ",") : "");
const [date, setDate] = useState(today);
const [error, setError] = useState<string | null>(null);
const [pending, startTransition] = useTransition();
const submit = () =>
startTransition(async () => {
const r = await saveSettlementAction({ fromUserId: from, toUserId: to, amount: value, date });
if (!r.ok) return setError(r.error);
setOpen(false);
});
return (
<>
<Button variant="ghost" onClick={() => setOpen(true)} className="shrink-0">
Enregistrer un remboursement
</Button>
{open && (
<div className="fixed inset-0 z-50 grid place-items-center bg-black/30 p-4" onClick={() => setOpen(false)}>
<Card className="w-full max-w-sm space-y-4 p-5 shadow-xl" onClick={(e) => e.stopPropagation()}>
<h2 className="text-lg font-bold">Remboursement entre vous</h2>
<div className="grid grid-cols-2 gap-3">
<Field label="De">
<Select value={from} onChange={(e) => setFrom(e.target.value)}>
{users.map((u) => (
<option key={u.id} value={u.id}>
{u.firstName}
</option>
))}
</Select>
</Field>
<Field label="À">
<Select value={to} onChange={(e) => setTo(e.target.value)}>
{users.map((u) => (
<option key={u.id} value={u.id}>
{u.firstName}
</option>
))}
</Select>
</Field>
</div>
<Field label="Montant (€)">
<Input inputMode="decimal" value={value} onChange={(e) => setValue(e.target.value)} />
</Field>
<Field label="Date">
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
</Field>
<FormError message={error} />
<div className="flex gap-3">
<Button variant="ghost" onClick={() => setOpen(false)} className="flex-1">
Annuler
</Button>
<Button onClick={submit} disabled={pending} className="flex-1">
Enregistrer
</Button>
</div>
</Card>
</div>
)}
</>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { computeBalances, describeBalance } from "@/domain/balance";
import { formatEuro, centsFromDecimal } from "@/domain/money";
import {
budgetForMonth,
budgetStatus,
householdTotals,
netCharges,
personFlows,
type BudgetLine,
type ChargeRef,
type HouseholdTotals,
type NetCharge,
type PersonFlows,
} from "@/domain/monthly";
import type { Op } from "@/domain/types";
import { fromIsoDate, todayParis } from "@/lib/dates";
import { prisma } from "./db";
import { getAllActualOps, getCategories, getOpsForMonth, getRecurringDefs, getSettlements, getUsers, type UserLite } from "./repo";
export interface DashboardData {
users: UserLite[];
totals: HouseholdTotals;
persons: { user: UserLite; flows: PersonFlows }[];
balance: { text: string; debtorId?: string; creditorId?: string; amount?: number } | null;
lastSettlementDate: string | null;
budgets: (BudgetLine & { name: string; emoji: string })[];
netCharges: NetCharge[];
recent: Op[];
toConfirmCount: number;
categories: Record<string, { name: string; emoji: string }>;
chargeLabels: Record<string, string>;
}
export async function loadDashboard(month: string, viewerId: string, today: string = todayParis()): Promise<DashboardData> {
const [users, monthOps, actualOps, settlements, recurrings, budgetRows, categories, toConfirmCount] = await Promise.all([
getUsers(),
getOpsForMonth(month),
getAllActualOps(),
getSettlements(),
getRecurringDefs(),
prisma.budget.findMany(),
getCategories(undefined, true),
prisma.operation.count({ where: { status: "PLANNED", date: { lte: fromIsoDate(today) } } }),
]);
const userIds = users.map((u) => u.id);
const name = (id: string) => users.find((u) => u.id === id)?.firstName ?? "?";
const described = describeBalance(computeBalances(actualOps, settlements, userIds));
let balance: DashboardData["balance"] = { text: "Vous êtes à l'équilibre" };
if (described) {
const amount = formatEuro(described.amount);
let text = `${name(described.debtor)} doit ${amount} à ${name(described.creditor)}`;
if (viewerId === described.creditor) text = `${name(described.debtor)} te doit ${amount}`;
if (viewerId === described.debtor) text = `Tu dois ${amount} à ${name(described.creditor)}`;
balance = { text, debtorId: described.debtor, creditorId: described.creditor, amount: described.amount };
}
const categoryMap = Object.fromEntries(categories.map((c) => [c.id, { name: c.name, emoji: c.emoji }]));
const budgets = budgetStatus(
monthOps,
month,
budgetForMonth(
budgetRows.map((b) => ({ ...b, monthlyAmount: centsFromDecimal(b.monthlyAmount) })),
month,
),
).map((b) => ({ ...b, ...(categoryMap[b.categoryId] ?? { name: "?", emoji: "" }) }));
const opTargets = new Set(monthOps.map((o) => o.allocatedToOperationId).filter((id): id is string => id !== null));
const charges: ChargeRef[] = [
...recurrings.filter((r) => r.kind === "EXPENSE").map((r) => ({ id: r.id, label: r.label, kind: "recurring" as const, split: r.split })),
...monthOps.filter((o) => opTargets.has(o.id)).map((o) => ({ id: o.id, label: o.label, kind: "operation" as const, split: o.split })),
];
const chargeLabels = Object.fromEntries([
...recurrings.map((r) => [r.id, r.label]),
...monthOps.map((o) => [o.id, o.label]),
]);
return {
users,
totals: householdTotals(monthOps, month),
persons: users.map((user) => ({ user, flows: personFlows(monthOps, month, user.id) })),
balance,
lastSettlementDate: settlements[0]?.date ?? null,
budgets,
netCharges: netCharges(monthOps, month, charges),
recent: monthOps.filter((o) => o.status !== "SKIPPED").slice(0, 8),
toConfirmCount,
categories: categoryMap,
chargeLabels,
};
}
+87
View File
@@ -0,0 +1,87 @@
import { beforeEach, describe, expect, it } from "vitest";
import { formatEuro } from "@/domain/money";
import { loadDashboard } from "@/server/dashboard";
import { prisma } from "@/server/db";
import { saveOperation } from "@/server/services/operations";
import { categoryId, makeUsers, resetDb } from "./helpers";
let H: string;
let C: string;
async function add(input: Parameters<typeof saveOperation>[0]) {
const r = await saveOperation(input, H);
if (!r.ok) throw new Error(r.error);
return r.id;
}
beforeEach(async () => {
await resetDb();
const users = await makeUsers();
H = users.h.id;
C = users.c.id;
const half = { [H]: 5000, [C]: 5000 };
const allH = { [H]: 10000, [C]: 0 };
const base = { status: "ACTUAL" as const, date: "2026-10-15" };
await add({ ...base, kind: "INCOME", amount: "3000", label: "Salaire", categoryId: await categoryId("Salaire"), accountUserId: H, split: allH, date: "2026-10-25" });
await add({ ...base, kind: "INCOME", amount: "2000", label: "Salaire", categoryId: await categoryId("Salaire"), accountUserId: C, split: { [H]: 0, [C]: 10000 }, date: "2026-10-25" });
await add({
...base,
kind: "EXPENSE",
amount: "1000",
label: "Loyer",
categoryId: await categoryId("Logement"),
accountUserId: H,
split: half,
date: "2026-10-05",
makeRecurring: { frequency: "MONTHLY", endDate: null },
});
const rent = await prisma.recurring.findFirstOrThrow();
await add({
...base,
kind: "INCOME",
amount: "200",
label: "Part loyer employeur",
categoryId: await categoryId("Remboursement employeur"),
accountUserId: H,
split: half,
allocatedToRecurringId: rent.id,
allocationMode: "REDUCE_SHARED",
});
await add({ ...base, kind: "EXPENSE", amount: "86,40", label: "Carrefour", categoryId: await categoryId("Courses"), accountUserId: C, split: half, date: "2026-10-27" });
await add({ ...base, kind: "EXPENSE", amount: "350", label: "Révision", categoryId: await categoryId("Auto"), accountUserId: H, split: allH, status: "PLANNED", date: "2026-10-30" });
await prisma.budget.create({ data: { categoryId: await categoryId("Courses"), monthlyAmount: "400", startMonth: "2026-01" } });
});
describe("loadDashboard", () => {
it("phrases the balance from the viewer's point of view", async () => {
// H : loyer +500, employeur −100, courses payées par C −43,20 = 356,80 €
expect((await loadDashboard("2026-10", H, "2026-10-27")).balance?.text).toBe(`C te doit ${formatEuro(35680)}`);
expect((await loadDashboard("2026-10", C, "2026-10-27")).balance?.text).toBe(`Tu dois ${formatEuro(35680)} à H`);
});
it("assembles flows, totals, budgets, net charges and recent operations", async () => {
const d = await loadDashboard("2026-10", H, "2026-10-27");
expect(d.persons.map((p) => p.user.firstName)).toEqual(["H", "C"]);
// H : revenus propres 3000 − (500 + 43,20 − 100) = 2556,80
expect(d.persons[0].flows.remaining).toBe(255680);
expect(d.totals.plannedExpense).toBe(35000);
expect(d.budgets).toEqual([
expect.objectContaining({ name: "Courses", emoji: "🛒", budget: 40000, actual: 8640, over: false }),
]);
expect(d.netCharges).toEqual([expect.objectContaining({ label: "Loyer", gross: 100000, reimbursed: 20000, net: 80000 })]);
expect(d.recent[0].label).toBe("Révision");
expect(d.recent.length).toBeLessThanOrEqual(8);
expect(d.toConfirmCount).toBe(0);
expect((await loadDashboard("2026-10", H, "2026-10-31")).toConfirmCount).toBe(1);
});
it("reports a balanced household", async () => {
await prisma.settlement.create({
data: { fromUserId: C, toUserId: H, amount: "356.80", date: new Date("2026-10-28T00:00:00Z") },
});
const d = await loadDashboard("2026-10", H, "2026-10-28");
expect(d.balance?.text).toBe("Vous êtes à l'équilibre");
expect(d.lastSettlementDate).toBe("2026-10-28");
});
});