diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index 0ca2a00..6d9c6bb 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -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 { loadDashboard } from "@/server/dashboard"; -export default async function DashboardPage() { - const user = await requireUser(); - return

Bonjour {user.firstName}

; +const validMonth = (m?: string) => (m && /^\d{4}-(0[1-9]|1[0-2])$/.test(m) ? m : currentMonthParis()); + +function Row({ k, v, strong, className = "" }: { k: string; v: React.ReactNode; strong?: boolean; className?: string }) { + return ( +
+ {k} + {v} +
+ ); } + +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 ( +
+
+ +
+ {d.toConfirmCount > 0 && ( + + {d.toConfirmCount} à confirmer + + )} + + + Nouvelle opération + +
+
+ +
+ + Entrées du foyer +
{formatEuro(d.totals.income, { sign: true })}
+
+ {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` + : " "} +
+
+ + Sorties du foyer +
{formatEuro(-d.totals.expense)}
+
+ {d.totals.plannedExpense > 0 ? `dont ${formatEuro(d.totals.plannedExpense)} prévus, pas encore passés` : " "} +
+
+ + Reste +
{formatEuro(d.totals.remaining, { sign: true })}
+
après les dépenses prévues
+
+
+ + {d.balance && ( +
+
+ {d.balance.text} +
+ Cumul des dépenses partagées + {d.lastSettlementDate ? ` depuis le dernier remboursement (${formatDateFr(d.lastSettlementDate).slice(0, 5)})` : ""} +
+
+ +
+ )} + +
+ {d.persons.map(({ user: u, flows }) => ( + +
+ + {u.firstName} +
+ {formatEuro(flows.income, { sign: true })}} /> + + + = 0 ? "text-pos" : "text-neg"}>{formatEuro(flows.remaining, { sign: true })}} + /> +
+ ))} +
+ +
0 ? "md:grid-cols-2" : ""}`}> + + Budgets du mois + {d.budgets.length === 0 ? ( +

+ Aucun budget défini.{" "} + + Définir des budgets + +

+ ) : ( +
+ {d.budgets.map((b) => ( +
+
+ + {b.emoji} {b.name} + + + {formatEuro(b.actual)} / {formatEuro(b.budget)} + +
+
+
+
+
+ ))} +
+ )} + + {d.netCharges.length > 0 && ( + + Charges nettes + {d.netCharges.map((c) => { + const full = d.users.find((u) => c.split[u.id] === 10000); + return ( +
+
+ {c.label} +
+ {formatEuro(c.gross)} − {formatEuro(c.reimbursed)} remboursés +
+
+
+ {formatEuro(c.net)} +
+ {full ? ( + {full.firstName} 100 % + ) : ( + {d.users.map((u) => formatEuro(Math.round((c.net * (c.split[u.id] ?? 0)) / 10000))).join(" / ")} + )} +
+
+
+ ); + })} +
+ )} +
+ + +
+ Dernières opérations + + Tout voir + +
+ {d.recent.length === 0 ? ( +

Aucune opération ce mois-ci.

+ ) : ( + + )} +
+
+ ); +} + diff --git a/src/components/OpList.tsx b/src/components/OpList.tsx new file mode 100644 index 0000000..2a899f4 --- /dev/null +++ b/src/components/OpList.tsx @@ -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; + chargeLabels: Record; +} + +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 ( +
+ {op.status === "PLANNED" && prévue} + {account && ( + + {op.kind === "EXPENSE" ? "payé par" : "reçu par"} {account.firstName} + + )} + {split && {split}} + {!split && fullUser && fullUser.id !== op.accountUserId && pour {fullUser.firstName}} + {target && ↳ {ctx.chargeLabels[target] ?? "charge"}} +
+ ); +} + +/** 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 ( +
+ {ops.map((op) => { + const cat = ctx.categories[op.categoryId]; + return ( + + {formatDateFr(op.date).slice(0, 5)} + {cat?.emoji} + + {op.label} + + {formatDateFr(op.date).slice(0, 5)} · + {cat?.name} + + + + + + + + + + + ); + })} +
+ ); +} diff --git a/src/components/dashboard/SettlementDialog.tsx b/src/components/dashboard/SettlementDialog.tsx new file mode 100644 index 0000000..d19e92e --- /dev/null +++ b/src/components/dashboard/SettlementDialog.tsx @@ -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(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 ( + <> + + {open && ( +
setOpen(false)}> + e.stopPropagation()}> +

Remboursement entre vous

+
+ + + + + + +
+ + setValue(e.target.value)} /> + + + setDate(e.target.value)} /> + + +
+ + +
+
+
+ )} + + ); +} diff --git a/src/server/dashboard.ts b/src/server/dashboard.ts new file mode 100644 index 0000000..cd5814a --- /dev/null +++ b/src/server/dashboard.ts @@ -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; + chargeLabels: Record; +} + +export async function loadDashboard(month: string, viewerId: string, today: string = todayParis()): Promise { + 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, + }; +} diff --git a/tests/server/dashboard.test.ts b/tests/server/dashboard.test.ts new file mode 100644 index 0000000..2ff6074 --- /dev/null +++ b/tests/server/dashboard.test.ts @@ -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[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"); + }); +});