feat: quick entry form and operation/settlement actions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
08f23f909f
commit
2860f2f776
8 files changed
+859
-2
No files matched your search
@@ -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 (
|
||||||
|
<FormPage title="Nouvelle opération" back={returnTo}>
|
||||||
|
<OperationForm
|
||||||
|
{...data}
|
||||||
|
currentUserId={user.id}
|
||||||
|
today={today}
|
||||||
|
initialKind={sp.type === "entree" ? "INCOME" : "EXPENSE"}
|
||||||
|
initialPlanned={sp.prevue === "1"}
|
||||||
|
returnTo={returnTo}
|
||||||
|
/>
|
||||||
|
</FormPage>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 (
|
||||||
|
<FormPage title="Modifier l'opération" back={safeReturn((await searchParams).retour)}>
|
||||||
|
{op.recurringId && (
|
||||||
|
<p className="mb-4 rounded-[10px] bg-accent-soft px-3 py-2 text-[13px] text-accent">
|
||||||
|
Occurrence d'un récurrent : cette modification ne change que ce mois-ci.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<OperationForm
|
||||||
|
{...data}
|
||||||
|
charges={charges}
|
||||||
|
currentUserId={user.id}
|
||||||
|
today={today}
|
||||||
|
returnTo={safeReturn((await searchParams).retour)}
|
||||||
|
initial={{
|
||||||
|
id: op.id,
|
||||||
|
kind: op.kind,
|
||||||
|
amount: formatEuro(op.amount).replace(/[^\d,]/g, ""),
|
||||||
|
label: op.label,
|
||||||
|
categoryId: op.categoryId,
|
||||||
|
date: op.date,
|
||||||
|
accountUserId: op.accountUserId,
|
||||||
|
status: op.status === "PLANNED" ? "PLANNED" : "ACTUAL",
|
||||||
|
split: op.split,
|
||||||
|
note: row.note ?? "",
|
||||||
|
chargeKey,
|
||||||
|
allocationMode: op.allocationMode,
|
||||||
|
isRecurringOccurrence: op.recurringId !== null,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</FormPage>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 (
|
||||||
|
<div className="mx-auto max-w-lg">
|
||||||
|
<div className="mb-4 flex items-center gap-3">
|
||||||
|
<Link href={back} className="grid h-[30px] w-[30px] place-items-center rounded-lg border border-line bg-white text-muted" aria-label="Retour">
|
||||||
|
‹
|
||||||
|
</Link>
|
||||||
|
<h1 className="text-lg font-bold">{title}</h1>
|
||||||
|
</div>
|
||||||
|
<Card className="p-5">{children}</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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:<recurringId>" ou "o:<operationId>" */
|
||||||
|
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<string | null>(null);
|
||||||
|
|
||||||
|
const [kind, setKind] = useState<OpKind>(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<AllocationMode>(initial?.allocationMode ?? "REDUCE_SHARED");
|
||||||
|
const [recurring, setRecurring] = useState(false);
|
||||||
|
const [frequency, setFrequency] = useState<Frequency>("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<SplitChoice>(initialChoice);
|
||||||
|
const [custom, setCustom] = useState<Record<string, string>>(() =>
|
||||||
|
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 (
|
||||||
|
<form
|
||||||
|
className="space-y-4"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
submit();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="flex rounded-[10px] bg-gray-100 p-1">
|
||||||
|
{(["EXPENSE", "INCOME"] as const).map((k) => (
|
||||||
|
<button
|
||||||
|
key={k}
|
||||||
|
type="button"
|
||||||
|
onClick={() => changeKind(k)}
|
||||||
|
className={`flex-1 rounded-lg py-2 font-semibold transition ${
|
||||||
|
kind === k ? `bg-white shadow-sm ${k === "EXPENSE" ? "text-neg" : "text-pos"}` : "text-muted"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{k === "EXPENSE" ? "Dépense" : "Entrée"}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-baseline justify-center gap-1 py-1">
|
||||||
|
<input
|
||||||
|
aria-label="Montant"
|
||||||
|
inputMode="decimal"
|
||||||
|
placeholder="0,00"
|
||||||
|
value={amount}
|
||||||
|
onChange={(e) => setAmount(e.target.value)}
|
||||||
|
autoFocus={!initial}
|
||||||
|
style={{ width: `${Math.max(amount.length, 4) + 0.5}ch` }}
|
||||||
|
className="max-w-full bg-transparent text-right text-4xl font-bold tracking-tight outline-none placeholder:text-gray-300"
|
||||||
|
/>
|
||||||
|
<span className="text-xl text-muted">€</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Input aria-label="Libellé" placeholder="Libellé (ex. Carrefour)" value={label} onChange={(e) => setLabel(e.target.value)} />
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="mb-2 text-xs font-semibold text-muted">Catégorie</div>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{kindCategories.map((c) => (
|
||||||
|
<button
|
||||||
|
key={c.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setCategoryId(c.id)}
|
||||||
|
className={`rounded-full border px-3 py-1.5 text-[13px] font-medium transition-colors ${
|
||||||
|
categoryId === c.id ? "border-accent bg-accent text-white" : "border-line bg-white hover:border-gray-300"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{c.emoji} {c.name}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<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={changeAccount}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!allocated && (
|
||||||
|
<div>
|
||||||
|
<div className="mb-2 text-xs font-semibold text-muted">Répartition</div>
|
||||||
|
<Pills options={splitOptions} value={choice} onChange={setChoice} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showCustom && (
|
||||||
|
<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) => setCustom({ ...custom, [u.id]: e.target.value })}
|
||||||
|
/>
|
||||||
|
%
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<span className={`text-xs font-semibold ${customTotal === 10000 ? "text-pos" : "text-neg"}`}>
|
||||||
|
Total {bpToPercentLabel(customTotal)} %
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Field label="Date">
|
||||||
|
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} required />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<button type="button" onClick={() => setShowMore((v) => !v)} className="text-[13px] font-semibold text-accent">
|
||||||
|
{showMore ? "− Moins d'options" : "+ Récurrent, prévue, affecter à une charge"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{showMore && (
|
||||||
|
<div className="space-y-4 rounded-card border border-line p-4">
|
||||||
|
<label className="flex items-center gap-2 font-medium">
|
||||||
|
<input type="checkbox" checked={planned} onChange={(e) => setPlanned(e.target.checked)} className="h-4 w-4 accent-accent" />
|
||||||
|
Prévue (pas encore passée)
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{!initial && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<label className="flex items-center gap-2 font-medium">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={recurring}
|
||||||
|
onChange={(e) => setRecurring(e.target.checked)}
|
||||||
|
className="h-4 w-4 accent-accent"
|
||||||
|
/>
|
||||||
|
Rendre récurrent
|
||||||
|
</label>
|
||||||
|
{recurring && (
|
||||||
|
<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="Jusqu'au (facultatif)">
|
||||||
|
<Input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{kind === "INCOME" && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<Field label="Affecter à une charge" hint="Ex. IK → crédit voiture, part loyer employeur → loyer">
|
||||||
|
<Select value={chargeKey} onChange={(e) => setChargeKey(e.target.value)}>
|
||||||
|
<option value="">Aucune</option>
|
||||||
|
{charges.map((c) => (
|
||||||
|
<option key={c.key} value={c.key}>
|
||||||
|
{c.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={allocationMode}
|
||||||
|
onChange={setAllocationMode}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Field label="Note">
|
||||||
|
<Textarea rows={2} value={note} onChange={(e) => setNote(e.target.value)} />
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FormError message={error} />
|
||||||
|
|
||||||
|
<div className="flex gap-3">
|
||||||
|
{initial && (
|
||||||
|
<Button type="button" variant="danger" onClick={remove} disabled={pending}>
|
||||||
|
Supprimer
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button type="submit" className="flex-1 py-3" disabled={pending}>
|
||||||
|
{pending ? "Enregistrement…" : "Enregistrer"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<typeof ops.saveSettlement>[0]) {
|
||||||
|
await requireUser();
|
||||||
|
const result = await ops.saveSettlement(input);
|
||||||
|
if (result.ok) refresh();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
+40
-2
@@ -1,9 +1,10 @@
|
|||||||
import type { OpKind } from "@prisma/client";
|
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 { RecurringDef } from "@/domain/recurrence";
|
||||||
import type { Op, Settlement, Split } from "@/domain/types";
|
import type { Op, Settlement, Split } from "@/domain/types";
|
||||||
import { prisma } from "./db";
|
import { prisma } from "./db";
|
||||||
import { toOp, toRecurringDef, toSettlement } from "./mappers";
|
import { splitOf, toOp, toRecurringDef, toSettlement } from "./mappers";
|
||||||
|
|
||||||
export interface UserLite {
|
export interface UserLite {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -54,3 +55,40 @@ export async function getDefaultSplit(): Promise<Split> {
|
|||||||
const setting = await prisma.setting.findUnique({ where: { id: 1 } });
|
const setting = await prisma.setting.findUnique({ where: { id: 1 } });
|
||||||
return (setting?.defaultSplit ?? {}) as Split;
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<T = object> = ({ 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<typeof operationSchema>;
|
||||||
|
|
||||||
|
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<Result<{ id: string }>> {
|
||||||
|
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<Result> {
|
||||||
|
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<Result> {
|
||||||
|
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<Result> {
|
||||||
|
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<Result> {
|
||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -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> = {}): 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.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user