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 ( +
{ + 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 && ( + + )} +
+ )} + + +