Files
co-lite/solvway-admin-portal/app/components/pages/TicketsBlock.tsx
T

225 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import Link from "next/link";
import { useEffect, useState, type FormEvent } from "react";
import { AlertCircle, CheckCircle2, Minus, Plus } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { VisitorState } from "@/app/components/registration/VisitorCard";
import { apiData, failMessage } from "@/app/components/registration/RegistrationForm";
import { utmTags } from "./LandingForm";
import { listTicketTypes, money } from "@/app/lib/services/adminTickets";
import { publicCall } from "@/app/lib/services/publicRegistration";
import { when, type PublicTicketType, type TicketRequestResult, type TicketsInfo } from "@/app/lib/services/publicTickets";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const MAX = 10;
type Buyer = { name: string; mobile: string; email: string; companyName: string; consent: boolean; website: string };
const EMPTY: Buyer = { name: "", mobile: "", email: "", companyName: "", consent: false, website: "" };
const FIELDS = ["name", "mobile", "email", "companyName", "consent"];
const NOTICE = "rounded-md bg-muted p-3 text-xs text-muted-foreground";
/** One type's row: name, price and seats, and a stepper while it is on sale. */
function TypeRow({ type, qty, canAdd, onChange, disabled }: { type: PublicTicketType; qty?: number; canAdd?: boolean; onChange?: (n: number) => void; disabled?: boolean }) {
const t = useT();
const onSale = type.state === "ON_SALE" && type.left > 0;
return (
<div role="group" aria-label={type.name} className="flex items-center justify-between gap-3 rounded-md border p-3">
<div className="min-w-0">
<p className="font-medium">{type.name}</p>
<p className="text-sm text-muted-foreground">
<span>{type.priceSen === 0 ? t("TktFree") : money(type.priceSen)}</span>
{" · "}
<span>{type.state === "ENDED" ? t("TktSalesEnded") : onSale ? t("TktSeatsLeft", { count: type.left }) : t("TktSoldOut")}</span>
</p>
</div>
{onSale && onChange && (
<div className="flex items-center gap-2">
<Button type="button" variant="outline" size="icon" className="size-11" aria-label={t("TktRemoveOne", { name: type.name })}
disabled={disabled || !qty} onClick={() => onChange((qty ?? 0) - 1)}>
<Minus className="size-4" aria-hidden="true" />
</Button>
<span className="w-6 text-center tabular-nums" aria-live="polite">{qty ?? 0}</span>
<Button type="button" variant="outline" size="icon" className="size-11" aria-label={t("TktAddOne", { name: type.name })}
disabled={disabled || !canAdd} onClick={() => onChange((qty ?? 0) + 1)}>
<Plus className="size-4" aria-hidden="true" />
</Button>
</div>
)}
</div>
);
}
/** The editor canvas: the event's real types (read with the staff ticket call), with no form. */
function TicketsPreview({ eventUuid }: { eventUuid?: string | null }) {
const t = useT();
const [types, setTypes] = useState<PublicTicketType[] | null>(null);
useEffect(() => {
if (!eventUuid) return;
listTicketTypes(eventUuid)
.then((list) => setTypes(list.filter((x) => x.enabled).map((x) => ({ id: x.id, name: x.name, priceSen: x.priceSen, left: x.left, state: x.left > 0 ? "ON_SALE" : "SOLD_OUT" }))))
.catch(() => setTypes([]));
}, [eventUuid]);
return (
<div className="space-y-3">
{types?.map((x) => <TypeRow key={x.id} type={x} />)}
<p role="status" className="text-sm text-muted-foreground">{t("TktPreviewNote")}</p>
</div>
);
}
/** add-event-ticket-orders: a landing page's TICKETS block. Quantities per type (10 in all), the buyer, the consent; then the thank-you. */
export function TicketsBlock({ companyCode, slug, index, info, preview, eventUuid }: {
companyCode: string; slug: string; index: number; info?: TicketsInfo; preview?: boolean; eventUuid?: string | null;
}) {
const t = useT();
const [qty, setQty] = useState<Record<number, number>>({});
const [buyer, setBuyer] = useState<Buyer>(EMPTY);
const [errors, setErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [done, setDone] = useState<TicketRequestResult | null>(null);
const [closed, setClosed] = useState(false);
if (preview) return <TicketsPreview eventUuid={eventUuid} />;
if (!info || closed) return <VisitorState icon={AlertCircle} heading={t("TktSalesClosed")} role="status" />;
if (done) return <Thanks result={done} />;
const count = Object.values(qty).reduce((a, b) => a + b, 0);
const total = info.types.reduce((sum, x) => sum + (qty[x.id] ?? 0) * x.priceSen, 0);
const set = (patch: Partial<Buyer>) => setBuyer((b) => ({ ...b, ...patch }));
async function onSubmit(e: FormEvent) {
e.preventDefault();
const errs: Record<string, string> = {};
if (count < 1) errs.tickets = t("TktChooseTickets");
if (!buyer.name.trim()) errs.name = t("RegNameRequired");
if (!buyer.email.trim()) errs.email = t("TktEmailRequired");
if (!buyer.consent) errs.consent = t("TktConsentRequired");
setErrors(errs);
setFormError(null);
if (Object.keys(errs).length) return;
setSaving(true);
try {
const lines = info!.types.filter((x) => qty[x.id]).map((x) => ({ ticketTypeId: x.id, quantity: qty[x.id] }));
const body = { lines, ...buyer, name: buyer.name.trim(), mobile: buyer.mobile.trim(), email: buyer.email.trim(), companyName: buyer.companyName.trim() };
setDone(await publicCall<TicketRequestResult>(`/api/public/pages/${encodeURIComponent(companyCode)}/${encodeURIComponent(slug)}/tickets/${index}`, {
method: "POST",
body: JSON.stringify({ ...body, ...utmTags(window.location.search) }),
}));
} catch (err) {
const { status, code, error, field } = apiData(err);
if (code === "TICKETS_CLOSED") setClosed(true);
else if (status === 400 && error && field && FIELDS.includes(field)) setErrors({ [field]: error });
else setFormError(failMessage(t, err));
setSaving(false);
}
}
const fieldError = (id: string) => errors[id] && <p id={`tkt-${id}-error`} className="text-sm text-destructive">{errors[id]}</p>;
const field = (id: "name" | "mobile" | "email" | "companyName", label: string, type = "text") => (
<div className="space-y-1.5">
<Label htmlFor={`tkt-${id}`}>{label}</Label>
<Input id={`tkt-${id}`} className="h-11" type={type} value={buyer[id]} disabled={saving} onChange={(e) => set({ [id]: e.target.value })}
aria-invalid={!!errors[id]} aria-describedby={errors[id] ? `tkt-${id}-error` : undefined} />
{fieldError(id)}
</div>
);
return (
<form onSubmit={onSubmit} className="space-y-4" noValidate>
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
<div className="space-y-2">
{info.types.map((x) => (
<TypeRow key={x.id} type={x} qty={qty[x.id]} disabled={saving}
canAdd={count < MAX && (qty[x.id] ?? 0) < x.left}
onChange={(n) => setQty((q) => ({ ...q, [x.id]: Math.max(0, n) }))} />
))}
<p className="text-xs text-muted-foreground">{t("TktMax")}</p>
{fieldError("tickets")}
</div>
<p className="flex items-baseline justify-between text-lg font-semibold">
<span>{t("TktTotal")}</span>
<span data-testid="tickets-total" className="tabular-nums">{money(total)}</span>
</p>
{field("name", t("RegName"))}
{field("email", t("RegEmail"), "email")}
{field("mobile", t("RegMobile"), "tel")}
{field("companyName", t("RegCompany"))}
<details className={NOTICE}>
<summary className="cursor-pointer font-medium text-foreground">{t("RegNoticeSummary")}</summary>
<div className="mt-2 space-y-2">
<h3 className="font-semibold text-foreground">{t("RegNoticeEn")}</h3>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h3 className="font-semibold text-foreground">{t("RegNoticeMs")}</h3>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</div>
</details>
<Label htmlFor={`tkt-consent-${index}`} className="flex min-h-11 w-full cursor-pointer items-start gap-3 rounded-md border p-3 leading-normal">
<Checkbox id={`tkt-consent-${index}`} className="mt-0.5 size-6" checked={buyer.consent} onCheckedChange={(on) => set({ consent: on === true })}
aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "tkt-consent-error" : undefined} />
<span className="space-y-1 text-sm font-normal">
<span className="block">{t("RegConsentEn", { company: info.companyName })}</span>
<span className="block">{t("RegConsentMs", { company: info.companyName })}</span>
</span>
</Label>
{fieldError("consent")}
{/* Honeypot: people never see or reach it; bots fill it and the server saves nothing. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<input name="website" tabIndex={-1} autoComplete="off" value={buyer.website} onChange={(e) => set({ website: e.target.value })} />
</div>
<Button type="submit" className="h-11 w-full" disabled={saving}>{t("TktRequest")}</Button>
</form>
);
}
/** The thank-you: the order, how and by when to pay while it awaits payment, and its link. */
export function Thanks({ result }: { result: TicketRequestResult }) {
const t = useT();
if (!result.reference || !result.token) return <VisitorState icon={CheckCircle2} heading={t("TktThanksPlain", { event: result.eventName })} role="status" />;
const paid = result.status === "PAID";
return (
<div role="status" className="space-y-4">
<VisitorState icon={CheckCircle2} heading={t(paid ? "TktThanksPaid" : "TktThanks", { reference: result.reference })} />
<OrderSummary lines={result.lines ?? []} totalSen={result.totalSen ?? 0} />
{!paid && result.paymentInstructions && (
<PaymentBox instructions={result.paymentInstructions} holdUntil={result.holdUntil} />
)}
<Button asChild className="h-11 w-full">
<Link href={`/o/${encodeURIComponent(result.token)}`}>{t("TktViewOrder")}</Link>
</Button>
</div>
);
}
export function OrderSummary({ lines, totalSen }: { lines: { name: string; unitPriceSen: number; quantity: number }[]; totalSen: number }) {
const t = useT();
return (
<ul className="divide-y rounded-md border text-sm">
{lines.map((l, i) => (
<li key={i} className="flex justify-between gap-3 p-3">
<span>{l.name} × {l.quantity}</span>
<span className="tabular-nums">{money(l.unitPriceSen * l.quantity)}</span>
</li>
))}
<li className="flex justify-between gap-3 p-3 font-semibold">
<span>{t("TktTotal")}</span>
<span className="tabular-nums">{money(totalSen)}</span>
</li>
</ul>
);
}
export function PaymentBox({ instructions, holdUntil }: { instructions: string; holdUntil?: string | null }) {
const t = useT();
return (
<div className="space-y-2 rounded-md bg-muted p-4 text-sm">
<h3 className="font-semibold">{t("TktHowToPay")}</h3>
<p className="whitespace-pre-line">{instructions}</p>
{holdUntil && <p className="font-medium">{t("TktPayBy", { when: when(holdUntil) })}</p>}
</div>
);
}