diff --git a/src/app/(app)/nouvelle/page.tsx b/src/app/(app)/nouvelle/page.tsx
new file mode 100644
index 0000000..107d686
--- /dev/null
+++ b/src/app/(app)/nouvelle/page.tsx
@@ -0,0 +1,31 @@
+import { FormPage } from "@/components/FormPage";
+import { OperationForm } from "@/components/OperationForm";
+import { todayParis } from "@/lib/dates";
+import { requireUser } from "@/server/auth";
+import { getFormData } from "@/server/repo";
+
+const safeReturn = (r?: string) => (r && r.startsWith("/") && !r.startsWith("//") ? r : "/");
+
+export default async function NewOperationPage({
+ searchParams,
+}: {
+ searchParams: Promise<{ type?: string; prevue?: string; retour?: string }>;
+}) {
+ const user = await requireUser();
+ const sp = await searchParams;
+ const today = todayParis();
+ const data = await getFormData(today);
+ const returnTo = safeReturn(sp.retour);
+ return (
+
+
+
+ );
+}
diff --git a/src/app/(app)/operations/[id]/page.tsx b/src/app/(app)/operations/[id]/page.tsx
new file mode 100644
index 0000000..e9befeb
--- /dev/null
+++ b/src/app/(app)/operations/[id]/page.tsx
@@ -0,0 +1,67 @@
+import { notFound } from "next/navigation";
+import { FormPage } from "@/components/FormPage";
+import { OperationForm } from "@/components/OperationForm";
+import { formatEuro } from "@/domain/money";
+import { todayParis } from "@/lib/dates";
+import { requireUser } from "@/server/auth";
+import { prisma } from "@/server/db";
+import { toOp } from "@/server/mappers";
+import { getFormData } from "@/server/repo";
+
+const safeReturn = (r?: string) => (r && r.startsWith("/") && !r.startsWith("//") ? r : "/operations");
+
+export default async function EditOperationPage({
+ params,
+ searchParams,
+}: {
+ params: Promise<{ id: string }>;
+ searchParams: Promise<{ retour?: string }>;
+}) {
+ const user = await requireUser();
+ const { id } = await params;
+ const row = await prisma.operation.findUnique({ where: { id }, include: { splits: true } });
+ if (!row || row.status === "SKIPPED") notFound();
+ const op = toOp(row);
+ const today = todayParis();
+ const data = await getFormData(today);
+ const chargeKey = op.allocatedToRecurringId
+ ? `r:${op.allocatedToRecurringId}`
+ : op.allocatedToOperationId
+ ? `o:${op.allocatedToOperationId}`
+ : "";
+ // La dépense éditée ne peut pas être sa propre cible ; une cible hors des 3 derniers mois reste sélectionnable.
+ const charges = data.charges.filter((c) => c.key !== `o:${op.id}`);
+ if (chargeKey && !charges.some((c) => c.key === chargeKey)) charges.push({ key: chargeKey, label: "Charge actuelle", split: op.split });
+
+ return (
+
+ {op.recurringId && (
+
+ Occurrence d'un récurrent : cette modification ne change que ce mois-ci.
+
+ )}
+
+
+ );
+}
diff --git a/src/components/FormPage.tsx b/src/components/FormPage.tsx
new file mode 100644
index 0000000..11f1197
--- /dev/null
+++ b/src/components/FormPage.tsx
@@ -0,0 +1,18 @@
+import Link from "next/link";
+import type { ReactNode } from "react";
+import { Card } from "./ui/Card";
+
+/** Page de formulaire : plein écran sur mobile, carte centrée sur ordinateur. */
+export function FormPage({ title, back, children }: { title: string; back: string; children: ReactNode }) {
+ return (
+
+
+
+ ‹
+
+
{title}
+
+
{children}
+
+ );
+}
diff --git a/src/components/OperationForm.tsx b/src/components/OperationForm.tsx
new file mode 100644
index 0000000..19075ab
--- /dev/null
+++ b/src/components/OperationForm.tsx
@@ -0,0 +1,365 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useMemo, useState, useTransition } from "react";
+import { bpToPercentLabel, fullSplit, percentToBp, validateSplit } from "@/domain/money";
+import type { AllocationMode, Frequency, OpKind, Split } from "@/domain/types";
+import { deleteOperationAction, saveOperationAction } from "@/server/actions/operations";
+import { Button } from "./ui/Button";
+import { Field, FormError, Input, Select, Textarea } from "./ui/Field";
+import { Pills } from "./ui/Pills";
+
+export interface FormUser {
+ id: string;
+ firstName: string;
+ color: string;
+}
+
+export interface FormCategory {
+ id: string;
+ name: string;
+ emoji: string;
+ kind: OpKind;
+}
+
+export interface ChargeOption {
+ /** "r:" ou "o:" */
+ key: string;
+ label: string;
+ split: Split;
+}
+
+export interface OperationInitial {
+ id: string;
+ kind: OpKind;
+ amount: string;
+ label: string;
+ categoryId: string;
+ date: string;
+ accountUserId: string;
+ status: "PLANNED" | "ACTUAL";
+ split: Split;
+ note: string;
+ chargeKey: string;
+ allocationMode: AllocationMode | null;
+ isRecurringOccurrence: boolean;
+}
+
+type SplitChoice = "default" | `full:${string}` | "custom";
+
+const sameSplit = (a: Split, b: Split) => Object.keys({ ...a, ...b }).every((k) => (a[k] ?? 0) === (b[k] ?? 0));
+
+export function OperationForm({
+ users,
+ categories,
+ defaultSplit,
+ currentUserId,
+ today,
+ charges,
+ initial,
+ initialKind = "EXPENSE",
+ initialPlanned = false,
+ returnTo = "/",
+}: {
+ users: FormUser[];
+ categories: FormCategory[];
+ defaultSplit: Split;
+ currentUserId: string;
+ today: string;
+ charges: ChargeOption[];
+ initial?: OperationInitial;
+ initialKind?: OpKind;
+ initialPlanned?: boolean;
+ returnTo?: string;
+}) {
+ const router = useRouter();
+ const userIds = users.map((u) => u.id);
+ const [pending, startTransition] = useTransition();
+ const [error, setError] = useState(null);
+
+ const [kind, setKind] = useState(initial?.kind ?? initialKind);
+ const [amount, setAmount] = useState(initial?.amount ?? "");
+ const [label, setLabel] = useState(initial?.label ?? "");
+ const [categoryId, setCategoryId] = useState(initial?.categoryId ?? "");
+ const [date, setDate] = useState(initial?.date ?? today);
+ const [accountUserId, setAccountUserId] = useState(initial?.accountUserId ?? currentUserId);
+ const [planned, setPlanned] = useState(initial ? initial.status === "PLANNED" : initialPlanned);
+ const [note, setNote] = useState(initial?.note ?? "");
+ const [chargeKey, setChargeKey] = useState(initial?.chargeKey ?? "");
+ const [allocationMode, setAllocationMode] = useState(initial?.allocationMode ?? "REDUCE_SHARED");
+ const [recurring, setRecurring] = useState(false);
+ const [frequency, setFrequency] = useState("MONTHLY");
+ const [endDate, setEndDate] = useState("");
+ const [showMore, setShowMore] = useState(
+ Boolean(initial && (initial.status === "PLANNED" || initial.note || initial.chargeKey)) || initialPlanned,
+ );
+
+ const initialChoice = (): SplitChoice => {
+ if (!initial) return kind === "INCOME" ? `full:${accountUserId}` : "default";
+ if (sameSplit(initial.split, defaultSplit)) return "default";
+ const full = userIds.find((id) => initial.split[id] === 10000);
+ return full ? `full:${full}` : "custom";
+ };
+ const [choice, setChoice] = useState(initialChoice);
+ const [custom, setCustom] = useState>(() =>
+ Object.fromEntries(userIds.map((id) => [id, bpToPercentLabel((initial?.split ?? defaultSplit)[id] ?? 0)])),
+ );
+
+ const charge = charges.find((c) => c.key === chargeKey) ?? null;
+ const allocated = kind === "INCOME" && charge !== null;
+
+ const customSplit: Split = Object.fromEntries(userIds.map((id) => [id, percentToBp(custom[id] ?? "") ?? -1]));
+ const customTotal = Object.values(customSplit).reduce((t, v) => t + Math.max(v, 0), 0);
+
+ // La répartition effective découle du choix (ou du mode d'affectation pour une entrée affectée).
+ const split: Split = useMemo(() => {
+ if (allocated) {
+ if (allocationMode === "REDUCE_SHARED") return charge!.split;
+ if (allocationMode === "BENEFICIARY_ONLY") return fullSplit(accountUserId, userIds);
+ return customSplit;
+ }
+ if (choice === "default") return defaultSplit;
+ if (choice === "custom") return customSplit;
+ return fullSplit(choice.slice(5), userIds);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [allocated, allocationMode, charge, accountUserId, choice, custom, defaultSplit]);
+
+ const changeKind = (k: OpKind) => {
+ setKind(k);
+ setCategoryId("");
+ if (choice !== "custom") setChoice(k === "INCOME" ? `full:${accountUserId}` : "default");
+ if (k === "EXPENSE") setChargeKey("");
+ };
+
+ const changeAccount = (id: string) => {
+ setAccountUserId(id);
+ if (kind === "INCOME" && choice.startsWith("full:")) setChoice(`full:${id}`);
+ };
+
+ const defaultLabel = userIds.map((id) => bpToPercentLabel(defaultSplit[id] ?? 0)).join(" / ");
+ const splitOptions = [
+ { value: "default" as SplitChoice, label: defaultLabel },
+ ...users.map((u) => ({ value: `full:${u.id}` as SplitChoice, label: `100 % ${u.firstName}` })),
+ { value: "custom" as SplitChoice, label: "Perso…" },
+ ];
+
+ const kindCategories = categories.filter((c) => c.kind === kind);
+ const showCustom = allocated ? allocationMode === "CUSTOM" : choice === "custom";
+
+ const submit = () => {
+ setError(null);
+ const splitError = validateSplit(split);
+ if (splitError) return setError(splitError);
+ startTransition(async () => {
+ const result = await saveOperationAction({
+ id: initial?.id,
+ kind,
+ amount,
+ label,
+ categoryId,
+ date,
+ accountUserId,
+ status: planned ? "PLANNED" : "ACTUAL",
+ split,
+ note,
+ allocatedToRecurringId: allocated && chargeKey.startsWith("r:") ? chargeKey.slice(2) : null,
+ allocatedToOperationId: allocated && chargeKey.startsWith("o:") ? chargeKey.slice(2) : null,
+ allocationMode: allocated ? allocationMode : null,
+ makeRecurring: !initial && recurring ? { frequency, endDate: endDate || null } : undefined,
+ });
+ if (!result.ok) return setError(result.error);
+ router.push(returnTo);
+ });
+ };
+
+ const remove = () => {
+ if (!initial || !confirm("Supprimer cette opération ?")) return;
+ startTransition(async () => {
+ await deleteOperationAction(initial.id);
+ router.push(returnTo);
+ });
+ };
+
+ return (
+
+ );
+}
diff --git a/src/server/actions/operations.ts b/src/server/actions/operations.ts
new file mode 100644
index 0000000..f27eb81
--- /dev/null
+++ b/src/server/actions/operations.ts
@@ -0,0 +1,42 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import { requireUser } from "@/server/auth";
+import * as ops from "@/server/services/operations";
+
+const refresh = () => revalidatePath("/", "layout");
+
+export async function saveOperationAction(input: ops.OperationInput) {
+ const user = await requireUser();
+ const result = await ops.saveOperation(input, user.id);
+ if (result.ok) refresh();
+ return result;
+}
+
+export async function deleteOperationAction(id: string) {
+ await requireUser();
+ const result = await ops.deleteOperation(id);
+ refresh();
+ return result;
+}
+
+export async function confirmOperationAction(id: string, amount: string, date: string) {
+ await requireUser();
+ const result = await ops.confirmOperation(id, amount, date);
+ if (result.ok) refresh();
+ return result;
+}
+
+export async function skipOperationAction(id: string) {
+ await requireUser();
+ const result = await ops.skipOperation(id);
+ refresh();
+ return result;
+}
+
+export async function saveSettlementAction(input: Parameters[0]) {
+ await requireUser();
+ const result = await ops.saveSettlement(input);
+ if (result.ok) refresh();
+ return result;
+}
diff --git a/src/server/repo.ts b/src/server/repo.ts
index 4959111..8bf5734 100644
--- a/src/server/repo.ts
+++ b/src/server/repo.ts
@@ -1,9 +1,10 @@
import type { OpKind } from "@prisma/client";
-import { addMonths, fromIsoDate } from "@/lib/dates";
+import { addMonths, formatDateFr, fromIsoDate } from "@/lib/dates";
+import { formatEuro } from "@/domain/money";
import type { RecurringDef } from "@/domain/recurrence";
import type { Op, Settlement, Split } from "@/domain/types";
import { prisma } from "./db";
-import { toOp, toRecurringDef, toSettlement } from "./mappers";
+import { splitOf, toOp, toRecurringDef, toSettlement } from "./mappers";
export interface UserLite {
id: string;
@@ -54,3 +55,40 @@ export async function getDefaultSplit(): Promise {
const setting = await prisma.setting.findUnique({ where: { id: 1 } });
return (setting?.defaultSplit ?? {}) as Split;
}
+
+/** Charges auxquelles une entrée peut être affectée : récurrents de dépense et dépenses des 3 derniers mois. */
+export async function getChargeOptions(today: string) {
+ const since = `${addMonths(today.slice(0, 7), -3)}-01`;
+ const [recurrings, ops] = await Promise.all([
+ prisma.recurring.findMany({ where: { kind: "EXPENSE" }, include: { splits: true }, orderBy: { label: "asc" } }),
+ prisma.operation.findMany({
+ where: { kind: "EXPENSE", recurringId: null, status: { not: "SKIPPED" }, date: { gte: fromIsoDate(since) } },
+ include: { splits: true },
+ orderBy: { date: "desc" },
+ take: 100,
+ }),
+ ]);
+ return [
+ ...recurrings.map((r) => ({ key: `r:${r.id}`, label: `↻ ${r.label}`, split: splitOf(r.splits) })),
+ ...ops.map((o) => {
+ const op = toOp(o);
+ return { key: `o:${o.id}`, label: `${o.label} · ${formatDateFr(op.date)} · ${formatEuro(op.amount)}`, split: op.split };
+ }),
+ ];
+}
+
+/** Données communes au formulaire de saisie. */
+export async function getFormData(today: string) {
+ const [users, categories, defaultSplit, charges] = await Promise.all([
+ getUsers(),
+ getCategories(),
+ getDefaultSplit(),
+ getChargeOptions(today),
+ ]);
+ return {
+ users,
+ categories: categories.map((c) => ({ id: c.id, name: c.name, emoji: c.emoji, kind: c.kind })),
+ defaultSplit,
+ charges,
+ };
+}
diff --git a/src/server/services/operations.ts b/src/server/services/operations.ts
new file mode 100644
index 0000000..116a006
--- /dev/null
+++ b/src/server/services/operations.ts
@@ -0,0 +1,154 @@
+import { z } from "zod";
+import { decimalFromCents, parseEuro, validateSplit } from "@/domain/money";
+import type { Split } from "@/domain/types";
+import { fromIsoDate } from "@/lib/dates";
+import { prisma } from "../db";
+import { splitRows } from "../mappers";
+
+export type Result = ({ ok: true } & T) | { ok: false; error: string };
+
+const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date invalide.");
+
+const operationSchema = 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."),
+ date: isoDate,
+ accountUserId: z.string().min(1),
+ status: z.enum(["PLANNED", "ACTUAL"]),
+ split: z.record(z.string(), z.number().int()),
+ note: z.string().max(2000).optional(),
+ allocatedToRecurringId: z.string().nullish(),
+ allocatedToOperationId: z.string().nullish(),
+ allocationMode: z.enum(["REDUCE_SHARED", "BENEFICIARY_ONLY", "CUSTOM"]).nullish(),
+ makeRecurring: z
+ .object({ frequency: z.enum(["MONTHLY", "QUARTERLY", "YEARLY"]), endDate: isoDate.nullable() })
+ .optional(),
+});
+
+export type OperationInput = z.input;
+
+const firstError = (e: z.ZodError) => e.issues[0]?.message ?? "Données invalides.";
+
+/** Création ou modification d'une opération (saisie rapide et édition). */
+export async function saveOperation(raw: OperationInput, currentUserId: string): Promise> {
+ const parsed = operationSchema.safeParse(raw);
+ if (!parsed.success) return { ok: false, error: firstError(parsed.error) };
+ 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 };
+
+ const allocatedToRecurringId = input.allocatedToRecurringId || null;
+ const allocatedToOperationId = input.allocatedToOperationId || null;
+ const allocated = allocatedToRecurringId !== null || allocatedToOperationId !== null;
+ if (allocated && input.kind === "EXPENSE") {
+ return { ok: false, error: "Seule une entrée peut être affectée à une charge." };
+ }
+ if (allocatedToRecurringId && allocatedToOperationId) {
+ return { ok: false, error: "Une entrée ne peut être affectée qu'à une seule charge." };
+ }
+
+ const fields = {
+ kind: input.kind,
+ amount: decimalFromCents(cents),
+ label: input.label,
+ categoryId: input.categoryId,
+ date: fromIsoDate(input.date),
+ accountUserId: input.accountUserId,
+ status: input.status,
+ note: input.note?.trim() || null,
+ allocatedToRecurringId,
+ allocatedToOperationId,
+ allocationMode: allocated ? (input.allocationMode ?? "REDUCE_SHARED") : null,
+ };
+ const splits = splitRows(input.split as Split);
+
+ const id = await prisma.$transaction(async (tx) => {
+ if (input.id) {
+ await tx.operationSplit.deleteMany({ where: { operationId: input.id } });
+ await tx.operation.update({ where: { id: input.id }, data: { ...fields, splits: { create: splits } } });
+ return input.id;
+ }
+
+ let recurring: { recurringId: string; occurrenceDate: Date } | object = {};
+ if (input.makeRecurring) {
+ const rec = await tx.recurring.create({
+ data: {
+ kind: fields.kind,
+ amount: fields.amount,
+ label: fields.label,
+ categoryId: fields.categoryId,
+ accountUserId: fields.accountUserId,
+ frequency: input.makeRecurring.frequency,
+ dayOfMonth: Number(input.date.slice(8, 10)),
+ startDate: fields.date,
+ endDate: input.makeRecurring.endDate ? fromIsoDate(input.makeRecurring.endDate) : null,
+ allocatedToRecurringId,
+ allocationMode: allocatedToRecurringId ? fields.allocationMode : null,
+ splits: { create: splits },
+ },
+ });
+ recurring = { recurringId: rec.id, occurrenceDate: fields.date };
+ }
+
+ const op = await tx.operation.create({
+ data: { ...fields, ...recurring, createdById: currentUserId, splits: { create: splits } },
+ });
+ return op.id;
+ });
+
+ return { ok: true, id };
+}
+
+export async function deleteOperation(id: string): Promise {
+ await prisma.operation.delete({ where: { id } });
+ return { ok: true };
+}
+
+/** Passe une opération prévue en réelle, avec montant et date ajustables. */
+export async function confirmOperation(id: string, amount: string, date: string): Promise {
+ const cents = parseEuro(amount);
+ if (cents === null) return { ok: false, error: "Montant invalide." };
+ if (!isoDate.safeParse(date).success) return { ok: false, error: "Date invalide." };
+ await prisma.operation.update({
+ where: { id },
+ data: { status: "ACTUAL", amount: decimalFromCents(cents), date: fromIsoDate(date) },
+ });
+ return { ok: true };
+}
+
+/** Occurrence de récurrent : marquée ignorée (pas régénérée). Prévue ponctuelle : supprimée. */
+export async function skipOperation(id: string): Promise {
+ const op = await prisma.operation.findUniqueOrThrow({ where: { id } });
+ if (op.recurringId) await prisma.operation.update({ where: { id }, data: { status: "SKIPPED" } });
+ else await prisma.operation.delete({ where: { id } });
+ return { ok: true };
+}
+
+export async function saveSettlement(input: {
+ fromUserId: string;
+ toUserId: string;
+ amount: string;
+ date: string;
+ note?: string;
+}): Promise {
+ if (input.fromUserId === input.toUserId) return { ok: false, error: "Choisissez deux personnes différentes." };
+ const cents = parseEuro(input.amount);
+ if (cents === null) return { ok: false, error: "Montant invalide." };
+ if (!isoDate.safeParse(input.date).success) return { ok: false, error: "Date invalide." };
+ await prisma.settlement.create({
+ data: {
+ fromUserId: input.fromUserId,
+ toUserId: input.toUserId,
+ amount: decimalFromCents(cents),
+ date: fromIsoDate(input.date),
+ note: input.note?.trim() || null,
+ },
+ });
+ return { ok: true };
+}
diff --git a/tests/server/operations.test.ts b/tests/server/operations.test.ts
new file mode 100644
index 0000000..880be48
--- /dev/null
+++ b/tests/server/operations.test.ts
@@ -0,0 +1,142 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { prisma } from "@/server/db";
+import {
+ confirmOperation,
+ deleteOperation,
+ saveOperation,
+ saveSettlement,
+ skipOperation,
+ type OperationInput,
+} from "@/server/services/operations";
+import { syncRecurrings } from "@/server/sync";
+import { categoryId, makeUsers, resetDb } from "./helpers";
+
+let H: string;
+let C: string;
+let courses: string;
+let salaire: string;
+
+const expense = (over: Partial = {}): OperationInput => ({
+ kind: "EXPENSE",
+ amount: "86,40",
+ label: "Carrefour",
+ categoryId: courses,
+ date: "2026-10-27",
+ accountUserId: C,
+ status: "ACTUAL",
+ split: { [H]: 5000, [C]: 5000 },
+ ...over,
+});
+
+beforeEach(async () => {
+ await resetDb();
+ const { h, c } = await makeUsers();
+ H = h.id;
+ C = c.id;
+ courses = await categoryId("Courses");
+ salaire = await categoryId("Salaire");
+});
+
+describe("saveOperation", () => {
+ it("stores a French amount with its split", async () => {
+ const r = await saveOperation(expense(), H);
+ expect(r).toMatchObject({ ok: true });
+ const op = await prisma.operation.findFirstOrThrow({ include: { splits: true } });
+ expect(op.amount.toString()).toBe("86.4");
+ expect(op.createdById).toBe(H);
+ expect(op.splits).toHaveLength(2);
+ });
+
+ it("rejects a split that does not sum to 100 %", async () => {
+ expect(await saveOperation(expense({ split: { [H]: 3333, [C]: 3333 } }), H)).toEqual({
+ ok: false,
+ error: "La répartition doit totaliser 100 %.",
+ });
+ });
+
+ it("rejects a zero amount", async () => {
+ expect(await saveOperation(expense({ amount: "0" }), H)).toEqual({ ok: false, error: "Montant invalide." });
+ });
+
+ it("rejects an allocation on an expense", async () => {
+ const r = await saveOperation(expense({ allocatedToRecurringId: "x", allocationMode: "REDUCE_SHARED" }), H);
+ expect(r).toEqual({ ok: false, error: "Seule une entrée peut être affectée à une charge." });
+ });
+
+ it("replaces splits on update", async () => {
+ const r = await saveOperation(expense(), H);
+ if (!r.ok) throw new Error(r.error);
+ await saveOperation(expense({ id: r.id, split: { [H]: 0, [C]: 10000 } }), H);
+ const splits = await prisma.operationSplit.findMany({ where: { operationId: r.id }, orderBy: { basisPoints: "asc" } });
+ expect(splits.map((s) => s.basisPoints)).toEqual([0, 10000]);
+ });
+
+ it("keeps an allocated income when its target expense is deleted", async () => {
+ const hotel = await saveOperation(expense({ label: "Hôtel", amount: "150" }), H);
+ if (!hotel.ok) throw new Error(hotel.error);
+ const refund = await saveOperation(
+ {
+ kind: "INCOME",
+ amount: "150",
+ label: "Note de frais",
+ categoryId: salaire,
+ date: "2026-10-28",
+ accountUserId: H,
+ status: "ACTUAL",
+ split: { [H]: 5000, [C]: 5000 },
+ allocatedToOperationId: hotel.id,
+ allocationMode: "REDUCE_SHARED",
+ },
+ H,
+ );
+ if (!refund.ok) throw new Error(refund.error);
+ await deleteOperation(hotel.id);
+ const kept = await prisma.operation.findUniqueOrThrow({ where: { id: refund.id } });
+ expect(kept.allocatedToOperationId).toBeNull();
+ });
+
+ it("creates a recurring template with this operation as its first occurrence", async () => {
+ const r = await saveOperation(expense({ makeRecurring: { frequency: "MONTHLY", endDate: null } }), H);
+ if (!r.ok) throw new Error(r.error);
+ const rec = await prisma.recurring.findFirstOrThrow({ include: { splits: true } });
+ expect(rec.dayOfMonth).toBe(27);
+ expect(rec.splits).toHaveLength(2);
+ const op = await prisma.operation.findUniqueOrThrow({ where: { id: r.id } });
+ expect(op.recurringId).toBe(rec.id);
+ expect(op.occurrenceDate?.toISOString().slice(0, 10)).toBe("2026-10-27");
+ expect(await syncRecurrings("2026-10-27")).toBe(11);
+ });
+});
+
+describe("confirm / skip", () => {
+ it("confirms a planned operation with an adjusted amount and date", async () => {
+ const r = await saveOperation(expense({ status: "PLANNED" }), H);
+ if (!r.ok) throw new Error(r.error);
+ expect(await confirmOperation(r.id, "90", "2026-10-29")).toEqual({ ok: true });
+ const op = await prisma.operation.findUniqueOrThrow({ where: { id: r.id } });
+ expect(op.status).toBe("ACTUAL");
+ expect(op.amount.toString()).toBe("90");
+ expect(op.date.toISOString().slice(0, 10)).toBe("2026-10-29");
+ });
+
+ it("marks a recurring occurrence skipped but deletes a one-off", async () => {
+ const rec = await saveOperation(expense({ status: "PLANNED", makeRecurring: { frequency: "MONTHLY", endDate: null } }), H);
+ const oneOff = await saveOperation(expense({ status: "PLANNED" }), H);
+ if (!rec.ok || !oneOff.ok) throw new Error("setup");
+ await skipOperation(rec.id);
+ await skipOperation(oneOff.id);
+ expect((await prisma.operation.findUniqueOrThrow({ where: { id: rec.id } })).status).toBe("SKIPPED");
+ expect(await prisma.operation.findUnique({ where: { id: oneOff.id } })).toBeNull();
+ });
+});
+
+describe("saveSettlement", () => {
+ it("records a repayment and refuses one to oneself", async () => {
+ expect(await saveSettlement({ fromUserId: C, toUserId: H, amount: "450", date: "2026-10-27" })).toEqual({ ok: true });
+ expect(await prisma.settlement.count()).toBe(1);
+ expect(await saveSettlement({ fromUserId: H, toUserId: H, amount: "10", date: "2026-10-27" })).toEqual({
+ ok: false,
+ error: "Choisissez deux personnes différentes.",
+ });
+ });
+});