From bfaa38510b773f7fcc25c0809fb35dc9bd5f6b75 Mon Sep 17 00:00:00 2001 From: Yugonito Date: Tue, 27 Oct 2026 18:25:40 +0100 Subject: [PATCH] feat: recurring templates, planned and to-confirm lists Co-Authored-By: Claude Opus 5.5 --- src/app/(app)/recurrents/[id]/page.tsx | 37 ++++ src/app/(app)/recurrents/nouveau/page.tsx | 17 ++ src/app/(app)/recurrents/page.tsx | 145 +++++++++++++ src/components/SplitPicker.tsx | 78 +++++++ .../recurrents/RecurringActions.tsx | 46 +++++ src/components/recurrents/RecurringForm.tsx | 193 ++++++++++++++++++ src/components/recurrents/ToConfirmRow.tsx | 52 +++++ src/server/actions/recurrings.ts | 35 ++++ src/server/services/recurrings.ts | 102 +++++++++ tests/server/recurrings.test.ts | 87 ++++++++ 10 files changed, 792 insertions(+) create mode 100644 src/app/(app)/recurrents/[id]/page.tsx create mode 100644 src/app/(app)/recurrents/nouveau/page.tsx create mode 100644 src/app/(app)/recurrents/page.tsx create mode 100644 src/components/SplitPicker.tsx create mode 100644 src/components/recurrents/RecurringActions.tsx create mode 100644 src/components/recurrents/RecurringForm.tsx create mode 100644 src/components/recurrents/ToConfirmRow.tsx create mode 100644 src/server/actions/recurrings.ts create mode 100644 src/server/services/recurrings.ts create mode 100644 tests/server/recurrings.test.ts diff --git a/src/app/(app)/recurrents/[id]/page.tsx b/src/app/(app)/recurrents/[id]/page.tsx new file mode 100644 index 0000000..f47f0c0 --- /dev/null +++ b/src/app/(app)/recurrents/[id]/page.tsx @@ -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 ( + +

+ Les changements s'appliquent aux prochaines échéances. Les opérations déjà passées ne bougent pas. +

+ +
+ ); +} diff --git a/src/app/(app)/recurrents/nouveau/page.tsx b/src/app/(app)/recurrents/nouveau/page.tsx new file mode 100644 index 0000000..a0567d0 --- /dev/null +++ b/src/app/(app)/recurrents/nouveau/page.tsx @@ -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 ( + + + + ); +} diff --git a/src/app/(app)/recurrents/page.tsx b/src/app/(app)/recurrents/page.tsx new file mode 100644 index 0000000..bed1bba --- /dev/null +++ b/src/app/(app)/recurrents/page.tsx @@ -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 ( +
+
+

Récurrents & prévu

+
+ + + Dépense prévue + + + + Récurrent + +
+
+ + + + À confirmer {toConfirm.length > 0 && {toConfirm.length}} + + {toConfirm.length === 0 ? ( +

Rien à confirmer, tout est à jour ✓

+ ) : ( + toConfirm.map((o) => ( + + )) + )} +
+ + + À venir (60 jours) + {upcoming.length === 0 ? ( +

Aucune opération prévue.

+ ) : ( + + )} +
+ +
+ Modèles récurrents + {defs.length === 0 && ( + +

Aucun récurrent. Ajoutez le loyer, les salaires, les abonnements…

+
+ )} +
+ {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 ( + +
+
+ + {cat[d.categoryId]?.emoji} {d.label} + +
+ {FREQ[d.frequency]} · le {d.dayOfMonth} + {status} +
+
+ +
+
+ {account && ( + + {d.kind === "EXPENSE" ? "payé par" : "reçu par"} {account.firstName} + + )} + {d.kind === "EXPENSE" && !full && ( + {users.map((u) => bpToPercentLabel(d.split[u.id] ?? 0)).join("/")} + )} + {d.kind === "EXPENSE" && full && full.id !== d.accountUserId && pour {full.firstName}} + {d.allocatedToRecurringId && ↳ {labels[d.allocatedToRecurringId]}} +
+
+ {fromLoan.has(d.id) ? ( + + Géré depuis Crédits → + + ) : ( + + )} +
+
+ ); + })} +
+
+
+ ); +} diff --git a/src/components/SplitPicker.tsx b/src/components/SplitPicker.tsx new file mode 100644 index 0000000..0ee06f6 --- /dev/null +++ b/src/components/SplitPicker.tsx @@ -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(() => { + if (same(value, defaultSplit)) return "default"; + const full = ids.find((id) => value[id] === 10000); + return full ? `full:${full}` : "custom"; + }); + const [custom, setCustom] = useState>(() => + Object.fromEntries(ids.map((id) => [id, bpToPercentLabel(value[id] ?? 0)])), + ); + + const fromCustom = (c: Record): 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 ( +
+ 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" && ( +
+ {users.map((u) => ( + + ))} + Total {bpToPercentLabel(total)} % +
+ )} +
+ ); +} diff --git a/src/components/recurrents/RecurringActions.tsx b/src/components/recurrents/RecurringActions.tsx new file mode 100644 index 0000000..31f1839 --- /dev/null +++ b/src/components/recurrents/RecurringActions.tsx @@ -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 ( +
+ + Modifier + + + + +
+ ); +} diff --git a/src/components/recurrents/RecurringForm.tsx b/src/components/recurrents/RecurringForm.tsx new file mode 100644 index 0000000..db6ccbd --- /dev/null +++ b/src/components/recurrents/RecurringForm.tsx @@ -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(null); + const [kind, setKind] = useState(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(initial?.split ?? defaultSplit); + const [frequency, setFrequency] = useState(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(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 ( +
{ + e.preventDefault(); + submit(); + }} + > + { + setKind(k); + setCategoryId(""); + }} + /> +
+ + setLabel(e.target.value)} placeholder="Loyer, salaire, Netflix…" /> + + + setAmount(e.target.value)} placeholder="0,00" /> + +
+ + + +
+
{kind === "EXPENSE" ? "Payé par" : "Reçu par"}
+ ({ value: u.id, label: u.firstName }))} value={accountUserId} onChange={setAccountUserId} /> +
+ {kind === "EXPENSE" && ( +
+
Répartition
+ +
+ )} +
+ + + + + setDayOfMonth(e.target.value)} /> + + + setStartDate(e.target.value)} /> + + + setEndDate(e.target.value)} /> + +
+ {kind === "INCOME" && ( +
+ + + + {allocated && ( + <> + + {mode === "CUSTOM" && } + + )} +
+ )} + + + + ); +} diff --git a/src/components/recurrents/ToConfirmRow.tsx b/src/components/recurrents/ToConfirmRow.tsx new file mode 100644 index 0000000..9b3996b --- /dev/null +++ b/src/components/recurrents/ToConfirmRow.tsx @@ -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(null); + const [pending, start] = useTransition(); + + return ( +
+
+ + {op.emoji} {op.label} + +
+ prévu le {formatDateFr(op.date)} · {op.kind === "EXPENSE" ? "payé par" : "reçu par"} {op.who} +
+ {error &&
{error}
} +
+
+ setAmount(e.target.value)} /> + setDate(e.target.value)} /> + + +
+
+ ); +} diff --git a/src/server/actions/recurrings.ts b/src/server/actions/recurrings.ts new file mode 100644 index 0000000..2e76883 --- /dev/null +++ b/src/server/actions/recurrings.ts @@ -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; +} diff --git a/src/server/services/recurrings.ts b/src/server/services/recurrings.ts new file mode 100644 index 0000000..3345f32 --- /dev/null +++ b/src/server/services/recurrings.ts @@ -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; + +/** 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> { + 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 { + 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 { + 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 { + 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 }; +} diff --git a/tests/server/recurrings.test.ts b/tests/server/recurrings.test.ts new file mode 100644 index 0000000..a03b5e2 --- /dev/null +++ b/tests/server/recurrings.test.ts @@ -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); + }); +});