Type supervisor forms, manual registration and events pages

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 b560d0d340
commit 0a8788afff
4 changed files with 204 additions and 163 deletions
@@ -10,33 +10,33 @@ import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeFi
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { UserPlus, CreditCard } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import type { EarlyBirdTier, Event, EventOption, OptionVariant, Registration, RegistrationOption, User } from "@/types";
// ─── Pricing helpers ─────────────────────────────────────────────────────────
function effectiveOptionUnit(opt: any): number {
const base = opt.price || 0;
const tiers = (Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : []).filter((t: any) => !t.variantId);
if (tiers.length === 0) return base;
// The earliest-deadline tier that's still open, or undefined when none are.
function currentTier(tiers: EarlyBirdTier[]): EarlyBirdTier | undefined {
const now = new Date();
const applicable = tiers
.map((t: any) => ({ ...t, deadline: new Date(t.deadline) }))
.filter((t: any) => now < t.deadline)
.sort((a: any, b: any) => a.deadline - b.deadline || (a.order || 0) - (b.order || 0) || a.price - b.price);
return applicable.length > 0 ? applicable[0].price : base;
return tiers
.map((t) => ({ ...t, deadlineAt: new Date(t.deadline) }))
.filter((t) => now < t.deadlineAt)
.sort((a, b) => a.deadlineAt.getTime() - b.deadlineAt.getTime() || (a.order || 0) - (b.order || 0) || a.price - b.price)[0];
}
function effectiveVariantUnit(opt: any, variant: any): number {
function effectiveOptionUnit(opt: EventOption): number {
const base = opt.price || 0;
const tiers = (Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : []).filter((t) => !t.variantId);
if (tiers.length === 0) return base;
return currentTier(tiers)?.price ?? base;
}
function effectiveVariantUnit(opt: EventOption, variant: OptionVariant): number {
const base = variant.price !== null && variant.price !== undefined ? variant.price : opt.price || 0;
const allTiers = Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : [];
const variantTiers = allTiers.filter((t: any) => t.variantId === variant.id);
const tiers = variantTiers.length > 0 ? variantTiers : allTiers.filter((t: any) => !t.variantId);
const variantTiers = allTiers.filter((t) => t.variantId === variant.id);
const tiers = variantTiers.length > 0 ? variantTiers : allTiers.filter((t) => !t.variantId);
if (tiers.length === 0) return base;
const now = new Date();
const applicable = tiers
.map((t: any) => ({ ...t, deadline: new Date(t.deadline) }))
.filter((t: any) => now < t.deadline)
.sort((a: any, b: any) => a.deadline - b.deadline || (a.order || 0) - (b.order || 0) || a.price - b.price);
return applicable.length > 0 ? applicable[0].price : base;
return currentTier(tiers)?.price ?? base;
}
function fmtPrice(n: number) {
@@ -46,11 +46,12 @@ function fmtPrice(n: number) {
// Effective unit price for an existing registration option (as returned by /api/registrations).
// Prefers priceSnapshot (authoritative price captured at registration time) and only falls
// back to a live early-bird calculation for legacy rows without a snapshot.
function optionUnitPrice(opt: any): number {
function optionUnitPrice(opt: RegistrationOption): number {
if (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) {
return Number(opt.priceSnapshot);
}
const eo = opt.eventOption;
if (!eo) return 0;
if (opt.variant) return effectiveVariantUnit(eo, opt.variant);
return effectiveOptionUnit(eo);
}
@@ -71,12 +72,12 @@ export default function ManualRegistrationPage() {
if (!user) router.replace("/login");
}, [user, loading, router]);
const [events, setEvents] = useState<any[]>([]);
const [events, setEvents] = useState<Event[]>([]);
const [selectedEventId, setSelectedEventId] = useState<string>("");
const [options, setOptions] = useState<any[]>([]);
const [options, setOptions] = useState<EventOption[]>([]);
// All system users for fuzzy lookup
const [allUsers, setAllUsers] = useState<any[]>([]);
const [allUsers, setAllUsers] = useState<User[]>([]);
const [guest, setGuest] = useState({ name: "", email: "", phoneNumber: "" });
const [notifPref, setNotifPref] = useState<"email" | "whatsapp" | "both">("email");
@@ -95,7 +96,7 @@ export default function ManualRegistrationPage() {
const [tab, setTab] = useState<"register" | "payment">("register");
// ── Record Payment tab state ─────────────────────────────────────────────
const [allRegistrations, setAllRegistrations] = useState<any[]>([]);
const [allRegistrations, setAllRegistrations] = useState<Registration[]>([]);
const [payUserId, setPayUserId] = useState<string>("");
const [payUserQuery, setPayUserQuery] = useState("");
const [payDropdownOpen, setPayDropdownOpen] = useState(false);
@@ -120,7 +121,7 @@ export default function ManualRegistrationPage() {
// balances can be computed without a per-registration fetch loop).
useEffect(() => {
if (!token) return;
apiFetch<any[]>("/api/registrations", { authToken: token })
apiFetch<Registration[]>("/api/registrations", { authToken: token })
.then(regs => setAllRegistrations(Array.isArray(regs) ? regs : []))
.catch(() => {});
}, [token]);
@@ -128,8 +129,8 @@ export default function ManualRegistrationPage() {
const regOutstanding = useMemo(() => {
const map: Record<string, { totalDue: number; totalPaid: number; outstanding: number }> = {};
for (const r of allRegistrations) {
const totalDue = r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum: number, opt: any) => sum + optionUnitPrice(opt) * (opt.quantity || 0), 0);
const totalPaid = (r.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0);
const totalDue = r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => sum + optionUnitPrice(opt) * (opt.quantity || 0), 0);
const totalPaid = (r.payments || []).reduce((s, p) => s + (p.amount || 0), 0);
map[r.id] = { totalDue, totalPaid, outstanding: Math.max(0, totalDue - totalPaid) };
}
return map;
@@ -145,7 +146,7 @@ export default function ManualRegistrationPage() {
.map(x => x.u);
}, [payUserQuery, allUsers]);
const selectPayUser = (u: any) => {
const selectPayUser = (u: User) => {
setPayUserId(u.id);
setPayUserQuery(u.name || "");
setPayDropdownOpen(false);
@@ -166,9 +167,9 @@ export default function ManualRegistrationPage() {
const regsForPayUser = useMemo(() => {
if (!payUserId) return [];
return allRegistrations
.filter((r: any) => String(r.userId || r.user?.id) === String(payUserId))
.filter((r: any) => (regOutstanding[r.id]?.outstanding ?? 0) > 0.000001)
.sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
.filter((r) => String(r.userId || r.user?.id) === String(payUserId))
.filter((r) => (regOutstanding[r.id]?.outstanding ?? 0) > 0.000001)
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
}, [allRegistrations, payUserId, regOutstanding]);
const createManualPayment = async () => {
@@ -180,7 +181,7 @@ export default function ManualRegistrationPage() {
if (!payRegistrationId) { setPayError("Please select a registration"); return; }
try {
setPaySubmitting(true);
await apiFetch<any>("/api/payments", {
await apiFetch("/api/payments", {
method: "POST",
authToken: token,
body: {
@@ -197,7 +198,7 @@ export default function ManualRegistrationPage() {
setPayPaidAtLocal("");
// Refresh registrations so the displayed outstanding balance updates
try {
const regs = await apiFetch<any[]>("/api/registrations", { authToken: token });
const regs = await apiFetch<Registration[]>("/api/registrations", { authToken: token });
setAllRegistrations(Array.isArray(regs) ? regs : []);
} catch {}
} catch (e) {
@@ -230,7 +231,7 @@ export default function ManualRegistrationPage() {
const selectedEventAllowsNames = !!selectedEv?.allowNamedAttendees || selectedIsYouth;
const [pickedUserId, setPickedUserId] = useState<string | null>(null);
const selectUser = (u: any) => {
const selectUser = (u: User) => {
setPickedUserId(u.id || null);
setGuest({ name: u.name || "", email: u.email || "", phoneNumber: u.phoneNumber || "" });
setUserQuery(u.name || "");
@@ -252,7 +253,7 @@ export default function ManualRegistrationPage() {
(async () => {
try {
if (!token) return;
const evs = await apiFetch<any[]>("/api/events/all", { authToken: token });
const evs = await apiFetch<Event[]>("/api/events/all", { authToken: token });
const now = Date.now();
const active = (evs || []).filter(ev => {
const t = new Date(ev.endDate).getTime();
@@ -274,9 +275,9 @@ export default function ManualRegistrationPage() {
const opts = ev.options || ev.eventOptions || [];
setOptions(opts);
const map: Record<string, number> = {};
opts.forEach((o: any) => {
opts.forEach((o) => {
if ((o.variants || []).length > 0) {
(o.variants as any[]).forEach(v => { map[`${o.id}::${v.id}`] = 0; });
(o.variants || []).forEach(v => { map[`${o.id}::${v.id}`] = 0; });
} else {
map[o.id] = 0;
}
@@ -291,7 +292,7 @@ export default function ManualRegistrationPage() {
const totalDue = useMemo(() => {
return options.reduce((sum, o) => {
if ((o.variants || []).length > 0) {
return sum + (o.variants as any[]).reduce((vs: number, v: any) => vs + (quantities[`${o.id}::${v.id}`] || 0) * effectiveVariantUnit(o, v), 0);
return sum + (o.variants || []).reduce((vs, v) => vs + (quantities[`${o.id}::${v.id}`] || 0) * effectiveVariantUnit(o, v), 0);
}
return sum + (quantities[o.id] || 0) * effectiveOptionUnit(o);
}, 0);
@@ -320,7 +321,7 @@ export default function ManualRegistrationPage() {
const hasEmail = !!guest.email.trim();
const hasPhone = !!guest.phoneNumber.trim();
const resolvedPref = hasEmail && hasPhone ? notifPref : hasPhone ? "whatsapp" : "email";
const res = await apiFetch<any>("/api/registrations/manual", {
const res = await apiFetch<Registration & { couponError?: string }>("/api/registrations/manual", {
method: "POST",
authToken: token,
body: {
@@ -340,7 +341,7 @@ export default function ManualRegistrationPage() {
// Pre-load the Record Payment tab with this registration so it's ready to go the
// moment a supervisor clicks over — the tab itself is never switched to automatically.
setAllRegistrations(prev => [res, ...prev.filter((r: any) => r.id !== res.id)]);
setAllRegistrations(prev => [res, ...prev.filter((r) => r.id !== res.id)]);
setPayUserId(res.userId || res.user?.id || "");
setPayUserQuery(res.user?.name || guest.name || "");
setPayRegistrationId(res.id);
@@ -559,7 +560,7 @@ export default function ManualRegistrationPage() {
<div className="px-3 py-2 bg-gray-50 border-b text-sm font-medium text-gray-800">
{opt.name}{opt.isMainTicket ? <span className="ml-1.5 text-xs text-brand-600 font-normal">• Main</span> : null}
</div>
{(opt.variants as any[]).map((v: any) => {
{(opt.variants || []).map((v) => {
const unit = effectiveVariantUnit(opt, v);
const basePrice = v.price !== null && v.price !== undefined ? v.price : opt.price;
const key = `${opt.id}::${v.id}`;
@@ -719,7 +720,7 @@ export default function ManualRegistrationPage() {
<label className="block text-xs text-gray-600 mb-1">Registration</label>
<select className="w-full max-w-full border rounded px-3 py-2 text-sm truncate" value={payRegistrationId} onChange={e => setPayRegistrationId(e.target.value)} disabled={!payUserId}>
<option value="">Select registration…</option>
{regsForPayUser.map((r: any) => {
{regsForPayUser.map((r) => {
const out = regOutstanding[r.id]?.outstanding ?? 0;
const label = `${r.event?.title || r.eventId || 'Event'} — Outstanding: R ${out.toFixed(2)} — #${String(r.id).slice(0,8)}`;
return <option key={r.id} value={r.id} title={label}>{label}</option>;