Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
306 lines
12 KiB
TypeScript
306 lines
12 KiB
TypeScript
"use client";
|
|
|
|
import Link from "next/link";
|
|
import { useCallback, useEffect, useState } from "react";
|
|
import { Badge } from "@/app/components/ui/badge";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
|
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
|
import { DatePicker } from "@/app/components/ui/date-picker";
|
|
import { Input } from "@/app/components/ui/input";
|
|
import { Label } from "@/app/components/ui/label";
|
|
import { ErrorState } from "@/app/components/ui/states";
|
|
import { Switch } from "@/app/components/ui/switch";
|
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
|
|
import { Textarea } from "@/app/components/ui/textarea";
|
|
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
|
import { ApiError } from "@/app/lib/clientApi";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import {
|
|
TICKET_ERRORS,
|
|
deleteTicketType,
|
|
getTicketSettings,
|
|
listTicketTypes,
|
|
money,
|
|
saveTicketSettings,
|
|
saveTicketType,
|
|
type TicketSettings,
|
|
type TicketType,
|
|
type TicketTypeInput,
|
|
} from "@/app/lib/services/adminTickets";
|
|
|
|
type Form = { id?: number; name: string; price: string; quantity: string; salesEndDate: string; enabled: boolean };
|
|
const EMPTY: Form = { name: "", price: "", quantity: "", salesEndDate: "", enabled: true };
|
|
const PRICE = /^\d{1,5}(\.\d{1,2})?$/;
|
|
|
|
/** A refusal's label and the field it belongs to; anything unknown falls back to the caller's generic text. */
|
|
function refusal(err: unknown): { code?: string; field?: string } {
|
|
if (!(err instanceof ApiError) || err.status < 400 || err.status >= 500) return {};
|
|
const body = err.data as { code?: string; details?: { field?: string } } | undefined;
|
|
return { code: body?.code, field: body?.details?.field };
|
|
}
|
|
|
|
/** add-event-ticket-orders: the event's Tickets section (BO_EVENT_TICKETS): settings, ticket types and a link to the orders. */
|
|
export function TicketsCard({ eventUuid }: { eventUuid: string }) {
|
|
const { hasModule } = useAdminAuth();
|
|
if (!hasModule("BO_EVENT_TICKETS")) return null;
|
|
return <TicketsCardContent eventUuid={eventUuid} />;
|
|
}
|
|
|
|
function TicketsCardContent({ eventUuid }: { eventUuid: string }) {
|
|
const t = useT();
|
|
const [settings, setSettings] = useState<TicketSettings | null>(null);
|
|
const [holdDays, setHoldDays] = useState("3");
|
|
const [types, setTypes] = useState<TicketType[] | null>(null);
|
|
const [loadError, setLoadError] = useState(false);
|
|
const [form, setForm] = useState<Form>(EMPTY);
|
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [notice, setNotice] = useState<string | null>(null);
|
|
const [deleting, setDeleting] = useState<TicketType | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
|
|
const load = useCallback(async () => {
|
|
try {
|
|
const [s, list] = await Promise.all([getTicketSettings(eventUuid), listTicketTypes(eventUuid)]);
|
|
setSettings(s);
|
|
setHoldDays(String(s.holdDays ?? 3));
|
|
setTypes(list);
|
|
setLoadError(false);
|
|
} catch {
|
|
setLoadError(true);
|
|
}
|
|
}, [eventUuid]);
|
|
|
|
useEffect(() => {
|
|
// eslint-disable-next-line react-hooks/set-state-in-effect -- load() fetches from the API; its setState runs after the await.
|
|
load();
|
|
}, [load]);
|
|
|
|
/** Runs a save; a refusal goes under its field when it names one, else into the card's error line. */
|
|
async function run(action: () => Promise<void>, failed: string) {
|
|
setErrors({});
|
|
setError(null);
|
|
setNotice(null);
|
|
setBusy(true);
|
|
try {
|
|
await action();
|
|
} catch (err) {
|
|
const { code, field } = refusal(err);
|
|
const label = code && TICKET_ERRORS[code] ? t(TICKET_ERRORS[code]) : failed;
|
|
if (field) setErrors({ [field]: label });
|
|
else setError(label);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
const saveSettings = (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (!settings) return;
|
|
return run(async () => {
|
|
const next = { ...settings, holdDays: Number(holdDays) };
|
|
await saveTicketSettings(eventUuid, next);
|
|
setSettings(next);
|
|
setNotice(t("TktSettingsSaved"));
|
|
}, t("TktSaveFailed"));
|
|
};
|
|
|
|
const input = (f: Form): TicketTypeInput | null => {
|
|
const bad: Record<string, string> = {};
|
|
if (!PRICE.test(f.price.trim())) bad.priceSen = t("TktErrPrice");
|
|
if (!/^\d+$/.test(f.quantity.trim())) bad.quantity = t("TktErrQuantity");
|
|
if (Object.keys(bad).length) {
|
|
setErrors(bad);
|
|
return null;
|
|
}
|
|
const sort = f.id == null ? (types?.length ?? 0) : (types?.find((x) => x.id === f.id)?.sort ?? 0);
|
|
return {
|
|
name: f.name.trim(),
|
|
priceSen: Math.round(Number(f.price.trim()) * 100),
|
|
quantity: Number(f.quantity.trim()),
|
|
salesEndDate: f.salesEndDate || null,
|
|
sort,
|
|
enabled: f.enabled,
|
|
};
|
|
};
|
|
|
|
const saveType = (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
const body = input(form);
|
|
if (!body) return;
|
|
return run(async () => {
|
|
await saveTicketType(eventUuid, body, form.id);
|
|
setForm(EMPTY);
|
|
await load();
|
|
}, t("TktSaveFailed"));
|
|
};
|
|
|
|
const toggle = (x: TicketType) =>
|
|
run(async () => {
|
|
await saveTicketType(eventUuid, { name: x.name, priceSen: x.priceSen, quantity: x.quantity, salesEndDate: x.salesEndDate, sort: x.sort, enabled: !x.enabled }, x.id);
|
|
await load();
|
|
}, t("TktSaveFailed"));
|
|
|
|
const remove = async () => {
|
|
const x = deleting;
|
|
setDeleting(null);
|
|
if (x)
|
|
await run(async () => {
|
|
await deleteTicketType(eventUuid, x.id);
|
|
await load();
|
|
}, t("TktSaveFailed"));
|
|
};
|
|
|
|
const edit = (x: TicketType) => {
|
|
setErrors({});
|
|
setForm({ id: x.id, name: x.name, price: (x.priceSen / 100).toFixed(2), quantity: String(x.quantity), salesEndDate: x.salesEndDate ?? "", enabled: x.enabled });
|
|
};
|
|
|
|
const fieldError = (field: string) => errors[field] && <p className="text-sm text-destructive">{errors[field]}</p>;
|
|
|
|
return (
|
|
<Card>
|
|
<CardHeader className="flex flex-row items-center justify-between gap-2">
|
|
<CardTitle>{t("TktTitle")}</CardTitle>
|
|
<Button asChild variant="outline" size="sm">
|
|
<Link href={`/events/${encodeURIComponent(eventUuid)}/orders`}>{t("TktViewOrders")}</Link>
|
|
</Button>
|
|
</CardHeader>
|
|
<CardContent className="space-y-6">
|
|
{loadError && <ErrorState message={t("TktLoadFailed")} onRetry={load} />}
|
|
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
|
{notice && <p role="status" className="text-sm text-muted-foreground">{notice}</p>}
|
|
|
|
{settings && (
|
|
<form onSubmit={saveSettings} className="space-y-3">
|
|
<div className="flex items-center gap-2">
|
|
<Switch
|
|
id="tickets-enabled"
|
|
aria-label={t("TktSellTickets")}
|
|
checked={settings.ticketsEnabled}
|
|
onCheckedChange={(on) => setSettings({ ...settings, ticketsEnabled: on })}
|
|
/>
|
|
<Label htmlFor="tickets-enabled">{t("TktSellTickets")}</Label>
|
|
</div>
|
|
<div className="space-y-1">
|
|
<Label htmlFor="tickets-instructions">{t("TktPaymentInstructions")}</Label>
|
|
<Textarea
|
|
id="tickets-instructions"
|
|
maxLength={1000}
|
|
value={settings.paymentInstructions ?? ""}
|
|
onChange={(e) => setSettings({ ...settings, paymentInstructions: e.target.value })}
|
|
/>
|
|
<p className="text-xs text-muted-foreground">{t("TktPaymentInstructionsHelp")}</p>
|
|
{fieldError("paymentInstructions")}
|
|
</div>
|
|
<div className="max-w-40 space-y-1">
|
|
<Label htmlFor="tickets-hold">{t("TktHoldDays")}</Label>
|
|
<Input id="tickets-hold" type="number" min={1} max={14} value={holdDays} onChange={(e) => setHoldDays(e.target.value)} />
|
|
{fieldError("holdDays")}
|
|
</div>
|
|
<Button type="submit" disabled={busy}>
|
|
{t("TktSaveSettings")}
|
|
</Button>
|
|
</form>
|
|
)}
|
|
|
|
{types && (
|
|
<>
|
|
<Table>
|
|
<TableHeader>
|
|
<TableRow>
|
|
<TableHead>{t("Name")}</TableHead>
|
|
<TableHead>{t("TktPrice")}</TableHead>
|
|
<TableHead>{t("TktQuantity")}</TableHead>
|
|
<TableHead>{t("TktLeft")}</TableHead>
|
|
<TableHead>{t("TktSalesEnd")}</TableHead>
|
|
<TableHead>{t("Status")}</TableHead>
|
|
<TableHead />
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{types.length === 0 && (
|
|
<TableRow>
|
|
<TableCell colSpan={7} className="text-muted-foreground">
|
|
{t("TktNoTypes")}
|
|
</TableCell>
|
|
</TableRow>
|
|
)}
|
|
{types.map((x) => (
|
|
<TableRow key={x.id}>
|
|
<TableCell>{x.name}</TableCell>
|
|
<TableCell>{x.priceSen === 0 ? t("TktFree") : money(x.priceSen)}</TableCell>
|
|
<TableCell>{x.quantity}</TableCell>
|
|
<TableCell>{x.left}</TableCell>
|
|
<TableCell>{x.salesEndDate ?? "-"}</TableCell>
|
|
<TableCell>
|
|
<Badge variant={x.enabled ? "positive" : "neutral"}>{t(x.enabled ? "Enabled" : "Disabled")}</Badge>
|
|
</TableCell>
|
|
<TableCell className="space-x-1 whitespace-nowrap text-right">
|
|
<Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => edit(x)}>
|
|
{t("Edit")}
|
|
</Button>
|
|
<Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => toggle(x)}>
|
|
{t(x.enabled ? "TktDisable" : "TktEnable")}
|
|
</Button>
|
|
<Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => setDeleting(x)}>
|
|
{t("TktDelete")}
|
|
</Button>
|
|
</TableCell>
|
|
</TableRow>
|
|
))}
|
|
</TableBody>
|
|
</Table>
|
|
|
|
<form onSubmit={saveType} className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
|
|
<div className="space-y-1">
|
|
<Label htmlFor="type-name">{t("TktTypeName")}</Label>
|
|
<Input id="type-name" maxLength={80} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
|
{fieldError("name")}
|
|
</div>
|
|
<div className="space-y-1">
|
|
<Label htmlFor="type-price">{t("TktPriceRm")}</Label>
|
|
<Input id="type-price" inputMode="decimal" value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} />
|
|
{fieldError("priceSen")}
|
|
</div>
|
|
<div className="space-y-1">
|
|
<Label htmlFor="type-quantity">{t("TktQuantity")}</Label>
|
|
<Input id="type-quantity" inputMode="numeric" value={form.quantity} onChange={(e) => setForm({ ...form, quantity: e.target.value })} />
|
|
{fieldError("quantity")}
|
|
</div>
|
|
<div className="space-y-1">
|
|
<Label htmlFor="type-end">{t("TktSalesEnd")}</Label>
|
|
<DatePicker id="type-end" value={form.salesEndDate} onChange={(v) => setForm({ ...form, salesEndDate: v })} />
|
|
{fieldError("salesEndDate")}
|
|
</div>
|
|
<div className="flex items-end gap-2">
|
|
<Button type="submit" disabled={busy}>
|
|
{t(form.id == null ? "TktAddType" : "TktSaveType")}
|
|
</Button>
|
|
{form.id != null && (
|
|
<Button type="button" variant="outline" disabled={busy} onClick={() => setForm(EMPTY)}>
|
|
{t("Cancel")}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</form>
|
|
<p className="text-xs text-muted-foreground">{t("TktSalesEndHelp")}</p>
|
|
</>
|
|
)}
|
|
|
|
{deleting && (
|
|
<ConfirmDialog
|
|
title={t("TktDeleteTitle")}
|
|
message={t("TktDeleteMessage", { name: deleting.name })}
|
|
confirmLabel={t("TktDelete")}
|
|
destructive
|
|
onConfirm={remove}
|
|
onCancel={() => setDeleting(null)}
|
|
/>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|