From 08c45e9109ac5797e9c85bfd5a4becf4fadc95c9 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 12:57:18 +0800 Subject: [PATCH] feat(portal): QR self-registration page, event QR card, My QR codes, privacy notice editor The public /r/ 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 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../companies/[id]/privacy-notice/route.ts | 29 +++ .../registration-links/[token]/route.ts | 17 ++ .../events/[uuid]/registration-links/route.ts | 13 ++ .../app/api/my-registration-links/route.ts | 12 ++ .../public/registration/[token]/route.test.ts | 47 +++++ .../api/public/registration/[token]/route.ts | 35 ++++ .../app/api/registrationAdminRoutes.test.ts | 43 +++++ .../app/companies/page.privacy.test.tsx | 74 ++++++++ solvway-admin-portal/app/companies/page.tsx | 73 ++++++++ .../app/Header.changePassword.test.tsx | 2 +- .../app/components/app/Header.tsx | 3 + .../events/RegistrationQrCard.test.tsx | 47 +++++ .../components/events/RegistrationQrCard.tsx | 61 +++++++ .../registration/QrCodeItem.test.tsx | 52 ++++++ .../components/registration/QrCodeItem.tsx | 69 +++++++ .../app/events/[uuid]/page.tsx | 6 + .../app/lib/i18n/defaultMessages.ts | 35 ++++ solvway-admin-portal/app/lib/routeGuard.ts | 3 +- .../app/lib/services/adminRegistration.ts | 41 +++++ .../lib/services/publicRegistration.test.ts | 32 ++++ .../app/lib/services/publicRegistration.ts | 47 +++++ solvway-admin-portal/app/my-qr/page.test.tsx | 34 ++++ solvway-admin-portal/app/my-qr/page.tsx | 37 ++++ .../app/r/[token]/page.test.tsx | 165 +++++++++++++++++ solvway-admin-portal/app/r/[token]/page.tsx | 169 ++++++++++++++++++ .../middleware.public.test.ts | 26 +++ 26 files changed, 1170 insertions(+), 2 deletions(-) create mode 100644 solvway-admin-portal/app/api/companies/[id]/privacy-notice/route.ts create mode 100644 solvway-admin-portal/app/api/events/[uuid]/registration-links/[token]/route.ts create mode 100644 solvway-admin-portal/app/api/events/[uuid]/registration-links/route.ts create mode 100644 solvway-admin-portal/app/api/my-registration-links/route.ts create mode 100644 solvway-admin-portal/app/api/public/registration/[token]/route.test.ts create mode 100644 solvway-admin-portal/app/api/public/registration/[token]/route.ts create mode 100644 solvway-admin-portal/app/api/registrationAdminRoutes.test.ts create mode 100644 solvway-admin-portal/app/companies/page.privacy.test.tsx create mode 100644 solvway-admin-portal/app/components/events/RegistrationQrCard.test.tsx create mode 100644 solvway-admin-portal/app/components/events/RegistrationQrCard.tsx create mode 100644 solvway-admin-portal/app/components/registration/QrCodeItem.test.tsx create mode 100644 solvway-admin-portal/app/components/registration/QrCodeItem.tsx create mode 100644 solvway-admin-portal/app/lib/services/adminRegistration.ts create mode 100644 solvway-admin-portal/app/lib/services/publicRegistration.test.ts create mode 100644 solvway-admin-portal/app/lib/services/publicRegistration.ts create mode 100644 solvway-admin-portal/app/my-qr/page.test.tsx create mode 100644 solvway-admin-portal/app/my-qr/page.tsx create mode 100644 solvway-admin-portal/app/r/[token]/page.test.tsx create mode 100644 solvway-admin-portal/app/r/[token]/page.tsx create mode 100644 solvway-admin-portal/middleware.public.test.ts diff --git a/solvway-admin-portal/app/api/companies/[id]/privacy-notice/route.ts b/solvway-admin-portal/app/api/companies/[id]/privacy-notice/route.ts new file mode 100644 index 0000000..0c18794 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/[id]/privacy-notice/route.ts @@ -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>(`/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>(`/api/admin/companies/${encodeURIComponent(id)}/privacy-notice`, { + method: "PUT", + body, + token, + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/events/[uuid]/registration-links/[token]/route.ts b/solvway-admin-portal/app/api/events/[uuid]/registration-links/[token]/route.ts new file mode 100644 index 0000000..a862b10 --- /dev/null +++ b/solvway-admin-portal/app/api/events/[uuid]/registration-links/[token]/route.ts @@ -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>( + `/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); +} diff --git a/solvway-admin-portal/app/api/events/[uuid]/registration-links/route.ts b/solvway-admin-portal/app/api/events/[uuid]/registration-links/route.ts new file mode 100644 index 0000000..e9d6321 --- /dev/null +++ b/solvway-admin-portal/app/api/events/[uuid]/registration-links/route.ts @@ -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>(`/api/admin/events/${encodeURIComponent(uuid)}/registration-links`, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/my-registration-links/route.ts b/solvway-admin-portal/app/api/my-registration-links/route.ts new file mode 100644 index 0000000..3609706 --- /dev/null +++ b/solvway-admin-portal/app/api/my-registration-links/route.ts @@ -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("/api/admin/my-registration-links", { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/public/registration/[token]/route.test.ts b/solvway-admin-portal/app/api/public/registration/[token]/route.test.ts new file mode 100644 index 0000000..1a3b4c8 --- /dev/null +++ b/solvway-admin-portal/app/api/public/registration/[token]/route.test.ts @@ -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[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).code).toBe("TOO_MANY"); + }); +}); diff --git a/solvway-admin-portal/app/api/public/registration/[token]/route.ts b/solvway-admin-portal/app/api/public/registration/[token]/route.ts new file mode 100644 index 0000000..2df1369 --- /dev/null +++ b/solvway-admin-portal/app/api/public/registration/[token]/route.ts @@ -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 { + 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>(`/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>(`/api/public/registration/${encodeURIComponent(token)}`, { + method: "POST", + body, + headers: forwardedFor(req), + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/registrationAdminRoutes.test.ts b/solvway-admin-portal/app/api/registrationAdminRoutes.test.ts new file mode 100644 index 0000000..3c01e50 --- /dev/null +++ b/solvway-admin-portal/app/api/registrationAdminRoutes.test.ts @@ -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 = (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" }], + ]); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.privacy.test.tsx b/solvway-admin-portal/app/companies/page.privacy.test.tsx new file mode 100644 index 0000000..40bebc6 --- /dev/null +++ b/solvway-admin-portal/app/companies/page.privacy.test.tsx @@ -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()).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(); + 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(); + await waitFor(() => expect(screen.queryByRole("button", { name: "Privacy notice" })).toBeNull()); + expect(mocks.getPrivacyNotice).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.tsx b/solvway-admin-portal/app/companies/page.tsx index 451c8bf..70b7d3c 100644 --- a/solvway-admin-portal/app/companies/page.tsx +++ b/solvway-admin-portal/app/companies/page.tsx @@ -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(null); + const [textEn, setTextEn] = useState(""); + const [textMs, setTextMs] = useState(""); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(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) { + 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 ( + !open && onClose()}> + + + {t("PrivNotice")} + + {error && ( +
+ {error} +
+ )} +
+
+ +