194 lines
7.2 KiB
TypeScript
194 lines
7.2 KiB
TypeScript
"use client";
|
|
|
|
import { useRouter } from "next/navigation";
|
|
import { useState, useTransition } from "react";
|
|
import { fullSplit, parseEuro } 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<string | null>(null);
|
|
const [kind, setKind] = useState<OpKind>(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<Split>(initial?.split ?? defaultSplit);
|
|
const [frequency, setFrequency] = useState<Frequency>(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<AllocationMode>(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 (
|
|
<form
|
|
className="space-y-4"
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
submit();
|
|
}}
|
|
>
|
|
<Pills
|
|
options={[
|
|
{ value: "EXPENSE" as OpKind, label: "Dépense" },
|
|
{ value: "INCOME" as OpKind, label: "Entrée" },
|
|
]}
|
|
value={kind}
|
|
onChange={(k) => {
|
|
setKind(k);
|
|
setCategoryId("");
|
|
}}
|
|
/>
|
|
<div className="grid gap-3 sm:grid-cols-[1fr_140px]">
|
|
<Field label="Libellé">
|
|
<Input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="Loyer, salaire, Netflix…" />
|
|
</Field>
|
|
<Field label="Montant (€)">
|
|
<Input inputMode="decimal" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="0,00" />
|
|
</Field>
|
|
</div>
|
|
<Field label="Catégorie">
|
|
<Select value={categoryId} onChange={(e) => setCategoryId(e.target.value)}>
|
|
<option value="">Choisir…</option>
|
|
{categories
|
|
.filter((c) => c.kind === kind)
|
|
.map((c) => (
|
|
<option key={c.id} value={c.id}>
|
|
{c.emoji} {c.name}
|
|
</option>
|
|
))}
|
|
</Select>
|
|
</Field>
|
|
<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={setAccountUserId} />
|
|
</div>
|
|
{kind === "EXPENSE" && (
|
|
<div>
|
|
<div className="mb-2 text-xs font-semibold text-muted">Répartition</div>
|
|
<SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} total={parseEuro(amount)} />
|
|
</div>
|
|
)}
|
|
<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="Jour du mois" hint="31 = dernier jour des mois plus courts">
|
|
<Input type="number" min={1} max={31} value={dayOfMonth} onChange={(e) => setDayOfMonth(e.target.value)} />
|
|
</Field>
|
|
<Field label="À partir du">
|
|
<Input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
|
|
</Field>
|
|
<Field label="Jusqu'au (facultatif)">
|
|
<Input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
|
|
</Field>
|
|
</div>
|
|
{kind === "INCOME" && (
|
|
<div className="space-y-3 rounded-card border border-line p-4">
|
|
<Field label="Affecter à une charge" hint="Ex. IK → crédit voiture, part loyer employeur → loyer">
|
|
<Select value={target} onChange={(e) => setTarget(e.target.value)}>
|
|
<option value="">Aucune</option>
|
|
{targetOptions.map((t) => (
|
|
<option key={t.id} value={t.id}>
|
|
{t.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={mode}
|
|
onChange={setMode}
|
|
/>
|
|
{mode === "CUSTOM" && <SplitPicker users={users} defaultSplit={defaultSplit} value={split} onChange={setSplit} total={parseEuro(amount)} />}
|
|
</>
|
|
)}
|
|
</div>
|
|
)}
|
|
<FormError message={error} />
|
|
<Button type="submit" className="w-full py-3" disabled={pending}>
|
|
{pending ? "Enregistrement…" : "Enregistrer"}
|
|
</Button>
|
|
</form>
|
|
);
|
|
}
|