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
@@ -17,7 +17,7 @@ export default function ForgotPasswordPage() {
try {
setLoading(true);
setStatus(null);
const res: any = await apiFetch("/api/users/forgot", { method: "POST", body: { email } });
const res = await apiFetch<{ message?: string }>("/api/users/forgot", { method: "POST", body: { email } });
setStatus(res?.message || "If that email exists, a password reset link has been sent.");
} catch (err) {
try {
@@ -25,7 +25,7 @@ function ActivateAccountContent() {
try {
setLoading(true);
setStatus(null);
const data = await apiFetch<any>("/api/users/activate", { method: "POST", body: { token, password } });
const data = await apiFetch<{ token?: string }>("/api/users/activate", { method: "POST", body: { token, password } });
// Auto-login: save the session token (under the key AuthContext reads) and load the
// dashboard fresh so the new session is picked up.
if (data?.token) saveToken(data.token);
@@ -7,12 +7,13 @@ import { apiFetch } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Wallet } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import type { Event } from "@/types";
export default function CashupLandingPage() {
const { token } = useAuth();
const router = useRouter();
const [events, setEvents] = useState<any[]>([]);
const [events, setEvents] = useState<Event[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useDismissingState<string | null>(null);
const [search, setSearch] = useState("");
@@ -26,7 +27,7 @@ export default function CashupLandingPage() {
setLoading(true);
setError(null);
try {
const evs = await apiFetch<any[]>("/api/events/all?includePast=true&includeInactive=true", { authToken: token });
const evs = await apiFetch<Event[]>("/api/events/all?includePast=true&includeInactive=true", { authToken: token });
setEvents(Array.isArray(evs) ? evs : []);
} catch (e) {
setError(errorMessage(e) || "Failed to load events");
@@ -34,7 +35,7 @@ export default function CashupLandingPage() {
setLoading(false);
}
})();
}, [token]);
}, [token, setError]);
const filtered = useMemo(() => {
const now = new Date();
@@ -1,6 +1,6 @@
"use client";
import React, { useEffect, useMemo, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
@@ -14,6 +14,7 @@ import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
import { AreaTrendChart } from "@/components/charts/AreaTrendChart";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import type { DashboardStats, PaymentStats } from "@/types";
const formatRand = (n: number) => `R ${(n || 0).toFixed(2)}`;
const formatRandAxis = (n: number) => `R${new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n)}`;
@@ -67,19 +68,19 @@ export default function AdminDashboardPage() {
// /api/stats/admin covers today/week/month payment totals (unchanged from before);
// /api/stats/overview is the month-over-month KPI/trend/top-events endpoint. Both are
// computed server-side — no full payments/events list ever ships to the client.
const [paymentStats, setPaymentStats] = useStableState<any | null>(null);
const [paymentStats, setPaymentStats] = useStableState<PaymentStats | null>(null);
const [overview, setOverview] = useStableState<Overview | null>(null);
const [loadingStats, setLoadingStats] = useState(false);
const hasLoadedOnce = useRef(false);
const [paymentsTab, setPaymentsTab] = useState<"today" | "week" | "month">("today");
const loadStats = async () => {
const loadStats = useCallback(async () => {
if (!token) return;
const isFirstLoad = !hasLoadedOnce.current;
try {
if (isFirstLoad) setLoadingStats(true);
const [dash, overviewData] = await Promise.all([
apiFetch<any>("/api/stats/admin", { authToken: token }),
apiFetch<DashboardStats>("/api/stats/admin", { authToken: token }),
apiFetch<Overview>("/api/stats/overview", { authToken: token }),
]);
setPaymentStats(dash.paymentStats);
@@ -90,12 +91,12 @@ export default function AdminDashboardPage() {
hasLoadedOnce.current = true;
if (isFirstLoad) setLoadingStats(false);
}
};
}, [token, setPaymentStats, setOverview]);
useEffect(() => {
if (!token) return;
loadStats();
}, [token]);
}, [token, loadStats]);
// Poll every 15s while the tab is visible; pause in the background and refetch
// immediately on return instead of leaving stale numbers up.
@@ -105,7 +106,7 @@ export default function AdminDashboardPage() {
}, 15000, !!token);
const paymentsTabValue = paymentStats
? paymentsTab === "today" ? paymentStats.totalToday : paymentsTab === "week" ? paymentStats.totalWeek : paymentStats.totalMonth
? (paymentsTab === "today" ? paymentStats.totalToday : paymentsTab === "week" ? paymentStats.totalWeek : paymentStats.totalMonth) ?? 0
: 0;
return (
@@ -179,9 +179,9 @@ function SiteSettingsPageInner() {
setConsentRetentionDays(s.consent_medical_retention_days || "30");
setNotifyOnImpersonation(s.notify_user_on_impersonation === "true");
})
.catch((e: any) => setResult({ ok: false, message: e?.message || "Failed to load settings" }))
.catch((e: unknown) => setResult({ ok: false, message: errorMessage(e) || "Failed to load settings" }))
.finally(() => setLoadingInitial(false));
}, [token]);
}, [token, setResult]);
// Clear result when switching tabs
const switchTab = (id: TabId) => { setActiveTab(id); setResult(null); };
@@ -921,7 +921,7 @@ function WhatsAppTab({ active }: { active: boolean }) {
setBusy(action);
setActionMsg(null);
try {
const res = await apiFetch<any>(`/api/whatsapp/${action}`, { method: "POST", authToken: token, body });
const res = await apiFetch<{ message?: string }>(`/api/whatsapp/${action}`, { method: "POST", authToken: token, body });
setActionMsg({ type: "ok", text: res?.message || `${action} successful.` });
await fetchStatus();
await fetchConfig();
@@ -978,7 +978,7 @@ function WhatsAppTab({ active }: { active: boolean }) {
setSavingInstance(true);
setActionMsg(null);
try {
const res = await apiFetch<any>("/api/whatsapp/create-instance", { method: "POST", authToken: token! });
const res = await apiFetch<{ message?: string }>("/api/whatsapp/create-instance", { method: "POST", authToken: token! });
setActionMsg({ type: "ok", text: res?.message || "Instance created." });
await fetchConfig();
} catch (e) {
@@ -1,6 +1,6 @@
"use client";
import React, { useEffect, useMemo, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
@@ -9,6 +9,7 @@ import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import { QrCode, Ticket, Activity, UserCheck, Clock, Users } from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
import type { DashboardStats, RecentScan, ScanStats } from "@/types";
const QUICK_ACTIONS = [
{ href: "/dashboard/staff/ticket-scanning", label: "Scan tickets", description: "Use your device camera to validate tickets", icon: QrCode },
@@ -35,17 +36,17 @@ export default function StaffDashboardPage() {
// (/api/stats/staff) instead of two separate calls. useStableState skips re-renders when
// a poll returns identical data, and hasLoadedOnce below means "Refreshing…" only shows
// on the very first load — together these stop the stats panel from flickering.
const [stats, setStats] = useStableState<any | null>(null);
const [recentScans, setRecentScans] = useStableState<any[]>([]);
const [stats, setStats] = useStableState<ScanStats | null>(null);
const [recentScans, setRecentScans] = useStableState<RecentScan[]>([]);
const [loadingStats, setLoadingStats] = useState(false);
const hasLoadedOnce = useRef(false);
const loadStats = async () => {
const loadStats = useCallback(async () => {
if (!token) return;
const isFirstLoad = !hasLoadedOnce.current;
try {
if (isFirstLoad) setLoadingStats(true);
const data = await apiFetch<any>("/api/stats/staff", { authToken: token });
const data = await apiFetch<DashboardStats>("/api/stats/staff", { authToken: token });
setStats(data.scanStats);
setRecentScans(Array.isArray(data.recentScans) ? data.recentScans : []);
} catch {
@@ -54,12 +55,12 @@ export default function StaffDashboardPage() {
hasLoadedOnce.current = true;
if (isFirstLoad) setLoadingStats(false);
}
};
}, [token, setStats, setRecentScans]);
useEffect(() => {
if (!token) return;
loadStats();
}, [token]);
}, [token, loadStats]);
// Poll every 10s while the tab is visible; pause in the background and refetch
// immediately on return instead of leaving stale numbers up.
@@ -104,7 +105,7 @@ export default function StaffDashboardPage() {
{loadingStats && <span className="text-xs text-gray-500">Refreshing…</span>}
</div>
<ul className="text-sm space-y-2 max-h-96 overflow-auto pr-2">
{recentScans.map((u: any) => (
{recentScans.map((u) => (
<li key={u.id} className="border rounded p-2">
<div className="flex justify-between">
<div className="font-medium">{u.ticket?.event?.title || u.ticket?.eventId || 'Event'}</div>
@@ -122,9 +123,9 @@ export default function StaffDashboardPage() {
<div>
<div className="border rounded-xl p-4 bg-white shadow-sm">
<h2 className="text-lg font-semibold mb-3">Today by staff</h2>
{stats?.byStaff?.length > 0 ? (
{stats && stats.byStaff?.length > 0 ? (
<ul className="text-sm text-gray-700 space-y-1">
{stats.byStaff.map((s: any) => (
{stats.byStaff.map((s) => (
<li key={s.scannedById} className="flex justify-between">
<span>{s.name || 'Staff'}</span>
<span className="font-medium">{s.count}</span>
@@ -8,6 +8,7 @@ import { formatDate } from "@/lib/date";
import { useDismissingState } from "@/hooks/useDismissingState";
import { WifiOff, Unlock, CheckCircle2 } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import type { Event } from "@/types";
type Lock = { id: string; sectionName: string | null; deviceName: string | null; user: { name: string }; lockedAt: string; snapshotAt: string | null; lastSyncAt: string | null };
type Report = {
@@ -29,7 +30,7 @@ export default function OfflineScansPage() {
if (!user) router.replace("/login");
}, [user, loading, router]);
const [events, setEvents] = useState<any[]>([]);
const [events, setEvents] = useState<Event[]>([]);
const [eventId, setEventId] = useState("");
const [locks, setLocks] = useState<Lock[]>([]);
const [reports, setReports] = useState<Report[]>([]);
@@ -39,7 +40,7 @@ export default function OfflineScansPage() {
useEffect(() => {
if (!token || !canView) return;
apiFetch<any[]>("/api/events/all?includePast=true", { authToken: token })
apiFetch<Event[]>("/api/events/all?includePast=true", { authToken: token })
.then(evs => {
const recent = (evs || []).filter(e => new Date(e.endDate).getTime() > Date.now() - 14 * 864e5);
setEvents(recent);
@@ -1,6 +1,6 @@
"use client";
import React, { useEffect, useMemo, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
@@ -14,6 +14,7 @@ import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
import { AreaTrendChart } from "@/components/charts/AreaTrendChart";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import type { DashboardStats, PaymentStats, RecentScan, ScanStats } from "@/types";
const formatRand = (n: number) => `R ${(n || 0).toFixed(2)}`;
const formatRandAxis = (n: number) => `R${new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n)}`;
@@ -66,20 +67,20 @@ export default function SupervisorDashboardPage() {
// /api/stats/supervisor covers scan activity + today's payments (unchanged from before);
// /api/stats/overview is the month-over-month KPI/trend/top-events endpoint, shared
// with the admin dashboard since supervisors already have full revenue/donation visibility.
const [scanStats, setScanStats] = useStableState<any | null>(null);
const [paymentStats, setPaymentStats] = useStableState<any | null>(null);
const [recentScans, setRecentScans] = useStableState<any[]>([]);
const [scanStats, setScanStats] = useStableState<ScanStats | null>(null);
const [paymentStats, setPaymentStats] = useStableState<PaymentStats | null>(null);
const [recentScans, setRecentScans] = useStableState<RecentScan[]>([]);
const [overview, setOverview] = useStableState<Overview | null>(null);
const [loadingStats, setLoadingStats] = useState(false);
const hasLoadedOnce = useRef(false);
const loadStats = async () => {
const loadStats = useCallback(async () => {
if (!token) return;
const isFirstLoad = !hasLoadedOnce.current;
try {
if (isFirstLoad) setLoadingStats(true);
const [data, overviewData] = await Promise.all([
apiFetch<any>("/api/stats/supervisor", { authToken: token }),
apiFetch<DashboardStats>("/api/stats/supervisor", { authToken: token }),
apiFetch<Overview>("/api/stats/overview", { authToken: token }),
]);
setScanStats(data.scanStats);
@@ -92,12 +93,12 @@ export default function SupervisorDashboardPage() {
hasLoadedOnce.current = true;
if (isFirstLoad) setLoadingStats(false);
}
};
}, [token, setScanStats, setPaymentStats, setRecentScans, setOverview]);
useEffect(() => {
if (!token) return;
loadStats();
}, [token]);
}, [token, loadStats]);
// Poll every 15s while the tab is visible; pause in the background and refetch
// immediately on return instead of leaving stale numbers up.
@@ -184,7 +185,7 @@ export default function SupervisorDashboardPage() {
{loadingStats && <span className="text-xs text-gray-500">Refreshing…</span>}
</div>
<ul className="text-sm space-y-2 max-h-96 overflow-auto pr-2">
{recentScans.map((u: any) => (
{recentScans.map((u) => (
<li key={u.id} className="border rounded p-2">
<div className="flex justify-between">
<div className="font-medium">{u.ticket?.event?.title || u.ticket?.eventId || 'Event'}</div>
@@ -236,11 +237,11 @@ export default function SupervisorDashboardPage() {
<div className="text-sm text-gray-500">No payment data yet.</div>
)}
{scanStats?.byStaff?.length > 0 && (
{scanStats && scanStats.byStaff?.length > 0 && (
<div className="mt-4">
<div className="text-sm font-medium mb-1">Today by staff</div>
<ul className="text-sm text-gray-700 space-y-1">
{scanStats.byStaff.map((s: any) => (
{scanStats.byStaff.map((s) => (
<li key={s.scannedById} className="flex justify-between">
<span>{s.name || 'Staff'}</span>
<span className="font-medium">{s.count}</span>
@@ -9,6 +9,7 @@ import { useDismissingState } from "@/hooks/useDismissingState";
import { ListChecks, ArrowUp, ArrowDown } from "lucide-react";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { errorMessage } from "@/lib/utils";
import type { Event } from "@/types";
type Entry = {
id: string;
@@ -44,7 +45,7 @@ export default function WaitlistPage() {
if (!user) router.replace("/login");
}, [user, loading, router]);
const [events, setEvents] = useState<any[]>([]);
const [events, setEvents] = useState<Event[]>([]);
const [eventId, setEventId] = useState(search.get("eventId") || "");
const [entries, setEntries] = useState<Entry[]>([]);
const [busy, setBusy] = useState(false);
@@ -53,7 +54,7 @@ export default function WaitlistPage() {
useEffect(() => {
if (!token || !canView) return;
apiFetch<any[]>("/api/events/all", { authToken: token })
apiFetch<Event[]>("/api/events/all", { authToken: token })
.then(evs => {
const withList = (evs || []).filter(e => e.waitlistEnabled);
setEvents(withList);
@@ -76,7 +77,7 @@ export default function WaitlistPage() {
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
const act = async (path: string, body?: any) => {
const act = async (path: string, body?: { direction: "up" | "down" }) => {
setBusy(true);
try {
const res = await apiFetch<{ message?: string }>(path, { method: "POST", authToken: token!, body });
@@ -5,10 +5,11 @@ import { apiFetch } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { HandHeart } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import type { Event } from "@/types";
export default function DonatePage() {
const { token } = useAuth();
const [events, setEvents] = useState<any[]>([]);
const [events, setEvents] = useState<Event[]>([]);
const [eventId, setEventId] = useState<string>("");
const [amount, setAmount] = useState<string>("");
const [loading, setLoading] = useState(false);
@@ -18,14 +19,14 @@ export default function DonatePage() {
useEffect(() => {
(async () => {
try {
const evs = await apiFetch<any[]>("/api/events");
const evs = await apiFetch<Event[]>("/api/events");
setEvents(evs);
if (evs.length > 0) setEventId(evs[0].id);
} catch (e) {
setError(errorMessage(e) || "Failed to load events");
}
})();
}, []);
}, [setError]);
const submit = async () => {
if (!token) { setError("Please login"); return; }
@@ -8,6 +8,7 @@ import { formatDateTime } from "@/lib/date";
import { formatPaymentMethod } from "@/lib/paymentMethod";
import { Receipt } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import type { Paginated } from "@/types";
interface PaymentItem {
id: string;
@@ -50,7 +51,7 @@ export default function UserPaymentsPage() {
setInfo(null);
setSendingReceipt(true);
try {
const res: any = await apiFetch<any>(`/api/payments/${encodeURIComponent(paymentId)}/send-receipt`, {
const res = await apiFetch<{ message?: string }>(`/api/payments/${encodeURIComponent(paymentId)}/send-receipt`, {
method: "POST",
body: { channel },
authToken: token,
@@ -83,7 +84,7 @@ export default function UserPaymentsPage() {
setError(null);
setFetching(true);
try {
const res = await apiFetch<any>(buildQuery(p), { authToken: token });
const res = await apiFetch<Paginated<PaymentItem>>(buildQuery(p), { authToken: token });
setPayments(Array.isArray(res?.data) ? res.data : []);
setTotal(res?.total ?? 0);
setTotalPages(res?.pages ?? 1);
@@ -93,9 +94,10 @@ export default function UserPaymentsPage() {
} finally {
setFetching(false);
}
}, [token, buildQuery]);
}, [token, buildQuery, setError]);
useEffect(() => { if (token) loadPayments(1); }, [token, startDate, endDate, method, kind]);
// loadPayments changes whenever a filter does (via buildQuery), so this refetches page 1 on filter changes.
useEffect(() => { if (token) loadPayments(1); }, [token, loadPayments]);
const goToPage = (p: number) => loadPayments(p);
@@ -151,7 +153,7 @@ export default function UserPaymentsPage() {
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">Type</label>
<select className="border rounded px-2 py-1.5 text-sm" value={kind} onChange={e => setKind(e.target.value as any)}>
<select className="border rounded px-2 py-1.5 text-sm" value={kind} onChange={e => setKind(e.target.value as "" | "payment" | "refund")}>
<option value="">Payments &amp; refunds</option>
<option value="payment">Payments only</option>
<option value="refund">Refunds only</option>
@@ -4,7 +4,9 @@ import { Share2, QrCode, CalendarPlus } from "lucide-react";
import QRCode from "qrcode";
import { API_BASE } from "@/lib/api";
export default function ClientActions({ event }: { event: any }) {
type Props = { event: { id: string; title: string; description?: string | null } };
export default function ClientActions({ event }: Props) {
return (
<div className="flex gap-2">
<button
@@ -12,7 +14,7 @@ export default function ClientActions({ event }: { event: any }) {
try {
await navigator.share({
title: event.title,
text: event.description,
text: event.description ?? undefined,
url: window.location.href,
});
} catch (err) {
@@ -12,7 +12,7 @@ import { Calendar, Ticket, Paperclip, Sparkles } from "lucide-react";
export const revalidate = 60;
type OptionVariant = { id: string; name: string; price: number | null; stockLimit?: number; availableCount?: number };
type OptionVariant = { id: string; name: string; price: number | null; stockLimit?: number; availableCount?: number; order?: number };
type EventOption = {
id: string;
name: string;
@@ -283,7 +283,7 @@ function TicketList({ event }: { event: Event }) {
</div>
</div>
<ul className="divide-y">
{opt.variants!.slice().sort((a, b) => (a as any).order - (b as any).order).map((v) => {
{opt.variants!.slice().sort((a, b) => (a.order ?? 0) - (b.order ?? 0)).map((v) => {
const vPrice = v.price !== null && v.price !== undefined ? v.price : opt.price;
const vSoldOut = (v.stockLimit ?? 0) > 0 && v.availableCount !== undefined && v.availableCount <= 0;
const vNearlyOut = !vSoldOut && (v.stockLimit ?? 0) > 0 && v.availableCount !== undefined && v.availableCount <= lowStockThreshold(v.stockLimit ?? 0);
@@ -19,7 +19,7 @@ function lowStockThreshold(stockLimit: number): number {
return Math.round(stockLimit * pct);
}
type EarlyBirdTier = { id: string; deadline: string; price: number; stockLimit?: number; order?: number };
type EarlyBirdTier = { id: string; deadline: string; price: number; stockLimit?: number; availableCount?: number; order?: number };
type OptionVariant = { id: string; name: string; price: number | null; stockLimit?: number; availableCount?: number; order?: number };
type EventOption = {
id: string;
@@ -32,7 +32,7 @@ type EventOption = {
variants?: OptionVariant[];
};
type Event = {
export type RegisterEvent = {
id: string;
title: string;
description?: string;
@@ -42,7 +42,8 @@ type Event = {
price: number;
picture?: string;
eventOptions?: EventOption[];
form?: { isRequired: boolean; fields?: any[] } | null;
form?: { isRequired: boolean; fields?: unknown[] } | null;
requiresRegistration?: boolean;
requiresAuth?: boolean;
allowNamedAttendees?: boolean;
requiresParentalConsent?: boolean;
@@ -62,7 +63,7 @@ function effectiveUnitForOption(opt: EventOption): number {
const now = new Date();
const applicable = tiers
.map((t) => ({ ...t, _d: new Date(t.deadline) }))
.filter((t) => now < t._d && (t.stockLimit === undefined || t.stockLimit === 0 || (t as any).availableCount === undefined || (t as any).availableCount > 0))
.filter((t) => now < t._d && (t.stockLimit === undefined || t.stockLimit === 0 || t.availableCount === undefined || t.availableCount > 0))
.sort((a, b) => a.price - b.price || a._d.getTime() - b._d.getTime());
return applicable.length > 0 ? applicable[0].price : base;
}
@@ -253,7 +254,7 @@ function OptionCard({
);
}
export default function RegisterForm({ event: baseEvent }: { event: Event }) {
export default function RegisterForm({ event: baseEvent }: { event: RegisterEvent }) {
const { token, user } = useAuth();
const eventId = baseEvent.id;
@@ -272,9 +273,9 @@ export default function RegisterForm({ event: baseEvent }: { event: Event }) {
setOffer(res);
setQuantities(q => ({ ...q, [res.variantId ? `${res.eventOptionId}:${res.variantId}` : res.eventOptionId]: res.quantity }));
})
.catch((e: any) => setOfferError(e?.message || "This waitlist link is not valid."));
.catch((e: unknown) => setOfferError(errorMessage(e) || "This waitlist link is not valid."));
}, []);
const event = useMemo<Event>(() => {
const event = useMemo<RegisterEvent>(() => {
if (!offer) return baseEvent;
return {
...baseEvent,
@@ -560,11 +561,11 @@ export default function RegisterForm({ event: baseEvent }: { event: Event }) {
const now = new Date();
const upcomingTiers = (event.eventOptions || []).flatMap(opt =>
(opt.earlyBirdTiers || [])
.map((t: any) => ({ ...t, deadline: new Date(t.deadline) }))
.filter((t: any) => t.deadline > now)
).sort((a: any, b: any) => a.deadline.getTime() - b.deadline.getTime());
.map((t) => ({ ...t, deadline: new Date(t.deadline) }))
.filter((t) => t.deadline > now)
).sort((a, b) => a.deadline.getTime() - b.deadline.getTime());
if (upcomingTiers.length === 0) return null;
const soonest = upcomingTiers[0].deadline as Date;
const soonest = upcomingTiers[0].deadline;
const dateStr = soonest.toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });
return (
<div className="mt-4 p-3 rounded-lg bg-amber-50 border border-amber-200 text-sm text-amber-800">
@@ -2,18 +2,18 @@ import { notFound, redirect } from "next/navigation";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { apiFetch, ApiError } from "@/lib/api";
import RegisterForm from "./RegisterForm";
import RegisterForm, { type RegisterEvent } from "./RegisterForm";
import { FunnelTracker } from "@/components/events/FunnelTracker";
export const revalidate = 60;
export default async function RegisterPage({ params }: { params: Promise<{ eventId: string }> }) {
const { eventId } = await params;
let event: any;
let event: RegisterEvent;
try {
// Fetched server-side (same pattern as /events/[id]) so the form's content is part of
// the initial HTML instead of showing a loading skeleton after a client-side fetch.
event = await apiFetch<any>(`/api/events/${eventId}`, { nextOptions: { next: { revalidate } } });
event = await apiFetch<RegisterEvent>(`/api/events/${eventId}`, { nextOptions: { next: { revalidate } } });
} catch (e) {
if (e instanceof ApiError && e.status === 404) notFound();
throw e;
@@ -6,6 +6,7 @@ import { useSearchParams, useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { CheckCircle2 } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import type { Registration } from "@/types";
type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown };
@@ -20,7 +21,7 @@ function RegistrationSuccessContent() {
return isNaN(n) ? 0 : n;
}, [fallbackTotalParam]);
const [reg, setReg] = React.useState<any | null>(null);
const [reg, setReg] = React.useState<Registration | null>(null);
const [form, setForm] = React.useState<{ isRequired: boolean; fields: FormField[] } | null>(null);
const [error, setError] = React.useState<string | null>(null);
const [payLoading, setPayLoading] = React.useState(false);
@@ -31,10 +32,10 @@ function RegistrationSuccessContent() {
if (!registrationId) return;
try {
// Try to fetch registration and event form
const r = token ? await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token }) : null;
const r = token ? await (await import('@/lib/api')).apiFetch<Registration>(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token }) : null;
if (r) {
setReg(r);
const ev = await (await import('@/lib/api')).apiFetch(`/api/events/${encodeURIComponent(r.eventId)}`);
const ev = await (await import('@/lib/api')).apiFetch<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(`/api/events/${encodeURIComponent(r.eventId)}`);
if (ev?.form) setForm(ev.form);
}
} catch (e) {
@@ -49,7 +50,7 @@ function RegistrationSuccessContent() {
// multiple early-bird prices) — fall back to the old client-side estimate otherwise.
if (reg.totalDueComputed !== null && reg.totalDueComputed !== undefined) return reg.totalDueComputed;
try {
return (reg.registrationOptions || []).reduce((s: number, ro: any) => {
return (reg.registrationOptions || []).reduce((s, ro) => {
const unit = (ro.priceSnapshot !== null && ro.priceSnapshot !== undefined)
? Number(ro.priceSnapshot)
: (ro.variant?.price ?? ro.eventOption?.price ?? 0);
@@ -86,7 +87,7 @@ function RegistrationSuccessContent() {
// reload the registration so the displayed totalDue reflects it, instead of redirecting.
setError(`${res.message || 'Pricing has changed.'} New total: R ${(res.newTotal ?? 0).toFixed(2)}. Please try again.`);
try {
const r = await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token });
const r = await (await import('@/lib/api')).apiFetch<Registration>(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token });
if (r) setReg(r);
} catch {}
return;
@@ -3,10 +3,11 @@ import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormField
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { apiFetch } from "@/lib/api";
import { TwoFactorChallenge, isTwoFactorChallenge } from "@/lib/auth";
import { AuthResponse, TwoFactorChallenge, isTwoFactorChallenge } from "@/lib/auth";
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { errorMessage } from "@/lib/utils";
import type { Registration } from "@/types";
// ─── Types ────────────────────────────────────────────────────────────────────
type EarlyBirdTier = { deadline: string; price: number; order?: number; variantId?: string | null };
@@ -26,7 +27,7 @@ type FormField = {
isRequired: boolean;
order: number;
helpText?: string | null;
options?: any;
options?: unknown;
};
type EventForm = {
id: string;
@@ -294,11 +295,11 @@ export default function SelfServicePage() {
// Second pass for accounts with two-factor on: exchange the code that was
// sent after the password step. The kiosk never asks to be remembered.
const data = setupChallenge
? await apiFetch("/api/users/login/2fa", {
? await apiFetch<AuthResponse>("/api/users/login/2fa", {
method: "POST",
body: { challengeId: setupChallenge.challengeId, code: setupCode, rememberDevice: false },
})
: await apiFetch("/api/users/login", {
: await apiFetch<AuthResponse | TwoFactorChallenge>("/api/users/login", {
method: "POST",
body: { email: setupEmail, password: setupPassword },
});
@@ -405,7 +406,15 @@ export default function SelfServicePage() {
async function handleRegister() {
setFormLoading(true);
try {
const payload: any = {
const user: { name: string; email?: string; phoneNumber?: string; password?: string } = {
name: visitorName.trim(),
...(visitorEmail.trim() ? { email: visitorEmail.trim() } : {}),
...(visitorPhone.trim() ? { phoneNumber: visitorPhone.trim() } : {}),
};
if (createAccount && visitorPassword) {
user.password = visitorPassword;
}
const payload: Record<string, unknown> = {
eventId: selectedEventId,
options: Object.entries(quantities)
.filter(([, qty]) => qty > 0)
@@ -413,11 +422,7 @@ export default function SelfServicePage() {
const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, ...(variantId ? { variantId } : {}) };
}),
user: {
name: visitorName.trim(),
...(visitorEmail.trim() ? { email: visitorEmail.trim() } : {}),
...(visitorPhone.trim() ? { phoneNumber: visitorPhone.trim() } : {}),
},
user,
// If the visitor declined to create an account, don't push an unsolicited
// activation email/WhatsApp at them afterward.
skipActivationNotice: !createAccount,
@@ -431,11 +436,7 @@ export default function SelfServicePage() {
payload.attendees = kioskNames;
payload.ticketDelivery = delivery;
}
if (createAccount && visitorPassword) {
payload.user.password = visitorPassword;
}
const result: any = await apiFetch("/api/registrations/manual", {
const result = await apiFetch<Registration>("/api/registrations/manual", {
method: "POST",
body: payload,
authToken: supervisorToken,
@@ -38,7 +38,7 @@ export default function SetBannerPage() {
// Load current banner
useEffect(() => {
apiFetch<any>("/api/banner")
apiFetch<{ message?: string; type?: BannerType; liveFrom?: string | null; liveTill?: string | null } | null>("/api/banner")
.then(b => {
if (!b) return;
setMessage(b.message || "");