feat: recurring templates, planned and to-confirm lists
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
63620f8c52
commit
bfaa38510b
10 files changed
+792
No files matched your search
@@ -0,0 +1,37 @@
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { FormPage } from "@/components/FormPage";
|
||||
import { RecurringForm } from "@/components/recurrents/RecurringForm";
|
||||
import { decimalFromCents } from "@/domain/money";
|
||||
import { todayParis } from "@/lib/dates";
|
||||
import { requireUser } from "@/server/auth";
|
||||
import { prisma } from "@/server/db";
|
||||
import { getFormData, getRecurringDefs } from "@/server/repo";
|
||||
|
||||
export default async function EditRecurringPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { id } = await params;
|
||||
const today = todayParis();
|
||||
const [data, defs, row] = await Promise.all([
|
||||
getFormData(today),
|
||||
getRecurringDefs(),
|
||||
prisma.recurring.findUnique({ where: { id }, select: { loanId: true } }),
|
||||
]);
|
||||
const def = defs.find((d) => d.id === id);
|
||||
if (!def || !row) notFound();
|
||||
if (row.loanId) redirect(`/credits/${row.loanId}`);
|
||||
const targets = defs.filter((d) => d.kind === "EXPENSE").map((d) => ({ id: d.id, label: d.label, split: d.split }));
|
||||
return (
|
||||
<FormPage title="Modifier le récurrent" back="/recurrents">
|
||||
<p className="mb-4 rounded-[10px] bg-accent-soft px-3 py-2 text-[13px] text-accent">
|
||||
Les changements s'appliquent aux prochaines échéances. Les opérations déjà passées ne bougent pas.
|
||||
</p>
|
||||
<RecurringForm
|
||||
{...data}
|
||||
targets={targets}
|
||||
currentUserId={user.id}
|
||||
today={today}
|
||||
initial={{ ...def, amount: decimalFromCents(def.amount).replace(".", ",") }}
|
||||
/>
|
||||
</FormPage>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { FormPage } from "@/components/FormPage";
|
||||
import { RecurringForm } from "@/components/recurrents/RecurringForm";
|
||||
import { todayParis } from "@/lib/dates";
|
||||
import { requireUser } from "@/server/auth";
|
||||
import { getFormData, getRecurringDefs } from "@/server/repo";
|
||||
|
||||
export default async function NewRecurringPage() {
|
||||
const user = await requireUser();
|
||||
const today = todayParis();
|
||||
const [data, defs] = await Promise.all([getFormData(today), getRecurringDefs()]);
|
||||
const targets = defs.filter((d) => d.kind === "EXPENSE").map((d) => ({ id: d.id, label: d.label, split: d.split }));
|
||||
return (
|
||||
<FormPage title="Nouveau récurrent" back="/recurrents">
|
||||
<RecurringForm {...data} targets={targets} currentUserId={user.id} today={today} />
|
||||
</FormPage>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { bpToPercentLabel, fullSplit, percentToBp } from "@/domain/money";
|
||||
import type { Split } from "@/domain/types";
|
||||
import { Input } from "./ui/Field";
|
||||
import { Pills } from "./ui/Pills";
|
||||
|
||||
type Choice = "default" | `full:${string}` | "custom";
|
||||
|
||||
const same = (a: Split, b: Split) => Object.keys({ ...a, ...b }).every((k) => (a[k] ?? 0) === (b[k] ?? 0));
|
||||
|
||||
/** Choix de répartition : défaut du foyer, 100 % pour une personne, ou pourcentages libres. */
|
||||
export function SplitPicker({
|
||||
users,
|
||||
defaultSplit,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
users: { id: string; firstName: string }[];
|
||||
defaultSplit: Split;
|
||||
value: Split;
|
||||
onChange: (s: Split) => void;
|
||||
}) {
|
||||
const ids = users.map((u) => u.id);
|
||||
const [choice, setChoice] = useState<Choice>(() => {
|
||||
if (same(value, defaultSplit)) return "default";
|
||||
const full = ids.find((id) => value[id] === 10000);
|
||||
return full ? `full:${full}` : "custom";
|
||||
});
|
||||
const [custom, setCustom] = useState<Record<string, string>>(() =>
|
||||
Object.fromEntries(ids.map((id) => [id, bpToPercentLabel(value[id] ?? 0)])),
|
||||
);
|
||||
|
||||
const fromCustom = (c: Record<string, string>): Split => Object.fromEntries(ids.map((id) => [id, percentToBp(c[id] ?? "") ?? -1]));
|
||||
const pick = (c: Choice) => {
|
||||
setChoice(c);
|
||||
if (c === "default") onChange(defaultSplit);
|
||||
else if (c === "custom") onChange(fromCustom(custom));
|
||||
else onChange(fullSplit(c.slice(5), ids));
|
||||
};
|
||||
const total = Object.values(fromCustom(custom)).reduce((t, v) => t + Math.max(v, 0), 0);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Pills
|
||||
options={[
|
||||
{ value: "default" as Choice, label: ids.map((id) => bpToPercentLabel(defaultSplit[id] ?? 0)).join(" / ") },
|
||||
...users.map((u) => ({ value: `full:${u.id}` as Choice, label: `100 % ${u.firstName}` })),
|
||||
{ value: "custom" as Choice, label: "Perso…" },
|
||||
]}
|
||||
value={choice}
|
||||
onChange={pick}
|
||||
/>
|
||||
{choice === "custom" && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-[10px] border border-line p-3">
|
||||
{users.map((u) => (
|
||||
<label key={u.id} className="flex items-center gap-2">
|
||||
<span className="font-medium">{u.firstName}</span>
|
||||
<Input
|
||||
inputMode="decimal"
|
||||
className="w-20"
|
||||
value={custom[u.id] ?? ""}
|
||||
onChange={(e) => {
|
||||
const next = { ...custom, [u.id]: e.target.value };
|
||||
setCustom(next);
|
||||
onChange(fromCustom(next));
|
||||
}}
|
||||
/>
|
||||
%
|
||||
</label>
|
||||
))}
|
||||
<span className={`text-xs font-semibold ${total === 10000 ? "text-pos" : "text-neg"}`}>Total {bpToPercentLabel(total)} %</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useTransition } from "react";
|
||||
import { deleteRecurringAction, endRecurringAction, setRecurringPausedAction } from "@/server/actions/recurrings";
|
||||
|
||||
const btn = "rounded-lg px-2.5 py-1.5 text-[13px] font-semibold hover:bg-page disabled:opacity-50";
|
||||
|
||||
export function RecurringActions({ id, paused, today }: { id: string; paused: boolean; today: string }) {
|
||||
const [pending, start] = useTransition();
|
||||
const run = (fn: () => Promise<{ ok: boolean; error?: string }>) =>
|
||||
start(async () => {
|
||||
const r = await fn();
|
||||
if (!r.ok && r.error) alert(r.error);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<Link href={`/recurrents/${id}`} className={`${btn} text-accent`}>
|
||||
Modifier
|
||||
</Link>
|
||||
<button className={`${btn} text-muted`} disabled={pending} onClick={() => run(() => setRecurringPausedAction(id, !paused))}>
|
||||
{paused ? "Reprendre" : "Pause"}
|
||||
</button>
|
||||
<button
|
||||
className={`${btn} text-muted`}
|
||||
disabled={pending}
|
||||
onClick={() => {
|
||||
const date = prompt("Dernière échéance le (AAAA-MM-JJ) :", today);
|
||||
if (date) run(() => endRecurringAction(id, date));
|
||||
}}
|
||||
>
|
||||
Terminer
|
||||
</button>
|
||||
<button
|
||||
className={`${btn} text-neg`}
|
||||
disabled={pending}
|
||||
onClick={() => {
|
||||
if (confirm("Supprimer ce récurrent ? Les opérations déjà passées sont conservées.")) run(() => deleteRecurringAction(id));
|
||||
}}
|
||||
>
|
||||
Supprimer
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
import { fullSplit } from "@/domain/money";
|
||||
import type { AllocationMode, Frequency, OpKind, Split } from "@/domain/types";
|
||||
import { saveRecurringAction } from "@/server/actions/recurrings";
|
||||
import type { FormCategory, FormUser } from "../OperationForm";
|
||||
import { SplitPicker } from "../SplitPicker";
|
||||
import { Button } from "../ui/Button";
|
||||
import { Field, FormError, Input, Select } from "../ui/Field";
|
||||
import { Pills } from "../ui/Pills";
|
||||
|
||||
export interface RecurringInitial {
|
||||
id: string;
|
||||
kind: OpKind;
|
||||
amount: string;
|
||||
label: string;
|
||||
categoryId: string;
|
||||
accountUserId: string;
|
||||
split: Split;
|
||||
frequency: Frequency;
|
||||
dayOfMonth: number;
|
||||
startDate: string;
|
||||
endDate: string | null;
|
||||
allocatedToRecurringId: string | null;
|
||||
allocationMode: AllocationMode | null;
|
||||
}
|
||||
|
||||
export function RecurringForm({
|
||||
users,
|
||||
categories,
|
||||
defaultSplit,
|
||||
currentUserId,
|
||||
today,
|
||||
targets,
|
||||
initial,
|
||||
}: {
|
||||
users: FormUser[];
|
||||
categories: FormCategory[];
|
||||
defaultSplit: Split;
|
||||
currentUserId: string;
|
||||
today: string;
|
||||
targets: { id: string; label: string; split: Split }[];
|
||||
initial?: RecurringInitial;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const ids = users.map((u) => u.id);
|
||||
const [pending, startTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [kind, setKind] = useState<OpKind>(initial?.kind ?? "EXPENSE");
|
||||
const [amount, setAmount] = useState(initial?.amount ?? "");
|
||||
const [label, setLabel] = useState(initial?.label ?? "");
|
||||
const [categoryId, setCategoryId] = useState(initial?.categoryId ?? "");
|
||||
const [accountUserId, setAccountUserId] = useState(initial?.accountUserId ?? currentUserId);
|
||||
const [split, setSplit] = useState<Split>(initial?.split ?? defaultSplit);
|
||||
const [frequency, setFrequency] = useState<Frequency>(initial?.frequency ?? "MONTHLY");
|
||||
const [startDate, setStartDate] = useState(initial?.startDate ?? today);
|
||||
const [dayOfMonth, setDayOfMonth] = useState(String(initial?.dayOfMonth ?? Number(today.slice(8, 10))));
|
||||
const [endDate, setEndDate] = useState(initial?.endDate ?? "");
|
||||
const [target, setTarget] = useState(initial?.allocatedToRecurringId ?? "");
|
||||
const [mode, setMode] = useState<AllocationMode>(initial?.allocationMode ?? "REDUCE_SHARED");
|
||||
|
||||
const allocated = kind === "INCOME" && target !== "";
|
||||
const targetOptions = targets.filter((t) => t.id !== initial?.id);
|
||||
|
||||
const submit = () => {
|
||||
setError(null);
|
||||
const effectiveSplit =
|
||||
kind === "INCOME" && !(allocated && mode === "CUSTOM") ? fullSplit(accountUserId, ids) : split;
|
||||
startTransition(async () => {
|
||||
const r = await saveRecurringAction({
|
||||
id: initial?.id,
|
||||
kind,
|
||||
amount,
|
||||
label,
|
||||
categoryId,
|
||||
accountUserId,
|
||||
split: effectiveSplit,
|
||||
frequency,
|
||||
dayOfMonth: Number(dayOfMonth),
|
||||
startDate,
|
||||
endDate: endDate || null,
|
||||
allocatedToRecurringId: allocated ? target : null,
|
||||
allocationMode: allocated ? mode : null,
|
||||
});
|
||||
if (!r.ok) return setError(r.error);
|
||||
router.push("/recurrents");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
<Pills
|
||||
options={[
|
||||
{ value: "EXPENSE" as OpKind, label: "Dépense" },
|
||||
{ value: "INCOME" as OpKind, label: "Entrée" },
|
||||
]}
|
||||
value={kind}
|
||||
onChange={(k) => {
|
||||
setKind(k);
|
||||
setCategoryId("");
|
||||
}}
|
||||
/>
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_140px]">
|
||||
<Field label="Libellé">
|
||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="Loyer, salaire, Netflix…" />
|
||||
</Field>
|
||||
<Field label="Montant (€)">
|
||||
<Input inputMode="decimal" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="0,00" />
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="Catégorie">
|
||||
<Select value={categoryId} onChange={(e) => setCategoryId(e.target.value)}>
|
||||
<option value="">Choisir…</option>
|
||||
{categories
|
||||
.filter((c) => c.kind === kind)
|
||||
.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.emoji} {c.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold text-muted">{kind === "EXPENSE" ? "Payé par" : "Reçu par"}</div>
|
||||
<Pills options={users.map((u) => ({ value: u.id, label: u.firstName }))} value={accountUserId} onChange={setAccountUserId} />
|
||||
</div>
|
||||
{kind === "EXPENSE" && (
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold text-muted">Répartition</div>
|
||||
<SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} />
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label="Fréquence">
|
||||
<Select value={frequency} onChange={(e) => setFrequency(e.target.value as Frequency)}>
|
||||
<option value="MONTHLY">Mensuelle</option>
|
||||
<option value="QUARTERLY">Trimestrielle</option>
|
||||
<option value="YEARLY">Annuelle</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Jour du mois" hint="31 = dernier jour des mois plus courts">
|
||||
<Input type="number" min={1} max={31} value={dayOfMonth} onChange={(e) => setDayOfMonth(e.target.value)} />
|
||||
</Field>
|
||||
<Field label="À partir du">
|
||||
<Input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Jusqu'au (facultatif)">
|
||||
<Input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
|
||||
</Field>
|
||||
</div>
|
||||
{kind === "INCOME" && (
|
||||
<div className="space-y-3 rounded-card border border-line p-4">
|
||||
<Field label="Affecter à une charge" hint="Ex. IK → crédit voiture, part loyer employeur → loyer">
|
||||
<Select value={target} onChange={(e) => setTarget(e.target.value)}>
|
||||
<option value="">Aucune</option>
|
||||
{targetOptions.map((t) => (
|
||||
<option key={t.id} value={t.id}>
|
||||
{t.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
{allocated && (
|
||||
<>
|
||||
<Pills
|
||||
options={[
|
||||
{ value: "REDUCE_SHARED" as AllocationMode, label: "Réduit la charge pour tous" },
|
||||
{ value: "BENEFICIARY_ONLY" as AllocationMode, label: "Profite au bénéficiaire" },
|
||||
{ value: "CUSTOM" as AllocationMode, label: "Perso" },
|
||||
]}
|
||||
value={mode}
|
||||
onChange={setMode}
|
||||
/>
|
||||
{mode === "CUSTOM" && <SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} />}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<FormError message={error} />
|
||||
<Button type="submit" className="w-full py-3" disabled={pending}>
|
||||
{pending ? "Enregistrement…" : "Enregistrer"}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { decimalFromCents } from "@/domain/money";
|
||||
import type { OpKind } from "@/domain/types";
|
||||
import { formatDateFr } from "@/lib/dates";
|
||||
import { confirmOperationAction, skipOperationAction } from "@/server/actions/operations";
|
||||
import { Button } from "../ui/Button";
|
||||
import { Input } from "../ui/Field";
|
||||
|
||||
export function ToConfirmRow({
|
||||
op,
|
||||
}: {
|
||||
op: { id: string; label: string; emoji: string; amount: number; date: string; kind: OpKind; who: string };
|
||||
}) {
|
||||
const [amount, setAmount] = useState(decimalFromCents(op.amount).replace(".", ","));
|
||||
const [date, setDate] = useState(op.date);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pending, start] = useTransition();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 border-b border-line-soft py-3 last:border-0 md:flex-row md:items-center">
|
||||
<div className="min-w-0 flex-1">
|
||||
<b>
|
||||
{op.emoji} {op.label}
|
||||
</b>
|
||||
<div className="text-[13px] text-muted">
|
||||
prévu le {formatDateFr(op.date)} · {op.kind === "EXPENSE" ? "payé par" : "reçu par"} {op.who}
|
||||
</div>
|
||||
{error && <div className="text-[13px] text-neg">{error}</div>}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input aria-label="Montant" inputMode="decimal" className="w-28" value={amount} onChange={(e) => setAmount(e.target.value)} />
|
||||
<Input aria-label="Date" type="date" className="w-40" value={date} onChange={(e) => setDate(e.target.value)} />
|
||||
<Button
|
||||
disabled={pending}
|
||||
onClick={() =>
|
||||
start(async () => {
|
||||
const r = await confirmOperationAction(op.id, amount, date);
|
||||
setError(r.ok ? null : r.error);
|
||||
})
|
||||
}
|
||||
>
|
||||
Confirmer
|
||||
</Button>
|
||||
<Button variant="ghost" disabled={pending} onClick={() => start(async () => void (await skipOperationAction(op.id)))}>
|
||||
Ignorer
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { requireUser } from "@/server/auth";
|
||||
import * as rec from "@/server/services/recurrings";
|
||||
|
||||
const refresh = () => revalidatePath("/", "layout");
|
||||
|
||||
export async function saveRecurringAction(input: rec.RecurringInput) {
|
||||
await requireUser();
|
||||
const result = await rec.saveRecurring(input);
|
||||
if (result.ok) refresh();
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function setRecurringPausedAction(id: string, paused: boolean) {
|
||||
await requireUser();
|
||||
const result = await rec.setRecurringPaused(id, paused);
|
||||
refresh();
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function endRecurringAction(id: string, endDate: string) {
|
||||
await requireUser();
|
||||
const result = await rec.endRecurring(id, endDate);
|
||||
if (result.ok) refresh();
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function deleteRecurringAction(id: string) {
|
||||
await requireUser();
|
||||
const result = await rec.deleteRecurring(id);
|
||||
if (result.ok) refresh();
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { z } from "zod";
|
||||
import { decimalFromCents, parseEuro, validateSplit } from "@/domain/money";
|
||||
import type { Split } from "@/domain/types";
|
||||
import { fromIsoDate, todayParis } from "@/lib/dates";
|
||||
import { prisma } from "../db";
|
||||
import { splitRows } from "../mappers";
|
||||
import { syncRecurrings } from "../sync";
|
||||
import type { Result } from "./operations";
|
||||
|
||||
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date invalide.");
|
||||
|
||||
const recurringSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
kind: z.enum(["INCOME", "EXPENSE"]),
|
||||
amount: z.string(),
|
||||
label: z.string().trim().min(1, "Le libellé est obligatoire.").max(190),
|
||||
categoryId: z.string().min(1, "Choisissez une catégorie."),
|
||||
accountUserId: z.string().min(1),
|
||||
split: z.record(z.string(), z.number().int()),
|
||||
frequency: z.enum(["MONTHLY", "QUARTERLY", "YEARLY"]),
|
||||
dayOfMonth: z.number().int().min(1, "Jour du mois invalide (1 à 31).").max(31, "Jour du mois invalide (1 à 31)."),
|
||||
startDate: isoDate,
|
||||
endDate: isoDate.nullable(),
|
||||
allocatedToRecurringId: z.string().nullish(),
|
||||
allocationMode: z.enum(["REDUCE_SHARED", "BENEFICIARY_ONLY", "CUSTOM"]).nullish(),
|
||||
});
|
||||
|
||||
export type RecurringInput = z.input<typeof recurringSchema>;
|
||||
|
||||
/** Supprime les occurrences prévues à partir d'une date (les réelles et les prévues passées restent). */
|
||||
async function dropPlannedFrom(recurringId: string, from: string) {
|
||||
await prisma.operation.deleteMany({ where: { recurringId, status: "PLANNED", date: { gte: fromIsoDate(from) } } });
|
||||
}
|
||||
|
||||
export async function saveRecurring(raw: RecurringInput, today: string = todayParis()): Promise<Result<{ id: string }>> {
|
||||
const parsed = recurringSchema.safeParse(raw);
|
||||
if (!parsed.success) return { ok: false, error: parsed.error.issues[0]?.message ?? "Données invalides." };
|
||||
const input = parsed.data;
|
||||
const cents = parseEuro(input.amount);
|
||||
if (cents === null) return { ok: false, error: "Montant invalide." };
|
||||
const splitError = validateSplit(input.split as Split);
|
||||
if (splitError) return { ok: false, error: splitError };
|
||||
if (input.endDate && input.endDate < input.startDate) return { ok: false, error: "La date de fin précède la date de début." };
|
||||
const allocatedTo = input.kind === "INCOME" ? input.allocatedToRecurringId || null : null;
|
||||
if (allocatedTo && allocatedTo === input.id) return { ok: false, error: "Un récurrent ne peut pas s'affecter à lui-même." };
|
||||
|
||||
if (input.id) {
|
||||
const existing = await prisma.recurring.findUnique({ where: { id: input.id } });
|
||||
if (!existing) return { ok: false, error: "Récurrent introuvable." };
|
||||
if (existing.loanId) return { ok: false, error: "Ce récurrent est géré depuis Crédits." };
|
||||
}
|
||||
|
||||
const data = {
|
||||
kind: input.kind,
|
||||
amount: decimalFromCents(cents),
|
||||
label: input.label,
|
||||
categoryId: input.categoryId,
|
||||
accountUserId: input.accountUserId,
|
||||
frequency: input.frequency,
|
||||
dayOfMonth: input.dayOfMonth,
|
||||
startDate: fromIsoDate(input.startDate),
|
||||
endDate: input.endDate ? fromIsoDate(input.endDate) : null,
|
||||
allocatedToRecurringId: allocatedTo,
|
||||
allocationMode: allocatedTo ? (input.allocationMode ?? "REDUCE_SHARED") : null,
|
||||
};
|
||||
|
||||
const id = await prisma.$transaction(async (tx) => {
|
||||
if (input.id) {
|
||||
await tx.recurringSplit.deleteMany({ where: { recurringId: input.id } });
|
||||
await tx.recurring.update({ where: { id: input.id }, data: { ...data, splits: { create: splitRows(input.split as Split) } } });
|
||||
return input.id;
|
||||
}
|
||||
return (await tx.recurring.create({ data: { ...data, splits: { create: splitRows(input.split as Split) } } })).id;
|
||||
});
|
||||
|
||||
await dropPlannedFrom(id, today);
|
||||
await syncRecurrings(today);
|
||||
return { ok: true, id };
|
||||
}
|
||||
|
||||
export async function setRecurringPaused(id: string, paused: boolean, today: string = todayParis()): Promise<Result> {
|
||||
await prisma.recurring.update({ where: { id }, data: { paused } });
|
||||
if (paused) await dropPlannedFrom(id, today);
|
||||
else await syncRecurrings(today);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export async function endRecurring(id: string, endDate: string, today: string = todayParis()): Promise<Result> {
|
||||
if (!isoDate.safeParse(endDate).success) return { ok: false, error: "Date invalide." };
|
||||
await prisma.recurring.update({ where: { id }, data: { endDate: fromIsoDate(endDate) } });
|
||||
await prisma.operation.deleteMany({ where: { recurringId: id, status: "PLANNED", date: { gt: fromIsoDate(endDate) } } });
|
||||
await syncRecurrings(today);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export async function deleteRecurring(id: string, today: string = todayParis()): Promise<Result> {
|
||||
const rec = await prisma.recurring.findUnique({ where: { id } });
|
||||
if (rec?.loanId) return { ok: false, error: "Ce récurrent est géré depuis Crédits." };
|
||||
await dropPlannedFrom(id, today);
|
||||
await prisma.recurring.delete({ where: { id } });
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { fromIsoDate } from "@/lib/dates";
|
||||
import { prisma } from "@/server/db";
|
||||
import { deleteRecurring, endRecurring, saveRecurring, setRecurringPaused, type RecurringInput } from "@/server/services/recurrings";
|
||||
import { categoryId, makeUsers, resetDb } from "./helpers";
|
||||
|
||||
const TODAY = "2026-10-27";
|
||||
let H: string;
|
||||
let C: string;
|
||||
let rentInput: RecurringInput;
|
||||
|
||||
const planned = (recurringId: string) =>
|
||||
prisma.operation.findMany({ where: { recurringId, status: "PLANNED" }, orderBy: { date: "asc" } });
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetDb();
|
||||
const u = await makeUsers();
|
||||
H = u.h.id;
|
||||
C = u.c.id;
|
||||
rentInput = {
|
||||
kind: "EXPENSE",
|
||||
amount: "1000",
|
||||
label: "Loyer",
|
||||
categoryId: await categoryId("Logement"),
|
||||
accountUserId: H,
|
||||
split: { [H]: 5000, [C]: 5000 },
|
||||
frequency: "MONTHLY",
|
||||
dayOfMonth: 5,
|
||||
startDate: "2026-01-05",
|
||||
endDate: null,
|
||||
};
|
||||
});
|
||||
|
||||
describe("saveRecurring", () => {
|
||||
it("creates the template and its planned occurrences", async () => {
|
||||
const r = await saveRecurring(rentInput, TODAY);
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
expect(await planned(r.id)).toHaveLength(12);
|
||||
});
|
||||
|
||||
it("applies an edit to future occurrences only", async () => {
|
||||
const r = await saveRecurring(rentInput, TODAY);
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
await prisma.operation.updateMany({ where: { recurringId: r.id, date: fromIsoDate("2026-10-05") }, data: { status: "ACTUAL" } });
|
||||
await saveRecurring({ ...rentInput, id: r.id, amount: "1050" }, TODAY);
|
||||
const october = await prisma.operation.findFirstOrThrow({ where: { recurringId: r.id, date: fromIsoDate("2026-10-05") } });
|
||||
expect(october.amount.toString()).toBe("1000");
|
||||
const future = await planned(r.id);
|
||||
expect(future[0].date.toISOString().slice(0, 10)).toBe("2026-11-05");
|
||||
expect(future.every((o) => o.amount.toString() === "1050")).toBe(true);
|
||||
});
|
||||
|
||||
it("validates the input", async () => {
|
||||
expect(await saveRecurring({ ...rentInput, amount: "0" }, TODAY)).toEqual({ ok: false, error: "Montant invalide." });
|
||||
expect(await saveRecurring({ ...rentInput, dayOfMonth: 32 }, TODAY)).toEqual({ ok: false, error: "Jour du mois invalide (1 à 31)." });
|
||||
});
|
||||
});
|
||||
|
||||
describe("pause / end / delete", () => {
|
||||
it("pausing removes future occurrences and resuming brings them back", async () => {
|
||||
const r = await saveRecurring(rentInput, TODAY);
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
await prisma.operation.updateMany({ where: { recurringId: r.id, date: fromIsoDate("2026-10-05") }, data: { status: "ACTUAL" } });
|
||||
await setRecurringPaused(r.id, true, TODAY);
|
||||
expect((await planned(r.id)).filter((o) => o.date >= fromIsoDate(TODAY))).toHaveLength(0);
|
||||
await setRecurringPaused(r.id, false, TODAY);
|
||||
expect(await planned(r.id)).toHaveLength(11);
|
||||
});
|
||||
|
||||
it("ending stops occurrences after the end date", async () => {
|
||||
const r = await saveRecurring(rentInput, TODAY);
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
await endRecurring(r.id, "2027-01-31", TODAY);
|
||||
const rest = await planned(r.id);
|
||||
expect(rest[rest.length - 1].date.toISOString().slice(0, 10)).toBe("2027-01-05");
|
||||
});
|
||||
|
||||
it("deleting keeps actual history", async () => {
|
||||
const r = await saveRecurring(rentInput, TODAY);
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
await prisma.operation.updateMany({ where: { recurringId: r.id, date: fromIsoDate("2026-10-05") }, data: { status: "ACTUAL" } });
|
||||
await deleteRecurring(r.id, TODAY);
|
||||
expect(await prisma.recurring.count()).toBe(0);
|
||||
expect(await prisma.operation.count({ where: { status: "ACTUAL" } })).toBe(1);
|
||||
expect(await prisma.operation.count({ where: { status: "PLANNED", date: { gte: fromIsoDate(TODAY) } } })).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user