88 lines
3.1 KiB
TypeScript
88 lines
3.1 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useTransition } from "react";
|
|
import { decimalFromCents } from "@/domain/money";
|
|
import { saveSettlementAction } from "@/server/actions/operations";
|
|
import { Button } from "../ui/Button";
|
|
import { Card } from "../ui/Card";
|
|
import { Field, FormError, Input, Select } from "../ui/Field";
|
|
|
|
export function SettlementDialog({
|
|
users,
|
|
debtorId,
|
|
creditorId,
|
|
amount,
|
|
today,
|
|
}: {
|
|
users: { id: string; firstName: string }[];
|
|
debtorId?: string;
|
|
creditorId?: string;
|
|
amount?: number;
|
|
today: string;
|
|
}) {
|
|
const [open, setOpen] = useState(false);
|
|
const [from, setFrom] = useState(debtorId ?? users[1]?.id ?? "");
|
|
const [to, setTo] = useState(creditorId ?? users[0]?.id ?? "");
|
|
const [value, setValue] = useState(amount ? decimalFromCents(amount).replace(".", ",") : "");
|
|
const [date, setDate] = useState(today);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [pending, startTransition] = useTransition();
|
|
|
|
const submit = () =>
|
|
startTransition(async () => {
|
|
const r = await saveSettlementAction({ fromUserId: from, toUserId: to, amount: value, date });
|
|
if (!r.ok) return setError(r.error);
|
|
setOpen(false);
|
|
});
|
|
|
|
return (
|
|
<>
|
|
<Button variant="ghost" onClick={() => setOpen(true)} className="shrink-0">
|
|
Enregistrer un remboursement
|
|
</Button>
|
|
{open && (
|
|
<div className="fixed inset-0 z-50 grid place-items-center bg-black/30 p-4" onClick={() => setOpen(false)}>
|
|
<Card className="w-full max-w-sm space-y-4 p-5 shadow-xl" onClick={(e) => e.stopPropagation()}>
|
|
<h2 className="text-lg font-bold">Remboursement entre vous</h2>
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<Field label="De">
|
|
<Select value={from} onChange={(e) => setFrom(e.target.value)}>
|
|
{users.map((u) => (
|
|
<option key={u.id} value={u.id}>
|
|
{u.firstName}
|
|
</option>
|
|
))}
|
|
</Select>
|
|
</Field>
|
|
<Field label="À">
|
|
<Select value={to} onChange={(e) => setTo(e.target.value)}>
|
|
{users.map((u) => (
|
|
<option key={u.id} value={u.id}>
|
|
{u.firstName}
|
|
</option>
|
|
))}
|
|
</Select>
|
|
</Field>
|
|
</div>
|
|
<Field label="Montant (€)">
|
|
<Input inputMode="decimal" value={value} onChange={(e) => setValue(e.target.value)} />
|
|
</Field>
|
|
<Field label="Date">
|
|
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
|
|
</Field>
|
|
<FormError message={error} />
|
|
<div className="flex gap-3">
|
|
<Button variant="ghost" onClick={() => setOpen(false)} className="flex-1">
|
|
Annuler
|
|
</Button>
|
|
<Button onClick={submit} disabled={pending} className="flex-1">
|
|
Enregistrer
|
|
</Button>
|
|
</div>
|
|
</Card>
|
|
</div>
|
|
)}
|
|
</>
|
|
);
|
|
}
|