Add shared API types and type the smaller frontend pages

Expand src/types with User, Event, EventOption, Registration, Payment,
Ticket, paginated results and dashboard stats, modelled on the Prisma
schema. apiFetch now defaults to unknown instead of any. Dashboard
loaders are wrapped in useCallback so their effects can list them as
dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 11:10:01 +02:00
co-authored by Claude Opus 5.5
parent 5024ab7241
commit dc4d2fff41
32 changed files with 375 additions and 175 deletions
@@ -5,6 +5,7 @@ import { useAuth } from "@/hooks/useAuth";
import { AuthUser, TwoFactorChallenge, isTwoFactorChallenge } from "@/lib/auth";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { errorMessage } from "@/lib/utils";
// Matches the backend's minimum gap between code sends.
const RESEND_COOLDOWN_SECONDS = 60;
@@ -42,24 +43,16 @@ export function LoginForm() {
window.location.href = hasExplicitRedirect ? redirectTo : `/dashboard/${loggedInUser.role || "user"}`;
};
const getErrorMessage = (err: any) => {
if (!err) return "Login failed";
// If it's already a normal Error
if (err.message && typeof err.message === "string") {
// Handle case where message is accidentally JSON string
try {
const parsed = JSON.parse(err.message);
return parsed.message || err.message;
} catch {
return err.message;
}
const getErrorMessage = (err: unknown) => {
const msg = errorMessage(err);
if (!msg) return "Login failed";
// Handle case where message is accidentally a JSON string
try {
const parsed = JSON.parse(msg);
return parsed?.message || msg;
} catch {
return msg;
}
// If API response object was thrown directly
if (err.message) return err.message;
return "Login failed";
};
const onSubmit = async (e: React.FormEvent) => {
@@ -5,6 +5,7 @@ import { useAuth } from "@/hooks/useAuth";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { isValidZAPhone } from "@/lib/phone";
import { errorMessage } from "@/lib/utils";
export function RegisterForm() {
const { register } = useAuth();
@@ -23,24 +24,16 @@ export function RegisterForm() {
const hasValidPhone = isValidZAPhone(phoneNumber);
const getErrorMessage = (err: any) => {
if (!err) return "Login failed";
// If it's already a normal Error
if (err.message && typeof err.message === "string") {
// Handle case where message is accidentally JSON string
try {
const parsed = JSON.parse(err.message);
return parsed.message || err.message;
} catch {
return err.message;
}
const getErrorMessage = (err: unknown) => {
const msg = errorMessage(err);
if (!msg) return "Registration failed. Please try again.";
// Handle case where message is accidentally a JSON string
try {
const parsed = JSON.parse(msg);
return parsed?.message || msg;
} catch {
return msg;
}
// If API response object was thrown directly
if (err.message) return err.message;
return "Registration failed. Please try again.";
};
const onSubmit = async (e: React.FormEvent) => {
@@ -28,11 +28,10 @@ export const QRScanner = React.forwardRef<QRScannerHandle, QRScannerProps>(
// Track the underlying HTMLVideoElement from react-webcam reliably
const [videoEl, setVideoEl] = useState<HTMLVideoElement | null>(null);
useEffect(() => {
let id: any;
let id: ReturnType<typeof setInterval> | undefined;
if (showCam) {
id = setInterval(() => {
const anyCam = webcamRef.current as any;
const v: HTMLVideoElement | null = anyCam?.video ?? null;
const v = webcamRef.current?.video ?? null;
if (v) { setVideoEl(v); clearInterval(id); }
}, 100);
} else {
@@ -43,13 +42,14 @@ export const QRScanner = React.forwardRef<QRScannerHandle, QRScannerProps>(
// Beep + cooldown state
const lastScanRef = useRef<number>(0);
const audioCtxRef = useRef<any>(null);
const audioCtxRef = useRef<AudioContext | null>(null);
const playBeep = () => {
try {
const AC = (window as any).AudioContext || (window as any).webkitAudioContext;
// Older Safari only has the prefixed constructor.
const AC = window.AudioContext || (window as Window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
if (!AC) return;
if (!audioCtxRef.current) audioCtxRef.current = new AC();
const ctx = audioCtxRef.current as AudioContext;
const ctx = audioCtxRef.current;
const oscillator = ctx.createOscillator();
const gainNode = ctx.createGain();
oscillator.type = "sine";
@@ -117,13 +117,14 @@ export const QRScanner = React.forwardRef<QRScannerHandle, QRScannerProps>(
async function startScan() {
const host = typeof window !== "undefined" ? window.location.hostname : "";
const isLocal = host === "localhost" || host === "127.0.0.1";
if (!(navigator as any)?.mediaDevices?.getUserMedia) {
// mediaDevices is missing on insecure origins and some older browsers.
if (typeof navigator === "undefined" || !navigator.mediaDevices?.getUserMedia) {
setLocalError("Camera API is not available in this browser.");
return;
}
setLocalError(null);
try {
const warmup = await navigator.mediaDevices.getUserMedia({ video: constraints, audio: false } as any);
const warmup = await navigator.mediaDevices.getUserMedia({ video: constraints, audio: false });
try { warmup.getTracks().forEach(t => t.stop()); } catch {}
setShowCam(true);
if (!active) toggle();
@@ -173,7 +174,7 @@ export const QRScanner = React.forwardRef<QRScannerHandle, QRScannerProps>(
className="absolute inset-0 w-full h-full object-cover"
onUserMedia={() => setLocalError(null)}
onUserMediaError={(e) => {
const name = (e as any)?.name || (e as any)?.message;
const name = typeof e === "string" ? e : e.name || e.message;
const protocol = typeof window !== "undefined" ? window.location.protocol : "";
const host = typeof window !== "undefined" ? window.location.hostname : "";
const isLocal = host === "localhost" || host === "127.0.0.1";
@@ -57,7 +57,7 @@ export function useOfflineScanning(token: string | null) {
queue.forEach(q => byLock.set(q.lockId, [...(byLock.get(q.lockId) || []), q]));
let accepted = 0, conflicts = 0;
for (const [lockId, scans] of byLock) {
const res = await apiFetch<{ accepted: number; duplicates: number; conflicts: any[] }>(`/api/scan-locks/${lockId}/sync`, {
const res = await apiFetch<{ accepted: number; duplicates: number; conflicts: unknown[] }>(`/api/scan-locks/${lockId}/sync`, {
method: "POST", authToken: token, body: { deviceId: deviceId(), scans },
});
accepted += res.accepted;
@@ -12,7 +12,7 @@ const CONSENT_LABEL: Record<string, { text: string; cls: string }> = {
declined: { text: "consent declined", cls: "text-red-700" },
};
type Attendee = {
export type Attendee = {
id: string; eventOptionId: string; variantId: string | null; name: string; email: string | null; phone: string | null;
dateOfBirth?: string | null; gender?: string | null; parentName?: string | null; parentEmail?: string | null; parentPhone?: string | null;
ticket?: { id: string; isUsed: boolean } | null;
@@ -23,20 +23,41 @@ type Row = {
dateOfBirth: string; gender: string; parentName: string; parentEmail: string; parentPhone: string;
};
// The parts of a registration (with its attendees, options and event) this panel reads.
export type AttendeesRegistration = {
id: string;
ticketDelivery?: "payer" | "each";
attendees?: Attendee[];
event?: {
requiresParentalConsent?: boolean;
collectGender?: boolean;
allowNamedAttendees?: boolean;
startDate?: string;
} | null;
registrationOptions?: {
eventOptionId: string;
variantId?: string | null;
quantity: number;
eventOption?: { name?: string; isMainTicket?: boolean } | null;
variant?: { name?: string } | null;
}[];
formResponses?: { attendeeId?: string | null }[];
};
/**
* Named attendees on a registration (group tickets): shows who each main-ticket place
* is for, and lets the payer (or staff) name places, change details, choose where the
* tickets go, and send an attendee the link to their own form.
*/
export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved, onMessage }: {
registration: any;
registration: AttendeesRegistration;
token: string;
canEdit: boolean;
hasForm: boolean;
onSaved: () => void;
onMessage: (msg: string) => void;
}) {
const attendees: Attendee[] = registration.attendees || [];
const attendees = useMemo<Attendee[]>(() => registration.attendees || [], [registration.attendees]);
const youth = !!registration.event?.requiresParentalConsent;
const collectGender = !!registration.event?.collectGender;
const eventStart: string | undefined = registration.event?.startDate;
@@ -117,7 +138,7 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
}
};
const answered = new Set((registration.formResponses || []).map((r: any) => r.attendeeId).filter(Boolean));
const answered = new Set((registration.formResponses || []).map((r) => r.attendeeId).filter(Boolean));
const resendConsent = async (requestId: string) => {
try {
@@ -6,8 +6,16 @@ import { apiFetch } from "@/lib/api";
import { isMinorOn } from "@/components/shared/AttendeeNamesEditor";
import { errorMessage } from "@/lib/utils";
type TransferTicket = { id: string; isUsed?: boolean; quantity?: number; usages?: unknown[] };
type TransferEvent = {
startDate?: string;
allowTicketTransfer?: boolean;
requiresParentalConsent?: boolean;
collectGender?: boolean;
};
/** Whether to offer "Transfer" on a ticket (the server checks the rules again). */
export function canOfferTransfer(ticket: any, event: any, isSupervisor = false): boolean {
export function canOfferTransfer(ticket: TransferTicket | null | undefined, event: TransferEvent | null | undefined, isSupervisor = false): boolean {
if (!ticket || !event) return false;
if ((ticket.usages || []).length > 0 || ticket.isUsed) return false;
if (event.startDate && new Date(event.startDate) <= new Date()) return false;
@@ -20,8 +28,8 @@ export function canOfferTransfer(ticket: any, event: any, isSupervisor = false):
* to the details typed, and the ticket only moves (with a new QR code) once they accept.
*/
export function TransferTicketModal({ ticket, event, token, onClose, onDone }: {
ticket: any;
event: any;
ticket: TransferTicket;
event: TransferEvent | null | undefined;
token: string;
onClose: () => void;
onDone: (message: string) => void;