feat(portal): QR self-registration page, event QR card, My QR codes, privacy notice editor

The public /r/<code> page (no admin shell, never redirects a visitor to the
staff login), its proxy sending only the last X-Forwarded-For hop, the event
page's Registration QR card, a My QR codes page in the user menu, and the
super-admin privacy notice editor on Companies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-01 12:57:18 +08:00
1 parent f13dac58a4
commit 08c45e9109
26 files changed
+1170 -2

No files matched your search

@@ -0,0 +1,29 @@
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<{ id: string }> };
export async function GET(_req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { id } = await params;
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/companies/${encodeURIComponent(id)}/privacy-notice`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export async function PUT(req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { id } = await params;
const body = await req.json().catch(() => ({}));
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/companies/${encodeURIComponent(id)}/privacy-notice`, {
method: "PUT",
body,
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,17 @@
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";
export async function PUT(req: NextRequest, { params }: { params: Promise<{ uuid: string; token: string }> }) {
const session = await getToken();
if (!session) return unauthorized();
const { uuid, token } = await params;
const body = await req.json().catch(() => ({}));
const result = await callMobileApi<Record<string, unknown>>(
`/api/admin/events/${encodeURIComponent(uuid)}/registration-links/${encodeURIComponent(token)}`,
{ method: "PUT", body, token: session },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,13 @@
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";
export async function GET(_req: NextRequest, { params }: { params: Promise<{ uuid: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { uuid } = await params;
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/${encodeURIComponent(uuid)}/registration-links`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,12 @@
import { NextResponse } 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";
export async function GET() {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<unknown>("/api/admin/my-registration-links", { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,47 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
import { GET, POST } from "./route";
type Req = Parameters<typeof GET>[0];
const ctx = { params: Promise.resolve({ token: "tok/1" }) };
const req = (init: RequestInit = {}) => new Request("http://localhost/api/public/registration/tok", init) as unknown as Req;
beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { eventName: "Expo" } }));
describe("/api/public/registration/[token]", () => {
it("GET forwards without a session and with the visitor IP", async () => {
const res = await GET(req({ headers: { "x-forwarded-for": "203.0.113.7" } }), ctx);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ eventName: "Expo" });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/registration/tok%2F1", {
headers: { "X-Forwarded-For": "203.0.113.7" },
});
});
it("POST forwards the body and drops client-written X-Forwarded-For entries and sends only the last hop", async () => {
const body = { name: "A", website: "" };
await POST(req({ method: "POST", body: JSON.stringify(body), headers: { "x-forwarded-for": "6.6.6.6, 203.0.113.7" } }), ctx);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/registration/tok%2F1", {
method: "POST",
body,
headers: { "X-Forwarded-For": "203.0.113.7" },
});
});
it("falls back to X-Real-Ip and sends no header when no address is known", async () => {
await GET(req({ headers: { "x-real-ip": "192.0.2.9" } }), ctx);
expect(mocks.callMobileApi.mock.calls[0][1].headers).toEqual({ "X-Forwarded-For": "192.0.2.9" });
await GET(req(), ctx);
expect(mocks.callMobileApi.mock.calls[1][1].headers).toEqual({});
});
it("passes upstream failures with status and code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Too many registrations from this device. Try again later.", status: 429, code: "TOO_MANY" });
const res = await POST(req({ method: "POST", body: "{}" }), ctx);
expect(res.status).toBe(429);
expect(((await res.json()) as Record<string, unknown>).code).toBe("TOO_MANY");
});
});
@@ -0,0 +1,35 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { clientIp } from "@/app/lib/server/clientContext";
import { errorResponse } from "@/app/lib/server/apiRoute";
// Public (signed-out) proxy for the QR registration page: no session token.
// X-Forwarded-For is rebuilt from clientIp(req) only (the LAST hop, same trusted rule as X-Client-Ip):
// client-written entries in an incoming header are never forwarded, so the rate-limit key cannot be spoofed.
type Ctx = { params: Promise<{ token: string }> };
function forwardedFor(req: NextRequest): Record<string, string> {
const xff = clientIp(req);
return xff ? { "X-Forwarded-For": xff } : {};
}
export async function GET(req: NextRequest, { params }: Ctx) {
const { token } = await params;
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
headers: forwardedFor(req),
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export async function POST(req: NextRequest, { params }: Ctx) {
const { token } = await params;
const body = await req.json().catch(() => ({}));
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
method: "POST",
body,
headers: forwardedFor(req),
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,43 @@
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 as getLinks } from "./events/[uuid]/registration-links/route";
import { PUT as putLink } from "./events/[uuid]/registration-links/[token]/route";
import { GET as getMine } from "./my-registration-links/route";
import { GET as getNotice, PUT as putNotice } from "./companies/[id]/privacy-notice/route";
const req = (init?: RequestInit) => new Request("http://localhost/x", init) as never;
const p = <T,>(v: T) => ({ params: Promise.resolve(v) });
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { ok: 1 } });
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("registration admin proxies", () => {
it("require a session", async () => {
mocks.getToken.mockResolvedValue(null);
for (const res of [await getLinks(req(), p({ uuid: "e" })), await getMine(), await getNotice(req(), p({ id: "1" }))]) {
expect(res.status).toBe(401);
}
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forward to the admin endpoints with the token", async () => {
await getLinks(req(), p({ uuid: "e1" }));
await putLink(req({ method: "PUT", body: '{"enabled":false}' }), p({ uuid: "e1", token: "t1" }));
await getMine();
await getNotice(req(), p({ id: "2" }));
await putNotice(req({ method: "PUT", body: '{"textEn":"a","textMs":"b"}' }), p({ id: "2" }));
expect(mocks.callMobileApi.mock.calls).toEqual([
["/api/admin/events/e1/registration-links", { token: "jwt" }],
["/api/admin/events/e1/registration-links/t1", { method: "PUT", body: { enabled: false }, token: "jwt" }],
["/api/admin/my-registration-links", { token: "jwt" }],
["/api/admin/companies/2/privacy-notice", { token: "jwt" }],
["/api/admin/companies/2/privacy-notice", { method: "PUT", body: { textEn: "a", textMs: "b" }, token: "jwt" }],
]);
});
});
@@ -0,0 +1,74 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ isSuper: true, apiGet: vi.fn(), getPrivacyNotice: vi.fn(), savePrivacyNotice: vi.fn() }));
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
apiGet: mocks.apiGet,
apiPost: vi.fn(),
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ loading: false, isSuper: mocks.isSuper }) }));
vi.mock("@/app/lib/services/adminRegistration", () => ({
getPrivacyNotice: mocks.getPrivacyNotice,
savePrivacyNotice: mocks.savePrivacyNotice,
}));
import CompaniesPage from "./page";
import { ApiError } from "@/app/lib/clientApi";
beforeEach(() => {
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
mocks.getPrivacyNotice.mockReset().mockResolvedValue({ id: 3, companyId: 1, textEn: "Old EN", textMs: "Old MS", createdBy: "boss", createdAt: "2026-11-30T10:00:00" });
mocks.savePrivacyNotice.mockReset().mockResolvedValue({ id: 4, companyId: 1, textEn: "x", textMs: "y", createdBy: "boss", createdAt: "2026-12-01T09:30:00" });
mocks.isSuper = true;
});
async function openEditor() {
render(<CompaniesPage />);
const row = (await screen.findByText("Insight")).closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: "Privacy notice" }));
}
describe("Companies privacy notice editor", () => {
it("loads both languages and shows who changed it last", async () => {
await openEditor();
expect(await screen.findByDisplayValue("Old EN")).toBeInTheDocument();
expect(screen.getByDisplayValue("Old MS")).toBeInTheDocument();
expect(screen.getByText(/boss/)).toBeInTheDocument();
expect(mocks.getPrivacyNotice).toHaveBeenCalledWith(1);
});
it("saves the edited text", async () => {
await openEditor();
const en = await screen.findByLabelText("English");
await userEvent.clear(en);
await userEvent.type(en, "New EN");
await userEvent.click(screen.getByRole("button", { name: "Save notice" }));
await waitFor(() => expect(mocks.savePrivacyNotice).toHaveBeenCalledWith(1, { textEn: "New EN", textMs: "Old MS" }));
});
it("shows the server error and starts empty when there is no notice", async () => {
mocks.getPrivacyNotice.mockResolvedValue(null);
mocks.savePrivacyNotice.mockRejectedValue(new ApiError("Notice text is required.", 400, { error: "Notice text is required." }));
await openEditor();
const en = (await screen.findByLabelText("English")) as HTMLTextAreaElement;
expect(en.value).toBe("");
await userEvent.click(screen.getByRole("button", { name: "Save notice" }));
expect(await screen.findByText("Notice text is required.")).toBeInTheDocument();
});
it("does not crash when the notice has no createdAt or createdBy", async () => {
mocks.getPrivacyNotice.mockResolvedValue({ id: 3, companyId: 1, textEn: "Old EN", textMs: "Old MS" });
await openEditor();
expect(await screen.findByDisplayValue("Old EN")).toBeInTheDocument();
expect(screen.queryByText(/Last changed/i)).toBeNull();
});
it("does not offer the editor to a non-super admin", async () => {
mocks.isSuper = false;
render(<CompaniesPage />);
await waitFor(() => expect(screen.queryByRole("button", { name: "Privacy notice" })).toBeNull());
expect(mocks.getPrivacyNotice).not.toHaveBeenCalled();
});
});
@@ -14,6 +14,7 @@ import { Badge } from "@/app/components/ui/badge";
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { NotAuthorized } from "@/app/lib/RequireModule";
import { getPrivacyNotice, savePrivacyNotice, type PrivacyNotice } from "@/app/lib/services/adminRegistration";
import { changeAdminCompanyCode, listAdminCompanies, saveAdminCompany } from "@/app/lib/services/adminCompanies";
import type { AdminCompany } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
@@ -114,6 +115,73 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
);
}
function PrivacyNoticeDialog({ company, onClose }: { company: AdminCompany; onClose: () => void }) {
const t = useT();
const [notice, setNotice] = useState<PrivacyNotice | null>(null);
const [textEn, setTextEn] = useState("");
const [textMs, setTextMs] = useState("");
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
getPrivacyNotice(company.id!)
.then((n) => {
setNotice(n);
setTextEn(n?.textEn ?? "");
setTextMs(n?.textMs ?? "");
})
.catch(() => setError(t("PrivLoadFailed")));
}, [company.id, t]);
async function save(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
setSaving(true);
try {
setNotice(await savePrivacyNotice(company.id!, { textEn, textMs }));
} catch (err) {
setError(err instanceof Error && err.message ? err.message : t("PrivSaveFailed"));
} finally {
setSaving(false);
}
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("PrivNotice")}</DialogTitle>
</DialogHeader>
{error && (
<div className="text-sm text-destructive" role="alert">
{error}
</div>
)}
<form onSubmit={save} className="space-y-4" noValidate>
<div className="space-y-1.5">
<Label htmlFor="notice-en">{t("RegNoticeEn")}</Label>
<textarea id="notice-en" className="w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm" rows={5} value={textEn} onChange={(e) => setTextEn(e.target.value)} disabled={saving} />
</div>
<div className="space-y-1.5">
<Label htmlFor="notice-ms">{t("RegNoticeMs")}</Label>
<textarea id="notice-ms" className="w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm" rows={5} value={textMs} onChange={(e) => setTextMs(e.target.value)} disabled={saving} />
</div>
{notice?.createdAt && notice.createdBy && (
<p className="text-xs text-muted-foreground">
{t("PrivLastChanged", { user: notice.createdBy, date: notice.createdAt.replace("T", " ").slice(0, 16) })}
</p>
)}
<DialogFooter>
<Button type="submit" disabled={saving}>
{t("PrivSave")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
function CompaniesPageContent() {
const t = useT();
const [companies, setCompanies] = useState<AdminCompany[]>([]);
@@ -121,6 +189,7 @@ function CompaniesPageContent() {
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [dialog, setDialog] = useState<DialogState | null>(null);
const [noticeFor, setNoticeFor] = useState<AdminCompany | null>(null);
const [page, setPage] = useState(1);
const { tableRef, pageSize } = useFitPageSize();
const size = pageSize ?? MIN_PAGE_SIZE;
@@ -165,6 +234,9 @@ function CompaniesPageContent() {
<Button variant="outline" size="sm" onClick={() => setDialog({ mode: "code", company: row.original })}>
{t("CompChangeCode")}
</Button>
<Button variant="outline" size="sm" onClick={() => setNoticeFor(row.original)}>
{t("PrivNotice")}
</Button>
</div>
),
},
@@ -200,6 +272,7 @@ function CompaniesPageContent() {
empty={<EmptyState title={t("CompNone")} />}
/>
{noticeFor && <PrivacyNoticeDialog company={noticeFor} onClose={() => setNoticeFor(null)} />}
{dialog && <CompanyDialog state={dialog} onClose={() => setDialog(null)} onSaved={refetch} />}
</>
);
@@ -31,7 +31,7 @@ describe("Header: change password", () => {
render(<Header />);
await userEvent.click(screen.getByRole("button", { name: /admin user/i }));
const items = (await screen.findAllByRole("menuitem")).map((i) => i.textContent);
expect(items).toEqual(["Change password", "Logout"]);
expect(items).toEqual(["My QR codes", "Change password", "Logout"]);
});
it("blocks empty fields and mismatched passwords without calling the server", async () => {
@@ -108,6 +108,9 @@ export default function Header() {
<span className="block text-sm font-medium">{name}</span>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => router.push("/my-qr")}>
{t("QrMyTitle")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setChangingPassword(true)}>
<KeyRound aria-hidden="true" className="size-4" />
{t("PwdChangeMenu")}
@@ -0,0 +1,47 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const mocks = vi.hoisted(() => ({ getEventLinks: vi.fn(), setLinkEnabled: vi.fn() }));
vi.mock("@/app/lib/services/adminRegistration", () => mocks);
vi.mock("qrcode.react", () => ({
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
QRCodeCanvas: () => <canvas />,
}));
import { RegistrationQrCard } from "./RegistrationQrCard";
const links = {
event: { token: "ev1", enabled: true },
members: [{ userId: 5, name: "Aini", token: "m1", enabled: false }],
};
beforeEach(() => {
mocks.getEventLinks.mockReset().mockResolvedValue(links);
mocks.setLinkEnabled.mockReset().mockResolvedValue(undefined);
});
describe("RegistrationQrCard", () => {
it("lists the event code and each team member code with a QR", async () => {
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Aini");
const values = screen.getAllByTestId("qr-svg").map((e) => e.getAttribute("data-value"));
expect(values).toEqual([`${window.location.origin}/r/ev1`, `${window.location.origin}/r/m1`]);
expect(screen.getByText(/dynamic-qr/)).toBeTruthy();
expect(mocks.getEventLinks).toHaveBeenCalledWith("u1");
});
it("toggles a code through the API", async () => {
const user = userEvent.setup();
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Aini");
await user.click(screen.getAllByRole("switch")[1]);
await waitFor(() => expect(mocks.setLinkEnabled).toHaveBeenCalledWith("u1", "m1", true));
});
it("hides the switches without write access", async () => {
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite={false} />);
await screen.findByText("Aini");
expect(screen.queryAllByRole("switch")).toHaveLength(0);
});
});
@@ -0,0 +1,61 @@
"use client";
import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { ErrorState } from "@/app/components/ui/states";
import { QrCodeItem } from "@/app/components/registration/QrCodeItem";
import { getEventLinks, setLinkEnabled, type EventLinks } from "@/app/lib/services/adminRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
export function RegistrationQrCard({ eventUuid, eventName, canWrite }: { eventUuid: string; eventName: string; canWrite: boolean }) {
const t = useT();
const [links, setLinks] = useState<EventLinks | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
getEventLinks(eventUuid)
.then((l) => !cancelled && setLinks(l))
.catch(() => !cancelled && setError(t("QrLoadFailed")));
return () => {
cancelled = true;
};
}, [eventUuid, t]);
async function toggle(token: string, enabled: boolean) {
setError(null);
try {
await setLinkEnabled(eventUuid, token, enabled);
setLinks((l) =>
l && {
event: l.event.token === token ? { ...l.event, enabled } : l.event,
members: l.members.map((m) => (m.token === token ? { ...m, enabled } : m)),
},
);
} catch {
setError(t("QrSaveFailed"));
}
}
const onToggle = (token: string) => (canWrite ? (on: boolean) => toggle(token, on) : undefined);
return (
<Card>
<CardHeader>
<CardTitle>{t("QrCardTitle")}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">{t("QrNote")}</p>
{error && <ErrorState message={error} />}
{links && (
<>
<QrCodeItem label={t("QrEventCode")} eventName={eventName} token={links.event.token} enabled={links.event.enabled} onToggle={onToggle(links.event.token)} />
{links.members.map((m) => (
<QrCodeItem key={m.token} label={m.name} eventName={eventName} fileLabel={m.name} token={m.token} enabled={m.enabled} onToggle={onToggle(m.token)} />
))}
</>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,52 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { forwardRef } from "react";
vi.mock("qrcode.react", () => ({
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
QRCodeCanvas: forwardRef<HTMLCanvasElement, { value: string }>(function C({ value }, ref) {
return <canvas ref={(el) => { if (el) el.toDataURL = () => "data:image/png;base64,AAA"; if (typeof ref === "function") ref(el); else if (ref) ref.current = el; }} data-value={value} />;
}),
}));
import { QrCodeItem } from "./QrCodeItem";
let clicked: HTMLAnchorElement | undefined;
beforeEach(() => {
clicked = undefined;
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) { clicked = this; });
});
afterEach(() => vi.restoreAllMocks());
describe("QrCodeItem", () => {
it("renders the QR for the origin link, copies it and downloads a slugified PNG", async () => {
const user = userEvent.setup(); // installs a clipboard stub on navigator
const writeText = vi.spyOn(navigator.clipboard, "writeText");
const link = `${window.location.origin}/r/abc`;
render(<QrCodeItem label="Aini Binti" eventName="Expo 2026!" fileLabel="Aini Binti" token="abc" enabled />);
expect(screen.getByTestId("qr-svg").getAttribute("data-value")).toBe(link);
expect(screen.getByText(link)).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Copy link" }));
expect(writeText).toHaveBeenCalledWith(link);
await user.click(screen.getByRole("button", { name: "Download PNG" }));
expect(clicked?.download).toBe("expo-2026-aini-binti-qr.png");
expect(clicked?.href).toBe("data:image/png;base64,AAA");
});
it("uses event as the file name part when there is no member", async () => {
const user = userEvent.setup();
render(<QrCodeItem label="Event code" eventName="Expo" token="abc" enabled />);
await user.click(screen.getByRole("button", { name: "Download PNG" }));
expect(clicked?.download).toBe("expo-event-qr.png");
});
it("shows a switch only when a toggle handler is given", async () => {
const onToggle = vi.fn();
const { rerender } = render(<QrCodeItem label="x" eventName="E" token="t" enabled onToggle={onToggle} />);
await userEvent.click(screen.getByRole("switch"));
expect(onToggle).toHaveBeenCalledWith(false);
rerender(<QrCodeItem label="x" eventName="E" token="t" enabled />);
expect(screen.queryByRole("switch")).toBeNull();
});
});
@@ -0,0 +1,69 @@
"use client";
import { useRef, useState } from "react";
import { QRCodeCanvas, QRCodeSVG } from "qrcode.react";
import { Copy, Download } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Switch } from "@/app/components/ui/switch";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
/** One registration code: QR, link, copy, PNG download and (when onToggle is given) an on/off switch. */
export function QrCodeItem({
label,
eventName,
fileLabel,
token,
enabled,
onToggle,
}: {
label: string;
eventName: string;
/** Member name for the download file name; omit for the event code. */
fileLabel?: string;
token: string;
enabled: boolean;
onToggle?: (enabled: boolean) => void;
}) {
const t = useT();
const canvas = useRef<HTMLCanvasElement>(null);
const [copied, setCopied] = useState(false);
const link = `${window.location.origin}/r/${token}`;
async function copy() {
await navigator.clipboard.writeText(link);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
function download() {
if (!canvas.current) return;
const a = document.createElement("a");
a.href = canvas.current.toDataURL("image/png");
a.download = `${slug(eventName)}-${slug(fileLabel || "event")}-qr.png`;
a.click();
}
return (
<div className="flex flex-col gap-3 rounded-lg border p-4 sm:flex-row sm:items-center">
<QRCodeSVG value={link} size={128} className="shrink-0" />
<QRCodeCanvas ref={canvas} value={link} size={512} className="hidden" />
<div className="min-w-0 flex-1 space-y-2">
<p className="text-sm font-medium">{label}</p>
<p className="break-all text-xs text-muted-foreground">{link}</p>
<div className="flex flex-wrap items-center gap-2">
<Button variant="outline" size="sm" onClick={copy}>
<Copy aria-hidden="true" className="size-4" />
{copied ? t("QrCopied") : t("QrCopy")}
</Button>
<Button variant="outline" size="sm" onClick={download}>
<Download aria-hidden="true" className="size-4" />
{t("QrDownload")}
</Button>
{onToggle && <Switch checked={enabled} onCheckedChange={onToggle} aria-label={t("QrEnabled")} />}
</div>
</div>
</div>
);
}
@@ -6,6 +6,8 @@ import { Alert, AlertDescription } from "@/app/components/ui/alert";
import { PageHeader } from "@/app/components/ui/page-header";
import { Skeleton } from "@/app/components/ui/skeleton";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RegistrationQrCard } from "@/app/components/events/RegistrationQrCard";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { RequireModule } from "@/app/lib/RequireModule";
import { ApiError } from "@/app/lib/clientApi";
import { getAdminEvent, saveAdminEvent } from "@/app/lib/services/adminEvents";
@@ -18,6 +20,7 @@ function EditEventPageContent() {
const { uuid } = useParams<{ uuid: string }>();
const searchParams = useSearchParams();
const { hasModule } = useAdminAuth();
const [event, setEvent] = useState<AdminEvent | null>(null);
const [loading, setLoading] = useState(true);
const [notFound, setNotFound] = useState(false);
@@ -114,6 +117,9 @@ function EditEventPageContent() {
)}
<EventForm initial={event} onSubmit={handleSubmit} submitLabel={t("Save")} />
{/* ponytail: no read-only role for events yet; the events module is the write gate for the code switches. */}
<RegistrationQrCard eventUuid={event.uuid} eventName={event.name} canWrite={hasModule("BO_EVENTS")} />
</div>
);
}
@@ -463,4 +463,39 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PwdRule_SYMBOLIC_LENGTH_MAX: "Maximum symbols",
PwdRule_NO_OTHER_LANGUAGE: "Latin characters only",
PwdRule_SPACE_NOT_ALLOWED: "No spaces",
// QR self-registration (public page, QR cards, privacy notice)
RegInactive: "This code is no longer active.",
RegLoadFailed: "Could not load this page. Try again later.",
RegName: "Your name",
RegMobile: "Mobile number",
RegEmail: "Email",
RegCompany: "Company",
RegJobTitle: "Job title",
RegInterests: "Interests (optional)",
RegNoticeEn: "English",
RegNoticeMs: "Bahasa Malaysia",
RegConsent: "I have read the notice and agree",
RegSubmit: "Register",
RegAnother: "Register another person",
RegThanks: "Thank you, you're registered for {event}",
RegNameRequired: "Enter your name.",
RegContactRequired: "Enter a mobile number or an email.",
RegTooMany: "Too many registrations from this device. Try again later.",
RegFailed: "Could not register. Try again.",
QrCardTitle: "Registration QR",
QrEventCode: "Event code",
QrCopy: "Copy link",
QrCopied: "Link copied",
QrDownload: "Download PNG",
QrEnabled: "Enabled",
QrNote: "Paste the link into the dynamic-qr console to get a QR that can be changed later.",
QrLoadFailed: "Could not load registration codes.",
QrSaveFailed: "Could not change the code.",
QrMyTitle: "My QR codes",
QrMyNone: "You have no registration codes yet.",
PrivNotice: "Privacy notice",
PrivSave: "Save notice",
PrivSaveFailed: "Could not save the notice.",
PrivLoadFailed: "Could not load the notice.",
PrivLastChanged: "Last changed by {user} on {date}",
};
+2 -1
View File
@@ -8,8 +8,9 @@
// resetPasswordRequired); it is reached right after login, so it stays public.
export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forgot-password"]);
// /r/<token> is the QR self-registration page: visitors are not signed in. (A prefix, so PUBLIC_PATHS stays exact.)
export function isPublicPath(pathname: string): boolean {
return PUBLIC_PATHS.has(pathname);
return PUBLIC_PATHS.has(pathname) || /^\/r\/[^/]+$/.test(pathname);
}
export interface SessionState {
@@ -0,0 +1,41 @@
import { ApiError, apiGet, apiPut } from "@/app/lib/clientApi";
export interface RegistrationLink {
token: string;
enabled: boolean;
}
export interface EventLinks {
event: RegistrationLink;
members: (RegistrationLink & { userId: number; name: string })[];
}
export interface MyLink extends RegistrationLink {
eventUuid: string;
eventName: string;
startDate: string;
endDate: string;
location: string;
}
export interface PrivacyNotice {
id: number;
companyId: number;
textEn: string;
textMs: string;
createdBy: string;
createdAt: string;
}
export const getEventLinks = (uuid: string) => apiGet<EventLinks>(`/api/events/${encodeURIComponent(uuid)}/registration-links`);
export const setLinkEnabled = (uuid: string, token: string, enabled: boolean) =>
apiPut(`/api/events/${encodeURIComponent(uuid)}/registration-links/${encodeURIComponent(token)}`, { enabled });
export const getMyLinks = () => apiGet<MyLink[]>("/api/my-registration-links");
export async function getPrivacyNotice(companyId: number): Promise<PrivacyNotice | null> {
try {
return await apiGet<PrivacyNotice>(`/api/companies/${companyId}/privacy-notice`);
} catch (err) {
if (err instanceof ApiError && err.status === 404) return null; // no notice published yet
throw err;
}
}
export const savePrivacyNotice = (companyId: number, body: { textEn: string; textMs: string }) =>
apiPut<PrivacyNotice>(`/api/companies/${companyId}/privacy-notice`, body);
@@ -0,0 +1,32 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { getRegistration, submitRegistration } from "./publicRegistration";
import { ApiError } from "@/app/lib/clientApi";
const body = { name: "A", mobile: "", email: "a@b.co", companyName: "", jobTitle: "", interestIds: [], consent: true, website: "" };
describe("publicRegistration service", () => {
const originalLocation = window.location;
beforeEach(() => {
Object.defineProperty(window, "location", { value: { ...window.location, assign: vi.fn() }, writable: true, configurable: true });
});
afterEach(() => {
Object.defineProperty(window, "location", { value: originalLocation, writable: true, configurable: true });
vi.unstubAllGlobals();
});
it("never sends a visitor to the admin login on a 401", async () => {
vi.stubGlobal("fetch", vi.fn().mockImplementation(async () => new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 })));
await expect(getRegistration("t")).rejects.toMatchObject({ status: 401 });
await expect(submitRegistration("t", body)).rejects.toBeInstanceOf(ApiError);
expect(window.location.assign).not.toHaveBeenCalled();
});
it("posts JSON and returns the parsed body", async () => {
const f = vi.fn().mockResolvedValue(new Response(JSON.stringify({ eventName: "Expo" }), { status: 200 }));
vi.stubGlobal("fetch", f);
expect(await submitRegistration("a/b", body)).toEqual({ eventName: "Expo" });
expect(f.mock.calls[0][0]).toBe("/api/public/registration/a%2Fb");
expect(f.mock.calls[0][1].method).toBe("POST");
});
});
@@ -0,0 +1,47 @@
import { ApiError } from "@/app/lib/clientApi";
export interface RegistrationInfo {
eventName: string;
startDate: string;
endDate: string;
location: string;
companyName: string;
notice: { id: number; textEn: string; textMs: string };
interests: { id: number; name: string }[];
}
export interface RegistrationBody {
name: string;
mobile: string;
email: string;
companyName: string;
jobTitle: string;
interestIds: number[];
consent: boolean;
website: string;
}
const url = (token: string) => `/api/public/registration/${encodeURIComponent(token)}`;
// Plain fetch on purpose: clientApi redirects a 401 to the admin /login, which a visitor must never see.
async function call<T>(token: string, init?: RequestInit): Promise<T> {
let res: Response;
try {
res = await fetch(url(token), { ...init, headers: init?.body ? { "Content-Type": "application/json" } : {} });
} catch {
throw new ApiError("Request failed", 0);
}
const text = await res.text();
let data: unknown;
try {
data = text ? JSON.parse(text) : undefined;
} catch {
data = undefined;
}
if (!res.ok) throw new ApiError(`Request failed (${res.status})`, res.status, data);
return data as T;
}
export const getRegistration = (token: string) => call<RegistrationInfo>(token);
export const submitRegistration = (token: string, body: RegistrationBody) =>
call<{ eventName: string }>(token, { method: "POST", body: JSON.stringify(body) });
@@ -0,0 +1,34 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
const mocks = vi.hoisted(() => ({ getMyLinks: vi.fn() }));
vi.mock("@/app/lib/services/adminRegistration", () => mocks);
vi.mock("qrcode.react", () => ({
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
QRCodeCanvas: () => <canvas />,
}));
import MyQrPage from "./page";
beforeEach(() => mocks.getMyLinks.mockReset());
describe("My QR codes", () => {
it("lists the caller's codes with event, dates, location and QR", async () => {
mocks.getMyLinks.mockResolvedValue([
{ eventUuid: "u1", eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", token: "t1", enabled: true },
]);
render(<MyQrPage />);
await screen.findByText("Expo 2026");
expect(screen.getByText(/KLCC/)).toBeTruthy();
expect(screen.getByText(/2026-12-01/)).toBeTruthy();
expect(screen.getByTestId("qr-svg").getAttribute("data-value")).toBe(`${window.location.origin}/r/t1`);
expect(screen.getByRole("button", { name: "Copy link" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Download PNG" })).toBeTruthy();
});
it("shows an empty state", async () => {
mocks.getMyLinks.mockResolvedValue([]);
render(<MyQrPage />);
await screen.findByText("You have no registration codes yet.");
});
});
+37
View File
@@ -0,0 +1,37 @@
"use client";
import { useEffect, useState } from "react";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { QrCodeItem } from "@/app/components/registration/QrCodeItem";
import { getMyLinks, type MyLink } from "@/app/lib/services/adminRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// Any signed-in staff user; deliberately not in ROUTE_MODULES. Read-only: no on/off switch.
export default function MyQrPage() {
const t = useT();
const [links, setLinks] = useState<MyLink[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
getMyLinks().then(setLinks).catch(() => setError(t("QrLoadFailed")));
}, [t]);
return (
<>
<PageHeader title={t("QrMyTitle")} />
{error && <ErrorState message={error} />}
{links?.length === 0 && <EmptyState title={t("QrMyNone")} />}
<div className="space-y-3">
{links?.map((l) => (
<div key={l.token} className="space-y-1">
<p className="text-sm text-muted-foreground">
{l.startDate} - {l.endDate} | {l.location}
</p>
<QrCodeItem label={l.eventName} eventName={l.eventName} token={l.token} enabled={l.enabled} />
</div>
))}
</div>
</>
);
}
@@ -0,0 +1,165 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const mocks = vi.hoisted(() => ({ getRegistration: vi.fn(), submitRegistration: vi.fn() }));
vi.mock("@/app/lib/services/publicRegistration", () => mocks);
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "tok1" }) }));
import { ApiError } from "@/app/lib/clientApi";
import RegisterPage from "./page";
const info = {
eventName: "Expo 2026",
startDate: "2026-12-01",
endDate: "2026-12-02",
location: "KLCC",
companyName: "INS",
notice: { id: 7, textEn: "We keep your data safe.", textMs: "Data anda selamat." },
interests: [{ id: 1, name: "Skincare" }, { id: 2, name: "Wellness" }],
};
beforeEach(() => {
mocks.getRegistration.mockReset().mockResolvedValue(info);
mocks.submitRegistration.mockReset().mockResolvedValue({ eventName: "Expo 2026" });
});
async function ready() {
render(<RegisterPage />);
await screen.findByLabelText("Your name");
}
describe("/r/[token] public page", () => {
it("shows a loading state, then the event, notice in both languages and the form", async () => {
render(<RegisterPage />);
expect(screen.getByRole("status")).toBeTruthy();
await screen.findByText("Expo 2026");
expect(screen.getByText("We keep your data safe.")).toBeTruthy();
expect(screen.getByText("Data anda selamat.")).toBeTruthy();
expect(screen.getByLabelText("Skincare")).toBeTruthy();
expect(mocks.getRegistration).toHaveBeenCalledWith("tok1");
});
it("shows only the inactive message, no event details, when the code is off", async () => {
mocks.getRegistration.mockRejectedValue(new ApiError("x", 404, { code: "CODE_INACTIVE" }));
render(<RegisterPage />);
await screen.findByText("This code is no longer active.");
expect(screen.queryByText("Expo 2026")).toBeNull();
expect(screen.queryByLabelText("Your name")).toBeNull();
});
it("hides the honeypot from people and assistive tech", async () => {
await ready();
const hp = document.querySelector('input[name="website"]') as HTMLInputElement;
expect(hp).toBeTruthy();
expect(hp.tabIndex).toBe(-1);
expect(hp.getAttribute("autocomplete")).toBe("off");
expect(hp.closest("[aria-hidden='true']")).toBeTruthy();
});
it("submits the form, then shows thank-you and lets another person register", async () => {
const user = userEvent.setup();
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Mobile number"), "0123456789");
await user.type(screen.getByLabelText("Company"), "Acme");
await user.type(screen.getByLabelText("Job title"), "Buyer");
await user.click(screen.getByLabelText("Wellness"));
await user.click(screen.getByLabelText("I have read the notice and agree"));
await user.click(screen.getByRole("button", { name: "Register" }));
await screen.findByText("Thank you, you're registered for Expo 2026");
expect(mocks.submitRegistration).toHaveBeenCalledWith("tok1", {
name: "Aini", mobile: "0123456789", email: "", companyName: "Acme", jobTitle: "Buyer",
interestIds: [2], consent: true, website: "",
});
await user.click(screen.getByRole("button", { name: "Register another person" }));
const name = (await screen.findByLabelText("Your name")) as HTMLInputElement;
expect(name.value).toBe("");
expect((screen.getByLabelText("I have read the notice and agree") as HTMLElement).getAttribute("aria-checked")).toBe("false");
expect((screen.getByLabelText("Wellness") as HTMLElement).getAttribute("aria-checked")).toBe("false");
expect((document.querySelector('input[name="website"]') as HTMLInputElement).value).toBe("");
});
it("clears a filled honeypot too when registering another person", async () => {
const user = userEvent.setup();
await ready();
await user.type(document.querySelector('input[name="website"]') as HTMLInputElement, "spam");
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByRole("button", { name: "Register" }));
await user.click(await screen.findByRole("button", { name: "Register another person" }));
await screen.findByLabelText("Your name");
expect((document.querySelector('input[name="website"]') as HTMLInputElement).value).toBe("");
});
it("asks for a name and a mobile or email before calling the API", async () => {
const user = userEvent.setup();
await ready();
await user.click(screen.getByRole("button", { name: "Register" }));
expect(screen.getByText("Enter your name.")).toBeTruthy();
expect(screen.getByText("Enter a mobile number or an email.")).toBeTruthy();
expect(mocks.submitRegistration).not.toHaveBeenCalled();
});
it("shows a server field error under the field", async () => {
const user = userEvent.setup();
mocks.submitRegistration.mockRejectedValue(
new ApiError("x", 400, { code: "VALIDATION", details: { field: "consent", code: "CONSENT_REQUIRED" }, error: "Consent is required." }),
);
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByRole("button", { name: "Register" }));
const msg = await screen.findByText("Consent is required.");
const box = screen.getByLabelText("I have read the notice and agree");
expect(box.getAttribute("aria-describedby")).toBe(msg.id);
expect(box.getAttribute("aria-invalid")).toBe("true");
});
it("shows the form-level error for a field the page does not render", async () => {
const user = userEvent.setup();
mocks.submitRegistration.mockRejectedValue(
new ApiError("x", 400, { code: "VALIDATION", details: { field: "interestIds" }, error: "Unknown interest." }),
);
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByRole("button", { name: "Register" }));
expect((await screen.findByRole("alert")).textContent).toBe("Unknown interest.");
});
it("shows a generic error, not the server text, for a 401", async () => {
const user = userEvent.setup();
mocks.submitRegistration.mockRejectedValue(new ApiError("Unauthorized", 401, { error: "Unauthorized" }));
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByRole("button", { name: "Register" }));
expect((await screen.findByRole("alert")).textContent).toBe("Could not register. Try again.");
});
it("gives inputs, buttons and checkbox rows large tap targets", async () => {
await ready();
expect(screen.getByLabelText("Your name").className).toContain("h-11");
expect(screen.getByRole("button", { name: "Register" }).className).toContain("h-11");
for (const l of ["Wellness", "I have read the notice and agree"]) {
const label = document.querySelector(`label[for="${screen.getByLabelText(l).id}"]`)!;
expect(label.className).toContain("w-full");
expect(label.className).toContain("min-h-11");
}
});
it("shows too-many and inactive messages from submit", async () => {
const user = userEvent.setup();
mocks.submitRegistration.mockRejectedValueOnce(new ApiError("x", 429, { code: "TOO_MANY" }));
await ready();
await user.type(screen.getByLabelText("Your name"), "Aini");
await user.type(screen.getByLabelText("Email"), "a@b.co");
await user.click(screen.getByLabelText("I have read the notice and agree"));
await user.click(screen.getByRole("button", { name: "Register" }));
await screen.findByText("Too many registrations from this device. Try again later.");
mocks.submitRegistration.mockRejectedValueOnce(new ApiError("x", 404, { code: "CODE_INACTIVE" }));
await user.click(screen.getByRole("button", { name: "Register" }));
await waitFor(() => expect(screen.getByText("This code is no longer active.")).toBeTruthy());
});
});
+169
View File
@@ -0,0 +1,169 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { useParams } from "next/navigation";
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 { ApiError } from "@/app/lib/clientApi";
import { getRegistration, submitRegistration, type RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const EMPTY = { name: "", mobile: "", email: "", companyName: "", jobTitle: "", interestIds: [] as number[], consent: false, website: "" };
// Fields the form renders; a server error for any other field goes to the form-level alert.
const FIELDS = ["name", "mobile", "email", "companyName", "jobTitle", "consent"];
const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3";
const BOX = "size-6";
type Phase = "loading" | "inactive" | "form" | "done";
function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } {
if (!(err instanceof ApiError)) return {};
const d = (err.data ?? {}) as { code?: string; error?: string; details?: { field?: string } };
return { status: err.status, code: d.code, error: d.error, field: d.details?.field };
}
// Public, signed-out, mobile-first page (no admin shell: AppShell skips it via isPublicPath).
export default function RegisterPage() {
const t = useT();
const { token } = useParams<{ token: string }>();
const [phase, setPhase] = useState<Phase>("loading");
const [info, setInfo] = useState<RegistrationInfo | null>(null);
const [form, setForm] = useState(EMPTY);
const [errors, setErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
useEffect(() => {
getRegistration(token)
.then((i) => {
setInfo(i);
setPhase("form");
})
.catch((err) => {
if (apiData(err).code === "CODE_INACTIVE") setPhase("inactive");
else {
setFormError(apiData(err).code === "TOO_MANY" ? t("RegTooMany") : t("RegLoadFailed"));
setPhase("form");
}
});
}, [token, t]);
const set = (patch: Partial<typeof EMPTY>) => setForm((f) => ({ ...f, ...patch }));
async function submit(e: FormEvent) {
e.preventDefault();
const errs: Record<string, string> = {};
if (!form.name.trim()) errs.name = t("RegNameRequired");
if (!form.mobile.trim() && !form.email.trim()) errs.mobile = t("RegContactRequired");
setErrors(errs);
setFormError(null);
if (Object.keys(errs).length) return;
setSaving(true);
try {
await submitRegistration(token, {
...form,
name: form.name.trim(),
mobile: form.mobile.trim(),
email: form.email.trim(),
companyName: form.companyName.trim(),
jobTitle: form.jobTitle.trim(),
});
setPhase("done");
} catch (err) {
const { status, code, error, field } = apiData(err);
if (code === "CODE_INACTIVE") setPhase("inactive");
else if (code === "TOO_MANY") setFormError(t("RegTooMany"));
else if (status === 400 && error && field && FIELDS.includes(field)) setErrors({ [field]: error });
else setFormError(status === 400 && error ? error : t("RegFailed"));
} finally {
setSaving(false);
}
}
const field = (id: keyof typeof EMPTY, label: string, type = "text") => (
<div className="space-y-1.5">
<Label htmlFor={`reg-${id}`}>{label}</Label>
<Input id={`reg-${id}`} className="h-11" type={type} value={String(form[id])} onChange={(e) => set({ [id]: e.target.value })} disabled={saving} aria-invalid={!!errors[id]} aria-describedby={errors[id] ? `reg-${id}-error` : undefined} />
{errors[id] && <p id={`reg-${id}-error`} className="text-sm text-destructive">{errors[id]}</p>}
</div>
);
let body;
if (phase === "loading") body = <p role="status">{t("UiLoading")}</p>;
else if (phase === "inactive") body = <p role="alert">{t("RegInactive")}</p>;
else if (phase === "done") {
body = (
<div className="space-y-4">
<p role="status" className="text-lg font-medium">{t("RegThanks", { event: info?.eventName ?? "" })}</p>
<Button
className="h-11"
onClick={() => {
setForm(EMPTY);
setErrors({});
setPhase("form");
}}
>
{t("RegAnother")}
</Button>
</div>
);
} else {
body = (
<form onSubmit={submit} className="space-y-4" noValidate>
{info && (
<div>
<h1 className="text-2xl font-semibold">{info.eventName}</h1>
<p className="text-sm text-muted-foreground">
{info.companyName} | {info.startDate} - {info.endDate} | {info.location}
</p>
</div>
)}
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
{info && (
<>
{field("name", t("RegName"))}
{field("mobile", t("RegMobile"), "tel")}
{field("email", t("RegEmail"), "email")}
{field("companyName", t("RegCompany"))}
{field("jobTitle", t("RegJobTitle"))}
{info.interests.length > 0 && (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t("RegInterests")}</legend>
{info.interests.map((i) => (
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}>
<Checkbox
className={BOX}
id={`reg-interest-${i.id}`}
checked={form.interestIds.includes(i.id)}
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
/>
{i.name}
</Label>
))}
</fieldset>
)}
<div className="space-y-2 rounded-md border p-3 text-sm">
<h2 className="font-medium">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h2 className="font-medium">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</div>
<Label htmlFor="reg-consent" className={ROW}>
<Checkbox id="reg-consent" className={BOX} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
{t("RegConsent")}
</Label>
{errors.consent && <p id="reg-consent-error" className="text-sm text-destructive">{errors.consent}</p>}
{/* Honeypot: people never see or reach it; bots fill it and the server drops the submission. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<input name="website" tabIndex={-1} autoComplete="off" value={form.website} onChange={(e) => set({ website: e.target.value })} />
</div>
<Button type="submit" className="h-11 w-full" disabled={saving}>{t("RegSubmit")}</Button>
</>
)}
</form>
);
}
return <main className="mx-auto w-full max-w-md px-4 py-6">{body}</main>;
}
@@ -0,0 +1,26 @@
import { describe, it, expect } from "vitest";
import { NextRequest } from "next/server";
import { middleware } from "./middleware";
// add-qr-self-registration: the QR landing page and its proxy are reachable signed out; admin paths still are not.
const get = (path: string) => middleware(new NextRequest(new URL(path, "https://portal.test")));
describe("middleware: public registration paths", () => {
it("lets a signed-out visitor open /r/<token>", async () => {
const res = await get("/r/abc123");
expect(res.headers.get("x-middleware-next")).toBe("1");
expect(res.headers.get("location")).toBeNull();
});
it("lets a signed-out visitor reach the public registration proxy", async () => {
const res = await get("/api/public/registration/abc123");
expect(res.headers.get("x-middleware-next")).toBe("1");
});
it("still redirects a signed-out visitor from admin paths", async () => {
for (const path of ["/events", "/my-qr", "/r", "/r/"]) {
const res = await get(path);
expect(res.headers.get("location"), path).toContain("/login");
}
});
});