Files
hcl-finances-manager/src/app/(app)/recurrents/page.tsx
T
2026-10-27 18:25:40 +01:00

146 lines
6.2 KiB
TypeScript

import Link from "next/link";
import { OpList } from "@/components/OpList";
import { RecurringActions } from "@/components/recurrents/RecurringActions";
import { ToConfirmRow } from "@/components/recurrents/ToConfirmRow";
import { Amount } from "@/components/ui/Amount";
import { Card, CardLabel } from "@/components/ui/Card";
import { Chip } from "@/components/ui/Chip";
import { bpToPercentLabel } from "@/domain/money";
import { occurrenceDates } from "@/domain/recurrence";
import { addMonths, formatDateFr, fromIsoDate, monthOf, todayParis } from "@/lib/dates";
import { requireUser } from "@/server/auth";
import { prisma } from "@/server/db";
import { toOp } from "@/server/mappers";
import { getCategories, getRecurringDefs, getUsers } from "@/server/repo";
const FREQ = { MONTHLY: "Mensuel", QUARTERLY: "Trimestriel", YEARLY: "Annuel" } as const;
export default async function RecurrentsPage() {
await requireUser();
const today = todayParis();
const in60 = new Date(fromIsoDate(today).getTime() + 60 * 86400000);
const [users, categories, defs, loanRecurrings, plannedRows] = await Promise.all([
getUsers(),
getCategories(undefined, true),
getRecurringDefs(),
prisma.recurring.findMany({ where: { loanId: { not: null } }, select: { id: true } }),
prisma.operation.findMany({
where: { status: "PLANNED", date: { lte: in60 } },
include: { splits: true },
orderBy: { date: "asc" },
}),
]);
const planned = plannedRows.map(toOp);
const toConfirm = planned.filter((o) => o.date <= today);
const upcoming = planned.filter((o) => o.date > today);
const cat = Object.fromEntries(categories.map((c) => [c.id, { name: c.name, emoji: c.emoji }]));
const person = (id: string) => users.find((u) => u.id === id);
const fromLoan = new Set(loanRecurrings.map((l) => l.id));
const labels = Object.fromEntries(defs.map((d) => [d.id, d.label]));
const ctx = { users, categories: cat, chargeLabels: labels };
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-xl font-bold md:text-[22px]">Récurrents & prévu</h1>
<div className="flex gap-2">
<Link href="/nouvelle?prevue=1&retour=%2Frecurrents" className="rounded-[10px] border border-line bg-white px-4 py-2.5 font-semibold">
+ Dépense prévue
</Link>
<Link href="/recurrents/nouveau" className="rounded-[10px] bg-accent px-4 py-2.5 font-semibold text-white hover:bg-indigo-700">
+ Récurrent
</Link>
</div>
</div>
<Card className={toConfirm.length ? "border-warn-line" : ""}>
<CardLabel className="mb-1 flex items-center gap-2">
À confirmer {toConfirm.length > 0 && <Chip tone="planned">{toConfirm.length}</Chip>}
</CardLabel>
{toConfirm.length === 0 ? (
<p className="py-2 text-muted">Rien à confirmer, tout est à jour ✓</p>
) : (
toConfirm.map((o) => (
<ToConfirmRow
key={o.id}
op={{
id: o.id,
label: o.label,
emoji: cat[o.categoryId]?.emoji ?? "",
amount: o.amount,
date: o.date,
kind: o.kind,
who: person(o.accountUserId)?.firstName ?? "?",
}}
/>
))
)}
</Card>
<Card>
<CardLabel className="mb-1">À venir (60 jours)</CardLabel>
{upcoming.length === 0 ? (
<p className="py-2 text-muted">Aucune opération prévue.</p>
) : (
<OpList ops={upcoming} ctx={ctx} returnTo="/recurrents" />
)}
</Card>
<div>
<CardLabel className="mb-2 px-1">Modèles récurrents</CardLabel>
{defs.length === 0 && (
<Card>
<p className="text-muted">Aucun récurrent. Ajoutez le loyer, les salaires, les abonnements…</p>
</Card>
)}
<div className="grid gap-3 md:grid-cols-2">
{defs.map((d) => {
const next = occurrenceDates(d, monthOf(today), addMonths(monthOf(today), 12)).find((x) => x >= today);
const account = person(d.accountUserId);
const full = users.find((u) => d.split[u.id] === 10000);
let status = next ? ` · prochaine le ${formatDateFr(next)}` : " · terminé";
if (d.paused) status = " · en pause";
return (
<Card key={d.id} className={d.paused ? "opacity-60" : ""}>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<b className="block truncate">
{cat[d.categoryId]?.emoji} {d.label}
</b>
<div className="text-[13px] text-muted">
{FREQ[d.frequency]} · le {d.dayOfMonth}
{status}
</div>
</div>
<Amount cents={d.amount} kind={d.kind} />
</div>
<div className="mt-2 flex flex-wrap gap-1">
{account && (
<Chip color={account.color}>
{d.kind === "EXPENSE" ? "payé par" : "reçu par"} {account.firstName}
</Chip>
)}
{d.kind === "EXPENSE" && !full && (
<Chip tone="split">{users.map((u) => bpToPercentLabel(d.split[u.id] ?? 0)).join("/")}</Chip>
)}
{d.kind === "EXPENSE" && full && full.id !== d.accountUserId && <Chip color={full.color}>pour {full.firstName}</Chip>}
{d.allocatedToRecurringId && <Chip tone="link">↳ {labels[d.allocatedToRecurringId]}</Chip>}
</div>
<div className="mt-3 border-t border-line-soft pt-2">
{fromLoan.has(d.id) ? (
<Link href="/credits" className="text-[13px] font-semibold text-muted">
Géré depuis Crédits →
</Link>
) : (
<RecurringActions id={d.id} paused={d.paused} today={today} />
)}
</div>
</Card>
);
})}
</div>
</div>
</div>
);
}