Files
hcl-finances-manager/src/components/OperationForm.tsx
T
2026-10-27 18:17:43 +01:00

366 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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>
);
}