feat: event guests, numbers, limits, check-in code and print cards in the portal

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 21:13:24 +08:00
1 parent 65b02fb927
commit 0027f294f2
22 files changed
+1317 -12

No files matched your search

@@ -194,3 +194,9 @@ Add these anchored method and path pairs:
4. A super admin grants Event guests to the admin roles under Roles.
Rollback: `sql/99-rollback.sql` drops the table and columns and deletes the module, losing guests and attendance marks. Redeploy the previous images.
## Build notes (portal)
- Add guest and Paste list are inline forms in the Guests section, not dialogs.
- A pasted line has no salesperson column; set one with Add guest. The counter refuses a salesperson who is not on the event team (`NOT_ON_TEAM`).
- The print page is gated like the other event sub-pages (`RequireModule pathname="/events"`, BO_EVENTS); ROUTE_MODULES has no per-sub-page entries.
@@ -140,7 +140,7 @@ Every portal verify must report the exit codes of lint, tsc and vitest. Vitest e
- **`/r/`:** works unchanged.
- Scope: `solvway-admin-portal/app/**`, `solvway-admin-portal/middleware*.test.ts`
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
- [ ] 5.2 Event page: the Guests section, the numbers strip, the capacity and cap fields, the check-in code in the QR card, Print cards (`/events/[uuid]/print`), and Copy all links.
- [x] 5.2 Event page: the Guests section, the numbers strip, the capacity and cap fields, the check-in code in the QR card, Print cards (`/events/[uuid]/print`), and Copy all links.
- Depends on: 3.1, 5.1
- Tests first:
- **Guest actions:** shown only with `BO_EVENT_GUESTS`.
@@ -0,0 +1,75 @@
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, POST, DELETE } from "./events/[uuid]/[...path]/route";
const req = (url = "http://localhost/x", init?: RequestInit) => new Request(url, init) as never;
const p = (uuid: string, ...path: string[]) => ({ params: Promise.resolve({ uuid, path }) });
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { ok: 1 } });
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("event guest proxies", () => {
it("require a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await GET(req(), p("e", "guests"))).status).toBe(401);
expect((await POST(req(), p("e", "guests"))).status).toBe(401);
expect((await DELETE(req(), p("e", "guests", "3"))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forward guests, check-in, attendance, preview, send and delete with the token", async () => {
await GET(req(), p("e1", "guests"));
await GET(req(), p("e1", "checkin"));
await GET(req(), p("e1", "attendance"));
await POST(req("http://localhost/x?preview=true", { method: "POST", body: '{"guests":[]}' }), p("e1", "guests"));
await POST(req("http://localhost/x", { method: "POST", body: '{"guests":[]}' }), p("e1", "guests"));
await POST(req("http://localhost/x", { method: "POST", body: '{"allUnsent":true}' }), p("e1", "guests", "send"));
await DELETE(req(), p("e1", "guests", "7"));
expect(mocks.callMobileApi.mock.calls).toEqual([
["/api/admin/events/e1/guests", { token: "jwt" }],
["/api/admin/events/e1/checkin", { token: "jwt" }],
["/api/admin/events/e1/attendance", { token: "jwt" }],
["/api/admin/events/e1/guests?preview=true", { method: "POST", body: { guests: [] }, token: "jwt" }],
["/api/admin/events/e1/guests", { method: "POST", body: { guests: [] }, token: "jwt" }],
["/api/admin/events/e1/guests/send", { method: "POST", body: { allUnsent: true }, token: "jwt" }],
["/api/admin/events/e1/guests/7", { method: "DELETE", token: "jwt" }],
]);
});
it("answers a delete with an empty success body", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: undefined });
const res = await DELETE(req(), p("e1", "guests", "7"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({});
});
it("passes the upstream error code and status through", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Registered", status: 409, code: "GUEST_REGISTERED" });
const res = await DELETE(req(), p("e1", "guests", "7"));
expect(res.status).toBe(409);
expect(await res.json()).toEqual({ error: "Registered", code: "GUEST_REGISTERED" });
});
it("refuse paths other than guests, checkin and attendance", async () => {
for (const path of [["registration-links"], ["guests", ".."], []]) {
expect((await GET(req(), p("e1", ...path))).status).toBe(400);
}
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("refuse an event id with path characters before forwarding", async () => {
for (const uuid of ["..", "a/b", "a%2Fb", "a b", "a?x=1", ""]) {
expect((await GET(req(), p(uuid, "guests"))).status).toBe(400);
expect((await DELETE(req(), p(uuid, "guests", "3"))).status).toBe(400);
}
expect(mocks.callMobileApi).not.toHaveBeenCalled();
await GET(req(), p("3f2a-9c", "guests"));
expect(mocks.callMobileApi).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,34 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// One proxy for the event guest, check-in and attendance endpoints; mobile-api owns validation and the BO_EVENTS / BO_EVENT_GUESTS guards.
type Ctx = { params: Promise<{ uuid: string; path: string[] }> };
const ALLOWED = /^(guests(\/(send|\d+))?|checkin|attendance)$/;
// Event uuids are strings, not numbers; word characters and hyphens cover them and nothing that can alter the upstream path.
const EVENT_ID = /^[\w-]+$/;
async function forward(req: NextRequest, { params }: Ctx, method?: "POST" | "DELETE") {
const token = await getToken();
if (!token) return unauthorized();
const { uuid, path } = await params;
if (!EVENT_ID.test(uuid) || !ALLOWED.test(path.join("/"))) return badRequest("Invalid path.");
// Only the preview flag is forwarded; nothing else from the browser's query string.
const preview = new URL(req.url).searchParams.getAll("preview").includes("true") ? "?preview=true" : "";
const target = `/api/admin/events/${encodeURIComponent(uuid)}/${path.map(encodeURIComponent).join("/")}${preview}`;
const result =
method === "POST"
? await callMobileApi<unknown>(target, { method, body: await req.json().catch(() => ({})), token })
: method
? await callMobileApi<unknown>(target, { method, token })
: await callMobileApi<unknown>(target, { token });
if (!result.ok) return errorResponse(result);
// A delete answers 204 with no body.
return NextResponse.json(result.data ?? {});
}
export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx);
export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST");
export const DELETE = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "DELETE");
@@ -31,7 +31,7 @@ const ROLES = [
beforeEach(() => {
mocks.listAdminRoles.mockReset().mockResolvedValue(ROLES);
mocks.listSalespersonOptions.mockReset().mockResolvedValue([{ id: 1, name: "Alice", username: "alice" }]);
mocks.useAdminAuth.mockReset().mockReturnValue({ id: 9, isSuper: true });
mocks.useAdminAuth.mockReset().mockReturnValue({ id: 9, isSuper: true, hasModule: () => false });
mocks.useCompanyScope.mockReset().mockReturnValue(scope(2));
});
@@ -85,7 +85,7 @@ describe("UserForm company", () => {
});
it("does not show Company to staff or send it", async () => {
mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false });
mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false, hasModule: () => false });
const onSubmit = vi.fn().mockResolvedValue(undefined);
const user = userEvent.setup();
render(<UserForm onSubmit={onSubmit} />);
@@ -131,7 +131,7 @@ describe("EventForm company", () => {
});
it("does not show Company to staff", async () => {
mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false });
mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false, hasModule: () => false });
render(<EventForm onSubmit={vi.fn()} />);
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenCalled());
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
@@ -60,7 +60,7 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
<Header />
<main className="mx-auto w-full max-w-[var(--content-max-width)] min-w-0 flex-1 p-4">{children}</main>
{/* The sidebar (and its credit) is hidden below lg, so repeat the credit under the content there. */}
<div data-testid="mobile-credit" className="px-4 pb-4 text-center lg:hidden">
<div data-testid="mobile-credit" className="px-4 pb-4 text-center lg:hidden print:hidden">
<PoweredBy />
</div>
</div>
@@ -55,7 +55,7 @@ export default function Header() {
const initial = (name ?? "?").slice(0, 1).toUpperCase();
return (
<header className="sticky top-0 z-30 flex h-14 shrink-0 items-center gap-2 border-b bg-card px-4">
<header className="sticky top-0 z-30 flex h-14 shrink-0 items-center gap-2 border-b bg-card px-4 print:hidden">
<Sheet open={menuOpen} onOpenChange={setMenuOpen}>
<Button
variant="ghost"
@@ -289,7 +289,7 @@ export default function Sidebar() {
data-collapsed={collapsed ? "true" : "false"}
style={{ width: collapsed ? "var(--sidebar-width-collapsed)" : "var(--sidebar-width)" }}
className={cn(
"sticky top-0 hidden h-svh shrink-0 flex-col border-r bg-sidebar lg:flex",
"sticky top-0 hidden h-svh print:!hidden shrink-0 flex-col border-r bg-sidebar lg:flex",
animate && "transition-[width] duration-200 ease-out motion-reduce:transition-none",
)}
>
@@ -0,0 +1,76 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({ listSalespersonOptions: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/services/adminEvents", () => ({ listSalespersonOptions: mocks.listSalespersonOptions }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import { EventForm } from "./EventForm";
const INITIAL = {
uuid: "e1", name: "Expo", location: "KL", startDate: "2026-12-01", endDate: "2026-12-02", enabled: true, team: [],
capacity: 200, invitationCap: 50,
};
const asAdmin = (guests: boolean) =>
mocks.useAdminAuth.mockReturnValue({ isSuper: false, hasModule: (m: string) => guests && m === "BO_EVENT_GUESTS" });
beforeEach(() => {
mocks.listSalespersonOptions.mockReset().mockResolvedValue([]);
asAdmin(true);
});
describe("EventForm capacity and invitation cap", () => {
it("prefills both fields on edit", async () => {
render(<EventForm initial={INITIAL} onSubmit={vi.fn()} />);
expect(await screen.findByLabelText("Capacity")).toHaveValue(200);
expect(screen.getByLabelText("Invitation cap")).toHaveValue(50);
});
it("disables both fields and leaves them out of the payload without BO_EVENT_GUESTS", async () => {
asAdmin(false);
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<EventForm initial={INITIAL} onSubmit={onSubmit} />);
expect(await screen.findByLabelText("Capacity")).toBeDisabled();
expect(screen.getByLabelText("Invitation cap")).toBeDisabled();
await userEvent.click(screen.getByRole("button", { name: "Edit" }));
await waitFor(() => expect(onSubmit).toHaveBeenCalled());
expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("capacity");
expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("invitationCap");
});
it("sends the numbers, and null when a field is cleared", async () => {
const user = userEvent.setup();
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<EventForm initial={INITIAL} onSubmit={onSubmit} />);
const cap = await screen.findByLabelText("Capacity");
await user.clear(cap);
await user.type(cap, "300");
await user.clear(screen.getByLabelText("Invitation cap"));
await user.click(screen.getByRole("button", { name: "Edit" }));
await waitFor(() => expect(onSubmit).toHaveBeenCalled());
expect(onSubmit.mock.calls[0][0]).toMatchObject({ capacity: 300, invitationCap: null });
});
it("shows CAP_BELOW_GUESTS on the invitation cap field", async () => {
const user = userEvent.setup();
const onSubmit = vi.fn().mockRejectedValue(new ApiError("Cap is below the guests already invited", 409, { code: "CAP_BELOW_GUESTS" }));
render(<EventForm initial={INITIAL} onSubmit={onSubmit} />);
await screen.findByLabelText("Capacity");
await user.click(screen.getByRole("button", { name: "Edit" }));
expect(await screen.findByText("Cap is below the guests already invited")).toBeInTheDocument();
expect(screen.getByLabelText("Invitation cap")).toHaveAttribute("aria-invalid", "true");
expect(screen.getByLabelText("Capacity")).not.toHaveAttribute("aria-invalid", "true");
});
it("shows INVALID_LIMIT on the field the server names", async () => {
const user = userEvent.setup();
const onSubmit = vi.fn().mockRejectedValue(new ApiError("Capacity must be at least 1", 400, { code: "INVALID_LIMIT", details: { field: "capacity" } }));
render(<EventForm initial={INITIAL} onSubmit={onSubmit} />);
await screen.findByLabelText("Capacity");
await user.click(screen.getByRole("button", { name: "Edit" }));
expect(await screen.findByText("Capacity must be at least 1")).toBeInTheDocument();
expect(screen.getByLabelText("Capacity")).toHaveAttribute("aria-invalid", "true");
});
});
@@ -34,11 +34,12 @@ const REQUIRED_MESSAGE: Record<string, string> = {
endDate: "EvtEndRequired",
};
/** Fields the form can show an API error under; anything else goes to the top of the form. */
const FIELD_ERROR_SLOTS = ["company", "name", "location", "startDate", "endDate", "salespersonIds"];
const FIELD_ERROR_SLOTS = ["company", "name", "location", "startDate", "endDate", "salespersonIds", "capacity", "invitationCap"];
export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
const t = useT();
const { isSuper } = useAdminAuth();
const { isSuper, hasModule } = useAdminAuth();
const canSetLimits = hasModule("BO_EVENT_GUESTS");
const scope = useCompanyScope();
// Super admins choose the company on create; on edit it is the event's own (it cannot move).
const showCompany = isSuper === true && !initial;
@@ -50,6 +51,8 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
const [startDate, setStartDate] = useState(initial?.startDate ?? "");
const [endDate, setEndDate] = useState(initial?.endDate ?? "");
const [enabled, setEnabled] = useState(initial?.enabled ?? true);
const [capacity, setCapacity] = useState(initial?.capacity != null ? String(initial.capacity) : "");
const [invitationCap, setInvitationCap] = useState(initial?.invitationCap != null ? String(initial.invitationCap) : "");
const [optionList, setOptionList] = useState<SalespersonOptionExtended[]>([]);
const [loadingPickers, setLoadingPickers] = useState(true);
@@ -147,12 +150,22 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
// `enabled` is only sent on edit (when initial exists).
if (initial) {
payload.enabled = enabled;
// Empty clears the limit; the server ignores these without BO_EVENT_GUESTS, so do not send them.
if (canSetLimits) {
payload.capacity = capacity.trim() === "" ? null : Number(capacity);
payload.invitationCap = invitationCap.trim() === "" ? null : Number(invitationCap);
}
}
await onSubmit(payload);
} catch (err) {
if (err instanceof Error && "status" in err && "data" in err) {
// The API sends errors[] (every missing field) and details.field (the failing field).
const data = (err as ApiError).data as { errors?: unknown; details?: { field?: unknown } } | undefined;
const data = (err as ApiError).data as { code?: unknown; errors?: unknown; details?: { field?: unknown } } | undefined;
if (data?.code === "CAP_BELOW_GUESTS") {
// The server sends no field for this one; it is always the invitation cap.
setFieldErrors({ invitationCap: err.message });
return;
}
const missing = (Array.isArray(data?.errors) ? data.errors : []).filter((f): f is string => typeof f === "string" && Object.hasOwn(REQUIRED_MESSAGE, f));
const field = data?.details?.field;
if (missing.length > 0) {
@@ -290,6 +303,45 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
</div>
)}
{initial && (
<>
<div className="space-y-1.5">
<Label htmlFor="evt-capacity">{t("EvtCapacity")}</Label>
<Input
id="evt-capacity"
type="number"
min={1}
value={capacity}
onChange={(e) => setCapacity(e.target.value)}
disabled={saving || !canSetLimits}
aria-invalid={!!fieldErrors.capacity}
/>
{fieldErrors.capacity && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.capacity}
</p>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="evt-invitation-cap">{t("EvtInvitationCap")}</Label>
<Input
id="evt-invitation-cap"
type="number"
min={1}
value={invitationCap}
onChange={(e) => setInvitationCap(e.target.value)}
disabled={saving || !canSetLimits}
aria-invalid={!!fieldErrors.invitationCap}
/>
{fieldErrors.invitationCap && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors.invitationCap}
</p>
)}
</div>
</>
)}
<fieldset className="space-y-1.5">
<legend className="text-sm font-medium">{t("EvtTeamLabel")}</legend>
{fieldErrors.salespersonIds && (
@@ -0,0 +1,293 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({
listGuests: vi.fn(),
addGuests: vi.fn(),
removeGuest: vi.fn(),
sendInvites: vi.fn(),
getAttendance: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminGuests", () => mocks);
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import { GuestsCard } from "./GuestsCard";
const guest = (over: object) => ({
id: 1, name: "Aini", mobileE164: "+60123", email: "a@x.my", companyName: "Acme", salespersonUserId: null,
salespersonName: null, token: "t1", invitedAt: "2026-12-01T00:00:00Z", inviteSentCount: 0, registeredAt: null,
attended: false, eventLeadUuid: null, ...over,
});
const GUESTS = [
guest({}),
guest({ id: 2, name: "Bob", email: null, token: "t2" }),
guest({ id: 3, name: "Cara", registeredAt: "2026-12-02T00:00:00Z", token: "t3" }),
guest({ id: 4, name: "Dan", registeredAt: "2026-12-02T00:00:00Z", attended: true, token: "t4" }),
];
const ATT = { invited: 4, cap: 10, registered: 2, attended: 1, walkIns: 3, total: 5, capacity: 100 };
const asAdmin = (guests: boolean) =>
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_EVENTS" || (guests && m === "BO_EVENT_GUESTS") });
beforeEach(() => {
mocks.listGuests.mockReset().mockResolvedValue(GUESTS);
mocks.getAttendance.mockReset().mockResolvedValue(ATT);
mocks.addGuests.mockReset();
mocks.removeGuest.mockReset().mockResolvedValue({});
mocks.sendInvites.mockReset().mockResolvedValue({ sent: 1, skippedNoEmail: 1 });
asAdmin(true);
});
const row = (name: string) => screen.getByRole("row", { name: new RegExp(name) });
describe("GuestsCard", () => {
it("shows the numbers strip as the API reports it", async () => {
render(<GuestsCard eventUuid="u1" />);
const strip = await screen.findByRole("list", { name: "Attendance numbers" });
const val = (label: string) => within(strip).getByText(label).nextSibling?.textContent;
expect(["Invited", "Invitation cap", "Registered", "Attended", "Walk-ins", "Total", "Capacity"].map(val)).toEqual(["4", "10", "2", "1", "3", "5", "100"]);
expect(mocks.getAttendance).toHaveBeenCalledWith("u1");
});
it("shows a dash for a missing cap or capacity", async () => {
mocks.getAttendance.mockResolvedValue({ ...ATT, cap: null, capacity: null });
render(<GuestsCard eventUuid="u1" />);
const strip = await screen.findByRole("list", { name: "Attendance numbers" });
await waitFor(() => expect(within(strip).getByText("Capacity").nextSibling?.textContent).toBe("-"));
expect(within(strip).getByText("Invitation cap").nextSibling?.textContent).toBe("-");
});
it("hides every guest action without BO_EVENT_GUESTS", async () => {
asAdmin(false);
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
for (const name of [/add guest/i, /preview/i, /send/i, /remove/i, /copy link/i]) {
expect(screen.queryByRole("button", { name })).toBeNull();
}
expect(screen.queryByLabelText("Paste guests")).toBeNull();
expect(screen.queryByText(/saved until delivery/i)).toBeNull();
});
it("shows the status of each guest", async () => {
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
expect(within(row("Aini")).getByText("Invited")).toBeInTheDocument();
expect(within(row("Cara")).getByText("Registered")).toBeInTheDocument();
expect(within(row("Dan")).getByText("Attended")).toBeInTheDocument();
});
it("states that emails are saved until delivery is set up", async () => {
render(<GuestsCard eventUuid="u1" />);
expect(await screen.findByText(/emails are saved until delivery is set up/i)).toBeInTheDocument();
});
it("adds one guest and reloads the list", async () => {
const user = userEvent.setup();
mocks.addGuests.mockResolvedValue({ added: 1, rejected: [] });
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
await user.type(screen.getByLabelText("Guest name"), "Eve");
await user.type(screen.getByLabelText("Guest email"), "e@x.my");
await user.click(screen.getByRole("button", { name: "Add guest" }));
await waitFor(() =>
expect(mocks.addGuests).toHaveBeenCalledWith("u1", [{ name: "Eve", mobile: "", email: "e@x.my", companyName: "" }], false),
);
await waitFor(() => expect(mocks.listGuests).toHaveBeenCalledTimes(2));
});
it("shows the server's field error under the field", async () => {
const user = userEvent.setup();
mocks.addGuests.mockResolvedValue({ added: 0, rejected: [{ index: 0, code: "INVALID_EMAIL", field: "email", message: "Email is not valid" }] });
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
await user.type(screen.getByLabelText("Guest name"), "Eve");
await user.type(screen.getByLabelText("Guest email"), "bad");
await user.click(screen.getByRole("button", { name: "Add guest" }));
expect(await screen.findByText("Email is not valid")).toBeInTheDocument();
expect(screen.getByLabelText("Guest email")).toHaveAttribute("aria-invalid", "true");
expect(mocks.listGuests).toHaveBeenCalledTimes(1);
});
it("previews pasted lines with per-line errors, then saves", async () => {
const user = userEvent.setup();
mocks.addGuests
.mockResolvedValueOnce({ added: 1, rejected: [{ index: 1, code: "DUPLICATE", field: "email", message: "Already invited" }] })
.mockResolvedValueOnce({ added: 1, rejected: [{ index: 1, code: "DUPLICATE", field: "email", message: "Already invited" }] });
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
await user.type(screen.getByLabelText("Paste guests"), "Eve, 0123, e@x.my, Acme{Enter}Aini, , a@x.my");
await user.click(screen.getByRole("button", { name: "Preview" }));
expect(mocks.addGuests).toHaveBeenNthCalledWith(
1,
"u1",
[
{ name: "Eve", mobile: "0123", email: "e@x.my", companyName: "Acme" },
{ name: "Aini", mobile: "", email: "a@x.my", companyName: "" },
],
true,
);
expect(await screen.findByText("Line 2: Already invited")).toBeInTheDocument();
expect(screen.getByText("1 guest will be added")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save guests" }));
await waitFor(() => expect(mocks.addGuests).toHaveBeenNthCalledWith(2, "u1", expect.any(Array), false));
await waitFor(() => expect(mocks.listGuests).toHaveBeenCalledTimes(2));
});
it("sends to one guest, and copy link only for a guest with no email", async () => {
const user = userEvent.setup();
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
expect(screen.queryByRole("button", { name: "Send invite to Bob" })).toBeNull();
await user.click(screen.getByRole("button", { name: "Send invite to Aini" }));
expect(mocks.sendInvites).toHaveBeenCalledWith("u1", { guestIds: [1] });
const write = vi.spyOn(navigator.clipboard, "writeText");
await user.click(screen.getByRole("button", { name: "Copy link for Bob" }));
expect(write).toHaveBeenCalledWith(`${window.location.origin}/i/t2`);
});
it("sends to all unsent and reports the counts", async () => {
const user = userEvent.setup();
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
await user.click(screen.getByRole("button", { name: "Send to all unsent" }));
expect(mocks.sendInvites).toHaveBeenCalledWith("u1", { allUnsent: true });
expect(await screen.findByText("Sent 1, skipped 1 with no email")).toBeInTheDocument();
});
it("offers Remove only for invited guests", async () => {
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
expect(screen.getByRole("button", { name: "Remove Aini" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Remove Bob" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Remove Cara" })).toBeNull();
expect(screen.queryByRole("button", { name: "Remove Dan" })).toBeNull();
});
it("removes a guest and reloads", async () => {
const user = userEvent.setup();
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
await user.click(screen.getByRole("button", { name: "Remove Aini" }));
expect(mocks.removeGuest).toHaveBeenCalledWith("u1", 1);
await waitFor(() => expect(mocks.listGuests).toHaveBeenCalledTimes(2));
});
it("shows the refusal when the server says the guest registered", async () => {
const user = userEvent.setup();
mocks.removeGuest.mockRejectedValue(new ApiError("Guest already registered", 409, { code: "GUEST_REGISTERED" }));
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
await user.click(screen.getByRole("button", { name: "Remove Aini" }));
expect(await screen.findByText("This guest has already registered and cannot be removed.")).toBeInTheDocument();
});
it("shows an error when the guest list does not load", async () => {
mocks.listGuests.mockRejectedValue(new ApiError("boom", 500));
render(<GuestsCard eventUuid="u1" />);
expect(await screen.findByText("Could not load guests.")).toBeInTheDocument();
});
it("shows the invite sent count and the salesperson of each guest", async () => {
mocks.listGuests.mockResolvedValue([guest({ inviteSentCount: 2, salespersonName: "Sam Lee" }), guest({ id: 2, name: "Bob", email: null, token: "t2" })]);
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
const head = screen.getAllByRole("columnheader").map((h) => h.textContent);
expect(head).toEqual(expect.arrayContaining(["Invites sent", "Salesperson"]));
const cells = (name: string) => within(row(name)).getAllByRole("cell").map((c) => c.textContent);
expect(cells("Aini")).toEqual(expect.arrayContaining(["2", "Sam Lee"]));
expect(cells("Bob")).toEqual(expect.arrayContaining(["0"]));
});
describe("salesperson picker", () => {
const team = [
{ id: 7, name: "Sam Lee", username: "sam@cv", enabled: true },
{ id: 8, name: null, username: "zed@cv", enabled: true },
];
it("sends the chosen team member as salespersonUserId", async () => {
const user = userEvent.setup();
mocks.addGuests.mockResolvedValue({ added: 1, rejected: [] });
render(<GuestsCard eventUuid="u1" team={team} />);
await screen.findByText("Aini");
await user.type(screen.getByLabelText("Guest name"), "Eve");
await user.click(screen.getByRole("combobox", { name: "Salesperson" }));
await user.click(await screen.findByRole("option", { name: "Sam Lee" }));
await user.click(screen.getByRole("button", { name: "Add guest" }));
await waitFor(() =>
expect(mocks.addGuests).toHaveBeenCalledWith("u1", [{ name: "Eve", mobile: "", email: "", companyName: "", salespersonUserId: 7 }], false),
);
});
it("sends no salespersonUserId after choosing None again", async () => {
const user = userEvent.setup();
mocks.addGuests.mockResolvedValue({ added: 1, rejected: [] });
render(<GuestsCard eventUuid="u1" team={team} />);
await screen.findByText("Aini");
await user.type(screen.getByLabelText("Guest name"), "Eve");
await user.click(screen.getByRole("combobox", { name: "Salesperson" }));
await user.click(await screen.findByRole("option", { name: "zed@cv" }));
await user.click(screen.getByRole("combobox", { name: "Salesperson" }));
await user.click(await screen.findByRole("option", { name: "None" }));
await user.click(screen.getByRole("button", { name: "Add guest" }));
await waitFor(() => expect(mocks.addGuests).toHaveBeenCalledWith("u1", [{ name: "Eve", mobile: "", email: "", companyName: "" }], false));
});
it("is hidden when the event has no team", async () => {
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
expect(screen.queryByRole("combobox", { name: "Salesperson" })).toBeNull();
});
});
it("after a save with rejections shows Added N and only the rejected lines, and cannot resend saved lines", async () => {
const user = userEvent.setup();
const rejected = [{ index: 1, code: "DUPLICATE", field: "email", message: "Already invited" }];
mocks.addGuests.mockResolvedValueOnce({ added: 1, rejected }).mockResolvedValueOnce({ added: 1, rejected });
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
await user.type(screen.getByLabelText("Paste guests"), "Eve, , e@x.my{Enter}Aini, , a@x.my");
await user.click(screen.getByRole("button", { name: "Preview" }));
await user.click(await screen.findByRole("button", { name: "Save guests" }));
expect(await screen.findByText("Added 1")).toBeInTheDocument();
expect(screen.getByText("Line 1: Already invited")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Save guests" })).toBeNull();
expect(screen.getByLabelText("Paste guests")).toHaveValue("Aini, , a@x.my");
expect(mocks.addGuests).toHaveBeenCalledTimes(2);
});
it("shows the server's message for a 4xx error without a mapped code", async () => {
const user = userEvent.setup();
mocks.removeGuest.mockRejectedValue(new ApiError("Event is closed for changes", 422, { code: "EVENT_CLOSED" }));
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
await user.click(screen.getByRole("button", { name: "Remove Aini" }));
expect(await screen.findByText("Event is closed for changes")).toBeInTheDocument();
expect(screen.queryByText("Could not remove the guest.")).toBeNull();
});
it("keeps the generic message for a 5xx error", async () => {
const user = userEvent.setup();
mocks.removeGuest.mockRejectedValue(new ApiError("stack trace", 500));
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
await user.click(screen.getByRole("button", { name: "Remove Aini" }));
expect(await screen.findByText("Could not remove the guest.")).toBeInTheDocument();
expect(screen.queryByText("stack trace")).toBeNull();
});
it("confirms a copied link and reports a clipboard failure", async () => {
const user = userEvent.setup();
render(<GuestsCard eventUuid="u1" />);
await screen.findByText("Aini");
const write = vi.spyOn(navigator.clipboard, "writeText");
await user.click(screen.getByRole("button", { name: "Copy link for Bob" }));
expect(await screen.findByText("Link copied")).toBeInTheDocument();
write.mockRejectedValue(new Error("denied"));
await user.click(screen.getByRole("button", { name: "Copy link for Bob" }));
expect(await screen.findByText("Could not copy.")).toBeInTheDocument();
expect(screen.queryByText("Link copied")).toBeNull();
});
});
@@ -0,0 +1,345 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { ErrorState } from "@/app/components/ui/states";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { ApiError } from "@/app/lib/clientApi";
import {
addGuests,
getAttendance,
listGuests,
removeGuest,
sendInvites,
type AddGuestsResult,
type Attendance,
type EventGuest,
type GuestInput,
} from "@/app/lib/services/adminGuests";
import type { AdminEventMember } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type Field = "name" | "mobile" | "email" | "companyName";
const FIELDS: Field[] = ["name", "mobile", "email", "companyName"];
const EMPTY: GuestInput = { name: "", mobile: "", email: "", companyName: "" };
// Radix Select rejects "" as an item value, so "None" is this sentinel, mapped to no salesperson.
const NONE = "none";
// One guest per line: name, mobile, email, company. ponytail: plain comma split, no quoted commas.
const splitLines = (text: string) =>
text
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
// ponytail: paste has no salesperson column; the backend accepts one per guest, add a column here if sales asks.
const parseLines = (text: string): GuestInput[] =>
splitLines(text).map((l) => {
const [name = "", mobile = "", email = "", companyName = ""] = l.split(",").map((c) => c.trim());
return { name, mobile, email, companyName };
});
export function GuestsCard({ eventUuid, team = [] }: { eventUuid: string; team?: AdminEventMember[] }) {
const t = useT();
const { hasModule } = useAdminAuth();
const canManage = hasModule("BO_EVENT_GUESTS");
const [guests, setGuests] = useState<EventGuest[] | null>(null);
const [att, setAtt] = useState<Attendance | null>(null);
const [loadError, setLoadError] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [form, setForm] = useState<GuestInput>(EMPTY);
const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});
const [paste, setPaste] = useState("");
const [salesperson, setSalesperson] = useState(NONE);
const [preview, setPreview] = useState<(AddGuestsResult & { saved: boolean }) | null>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
try {
setGuests(await listGuests(eventUuid));
setLoadError(false);
} catch {
setLoadError(true);
}
// ponytail: the numbers strip is secondary; a failed fetch leaves dashes.
getAttendance(eventUuid).then(setAtt).catch(() => {});
}, [eventUuid]);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- load() fetches from the API; its setState runs after the await.
load();
}, [load]);
async function run(action: () => Promise<void>, failed: string) {
setError(null);
setNotice(null);
setBusy(true);
try {
await action();
} catch (err) {
const api = err instanceof ApiError ? err : null;
const code = (api?.data as { code?: string } | undefined)?.code;
// A 4xx is the server explaining what is wrong; anything else gets the generic text.
const known = api && api.status >= 400 && api.status < 500 && api.message ? api.message : failed;
setError(code === "GUEST_REGISTERED" ? t("GuestRegisteredRefused") : known);
} finally {
setBusy(false);
}
}
const addOne = (e: React.FormEvent) => {
e.preventDefault();
return run(async () => {
setFieldErrors({});
const res = await addGuests(eventUuid, [salesperson === NONE ? form : { ...form, salespersonUserId: Number(salesperson) }], false);
if (res.rejected.length) {
const next: Partial<Record<Field, string>> = {};
for (const r of res.rejected) {
if (r.field && (FIELDS as string[]).includes(r.field)) next[r.field as Field] = r.message;
else setError(r.message);
}
setFieldErrors(next);
return;
}
setForm(EMPTY);
setSalesperson(NONE);
await load();
}, t("GuestAddFailed"));
};
const doPaste = (dryRun: boolean) =>
run(async () => {
const res = await addGuests(eventUuid, parseLines(paste), dryRun);
if (dryRun) {
setPreview({ ...res, saved: false });
return;
}
// Keep only the rejected lines, so a second save cannot resend the saved ones.
const lines = splitLines(paste);
const rejected = res.rejected.map((r, i) => ({ ...r, index: i }));
setPaste(res.rejected.map((r) => lines[r.index]).join("\n"));
setPreview({ added: res.added, rejected, saved: true });
await load();
}, t("GuestAddFailed"));
const send = (target: { guestIds: number[] } | { allUnsent: true }) =>
run(async () => {
const res = await sendInvites(eventUuid, target);
setNotice(t("GuestSendResult", { sent: res.sent, skipped: res.skippedNoEmail }));
await load();
}, t("GuestSendFailed"));
const remove = (id: number) =>
run(async () => {
await removeGuest(eventUuid, id);
await load();
}, t("GuestRemoveFailed"));
async function copyLink(token: string) {
setError(null);
setNotice(null);
try {
await navigator.clipboard.writeText(`${window.location.origin}/i/${token}`);
setNotice(t("QrCopied"));
} catch {
setError(t("CopyFailed"));
}
}
const status = (g: EventGuest) =>
g.attended ? (
<Badge variant="positive">{t("GuestAttended")}</Badge>
) : g.registeredAt ? (
<Badge variant="teal">{t("GuestRegistered")}</Badge>
) : (
<Badge variant="neutral">{t("GuestInvited")}</Badge>
);
const numbers: [string, number | null | undefined][] = [
[t("GuestInvited"), att?.invited],
[t("EvtInvitationCap"), att?.cap],
[t("GuestRegistered"), att?.registered],
[t("GuestAttended"), att?.attended],
[t("GuestWalkIns"), att?.walkIns],
[t("GuestTotal"), att?.total],
[t("EvtCapacity"), att?.capacity],
];
return (
<Card>
<CardHeader>
<CardTitle>{t("GuestsTitle")}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<ul aria-label={t("GuestNumbers")} className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-7">
{numbers.map(([label, value]) => (
<li key={label} className="rounded-md border p-2">
<span className="block text-xs text-muted-foreground">{label}</span>
<span className="text-lg font-semibold">{value ?? "-"}</span>
</li>
))}
</ul>
{error && <ErrorState message={error} />}
{loadError && <ErrorState message={t("GuestsLoadFailed")} onRetry={load} />}
{notice && (
<p role="status" className="text-sm">
{notice}
</p>
)}
{canManage && (
<>
<p className="text-sm text-muted-foreground">{t("GuestsNote")}</p>
<form onSubmit={addOne} className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5 lg:items-start">
{FIELDS.map((f) => {
const label = t({ name: "GuestName", mobile: "GuestMobile", email: "GuestEmail", companyName: "GuestCompany" }[f]);
return (
<div key={f} className="space-y-1.5">
<Label htmlFor={`guest-${f}`}>{label}</Label>
<Input
id={`guest-${f}`}
type="text"
value={form[f]}
onChange={(e) => setForm({ ...form, [f]: e.target.value })}
aria-invalid={!!fieldErrors[f]}
/>
{fieldErrors[f] && (
<p role="alert" className="text-sm text-destructive">
{fieldErrors[f]}
</p>
)}
</div>
);
})}
{team.length > 0 && (
<div className="space-y-1.5">
<Label htmlFor="guest-salesperson">{t("LeadSalesperson")}</Label>
<Select value={salesperson} onValueChange={setSalesperson}>
<SelectTrigger id="guest-salesperson" aria-label={t("LeadSalesperson")}>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>{t("LeadNone")}</SelectItem>
{team.map((m) => (
<SelectItem key={m.id} value={String(m.id)}>
{m.name ?? m.username ?? m.id}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
<Button type="submit" disabled={busy} className="lg:mt-6">
{t("GuestAdd")}
</Button>
</form>
<div className="space-y-1.5">
<Label htmlFor="guest-paste">{t("GuestPaste")}</Label>
<textarea
id="guest-paste"
rows={4}
value={paste}
onChange={(e) => {
setPaste(e.target.value);
setPreview(null);
}}
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
/>
<p className="text-xs text-muted-foreground">{t("GuestPasteHelp")}</p>
{preview && (
<div className="space-y-1 text-sm">
<p>
{preview.saved ? t("GuestAddedCount", { count: preview.added }) : t(preview.added === 1 ? "GuestWillAddOne" : "GuestWillAddMany", { count: preview.added })}
</p>
{preview.rejected.map((r) => (
<p key={r.index} className="text-destructive">
{t("GuestLineError", { line: r.index + 1, reason: r.message })}
</p>
))}
</div>
)}
<div className="flex gap-2">
<Button type="button" variant="outline" size="sm" disabled={busy || !paste.trim()} onClick={() => doPaste(true)}>
{t("GuestPreview")}
</Button>
{preview && !preview.saved && preview.added > 0 && (
<Button type="button" size="sm" disabled={busy} onClick={() => doPaste(false)}>
{t("GuestSave")}
</Button>
)}
</div>
</div>
<Button type="button" variant="outline" size="sm" disabled={busy} onClick={() => send({ allUnsent: true })}>
{t("GuestSendAll")}
</Button>
</>
)}
{guests && (
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("Name")}</TableHead>
<TableHead>{t("LeadMobile")}</TableHead>
<TableHead>{t("Email")}</TableHead>
<TableHead>{t("Company")}</TableHead>
<TableHead>{t("Status")}</TableHead>
<TableHead>{t("GuestInviteSent")}</TableHead>
<TableHead>{t("LeadSalesperson")}</TableHead>
{canManage && <TableHead />}
</TableRow>
</TableHeader>
<TableBody>
{guests.map((g) => (
<TableRow key={g.id}>
<TableCell>{g.name}</TableCell>
<TableCell>{g.mobileE164}</TableCell>
<TableCell>{g.email}</TableCell>
<TableCell>{g.companyName}</TableCell>
<TableCell>{status(g)}</TableCell>
<TableCell>{g.inviteSentCount}</TableCell>
<TableCell>{g.salespersonName}</TableCell>
{canManage && (
<TableCell>
<div className="flex flex-wrap gap-1">
{g.email && (
<Button variant="outline" size="sm" disabled={busy} aria-label={t("GuestSendTo", { name: g.name })} onClick={() => send({ guestIds: [g.id] })}>
{t("GuestSend")}
</Button>
)}
{g.token && (
<Button
variant="outline"
size="sm"
aria-label={t("GuestCopyLinkFor", { name: g.name })}
onClick={() => copyLink(g.token!)}
>
{t("QrCopy")}
</Button>
)}
{!g.registeredAt && !g.attended && (
<Button variant="outline" size="sm" disabled={busy} aria-label={t("GuestRemoveNamed", { name: g.name })} onClick={() => remove(g.id)}>
{t("GuestRemove")}
</Button>
)}
</div>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,76 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { forwardRef } from "react";
const mocks = vi.hoisted(() => ({ getEventLinks: vi.fn(), setLinkEnabled: vi.fn(), getCheckin: vi.fn() }));
vi.mock("@/app/lib/services/adminRegistration", () => ({ getEventLinks: mocks.getEventLinks, setLinkEnabled: mocks.setLinkEnabled }));
vi.mock("@/app/lib/services/adminGuests", () => ({ getCheckin: mocks.getCheckin }));
vi.mock("qrcode.react", () => ({
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
QRCodeCanvas: forwardRef<HTMLCanvasElement>(function QRCodeCanvas(_, ref) {
return <canvas ref={ref} />;
}),
}));
import { RegistrationQrCard } from "./RegistrationQrCard";
const links = {
event: { token: "ev1", enabled: true },
members: [
{ userId: 5, name: "Aini", username: "aini@cv", token: "m1", enabled: true },
{ userId: 6, name: "Bob", username: "", token: "m2", enabled: true },
],
};
const o = window.location.origin;
beforeEach(() => {
mocks.getEventLinks.mockReset().mockResolvedValue(links);
mocks.setLinkEnabled.mockReset();
mocks.getCheckin.mockReset().mockResolvedValue({ token: "chk1" });
});
describe("RegistrationQrCard check-in and print", () => {
it("shows the check-in code with its /c/ link and no on/off switch", async () => {
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Check-in code");
expect(screen.getAllByTestId("qr-svg").map((e) => e.getAttribute("data-value"))).toContain(`${o}/c/chk1`);
expect(screen.getAllByRole("switch")).toHaveLength(3);
expect(mocks.getCheckin).toHaveBeenCalledWith("u1");
});
it("still lists the other codes when the check-in code does not load", async () => {
mocks.getCheckin.mockRejectedValue(new Error("nope"));
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Aini (aini@cv)");
expect(screen.queryByText("Check-in code")).toBeNull();
});
it("links to the print cards page", async () => {
render(<RegistrationQrCard eventUuid="u 1" eventName="Expo" canWrite />);
expect(await screen.findByRole("link", { name: "Print cards" })).toHaveAttribute("href", "/events/u%201/print");
});
it("copies every code as a name: link line", async () => {
const user = userEvent.setup();
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Check-in code");
const write = vi.spyOn(navigator.clipboard, "writeText");
await user.click(screen.getByRole("button", { name: "Copy all links" }));
expect(write).toHaveBeenCalledWith(
[`Event code: ${o}/r/ev1`, `Aini (aini@cv): ${o}/r/m1`, `Bob: ${o}/r/m2`, `Check-in code: ${o}/c/chk1`].join("\n"),
);
});
it("confirms Copy all, and reports a clipboard failure", async () => {
const user = userEvent.setup();
render(<RegistrationQrCard eventUuid="u1" eventName="Expo" canWrite />);
await screen.findByText("Check-in code");
const write = vi.spyOn(navigator.clipboard, "writeText");
await user.click(screen.getByRole("button", { name: "Copy all links" }));
expect(await screen.findByRole("button", { name: "Link copied" })).toBeInTheDocument();
write.mockRejectedValue(new Error("denied"));
await user.click(screen.getByRole("button", { name: "Link copied" }));
expect(await screen.findByText("Could not copy.")).toBeInTheDocument();
});
});
@@ -1,16 +1,21 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { Button } from "@/app/components/ui/button";
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 { getCheckin } from "@/app/lib/services/adminGuests";
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 [checkin, setCheckin] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [copiedAll, setCopiedAll] = useState(false);
useEffect(() => {
let cancelled = false;
@@ -22,6 +27,38 @@ export function RegistrationQrCard({ eventUuid, eventName, canWrite }: { eventUu
};
}, [eventUuid, t]);
useEffect(() => {
let cancelled = false;
// ponytail: a missing check-in code only hides its card; the registration codes above stay usable.
getCheckin(eventUuid)
.then((c) => !cancelled && setCheckin(c.token))
.catch(() => {});
return () => {
cancelled = true;
};
}, [eventUuid]);
const memberLabel = (m: EventLinks["members"][number]) => (m.username ? `${m.name} (${m.username})` : m.name);
async function copyAll() {
if (!links) return;
const origin = window.location.origin;
const lines = [
`${t("QrEventCode")}: ${origin}/r/${links.event.token}`,
...links.members.map((m) => `${memberLabel(m)}: ${origin}/r/${m.token}`),
...(checkin ? [`${t("QrCheckinCode")}: ${origin}/c/${checkin}`] : []),
];
try {
await navigator.clipboard.writeText(lines.join("\n"));
} catch {
setError(t("CopyFailed"));
return;
}
setError(null);
setCopiedAll(true);
setTimeout(() => setCopiedAll(false), 2000);
}
async function toggle(token: string, enabled: boolean) {
setError(null);
try {
@@ -51,11 +88,20 @@ export function RegistrationQrCard({ eventUuid, eventName, canWrite }: { eventUu
<>
<QrCodeItem label={t("QrEventCode")} eventName={eventName} token={links.event.token} enabled={links.event.enabled} onToggle={onToggle(links.event.token)} />
{links.members.map((m) => {
const label = m.username ? `${m.name} (${m.username})` : m.name;
const label = memberLabel(m);
return (
<QrCodeItem key={m.token} label={label} eventName={eventName} fileLabel={label} token={m.token} enabled={m.enabled} onToggle={onToggle(m.token)} />
);
})}
{checkin && <QrCodeItem label={t("QrCheckinCode")} eventName={eventName} fileLabel={t("QrCheckinCode")} token={checkin} enabled prefix="c" />}
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm" onClick={copyAll}>
{copiedAll ? t("QrCopied") : t("QrCopyAll")}
</Button>
<Button variant="outline" size="sm" asChild>
<Link href={`/events/${encodeURIComponent(eventUuid)}/print`}>{t("QrPrintCards")}</Link>
</Button>
</div>
</>
)}
</CardContent>
@@ -17,6 +17,7 @@ export function QrCodeItem({
token,
enabled,
onToggle,
prefix = "r",
}: {
label: string;
eventName: string;
@@ -25,11 +26,13 @@ export function QrCodeItem({
token: string;
enabled: boolean;
onToggle?: (enabled: boolean) => void;
/** Public path the code opens: r = registration (default), c = check-in. */
prefix?: "r" | "c";
}) {
const t = useT();
const canvas = useRef<HTMLCanvasElement>(null);
const [copied, setCopied] = useState(false);
const link = `${window.location.origin}/r/${token}`;
const link = `${window.location.origin}/${prefix}/${token}`;
async function copy() {
await navigator.clipboard.writeText(link);
@@ -6,6 +6,7 @@ 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 { GuestsCard } from "@/app/components/events/GuestsCard";
import { RegistrationQrCard } from "@/app/components/events/RegistrationQrCard";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { RequireModule } from "@/app/lib/RequireModule";
@@ -120,6 +121,8 @@ function EditEventPageContent() {
{/* 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")} />
<GuestsCard eventUuid={event.uuid} team={event.team} />
</div>
);
}
@@ -0,0 +1,81 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { forwardRef } from "react";
const mocks = vi.hoisted(() => ({ getEventLinks: vi.fn(), getCheckin: vi.fn(), getAdminEvent: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/services/adminRegistration", () => ({ getEventLinks: mocks.getEventLinks }));
vi.mock("@/app/lib/services/adminGuests", () => ({ getCheckin: mocks.getCheckin }));
vi.mock("@/app/lib/services/adminEvents", () => ({ getAdminEvent: mocks.getAdminEvent }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", () => ({ useParams: () => ({ uuid: "u1" }) }));
vi.mock("qrcode.react", () => ({
QRCodeSVG: ({ value }: { value: string }) => <svg data-testid="qr-svg" data-value={value} />,
QRCodeCanvas: forwardRef<HTMLCanvasElement>(function QRCodeCanvas(_, ref) {
return <canvas ref={ref} />;
}),
}));
import PrintCardsPage from "./page";
const o = window.location.origin;
beforeEach(() => {
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
mocks.getAdminEvent.mockReset().mockResolvedValue({ uuid: "u1", name: "Expo" });
mocks.getEventLinks.mockReset().mockResolvedValue({
event: { token: "ev1", enabled: true },
members: [
{ userId: 5, name: "Aini", username: "aini@cv", token: "m1", enabled: true },
{ userId: 6, name: "Bob", username: "", token: "m2", enabled: true },
],
});
mocks.getCheckin.mockReset().mockResolvedValue({ token: "chk1" });
});
describe("print cards page", () => {
it("prints one card per team member plus the event walk-in code and the check-in code", async () => {
render(<PrintCardsPage />);
await screen.findByText("Aini (aini@cv)");
expect(screen.getAllByTestId("qr-svg").map((e) => e.getAttribute("data-value"))).toEqual([
`${o}/r/ev1`,
`${o}/r/m1`,
`${o}/r/m2`,
`${o}/c/chk1`,
]);
expect(screen.getByText("Event code")).toBeInTheDocument();
expect(screen.getByText("Bob")).toBeInTheDocument();
expect(screen.getByText("Check-in code")).toBeInTheDocument();
expect(screen.getAllByText("Expo").length).toBeGreaterThan(0);
});
it("opens the print dialog from the Print button", async () => {
const print = vi.spyOn(window, "print").mockImplementation(() => {});
render(<PrintCardsPage />);
await screen.findByText("Aini (aini@cv)");
await userEvent.click(screen.getByRole("button", { name: "Print" }));
expect(print).toHaveBeenCalled();
});
it("shows an error when the codes do not load", async () => {
mocks.getEventLinks.mockRejectedValue(new Error("x"));
render(<PrintCardsPage />);
expect(await screen.findByText("Could not load registration codes.")).toBeInTheDocument();
});
it("is blocked for a user without BO_EVENTS", async () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<PrintCardsPage />);
expect(await screen.findByTestId("not-authorized")).toBeInTheDocument();
expect(screen.queryAllByTestId("qr-svg")).toHaveLength(0);
});
it("lays out one column on a phone, two on wider screens and on paper, A4 with fixed card height", async () => {
const { container } = render(<PrintCardsPage />);
await screen.findByText("Aini (aini@cv)");
const grid = screen.getAllByTestId("qr-svg")[0].closest("div")!.parentElement!;
expect(grid).toHaveClass("grid-cols-1", "sm:grid-cols-2", "print:grid-cols-2");
expect(screen.getAllByTestId("qr-svg")[0].closest("div")).toHaveClass("print:h-[64mm]");
expect(container.querySelector("style")?.textContent).toMatch(/@page\s*{[^}]*size:\s*A4/);
});
});
@@ -0,0 +1,85 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { QRCodeSVG } from "qrcode.react";
import { Button } from "@/app/components/ui/button";
import { ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { getAdminEvent } from "@/app/lib/services/adminEvents";
import { getCheckin } from "@/app/lib/services/adminGuests";
import { getEventLinks } from "@/app/lib/services/adminRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
interface Card {
key: string;
label: string;
url: string;
}
function PrintCardsContent() {
const t = useT();
const { uuid } = useParams<{ uuid: string }>();
const [eventName, setEventName] = useState("");
const [cards, setCards] = useState<Card[] | null>(null);
const [error, setError] = useState(false);
useEffect(() => {
let cancelled = false;
const origin = window.location.origin;
// ponytail: the name and check-in code are optional extras; only the registration codes are required.
getAdminEvent(uuid).then((e) => !cancelled && setEventName(e.name)).catch(() => {});
Promise.all([getEventLinks(uuid), getCheckin(uuid).catch(() => null)])
.then(([links, checkin]) => {
if (cancelled) return;
setCards([
{ key: "event", label: t("QrEventCode"), url: `${origin}/r/${links.event.token}` },
...links.members.map((m) => ({
key: m.token,
label: m.username ? `${m.name} (${m.username})` : m.name,
url: `${origin}/r/${m.token}`,
})),
...(checkin ? [{ key: "checkin", label: t("QrCheckinCode"), url: `${origin}/c/${checkin.token}` }] : []),
]);
})
.catch(() => !cancelled && setError(true));
return () => {
cancelled = true;
};
}, [uuid, t]);
return (
<div className="space-y-4">
<div className="flex items-center gap-2 print:hidden">
<Button variant="outline" size="sm" asChild>
<Link href={`/events/${encodeURIComponent(uuid)}`}>{t("Back")}</Link>
</Button>
<Button size="sm" onClick={() => window.print()}>
{t("PrintButton")}
</Button>
</div>
<h1 className="text-xl font-semibold">{t("PrintCardsTitle")}</h1>
{error && <ErrorState message={t("QrLoadFailed")} />}
{/* A4 with 10mm margins: 2 columns x 4 rows of 64mm cards fit one page. */}
<style>{"@page { size: A4; margin: 10mm; }"}</style>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 print:grid-cols-2 print:gap-2">
{cards?.map((c) => (
<div key={c.key} className="flex break-inside-avoid flex-col items-center gap-2 rounded-lg border border-foreground p-4 text-center print:h-[64mm] print:overflow-hidden print:p-2">
<QRCodeSVG value={c.url} size={160} />
<p className="font-medium">{c.label}</p>
<p className="text-sm text-muted-foreground">{eventName}</p>
</div>
))}
</div>
</div>
);
}
export default function PrintCardsPage() {
return (
<RequireModule pathname="/events">
<PrintCardsContent />
</RequireModule>
);
}
@@ -502,6 +502,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
QrEventCode: "Event code",
QrCopy: "Copy link",
QrCopied: "Link copied",
CopyFailed: "Could not copy.",
QrDownload: "Download PNG",
QrEnabled: "Enabled",
QrNote: "Paste the link into the dynamic-qr console to get a QR that can be changed later.",
@@ -515,4 +516,45 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PrivSaveFailed: "Could not save the notice.",
PrivLoadFailed: "Could not load the notice.",
PrivLastChanged: "Last changed by {user} on {date}",
QrCheckinCode: "Check-in code",
QrCopyAll: "Copy all links",
QrPrintCards: "Print cards",
EvtCapacity: "Capacity",
EvtInvitationCap: "Invitation cap",
GuestsTitle: "Guests",
GuestsLoadFailed: "Could not load guests.",
GuestsNote: "Emails are saved until delivery is set up. Copy a guest's link to share it now.",
GuestNumbers: "Attendance numbers",
GuestInvited: "Invited",
GuestRegistered: "Registered",
GuestAttended: "Attended",
GuestWalkIns: "Walk-ins",
GuestTotal: "Total",
GuestName: "Guest name",
GuestMobile: "Guest mobile",
GuestEmail: "Guest email",
GuestCompany: "Guest company",
GuestAdd: "Add guest",
GuestAddFailed: "Could not add the guest.",
GuestPaste: "Paste guests",
GuestPasteHelp: "One guest per line: name, mobile, email, company.",
GuestPreview: "Preview",
GuestSave: "Save guests",
GuestWillAddOne: "1 guest will be added",
GuestWillAddMany: "{count} guests will be added",
GuestLineError: "Line {line}: {reason}",
GuestSend: "Send invite",
GuestSendTo: "Send invite to {name}",
GuestCopyLinkFor: "Copy link for {name}",
GuestRemove: "Remove",
GuestRemoveNamed: "Remove {name}",
GuestInviteSent: "Invites sent",
GuestAddedCount: "Added {count}",
GuestSendAll: "Send to all unsent",
GuestSendResult: "Sent {sent}, skipped {skipped} with no email",
GuestSendFailed: "Could not send the invites.",
GuestRegisteredRefused: "This guest has already registered and cannot be removed.",
GuestRemoveFailed: "Could not remove the guest.",
PrintCardsTitle: "Print cards",
PrintButton: "Print",
};
@@ -0,0 +1,28 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiDelete: vi.fn() }));
vi.mock("@/app/lib/clientApi", () => mocks);
import { addGuests, getAttendance, getCheckin, listGuests, removeGuest, sendInvites } from "./adminGuests";
beforeEach(() => Object.values(mocks).forEach((m) => m.mockReset().mockResolvedValue({})));
describe("adminGuests service", () => {
it("calls the event guest proxies", async () => {
const g = [{ name: "A", mobile: "", email: "a@x.my", companyName: "" }];
await listGuests("e 1");
await addGuests("e 1", g, true);
await addGuests("e 1", g, false);
await removeGuest("e 1", 7);
await sendInvites("e 1", { guestIds: [7] });
await getCheckin("e 1");
await getAttendance("e 1");
expect(mocks.apiGet.mock.calls).toEqual([["/api/events/e%201/guests"], ["/api/events/e%201/checkin"], ["/api/events/e%201/attendance"]]);
expect(mocks.apiPost.mock.calls).toEqual([
["/api/events/e%201/guests?preview=true", { guests: g }],
["/api/events/e%201/guests", { guests: g }],
["/api/events/e%201/guests/send", { guestIds: [7] }],
]);
expect(mocks.apiDelete.mock.calls).toEqual([["/api/events/e%201/guests/7"]]);
});
});
@@ -0,0 +1,55 @@
import { apiDelete, apiGet, apiPost } from "@/app/lib/clientApi";
export interface EventGuest {
id: number;
name: string;
mobileE164: string | null;
email: string | null;
companyName: string | null;
salespersonUserId: number | null;
salespersonName: string | null;
/** Absent without BO_EVENT_GUESTS. */
token?: string;
invitedAt: string;
inviteSentCount: number;
registeredAt: string | null;
attended: boolean;
eventLeadUuid: string | null;
}
export interface GuestInput {
name: string;
mobile: string;
email: string;
companyName: string;
salespersonUserId?: number;
}
export interface GuestRejection {
index: number;
code: string;
field: string | null;
message: string;
}
export interface AddGuestsResult {
added: number;
rejected: GuestRejection[];
}
export interface Attendance {
invited: number;
cap: number | null;
registered: number;
attended: number;
walkIns: number;
total: number;
capacity: number | null;
}
const base = (uuid: string) => `/api/events/${encodeURIComponent(uuid)}`;
export const listGuests = (uuid: string) => apiGet<EventGuest[]>(`${base(uuid)}/guests`);
export const addGuests = (uuid: string, guests: GuestInput[], preview: boolean) =>
apiPost<AddGuestsResult>(`${base(uuid)}/guests${preview ? "?preview=true" : ""}`, { guests });
export const removeGuest = (uuid: string, id: number) => apiDelete<unknown>(`${base(uuid)}/guests/${id}`);
export const sendInvites = (uuid: string, target: { guestIds: number[] } | { allUnsent: true }) =>
apiPost<{ sent: number; skippedNoEmail: number }>(`${base(uuid)}/guests/send`, target);
export const getCheckin = (uuid: string) => apiGet<{ token: string }>(`${base(uuid)}/checkin`);
export const getAttendance = (uuid: string) => apiGet<Attendance>(`${base(uuid)}/attendance`);
+5
View File
@@ -150,6 +150,8 @@ export interface AdminEvent {
enabled: boolean;
team?: AdminEventMember[];
companyId?: number;
capacity?: number | null;
invitationCap?: number | null;
}
export interface AdminEventMember {
@@ -168,6 +170,9 @@ export interface AdminEventPayload {
enabled?: boolean;
salespersonIds: number[];
companyId?: number;
/** Sent only by admins with BO_EVENT_GUESTS; null clears the limit. */
capacity?: number | null;
invitationCap?: number | null;
}
/** A salesperson row from the salesperson-options endpoint. */