feat(tickets): ticket page /t/<code> with public and staff views, proxies and labels

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-04 17:38:07 +08:00
1 parent 031ec8449e
commit 2b8b3d92bc
20 files changed
+698 -7

No files matched your search

+46
View File
@@ -2007,6 +2007,52 @@ INSERT INTO message (code, content, area) SELECT 'TktPublicExpired', JSON_OBJECT
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此订单在收到付款前已过期。') WHERE LOWER(code) = LOWER('TktPublicExpired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktOrderInvalid', JSON_OBJECT('en_US', 'This order link is not valid.', 'zh_CN', '此订单链接无效。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktOrderInvalid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此订单链接无效。') WHERE LOWER(code) = LOWER('TktOrderInvalid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketInvalid', JSON_OBJECT('en_US', 'This ticket link is not valid.', 'zh_CN', '此门票链接无效。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketInvalid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票链接无效。') WHERE LOWER(code) = LOWER('TktTicketInvalid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktTicketFor', JSON_OBJECT('en_US', 'Ticket for {name}', 'zh_CN', '{name} 的门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktTicketFor') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{name} 的门票') WHERE LOWER(code) = LOWER('TktTicketFor') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktQrAlt', JSON_OBJECT('en_US', 'Ticket QR code', 'zh_CN', '门票二维码'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktQrAlt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票二维码') WHERE LOWER(code) = LOWER('TktQrAlt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktShowQr', JSON_OBJECT('en_US', 'Show this QR code at the entrance.', 'zh_CN', '请在入口出示此二维码。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktShowQr') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请在入口出示此二维码。') WHERE LOWER(code) = LOWER('TktShowQr') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCheckedInAt', JSON_OBJECT('en_US', 'Checked in at {when}', 'zh_CN', '已于 {when} 签到'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCheckedInAt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已于 {when} 签到') WHERE LOWER(code) = LOWER('TktCheckedInAt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotValid', JSON_OBJECT('en_US', 'This ticket is not valid', 'zh_CN', '此门票无效'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotValid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此门票无效') WHERE LOWER(code) = LOWER('TktNotValid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonAWAITING', JSON_OBJECT('en_US', 'awaiting payment', 'zh_CN', '等待付款'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonAWAITING') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '等待付款') WHERE LOWER(code) = LOWER('TktReasonAWAITING') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonORDER_CANCELLED', JSON_OBJECT('en_US', 'order cancelled', 'zh_CN', '订单已取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonORDER_CANCELLED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已取消') WHERE LOWER(code) = LOWER('TktReasonORDER_CANCELLED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonORDER_EXPIRED', JSON_OBJECT('en_US', 'order expired', 'zh_CN', '订单已过期'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonORDER_EXPIRED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '订单已过期') WHERE LOWER(code) = LOWER('TktReasonORDER_EXPIRED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktReasonTICKET_CANCELLED', JSON_OBJECT('en_US', 'ticket cancelled', 'zh_CN', '门票已取消'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktReasonTICKET_CANCELLED') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票已取消') WHERE LOWER(code) = LOWER('TktReasonTICKET_CANCELLED') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktKeepUpdated', JSON_OBJECT('en_US', 'Keep me updated about {company} events', 'zh_CN', '向我发送 {company} 的活动资讯'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktKeepUpdated') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '向我发送 {company} 的活动资讯') WHERE LOWER(code) = LOWER('TktKeepUpdated') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktConsentSave', JSON_OBJECT('en_US', 'Save', 'zh_CN', '保存'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktConsentSave') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存') WHERE LOWER(code) = LOWER('TktConsentSave') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktConsentDone', JSON_OBJECT('en_US', 'Thank you. We will keep you updated.', 'zh_CN', '谢谢,我们会向您发送最新资讯。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktConsentDone') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '谢谢,我们会向您发送最新资讯。') WHERE LOWER(code) = LOWER('TktConsentDone') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStaffView', JSON_OBJECT('en_US', 'Staff check-in', 'zh_CN', '工作人员签到'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStaffView') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '工作人员签到') WHERE LOWER(code) = LOWER('TktStaffView') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktStaffValid', JSON_OBJECT('en_US', 'Valid', 'zh_CN', '有效'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktStaffValid') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有效') WHERE LOWER(code) = LOWER('TktStaffValid') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAlreadyCheckedIn', JSON_OBJECT('en_US', 'Already checked in at {when}', 'zh_CN', '已于 {when} 签到过'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAlreadyCheckedIn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '已于 {when} 签到过') WHERE LOWER(code) = LOWER('TktAlreadyCheckedIn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotValidReason', JSON_OBJECT('en_US', 'Not valid: {reason}', 'zh_CN', '无效:{reason}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotValidReason') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无效:{reason}') WHERE LOWER(code) = LOWER('TktNotValidReason') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktNotEventDay', JSON_OBJECT('en_US', 'Check-in is only open on the event days.', 'zh_CN', '仅在活动日开放签到。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktNotEventDay') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '仅在活动日开放签到。') WHERE LOWER(code) = LOWER('TktNotEventDay') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCheckIn', JSON_OBJECT('en_US', 'Check in', 'zh_CN', '签到'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCheckIn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '签到') WHERE LOWER(code) = LOWER('TktCheckIn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktCheckedInNow', JSON_OBJECT('en_US', 'Checked in.', 'zh_CN', '签到成功。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktCheckedInNow') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '签到成功。') WHERE LOWER(code) = LOWER('TktCheckedInNow') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktUnnamed', JSON_OBJECT('en_US', 'No attendee named yet', 'zh_CN', '尚未填写参加者'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktUnnamed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '尚未填写参加者') WHERE LOWER(code) = LOWER('TktUnnamed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktAttendeeName', JSON_OBJECT('en_US', 'Attendee name', 'zh_CN', '参加者姓名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktAttendeeName') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '参加者姓名') WHERE LOWER(code) = LOWER('TktAttendeeName') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'TktContactRequired', JSON_OBJECT('en_US', 'Enter a mobile number or an email.', 'zh_CN', '请输入手机号码或电子邮件。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('TktContactRequired') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请输入手机号码或电子邮件。') WHERE LOWER(code) = LOWER('TktContactRequired') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockTickets', JSON_OBJECT('en_US', 'Tickets', 'zh_CN', '门票'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockTickets') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门票') WHERE LOWER(code) = LOWER('PagesBlockTickets') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTicketsEvent', JSON_OBJECT('en_US', 'Event selling tickets', 'zh_CN', '售票活动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTicketsEvent') AND area = 'A');
+1 -1
View File
@@ -51,7 +51,7 @@ Product design: `docs/superpowers/specs/2026-12-04-event-ticketing-design.md` (a
- Normalisation and the `MOBILE_OR_EMAIL_REQUIRED`, name-length and email-format errors reuse the QR registration helpers in mobile-api.
4. **Consent creates the lead through `RegistrationService.register`.** It is called with source `TICKET`, no salesperson, the company's current notice and `attend=false`. At check-in it is called with `attend=true`. The returned event lead uuid is stored on the ticket. An attendee whose details match a lead is linked to it, as QR registration already does.
- **Unnamed tickets:** the consent needs a name and contact, so on the public page it is offered only for a named ticket. At the door, staff enter them first.
5. **Staff view detection.** The `/t/[code]` page always loads the public view (`GET /api/public/tickets/{code}`). When `/api/auth/session` reports a session, it also calls `GET /api/admin/tickets/{code}`. That call is guarded by `@AdminModule("BO_EVENTS")` and scoped by company in mobile-api with `loadEvent(uuid, null)`, so another company's event is a 404. On 401, 403 or 404 the page stays public. The admin call uses a plain `fetch`, not `clientApi`, so a signed-out visitor is never bounced to login.
5. **Staff view detection.** The `/t/[code]` page always loads the public view (`GET /api/public/tickets/{code}`). It also calls the portal's `/api/tickets/{code}`, which answers 401 at once when there is no session and otherwise calls `GET /api/admin/tickets/{code}`. That call is guarded by `@AdminModule("BO_EVENTS")` and scoped by company in mobile-api with `loadEvent(uuid, null)`, so another company's event is a 404. On 401, 403 or 404 the page stays public. The admin call uses a plain `fetch`, not `clientApi`, so a signed-out visitor is never bounced to login.
6. **Check-in.** `POST /api/admin/tickets/{code}/checkin` takes optional `{name, mobile, email, consent}`, which are required when the ticket is unnamed. Refusals are 409 with the codes `ALREADY_CHECKED_IN|<time>`, `NOT_VALID|<state>` and `NOT_EVENT_DAY`. The update is conditional (`checked_in_at IS NULL`), so two scanners cannot both check a ticket in; the loser gets `ALREADY_CHECKED_IN`. The action is `@Audited`.
7. **Self check-in on a ticketed event.** For `tickets_enabled` events only, `EventCheckInService.lookup` checks, in order:
1. the oldest `ACTIVE` ticket on a `PAID` order of the event, not checked in, whose attendee mobile or email matches, or whose attendee is blank and whose order's buyer mobile or email matches. It is checked in with `checked_in_by = 'self'`, and the lead is marked attended when the ticket has one;
+1 -1
View File
@@ -108,7 +108,7 @@ Design: `design.md` (technical contracts) and `docs/superpowers/specs/2026-12-04
## 4. admin-portal
- [ ] 4.1 The ticket page `/t/[code]`.
- [x] 4.1 The ticket page `/t/[code]`.
- Depends on: 3.2
- Tests first:
- **Public view:** valid, checked in, not valid and unknown.
@@ -0,0 +1,11 @@
import { NextResponse, type NextRequest } from "next/server";
import { forwardPublic } from "@/app/lib/server/publicProxy";
type Ctx = { params: Promise<{ token: string; ticketId: string }> };
// add-event-tickets: the buyer names a ticket's attendee from the order page.
export async function POST(req: NextRequest, { params }: Ctx) {
const { token, ticketId } = await params;
if (!/^\d{1,19}$/.test(ticketId)) return NextResponse.json({ error: "Not found" }, { status: 404 });
return forwardPublic(req, `/api/public/orders/${encodeURIComponent(token)}/tickets/${encodeURIComponent(ticketId)}/attendee`, "POST");
}
@@ -0,0 +1,59 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), callMobileApiBinary: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi, callMobileApiBinary: mocks.callMobileApiBinary }));
import { GET as ticketGet } from "./tickets/[token]/route";
import { POST as consentPost } from "./tickets/[token]/consent/route";
import { GET as qrGet } from "./tickets/[token]/qr.png/route";
import { POST as attendeePost } from "./orders/[token]/tickets/[ticketId]/attendee/route";
type Handler = (req: never, ctx: { params: Promise<Record<string, string>> }) => Promise<Response>;
const xff = { "x-forwarded-for": "6.6.6.6, 203.0.113.7" };
const call = (h: unknown, params: Record<string, string>, init: RequestInit = {}) =>
(h as Handler)(new Request("http://localhost/x", init) as never, { params: Promise.resolve(params) });
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { state: "VALID" } });
mocks.callMobileApiBinary.mockReset().mockResolvedValue({ ok: true, data: { body: new Uint8Array([137, 80, 78, 71]).buffer, contentType: "image/png" } });
});
// add-event-tickets: the ticket page, its consent, its QR PNG and naming an attendee, signed out, with only the last X-Forwarded-For hop.
describe("public ticket code proxies", () => {
it("GET a ticket by its code", async () => {
const res = await call(ticketGet, { token: "c/1" }, { headers: xff });
expect(await res.json()).toEqual({ state: "VALID" });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/tickets/c%2F1", { headers: { "X-Forwarded-For": "203.0.113.7" } });
});
it("POST a consent", async () => {
await call(consentPost, { token: "c1" }, { method: "POST", body: '{"consent":true}', headers: xff });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/tickets/c1/consent",
{ method: "POST", body: { consent: true }, headers: { "X-Forwarded-For": "203.0.113.7" } });
});
it("POST an attendee to an order's ticket", async () => {
await call(attendeePost, { token: "t/1", ticketId: "7" }, { method: "POST", body: '{"name":"Tan"}', headers: xff });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/orders/t%2F1/tickets/7/attendee",
{ method: "POST", body: { name: "Tan" }, headers: { "X-Forwarded-For": "203.0.113.7" } });
});
it("refuses a ticket id that is not a number without calling upstream", async () => {
const res = await call(attendeePost, { token: "t1", ticketId: "7/x" }, { method: "POST", body: "{}" });
expect(res.status).toBe(404);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes the QR PNG bytes and type, private, with the client hop", async () => {
const res = await call(qrGet, { token: "c1" }, { headers: xff });
expect(res.headers.get("Content-Type")).toBe("image/png");
expect(res.headers.get("Cache-Control")).toBe("private, max-age=300");
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([137, 80, 78, 71]));
expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/public/tickets/c1/qr.png", { headers: { "X-Forwarded-For": "203.0.113.7" } });
});
it("answers 404 for a QR that is not there", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: false, status: 404, error: "x" });
expect((await call(qrGet, { token: "c1" })).status).toBe(404);
});
});
@@ -0,0 +1,4 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
// add-event-tickets: the attendee's "keep me updated" on their ticket page.
export const POST = publicRoute("tickets", "/consent", "POST");
@@ -0,0 +1,19 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApiBinary } from "@/app/lib/server/mobileApi";
import { clientIp } from "@/app/lib/server/clientContext";
import type { TokenCtx } from "@/app/lib/server/publicProxy";
// add-event-tickets: a valid ticket's QR as a PNG, for the page and the emails. Rate-limited per client, so the client hop goes along.
export async function GET(req: NextRequest, { params }: TokenCtx) {
const xff = clientIp(req);
const result = await callMobileApiBinary(`/api/public/tickets/${encodeURIComponent((await params).token)}/qr.png`,
{ headers: xff ? { "X-Forwarded-For": xff } : {} });
if (!result.ok) return new NextResponse(null, { status: result.status === 404 ? 404 : 502 });
return new NextResponse(result.data.body, {
headers: {
"Content-Type": result.data.contentType ?? "image/png",
"Cache-Control": "private, max-age=300",
"X-Content-Type-Options": "nosniff",
},
});
}
@@ -0,0 +1,4 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
// add-event-tickets: the public ticket page reads its ticket by the code.
export const GET = publicRoute("tickets", "", "GET");
@@ -0,0 +1,16 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
type Ctx = { params: Promise<{ code: string }> };
// add-event-tickets: door check-in from the staff view.
export async function POST(req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<unknown>(`/api/admin/tickets/${encodeURIComponent((await params).code)}/checkin`,
{ method: "POST", body: await req.json().catch(() => ({})), token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data ?? {});
}
@@ -0,0 +1,15 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
type Ctx = { params: Promise<{ code: string }> };
// add-event-tickets: the staff view of a scanned ticket. mobile-api checks BO_EVENTS and the event's company.
export async function GET(_req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<unknown>(`/api/admin/tickets/${encodeURIComponent((await params).code)}`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data ?? {});
}
@@ -0,0 +1,42 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./tickets/[code]/route";
import { POST } from "./tickets/[code]/checkin/route";
const req = (init?: RequestInit) => new Request("http://localhost/x", init) as never;
const p = (code: string) => ({ params: Promise.resolve({ code }) });
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { state: "VALID" } });
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
// add-event-tickets: the staff ticket view and door check-in go to mobile-api with the session token.
describe("staff ticket proxies", () => {
it("forward the view and the check-in with the token", async () => {
await GET(req(), p("c/1"));
await POST(req({ method: "POST", body: '{"name":"Lim Wei"}' }), p("c1"));
expect(mocks.callMobileApi.mock.calls).toEqual([
["/api/admin/tickets/c%2F1", { token: "jwt" }],
["/api/admin/tickets/c1/checkin", { method: "POST", body: { name: "Lim Wei" }, token: "jwt" }],
]);
});
it("answer 401 without a session and never call upstream", async () => {
mocks.getToken.mockResolvedValue(undefined);
expect((await GET(req(), p("c1"))).status).toBe(401);
expect((await POST(req({ method: "POST", body: "{}" }), p("c1"))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("pass a refusal with its status and code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "NOT_EVENT_DAY", code: "NOT_EVENT_DAY" });
const res = await POST(req({ method: "POST", body: "{}" }), p("c1"));
expect(res.status).toBe(409);
expect(((await res.json()) as Record<string, unknown>).code).toBe("NOT_EVENT_DAY");
});
});
@@ -24,6 +24,8 @@ const ALLOW: Record<string, string[]> = {
"app/pos/_components/SplitTenderPanel.tsx": ["bg-white"],
// The full-screen QR sits on a white quiet zone so it scans in dark mode.
"app/components/registration/QrCodeItem.tsx": ["bg-white"],
// add-event-tickets: the ticket QR sits on a white quiet zone so it scans in dark mode.
"app/t/[code]/page.tsx": ["bg-white"],
// A sent email's HTML is authored for a white mail-client canvas; a theme surface would put the
// email's dark text on dark in dark mode.
"app/email-templates/logs/[id]/page.tsx": ["bg-white"],
@@ -1017,6 +1017,29 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
TktPublicCancelled: "This order was cancelled.",
TktPublicExpired: "This order expired before payment arrived.",
TktOrderInvalid: "This order link is not valid.",
TktTicketInvalid: "This ticket link is not valid.",
TktTicketFor: "Ticket for {name}",
TktQrAlt: "Ticket QR code",
TktShowQr: "Show this QR code at the entrance.",
TktCheckedInAt: "Checked in at {when}",
TktNotValid: "This ticket is not valid",
TktReasonAWAITING: "awaiting payment",
TktReasonORDER_CANCELLED: "order cancelled",
TktReasonORDER_EXPIRED: "order expired",
TktReasonTICKET_CANCELLED: "ticket cancelled",
TktKeepUpdated: "Keep me updated about {company} events",
TktConsentSave: "Save",
TktConsentDone: "Thank you. We will keep you updated.",
TktStaffView: "Staff check-in",
TktStaffValid: "Valid",
TktAlreadyCheckedIn: "Already checked in at {when}",
TktNotValidReason: "Not valid: {reason}",
TktNotEventDay: "Check-in is only open on the event days.",
TktCheckIn: "Check in",
TktCheckedInNow: "Checked in.",
TktUnnamed: "No attendee named yet",
TktAttendeeName: "Attendee name",
TktContactRequired: "Enter a mobile number or an email.",
PagesBlockTickets: "Tickets",
PagesTicketsEvent: "Event selling tickets",
PagesChooseTicketsEvent: "Choose an event with tickets on",
@@ -1000,6 +1000,29 @@
"TktPublicCancelled": "此订单已取消。",
"TktPublicExpired": "此订单在收到付款前已过期。",
"TktOrderInvalid": "此订单链接无效。",
"TktTicketInvalid": "此门票链接无效。",
"TktTicketFor": "{name} 的门票",
"TktQrAlt": "门票二维码",
"TktShowQr": "请在入口出示此二维码。",
"TktCheckedInAt": "已于 {when} 签到",
"TktNotValid": "此门票无效",
"TktReasonAWAITING": "等待付款",
"TktReasonORDER_CANCELLED": "订单已取消",
"TktReasonORDER_EXPIRED": "订单已过期",
"TktReasonTICKET_CANCELLED": "门票已取消",
"TktKeepUpdated": "向我发送 {company} 的活动资讯",
"TktConsentSave": "保存",
"TktConsentDone": "谢谢,我们会向您发送最新资讯。",
"TktStaffView": "工作人员签到",
"TktStaffValid": "有效",
"TktAlreadyCheckedIn": "已于 {when} 签到过",
"TktNotValidReason": "无效:{reason}",
"TktNotEventDay": "仅在活动日开放签到。",
"TktCheckIn": "签到",
"TktCheckedInNow": "签到成功。",
"TktUnnamed": "尚未填写参加者",
"TktAttendeeName": "参加者姓名",
"TktContactRequired": "请输入手机号码或电子邮件。",
"PagesBlockTickets": "门票",
"PagesTicketsEvent": "售票活动",
"PagesChooseTicketsEvent": "选择已开启售票的活动",
@@ -51,11 +51,11 @@ describe("guardDecision", () => {
describe("visitor pages /r, /i, /c, /o", () => {
it("pass signed out and with a reset pending; the bare prefixes and admin paths do not", () => {
const pending = { present: true, resetRequired: true };
for (const p of ["/r/x", "/i/x", "/c/x", "/o/x"]) {
for (const p of ["/r/x", "/i/x", "/c/x", "/o/x", "/t/x"]) {
expect(guardDecision(p, null), p).toBeNull();
expect(guardDecision(p, pending), p).toBeNull();
}
for (const p of ["/events", "/i", "/c/", "/i/", "/c/x/y", "/o/", "/o/x/y"]) {
for (const p of ["/events", "/i", "/c/", "/i/", "/c/x/y", "/o/", "/o/x/y", "/t/", "/t/x/y"]) {
expect(guardDecision(p, null), p).toBe("/login");
expect(guardDecision(p, pending), p).toBe("/reset-password");
}
+2 -2
View File
@@ -9,9 +9,9 @@
export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forgot-password"]);
// Visitor pages, not signed in: /r/<token> QR self-registration, /i/<token> personal invite, /c/<token> event check-in,
// /o/<token> a ticket order (add-event-ticket-orders).
// /o/<token> a ticket order (add-event-ticket-orders), /t/<code> a ticket (add-event-tickets; staff also open it signed in).
// (A pattern, so PUBLIC_PATHS stays exact.)
const VISITOR_PATH = /^\/[rico]\/[^/]+$/;
const VISITOR_PATH = /^\/[ricot]\/[^/]+$/;
// Published landing pages: /p/<company-code>/<slug>.
const LANDING_PATH = /^\/p\/[^/]+\/[^/]+$/;
// add-custom-html-block: a published page's Custom HTML frame, /p/<company-code>/<slug>/frame/<block>.
@@ -191,7 +191,7 @@ export interface BinaryPayload {
/** GET a binary upstream response (e.g. an xlsx export); failures use the same shape as callMobileApi. */
export async function callMobileApiBinary(
path: string,
opts: Pick<MobileCallOptions, "token" | "timeoutMs"> = {},
opts: Pick<MobileCallOptions, "token" | "timeoutMs" | "headers"> = {},
): Promise<ApiResult<BinaryPayload>> {
const up = await upstreamFetch(path, opts);
if ("fail" in up) return up.fail;
@@ -61,3 +61,63 @@ export function when(s: string | null | undefined): string {
}
export const getPublicOrder = (token: string) => publicCall<PublicOrder>(`/api/public/orders/${encodeURIComponent(token)}`);
// add-event-tickets: the ticket page, its staff view and naming attendees.
export type TicketState = "VALID" | "CHECKED_IN" | "AWAITING" | "ORDER_CANCELLED" | "ORDER_EXPIRED" | "TICKET_CANCELLED";
export interface TicketNotice {
id: number;
textEn: string;
textMs: string;
}
interface TicketEvent {
eventName: string;
startDate: string | null;
endDate: string | null;
location: string | null;
}
/** The public view: no contact details; the notice only when the attendee can still opt in. */
export interface PublicTicket extends TicketEvent {
companyName: string;
typeName: string | null;
attendeeFirstName: string | null;
named: boolean;
state: TicketState;
checkedInAt: string | null;
consented: boolean;
notice?: TicketNotice;
}
export interface StaffTicket extends TicketEvent {
typeName: string | null;
attendeeName: string | null;
named: boolean;
consented: boolean;
state: TicketState;
checkedInAt: string | null;
checkedInBy: string | null;
notice?: TicketNotice;
}
export interface CheckInBody {
name?: string;
mobile?: string;
email?: string;
consent: boolean;
}
const code = (c: string) => `/api/public/tickets/${encodeURIComponent(c)}`;
export const getPublicTicket = (c: string) => publicCall<PublicTicket>(code(c));
export const ticketQrUrl = (c: string) => `${code(c)}/qr.png`;
export const consentTicket = (c: string) =>
publicCall<{ consented: boolean }>(`${code(c)}/consent`, { method: "POST", body: JSON.stringify({ consent: true }) });
// Staff calls use plain fetch, not clientApi: a signed-out visitor or another company's staff gets an error and keeps
// the public view, never a redirect to the login page.
export const getStaffTicket = (c: string) => publicCall<StaffTicket>(`/api/tickets/${encodeURIComponent(c)}`);
export const checkInTicket = (c: string, body: CheckInBody) =>
publicCall<StaffTicket>(`/api/tickets/${encodeURIComponent(c)}/checkin`, { method: "POST", body: JSON.stringify(body) });
@@ -0,0 +1,147 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
const mocks = vi.hoisted(() => ({ getPublicTicket: vi.fn(), getStaffTicket: vi.fn(), consentTicket: vi.fn(), checkInTicket: vi.fn() }));
vi.mock("@/app/lib/services/publicTickets", async (orig) => ({
...(await orig<object>()),
getPublicTicket: mocks.getPublicTicket,
getStaffTicket: mocks.getStaffTicket,
consentTicket: mocks.consentTicket,
checkInTicket: mocks.checkInTicket,
}));
vi.mock("next/navigation", () => ({ useParams: () => ({ code: "abcdefghijklmnopqrstu_" }) }));
import { ApiError } from "@/app/lib/clientApi";
import TicketPage from "./page";
const CODE = "abcdefghijklmnopqrstu_";
const EVENT = { eventName: "KL Hotel Tech Day", startDate: "2027-01-15", endDate: "2027-01-16", location: "KLCC" };
const NOTICE = { id: 9, textEn: "English notice", textMs: "Notis" };
const VALID = {
...EVENT, companyName: "INS", typeName: "General", attendeeFirstName: "Tan", named: true, state: "VALID",
checkedInAt: null, consented: false, notice: NOTICE,
};
const STAFF = {
...EVENT, typeName: "General", attendeeName: "Tan Mei Ling", named: true, consented: false, state: "VALID",
checkedInAt: null, checkedInBy: null, notice: NOTICE,
};
beforeEach(() => {
mocks.getPublicTicket.mockReset().mockResolvedValue(VALID);
mocks.getStaffTicket.mockReset().mockRejectedValue(new ApiError("x", 401, { error: "Not authenticated" }));
mocks.consentTicket.mockReset().mockResolvedValue({ consented: true });
mocks.checkInTicket.mockReset().mockResolvedValue({ ...STAFF, state: "CHECKED_IN", checkedInAt: "2027-01-15T09:30:00", checkedInBy: "door1" });
});
// add-event-tickets: the ticket page /t/<code>, public view and staff view.
describe("/t/[code] public view", () => {
it("shows the event, the ticket, its QR and the consent offer", async () => {
render(<TicketPage />);
expect(await screen.findByRole("heading", { level: 1, name: "KL Hotel Tech Day" })).toBeInTheDocument();
expect(mocks.getPublicTicket).toHaveBeenCalledWith(CODE);
expect(screen.getByText("General")).toBeInTheDocument();
expect(screen.getByText("Ticket for Tan")).toBeInTheDocument();
expect(screen.getByRole("img", { name: "Ticket QR code" })).toHaveAttribute("src", `/api/public/tickets/${CODE}/qr.png`);
expect(screen.getByText("Keep me updated about INS events")).toBeInTheDocument();
expect(screen.getByText("English notice")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it("shows a checked-in ticket's time without a QR", async () => {
mocks.getPublicTicket.mockResolvedValue({ ...VALID, state: "CHECKED_IN", checkedInAt: "2027-01-15T09:30:00" });
render(<TicketPage />);
expect(await screen.findByText("Checked in at 15 Jan 2027, 09:30")).toBeInTheDocument();
expect(screen.queryByRole("img", { name: "Ticket QR code" })).not.toBeInTheDocument();
});
it.each(["AWAITING", "ORDER_CANCELLED", "ORDER_EXPIRED", "TICKET_CANCELLED"])("says a %s ticket is not valid, with no QR and no consent", async (state) => {
mocks.getPublicTicket.mockResolvedValue({ ...VALID, state, notice: undefined });
render(<TicketPage />);
expect(await screen.findByRole("alert")).toHaveTextContent("This ticket is not valid");
expect(screen.queryByRole("img", { name: "Ticket QR code" })).not.toBeInTheDocument();
expect(screen.queryByText("Keep me updated about INS events")).not.toBeInTheDocument();
});
it("says an unknown link is not valid", async () => {
mocks.getPublicTicket.mockRejectedValue(new ApiError("x", 404, { code: "TICKET_INVALID" }));
render(<TicketPage />);
expect(await screen.findByRole("alert")).toHaveTextContent("This ticket link is not valid.");
});
it("records the consent once ticked", async () => {
render(<TicketPage />);
const save = await screen.findByRole("button", { name: "Save" });
expect(save).toBeDisabled();
fireEvent.click(screen.getByRole("checkbox", { name: "Keep me updated about INS events" }));
fireEvent.click(save);
expect(await screen.findByText("Thank you. We will keep you updated.")).toBeInTheDocument();
expect(mocks.consentTicket).toHaveBeenCalledWith(CODE);
});
it("offers no consent without a notice", async () => {
mocks.getPublicTicket.mockResolvedValue({ ...VALID, named: false, attendeeFirstName: null, notice: undefined });
render(<TicketPage />);
await screen.findByRole("img", { name: "Ticket QR code" });
expect(screen.queryByText("Keep me updated about INS events")).not.toBeInTheDocument();
expect(screen.queryByText(/Ticket for/)).not.toBeInTheDocument();
});
});
describe("/t/[code] staff view", () => {
it.each([403, 404])("keeps the public view on a %s", async (status) => {
mocks.getStaffTicket.mockRejectedValue(new ApiError("x", status, {}));
render(<TicketPage />);
await screen.findByRole("img", { name: "Ticket QR code" });
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it("shows the state banner and checks a named ticket in", async () => {
mocks.getStaffTicket.mockResolvedValue(STAFF);
render(<TicketPage />);
expect(await screen.findByText("Valid")).toBeInTheDocument();
expect(screen.getByText("Tan Mei Ling")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Check in" }));
expect(await screen.findByText("Checked in.")).toBeInTheDocument();
expect(mocks.checkInTicket).toHaveBeenCalledWith(CODE, { consent: false });
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it("asks for the attendee of an unnamed ticket and sends the consent", async () => {
mocks.getStaffTicket.mockResolvedValue({ ...STAFF, named: false, attendeeName: null });
render(<TicketPage />);
expect(await screen.findByText("No attendee named yet")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Attendee name"), { target: { value: "Lim Wei" } });
fireEvent.change(screen.getByLabelText("Mobile number"), { target: { value: "012-555 0101" } });
fireEvent.click(screen.getByRole("checkbox", { name: "Keep me updated about INS events" }));
fireEvent.click(screen.getByRole("button", { name: "Check in" }));
await screen.findByText("Checked in.");
expect(mocks.checkInTicket).toHaveBeenCalledWith(CODE, { name: "Lim Wei", mobile: "012-555 0101", email: "", consent: true });
});
it("shows a second scan as already checked in", async () => {
mocks.getStaffTicket.mockResolvedValue({ ...STAFF, state: "CHECKED_IN", checkedInAt: "2027-01-15T09:30:00", checkedInBy: "door1" });
render(<TicketPage />);
expect(await screen.findByText("Already checked in at 15 Jan 2027, 09:30")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it("shows an unpaid ticket as not valid with no Check in", async () => {
mocks.getStaffTicket.mockResolvedValue({ ...STAFF, state: "AWAITING" });
render(<TicketPage />);
expect(await screen.findByText("Not valid: awaiting payment")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it.each([
[{ code: "ALREADY_CHECKED_IN", details: { value: "2027-01-15T09:30" } }, "Already checked in at 15 Jan 2027, 09:30"],
[{ code: "NOT_VALID", details: { value: "ORDER_CANCELLED" } }, "Not valid: order cancelled"],
[{ code: "NOT_EVENT_DAY" }, "Check-in is only open on the event days."],
[{ code: "MOBILE_OR_EMAIL_REQUIRED", error: "MOBILE_OR_EMAIL_REQUIRED", details: { field: "mobile" } }, "Enter a mobile number or an email."],
])("shows the refusal %o", async (data, text) => {
mocks.getStaffTicket.mockResolvedValue(STAFF);
mocks.checkInTicket.mockRejectedValue(new ApiError("x", 409, data));
render(<TicketPage />);
fireEvent.click(await screen.findByRole("button", { name: "Check in" }));
expect(await screen.findByRole("alert")).toHaveTextContent(text);
});
});
+220
View File
@@ -0,0 +1,220 @@
"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(() => {
getPublicTicket(code)
.then(setTicket)
.catch((err) => {
const c = apiData(err).code;
setError(t(c === "TICKET_INVALID" ? "TktTicketInvalid" : c === "TOO_MANY" ? "RegTooMany" : "RegLoadFailed"));
});
// Signed out, another company's staff or no BO_EVENTS: the call fails and the page stays public.
getStaffTicket(code).then(setStaff).catch(() => setStaff(null));
}, [code, t]);
if (error) return <VisitorCard><VisitorState h1 icon={AlertCircle} heading={error} role="alert" tone="error" /></VisitorCard>;
if (!ticket) return <VisitorCard><VisitorState h1 icon={Loader2} iconClassName="motion-safe:animate-spin" heading={t("UiLoading")} role="status" /></VisitorCard>;
const event = { ...ticket, startDate: ticket.startDate ?? ticket.endDate ?? "", endDate: ticket.endDate ?? "", location: ticket.location ?? "" };
return (
<VisitorCard event={event}>
{staff ? <StaffView code={code} staff={staff} companyName={ticket.companyName} onChange={setStaff} />
: <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>
);
}