"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 (
{ e.preventDefault(); submit(); }} >
{(["EXPENSE", "INCOME"] as const).map((k) => ( ))}
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" /> €
setLabel(e.target.value)} />
Catégorie
{kindCategories.map((c) => ( ))}
{kind === "EXPENSE" ? "Payé par" : "Reçu par"}
({ value: u.id, label: u.firstName }))} value={accountUserId} onChange={changeAccount} />
{!allocated && (
Répartition
)} {showCustom && (
{users.map((u) => ( ))} Total {bpToPercentLabel(customTotal)} %
)} setDate(e.target.value)} required /> {showMore && (
{!initial && (
{recurring && (
setEndDate(e.target.value)} />
)}
)} {kind === "INCOME" && (
{allocated && ( )}
)}