Files
co-lite/solvway-admin-portal/app/t/[code]/page.tsx
T

225 lines
10 KiB
TypeScript

"use client";
import { useEffect, useState, type FormEvent } from "react";
import { useParams } from "next/navigation";
import { AlertCircle, CheckCircle2, Loader2, XCircle } 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 { VisitorCard, VisitorState } from "@/app/components/registration/VisitorCard";
import { apiData, failMessage } from "@/app/components/registration/RegistrationForm";
import { ApiError } from "@/app/lib/clientApi";
import {
checkInTicket, consentTicket, getPublicTicket, getStaffTicket, ticketQrUrl, when,
type PublicTicket, type StaffTicket, type TicketNotice, type TicketState,
} from "@/app/lib/services/publicTickets";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type T = ReturnType<typeof useT>;
const REASON: Partial<Record<TicketState, string>> = {
AWAITING: "TktReasonAWAITING",
ORDER_CANCELLED: "TktReasonORDER_CANCELLED",
ORDER_EXPIRED: "TktReasonORDER_EXPIRED",
TICKET_CANCELLED: "TktReasonTICKET_CANCELLED",
};
const NOTICE = "space-y-2 rounded-md bg-muted p-3 text-xs text-muted-foreground";
/** add-event-tickets: one ticket, /t/<code>. Everyone sees the public view; staff of the event's company also get the staff view. */
export default function TicketPage() {
const t = useT();
const { code } = useParams<{ code: string }>();
const [ticket, setTicket] = useState<PublicTicket | null>(null);
const [staff, setStaff] = useState<StaffTicket | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Staff first: a door scan then never touches the rate-limited public view. Signed out, another company's staff
// or no BO_EVENTS: the staff call fails and the page loads the public view.
getStaffTicket(code)
.then(setStaff)
.catch(() => getPublicTicket(code)
.then(setTicket)
.catch((err) => {
const c = apiData(err).code;
setError(t(c === "TICKET_INVALID" ? "TktTicketInvalid" : c === "TOO_MANY" ? "RegTooMany" : "RegLoadFailed"));
}));
}, [code, t]);
const shown = staff ?? ticket;
if (error) return <VisitorCard><VisitorState h1 icon={AlertCircle} heading={error} role="alert" tone="error" /></VisitorCard>;
if (!shown) return <VisitorCard><VisitorState h1 icon={Loader2} iconClassName="motion-safe:animate-spin" heading={t("UiLoading")} role="status" /></VisitorCard>;
const event = { ...shown, companyName: shown.companyName ?? "", startDate: shown.startDate ?? shown.endDate ?? "",
endDate: shown.endDate ?? "", location: shown.location ?? "" };
return (
<VisitorCard event={event}>
{staff ? <StaffView code={code} staff={staff} companyName={event.companyName} onChange={setStaff} />
: ticket && <PublicView code={code} ticket={ticket} />}
</VisitorCard>
);
}
function PublicView({ code, ticket }: { code: string; ticket: PublicTicket }) {
const t = useT();
return (
<div className="space-y-4">
<div className="space-y-1 text-center">
{ticket.typeName && <p className="font-semibold">{ticket.typeName}</p>}
{ticket.attendeeFirstName && <p className="text-sm text-muted-foreground">{t("TktTicketFor", { name: ticket.attendeeFirstName })}</p>}
</div>
{ticket.state === "VALID" && (
<div className="flex flex-col items-center gap-2">
{/* eslint-disable-next-line @next/next/no-img-element -- a private, short-lived PNG from our own proxy */}
<img src={ticketQrUrl(code)} alt={t("TktQrAlt")} width={240} height={240} className="rounded-md border bg-white p-2" />
<p className="text-sm text-muted-foreground">{t("TktShowQr")}</p>
</div>
)}
{ticket.state === "CHECKED_IN" && (
<VisitorState icon={CheckCircle2} role="status" heading={t("TktCheckedInAt", { when: when(ticket.checkedInAt) })} />
)}
{ticket.state !== "VALID" && ticket.state !== "CHECKED_IN" && (
<VisitorState icon={XCircle} role="alert" tone="error" heading={t("TktNotValid")} />
)}
{ticket.notice && <PublicConsent code={code} notice={ticket.notice} companyName={ticket.companyName} />}
</div>
);
}
function NoticeText({ notice }: { notice: TicketNotice }) {
const t = useT();
return (
<details className={NOTICE}>
<summary className="cursor-pointer font-medium text-foreground">{t("RegNoticeSummary")}</summary>
<div className="mt-2 space-y-2">
<h2 className="font-semibold text-foreground">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{notice.textEn}</p>
<h2 className="font-semibold text-foreground">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{notice.textMs}</p>
</div>
</details>
);
}
function ConsentBox({ id, checked, onChange, companyName }: { id: string; checked: boolean; onChange: (on: boolean) => void; companyName: string }) {
const t = useT();
return (
<Label htmlFor={id} className="flex items-start gap-3 font-normal">
<Checkbox id={id} className="mt-0.5 size-5" checked={checked} onCheckedChange={(on) => onChange(on === true)} />
<span>{t("TktKeepUpdated", { company: companyName })}</span>
</Label>
);
}
function PublicConsent({ code, notice, companyName }: { code: string; notice: TicketNotice; companyName: string }) {
const t = useT();
const [on, setOn] = useState(false);
const [saving, setSaving] = useState(false);
const [done, setDone] = useState(false);
const [error, setError] = useState<string | null>(null);
if (done) return <p role="status" className="text-sm">{t("TktConsentDone")}</p>;
const save = () => {
setSaving(true);
setError(null);
consentTicket(code)
.then(() => setDone(true))
.catch((err) => setError(failMessage(t, err)))
.finally(() => setSaving(false));
};
return (
<div className="space-y-3 border-t pt-4">
<ConsentBox id="tkt-consent" checked={on} onChange={setOn} companyName={companyName} />
<NoticeText notice={notice} />
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<Button type="button" className="h-11 w-full" disabled={!on || saving} onClick={save}>{t("TktConsentSave")}</Button>
</div>
);
}
/** A refused check-in as the sentence staff read. */
function refusal(t: T, err: unknown): string {
const d = (err instanceof ApiError ? err.data : undefined) as { code?: string; details?: { value?: string } } | undefined;
const value = d?.details?.value;
switch (d?.code) {
case "ALREADY_CHECKED_IN": return t("TktAlreadyCheckedIn", { when: when(value) });
case "NOT_VALID": return t("TktNotValidReason", { reason: t(REASON[value as TicketState] ?? "TktNotValid") });
case "NOT_EVENT_DAY": return t("TktNotEventDay");
case "NAME_REQUIRED": return t("RegNameRequired");
case "MOBILE_OR_EMAIL_REQUIRED": return t("TktContactRequired");
default: return failMessage(t, err);
}
}
function StaffView({ code, staff, companyName, onChange }: {
code: string; staff: StaffTicket; companyName: string; onChange: (s: StaffTicket) => void;
}) {
const t = useT();
const [form, setForm] = useState({ name: "", mobile: "", email: "", consent: false });
const [saving, setSaving] = useState(false);
const [justCheckedIn, setJustCheckedIn] = useState(false);
const [error, setError] = useState<string | null>(null);
const submit = (e: FormEvent) => {
e.preventDefault();
setSaving(true);
setError(null);
checkInTicket(code, staff.named ? { consent: form.consent } : form)
.then((s) => {
setJustCheckedIn(true);
onChange(s);
})
.catch((err) => setError(refusal(t, err)))
.finally(() => setSaving(false));
};
const banner = justCheckedIn ? { tone: "ok", text: t("TktCheckedInNow") }
: staff.state === "VALID" ? { tone: "ok", text: t("TktStaffValid") }
: staff.state === "CHECKED_IN" ? { tone: "warn", text: t("TktAlreadyCheckedIn", { when: when(staff.checkedInAt) }) }
: { tone: "bad", text: t("TktNotValidReason", { reason: t(REASON[staff.state] ?? "TktNotValid") }) };
const tone = banner.tone === "ok" ? "border-2 border-positive bg-positive/10 text-positive"
: banner.tone === "warn" ? "border-2 border-warning bg-warning/10 text-warning" : "bg-destructive text-destructive-foreground";
return (
<div className="space-y-4">
<p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{t("TktStaffView")}</p>
<p role={banner.tone === "bad" ? "alert" : "status"} className={`rounded-md p-4 text-center text-xl font-semibold ${tone}`}>{banner.text}</p>
<div className="space-y-1 text-center">
{staff.typeName && <p className="font-semibold">{staff.typeName}</p>}
<p className="text-sm">{staff.attendeeName ?? t("TktUnnamed")}</p>
</div>
{staff.state === "VALID" && !justCheckedIn && (
<form onSubmit={submit} className="space-y-3" noValidate>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{!staff.named && (
<>
<div className="space-y-1">
<Label htmlFor="tkt-name">{t("TktAttendeeName")}</Label>
<Input id="tkt-name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
</div>
<div className="space-y-1">
<Label htmlFor="tkt-mobile">{t("RegMobile")}</Label>
<Input id="tkt-mobile" type="tel" value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value })} />
<p className="text-xs text-muted-foreground">{t("RegContactHint")}</p>
</div>
<div className="space-y-1">
<Label htmlFor="tkt-email">{t("RegEmail")}</Label>
<Input id="tkt-email" type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
</div>
</>
)}
{staff.notice && !staff.consented && (
<>
<ConsentBox id="tkt-staff-consent" checked={form.consent} onChange={(on) => setForm({ ...form, consent: on })} companyName={companyName} />
<NoticeText notice={staff.notice} />
</>
)}
<Button type="submit" className="h-12 w-full text-base" disabled={saving}>{t("TktCheckIn")}</Button>
</form>
)}
</div>
);
}