Type registrations, email and WhatsApp messaging pages

Adds typed payloads and results for the email/WhatsApp attendee and
broadcast endpoints. The WhatsApp page's messageDirty flag becomes a ref
(it only gated the template effect), and a no-op branch in the email
template effect is removed.

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 b21e7857d0
commit f2728892b4
6 changed files with 196 additions and 174 deletions
@@ -1,12 +1,13 @@
"use client";
import React, { useEffect, useMemo, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { ClipboardList } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import type { Event, FormResponse, Registration } from "@/types";
const STATUS_OPTIONS = ["pending", "confirmed", "partial_paid", "paid", "cancelled"] as const;
@@ -18,6 +19,16 @@ function fuzzyMatch(query: string, target: string): boolean {
return tokens.every(tok => t.includes(tok));
}
// Backend attaches a tranche-aware totalDueComputed (exact even when a line spans multiple
// early-bird prices) — fall back to the old client-side estimate only for stale payloads.
const totalDueFor = (r: Registration) => r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => {
const unit = (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined)
? Number(opt.priceSnapshot)
: (opt.eventOption?.price || 0);
return sum + unit * (opt.quantity || 0);
}, 0);
const totalPaidFor = (r: Registration) => (r.payments || []).reduce((sum, p) => sum + (p.amount || 0), 0);
export default function AdminRegistrationsPage() {
const { user, loading, token } = useAuth();
const router = useRouter();
@@ -29,8 +40,8 @@ export default function AdminRegistrationsPage() {
if (!user) router.replace("/login");
}, [user, loading, router]);
const [registrations, setRegistrations] = useState<any[]>([]);
const [events, setEvents] = useState<any[]>([]);
const [registrations, setRegistrations] = useState<Registration[]>([]);
const [events, setEvents] = useState<Event[]>([]);
const [loadingRegs, setLoadingRegs] = useState(false);
const [error, setError] = useDismissingState<string | null>(null);
const [info, setInfo] = useDismissingState<string | null>(null);
@@ -44,14 +55,14 @@ export default function AdminRegistrationsPage() {
// Expanded rows + form responses cache
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [formResponses, setFormResponses] = useState<Record<string, any[]>>({});
const [formResponses, setFormResponses] = useState<Record<string, FormResponse[]>>({});
const [loadingForms, setLoadingForms] = useState<Set<string>>(new Set());
const loadRegistrations = async () => {
const loadRegistrations = useCallback(async () => {
if (!token) return;
try {
setLoadingRegs(true);
const regs = await apiFetch<any[]>("/api/registrations", { authToken: token });
const regs = await apiFetch<Registration[]>("/api/registrations", { authToken: token });
const list = Array.isArray(regs) ? regs.sort((a, b) => {
const eventCompare = (a.event?.startDate || a.eventId).localeCompare(b.event?.startDate || b.eventId);
if (eventCompare !== 0) return eventCompare;
@@ -63,29 +74,29 @@ export default function AdminRegistrationsPage() {
} finally {
setLoadingRegs(false);
}
};
}, [token, setError]);
const loadEvents = async () => {
const loadEvents = useCallback(async () => {
if (!token) return;
try {
const params = new URLSearchParams();
if (includePastEvents) params.set("includePast", "true");
if (includeInactiveEvents) params.set("includeInactive", "true");
const qs = params.toString() ? `?${params.toString()}` : "";
const evs = await apiFetch<any[]>(`/api/events/all${qs}`, { authToken: token });
setEvents(Array.isArray(evs) ? evs.sort((a: any, b: any) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()) : []);
const evs = await apiFetch<Event[]>(`/api/events/all${qs}`, { authToken: token });
setEvents(Array.isArray(evs) ? evs.sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()) : []);
} catch {}
};
}, [token, includePastEvents, includeInactiveEvents]);
useEffect(() => {
loadRegistrations();
}, [token]);
}, [loadRegistrations]);
useEffect(() => {
loadEvents();
}, [token, includePastEvents, includeInactiveEvents]);
}, [loadEvents]);
const toggleExpand = async (reg: any) => {
const toggleExpand = async (reg: Registration) => {
const id = reg.id;
const next = new Set(expanded);
if (next.has(id)) {
@@ -99,8 +110,8 @@ export default function AdminRegistrationsPage() {
if (!formResponses[id] && !loadingForms.has(id)) {
setLoadingForms(prev => new Set(prev).add(id));
try {
const res = await apiFetch<any>(`/api/forms/responses?registrationId=${encodeURIComponent(id)}`, { authToken: token! });
const items = Array.isArray(res?.items) ? res.items : (Array.isArray(res) ? res : []);
const res = await apiFetch<{ items?: FormResponse[] } | FormResponse[]>(`/api/forms/responses?registrationId=${encodeURIComponent(id)}`, { authToken: token! });
const items = Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);
setFormResponses(prev => ({ ...prev, [id]: items }));
} catch {
setFormResponses(prev => ({ ...prev, [id]: [] }));
@@ -110,7 +121,7 @@ export default function AdminRegistrationsPage() {
}
};
const cancelRegistration = async (reg: any) => {
const cancelRegistration = async (reg: Registration) => {
if (!token) return;
setError(null); setInfo(null);
if (!confirm(`Cancel registration #${String(reg.id).slice(0, 8)} for ${reg.user?.name || reg.userId}?`)) return;
@@ -123,7 +134,7 @@ export default function AdminRegistrationsPage() {
}
};
const updateStatus = async (reg: any, status: string) => {
const updateStatus = async (reg: Registration, status: string) => {
if (!token) return;
setError(null); setInfo(null);
try {
@@ -135,10 +146,10 @@ export default function AdminRegistrationsPage() {
}
};
const eventIds = useMemo(() => new Set(events.map((ev: any) => ev.id)), [events]);
const eventIds = useMemo(() => new Set(events.map((ev) => ev.id)), [events]);
const filtered = useMemo(() => {
return registrations.filter((r: any) => {
return registrations.filter((r) => {
if (!eventIds.has(r.eventId)) return false;
if (eventFilter && r.eventId !== eventFilter) return false;
if (statusFilter && r.status !== statusFilter) return false;
@@ -146,10 +157,10 @@ export default function AdminRegistrationsPage() {
const haystack = [
r.id, r.user?.name, r.user?.email, r.user?.phoneNumber,
r.userId, r.event?.title, r.eventId, r.status,
].map((x: any) => String(x || "")).join(" ");
].map((x) => String(x || "")).join(" ");
return fuzzyMatch(query.trim(), haystack);
});
}, [registrations, query, eventFilter, statusFilter]);
}, [registrations, query, eventFilter, statusFilter, eventIds]);
const statusColor = (s: string) => {
if (s === "paid") return "text-green-700 bg-green-50";
@@ -159,15 +170,6 @@ export default function AdminRegistrationsPage() {
return "text-gray-700 bg-gray-50";
};
// Backend attaches a tranche-aware totalDueComputed (exact even when a line spans multiple
// early-bird prices) — fall back to the old client-side estimate only for stale payloads.
const totalDueFor = (r: any) => r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum: number, opt: any) => {
const unit = (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined)
? Number(opt.priceSnapshot)
: (opt.eventOption?.price || 0);
return sum + unit * (opt.quantity || 0);
}, 0);
const totalPaidFor = (r: any) => (r.payments || []).reduce((sum: number, p: any) => sum + (p.amount || 0), 0);
// Aggregate stats across the currently filtered registrations — counts by status, plus
// revenue/outstanding totals (cancelled registrations are excluded from the money totals
@@ -176,7 +178,7 @@ export default function AdminRegistrationsPage() {
const counts: Record<string, number> = {};
let totalRevenue = 0;
let totalOutstanding = 0;
filtered.forEach((r: any) => {
filtered.forEach((r) => {
counts[r.status] = (counts[r.status] || 0) + 1;
if (r.status === "cancelled") return;
const due = totalDueFor(r);
@@ -276,7 +278,7 @@ export default function AdminRegistrationsPage() {
<div className="border rounded-xl bg-white shadow-sm">
<ul className="divide-y text-sm">
{filtered.map((r: any) => {
{filtered.map((r) => {
const totalDue = totalDueFor(r);
const totalPaid = totalPaidFor(r);
const outstanding = Math.max(totalDue - totalPaid, 0);
@@ -337,7 +339,7 @@ export default function AdminRegistrationsPage() {
<div className="mb-3">
<div className="text-xs font-semibold text-gray-600 mb-1 uppercase tracking-wide">Ticket options</div>
<div className="grid sm:grid-cols-2 gap-2">
{r.registrationOptions.map((opt: any) => {
{(r.registrationOptions || []).map((opt) => {
// A line can span multiple price tranches (e.g. tickets bought
// before and after an early-bird tier expired) — show one row per
// tranche so its own price/tier status is accurate, not blended.
@@ -357,7 +359,7 @@ export default function AdminRegistrationsPage() {
{opt.eventOption?.name || opt.eventOptionId}
{opt.variant?.name && <span className="text-gray-500"> ({opt.variant.name})</span>}
</div>
{tranches.map((t: any, idx: number) => {
{tranches.map((t, idx) => {
const unit = Number(t.priceSnapshot || 0);
return (
<div key={t.id || idx} className="text-gray-500">
@@ -383,7 +385,7 @@ export default function AdminRegistrationsPage() {
<div className="text-xs text-gray-400">No payments recorded.</div>
) : (
<div className="grid sm:grid-cols-2 gap-2">
{r.payments.map((p: any) => (
{(r.payments || []).map((p) => (
<div key={p.id} className="bg-white border rounded p-2 text-xs">
<div className="font-medium">
{p.amount < 0 ? '-' : ''}R {Math.abs(p.amount).toFixed(2)} · {p.method || 'payment'}
@@ -410,11 +412,11 @@ export default function AdminRegistrationsPage() {
<div className="text-xs text-gray-400">No form responses submitted.</div>
) : (
<div className="space-y-2">
{responses.map((resp: any, idx: number) => (
{responses.map((resp, idx) => (
<div key={resp.id || idx} className="bg-white border rounded p-2">
<div className="text-xs font-medium text-gray-600 mb-1">Response #{idx + 1}</div>
<div className="grid sm:grid-cols-2 gap-1.5">
{(resp.answers || []).map((a: any) => (
{(resp.answers || []).map((a) => (
<div key={a.id} className="bg-gray-50 border rounded p-1.5 text-xs">
<div className="text-[10px] text-gray-500">{a.field?.label || a.fieldId}</div>
<div className="font-medium">{a.value}</div>
@@ -1,6 +1,6 @@
"use client";
import React, { Suspense, useEffect, useMemo, useState } from "react";
import React, { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter, useSearchParams } from "next/navigation";
import { apiFetch, fetchAllUsers } from "@/lib/api";
@@ -8,8 +8,15 @@ import { useDismissingState } from "@/hooks/useDismissingState";
import { Mail, Users, Zap, Clock } from "lucide-react";
import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter";
import { errorMessage } from "@/lib/utils";
import type { Event, MessageSendResult, Registration, User } from "@/types";
type Attendee = { id: string; name: string; email: string; pref: string };
type TemplateKey = 'custom'|'payment_reminder'|'event_reminder'|'tickets';
type StatusFilter = 'any'|'paid'|'unpaid'|'partial_paid'|'cancelled';
type MessageFilter = { status?: Exclude<StatusFilter, 'any'>; attendeeIds?: string[]; allocationGroupId?: string };
// A message body goes as `html` when it looks like markup, otherwise as plain `text`.
type EmailContent = { html?: string; text?: string };
type EmailSendResult = MessageSendResult<{ email: string; name?: string }>;
export default function EmailAttendeesPage() {
return (
@@ -136,16 +143,14 @@ function AttendeesCheckboxDropdown({
}
function PrefWarning({ attendees, selectedIds, channel }: { attendees: { id: string; pref: string }[]; selectedIds: string[]; channel: "email" | "whatsapp" }) {
const prefMatch = (pref: string) =>
channel === "email" ? pref === "email" || pref === "both" : pref === "whatsapp" || pref === "both";
const mismatched = useMemo(
() => selectedIds.filter(id => {
const mismatched = useMemo(() => {
const prefMatch = (pref: string) =>
channel === "email" ? pref === "email" || pref === "both" : pref === "whatsapp" || pref === "both";
return selectedIds.filter(id => {
const a = attendees.find(x => x.id === id);
return a && !prefMatch(a.pref);
}),
[attendees, selectedIds, channel]
);
});
}, [attendees, selectedIds, channel]);
if (mismatched.length === 0) return null;
return (
@@ -181,7 +186,7 @@ function EmailAttendeesPageInner() {
// Tabs: attendees (current), automations (coming soon), broadcasts
const [tab, setTab] = useState<'attendees'|'automations'|'broadcasts'|'scheduled'>('attendees');
const [allEvents, setAllEvents] = useState<any[]>([]);
const [allEvents, setAllEvents] = useState<Event[]>([]);
const [evIncludePast, setEvIncludePast] = useState(false);
const events = useMemo(() => {
@@ -193,20 +198,21 @@ function EmailAttendeesPageInner() {
});
}, [allEvents, evIncludePast]);
const loadEvents = async () => {
const loadEvents = useCallback(async () => {
try {
setLoadingEvents(true);
const evs = await apiFetch<any[]>("/api/events/all?includePast=true", { authToken: token || undefined });
const sorted = (evs || []).sort((a: any, b: any) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());
const evs = await apiFetch<Event[]>("/api/events/all?includePast=true", { authToken: token || undefined });
const sorted = (evs || []).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());
setAllEvents(sorted);
} catch (e) {
setError(errorMessage(e) || "Failed to load events");
} finally {
setLoadingEvents(false);
}
};
}, [token, setError]);
useEffect(() => { loadEvents(); }, [user, token]);
// Reload when the signed-in user changes too (e.g. after an impersonation switch).
useEffect(() => { loadEvents(); }, [user, loadEvents]);
// Load users for broadcasts
useEffect(() => {
@@ -216,9 +222,9 @@ function EmailAttendeesPageInner() {
setLoadingUsers(true);
const allUsers = await fetchAllUsers(token);
const mapped = allUsers
.filter((u: any) => u.isActive !== false && !u.email?.endsWith('@guest.local'))
.map((u: any) => ({ id: u.id, name: u.name || '', email: u.email || '', pref: u.notificationPreference || 'email' }))
.sort((a: any, b: any) => (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' }));
.filter((u) => u.isActive !== false && !u.email?.endsWith('@guest.local'))
.map((u) => ({ id: u.id, name: u.name || '', email: u.email || '', pref: u.notificationPreference || 'email' }))
.sort((a, b) => (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' }));
setUsers(mapped);
} catch {
// ignore for now
@@ -235,7 +241,7 @@ function EmailAttendeesPageInner() {
if (preselectEventId) setEventId(preselectEventId);
}, [preselectEventId]);
const [templateKey, setTemplateKey] = useState<'custom'|'payment_reminder'|'event_reminder'|'tickets'>('custom');
const [templateKey, setTemplateKey] = useState<TemplateKey>('custom');
const [showInfo, setShowInfo] = useState(false);
// Broadcasts state
@@ -270,7 +276,7 @@ function EmailAttendeesPageInner() {
const [editWhen, setEditWhen] = useState<string>('');
const [savingEdit, setSavingEdit] = useState(false);
const loadScheduled = async () => {
const loadScheduled = useCallback(async () => {
try {
if (!token) return;
setLoadingScheduled(true);
@@ -281,9 +287,9 @@ function EmailAttendeesPageInner() {
} finally {
setLoadingScheduled(false);
}
};
}, [token]);
useEffect(() => { if (tab === 'scheduled') loadScheduled(); }, [tab, token]);
useEffect(() => { if (tab === 'scheduled') loadScheduled(); }, [tab, loadScheduled]);
const openEdit = (job: ScheduledJob) => {
setEditing(job);
@@ -297,7 +303,7 @@ function EmailAttendeesPageInner() {
try {
setSavingEdit(true);
if (!token) { setError('Not authenticated'); return; }
const body: any = {};
const body: { scheduledAt?: string; subject?: string } & EmailContent = {};
if (editWhen) body.scheduledAt = new Date(editWhen).toISOString();
if (editSubject.trim().length || editBody.trim().length) {
body.subject = editSubject;
@@ -313,8 +319,8 @@ function EmailAttendeesPageInner() {
setInfo('Scheduled email updated.');
setEditing(null);
loadScheduled();
} catch (e:any) {
setError(e?.message || 'Failed to update scheduled email');
} catch (e) {
setError(errorMessage(e) || 'Failed to update scheduled email');
} finally {
setSavingEdit(false);
}
@@ -326,8 +332,8 @@ function EmailAttendeesPageInner() {
await apiFetch(`/api/scheduled-emails/${encodeURIComponent(job.id)}`, { method: 'DELETE', authToken: token });
setInfo('Scheduled email removed.');
loadScheduled();
} catch (e:any) {
setError(e?.message || 'Failed to remove scheduled email');
} catch (e) {
setError(errorMessage(e) || 'Failed to remove scheduled email');
}
};
@@ -335,7 +341,7 @@ function EmailAttendeesPageInner() {
const [body, setBody] = useState("");
const [subjectDirty, setSubjectDirty] = useState(false);
const [bodyDirty, setBodyDirty] = useState(false);
const [status, setStatus] = useState<'any'|'paid'|'unpaid'|'partial_paid'|'cancelled'>("any");
const [status, setStatus] = useState<StatusFilter>("any");
const [groupId, setGroupId] = useState("");
// Attendees list and selection
const [attendees, setAttendees] = useState<Attendee[]>([]);
@@ -359,11 +365,8 @@ function EmailAttendeesPageInner() {
setBodyDirty(false);
setSubject('');
setBody('');
} else {
// custom: do not overwrite user content unless not dirty and we have event change
if (!subjectDirty && subject) setSubject(subject); // keep as-is
if (!bodyDirty && body) setBody(body);
}
// custom: leave whatever the supervisor typed alone.
// When event changes, refresh defaults if not dirty
}, [templateKey, currentEvent, subjectDirty, bodyDirty]);
@@ -388,10 +391,10 @@ function EmailAttendeesPageInner() {
setAttendees([]);
setSelectedAttendeeIds([]);
if (!eventId || !token) return;
const regs = await apiFetch<any[]>(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token });
const regs = await apiFetch<Registration[]>(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token });
const uniq = new Map<string, Attendee>();
(regs || []).forEach((r: any) => {
const u = r?.user;
(regs || []).forEach((r) => {
const u: User | undefined = r?.user;
if (u?.id && u?.email && !u.email.endsWith('@guest.local') && u.isActive !== false) {
uniq.set(u.id, { id: u.id, name: u.name || '', email: u.email || '', pref: u.notificationPreference || 'email' });
}
@@ -419,7 +422,7 @@ function EmailAttendeesPageInner() {
if (!subject.trim()) { setError("Subject is required"); return; }
if (!body.trim()) { setError("Message is required"); return; }
}
const payload: any = {
const payload: { subject: string; filter: MessageFilter; dryRun: boolean; template: TemplateKey } & EmailContent = {
subject: subject || "(no subject)",
filter: { status: status !== 'any' ? status : undefined, attendeeIds: selectedAttendeeIds && selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
dryRun: true,
@@ -428,7 +431,7 @@ function EmailAttendeesPageInner() {
if (templateKey !== 'tickets') {
if (body.trim().startsWith('<')) payload.html = body; else payload.text = body;
}
const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/email-attendees`, { method: 'POST', authToken: token, body: payload });
const res = await apiFetch<EmailSendResult>(`/api/events/${encodeURIComponent(eventId)}/email-attendees`, { method: 'POST', authToken: token, body: payload });
setPreviewCount(res?.matched ?? 0);
setPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
setInfo(`Matched ${res?.matched ?? 0} recipient(s).`);
@@ -459,7 +462,7 @@ function EmailAttendeesPageInner() {
if (!body.trim()) { setError("Message is required"); return; }
}
setSending(true);
const payload: any = {
const payload: { subject: string; filter: MessageFilter; template: TemplateKey } & EmailContent = {
subject,
filter: { status: status !== 'any' ? status : undefined, attendeeIds: selectedAttendeeIds && selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
template: templateKey,
@@ -467,7 +470,7 @@ function EmailAttendeesPageInner() {
if (templateKey !== 'tickets') {
if (body.trim().startsWith('<')) payload.html = body; else payload.text = body.replace(/\n/g, '\n');
}
const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/email-attendees`, { method: 'POST', authToken: token, body: payload });
const res = await apiFetch<EmailSendResult>(`/api/events/${encodeURIComponent(eventId)}/email-attendees`, { method: 'POST', authToken: token, body: payload });
const queued = res?.queued ?? res?.matched ?? 0;
setInfo(`Queued ${queued} recipient(s) for sending.`);
// Reset form to default state
@@ -555,7 +558,7 @@ function EmailAttendeesPageInner() {
Info
</button>
</div>
<select className="w-full border rounded px-3 py-2 text-sm" value={templateKey} onChange={e => setTemplateKey(e.target.value as any)}>
<select className="w-full border rounded px-3 py-2 text-sm" value={templateKey} onChange={e => setTemplateKey(e.target.value as TemplateKey)}>
<option value="custom">Custom message</option>
<option value="payment_reminder">Payment reminder (with outstanding)</option>
<option value="event_reminder">Event reminder (date & time)</option>
@@ -600,7 +603,7 @@ function EmailAttendeesPageInner() {
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">Payment status filter</label>
<select className="w-full border rounded px-3 py-2 text-sm" value={status} onChange={e => setStatus(e.target.value as any)}>
<select className="w-full border rounded px-3 py-2 text-sm" value={status} onChange={e => setStatus(e.target.value as StatusFilter)}>
<option value="any">Any</option>
<option value="paid">Paid</option>
<option value="unpaid">Unpaid (pending or partial)</option>
@@ -659,16 +662,16 @@ function EmailAttendeesPageInner() {
if (!body.trim()) { setError('Message is required'); return; }
}
const whenIso = new Date(scheduledAtLocal).toISOString();
const payload = {
const payload: { subject: string; filter: MessageFilter; template: TemplateKey; scheduledAt: string } & EmailContent = {
subject,
filter: { status: status !== 'any' ? status : undefined, attendeeIds: selectedAttendeeIds && selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
template: templateKey,
scheduledAt: whenIso,
} as any;
};
if (templateKey !== 'tickets') {
if (body.trim().startsWith('<')) payload.html = body; else payload.text = body.replace(/\n/g, '\n');
}
const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/email-attendees/schedule`, { method: 'POST', authToken: token, body: payload });
const res = await apiFetch<EmailSendResult>(`/api/events/${encodeURIComponent(eventId)}/email-attendees/schedule`, { method: 'POST', authToken: token, body: payload });
if (res?.job?.id) {
setInfo('Email scheduled. It will be sent around the specified time.');
} else {
@@ -676,8 +679,8 @@ function EmailAttendeesPageInner() {
}
// Reset form to default state
resetAttendeesForm();
} catch (e:any) {
setError(e?.message || 'Failed to schedule email');
} catch (e) {
setError(errorMessage(e) || 'Failed to schedule email');
}
}}>Schedule send</button>
{previewCount != null && (
@@ -778,13 +781,13 @@ Jane Doe <jane@example.com>
if (!token) { setError('Not authenticated'); return; }
if (!broadcastSubject.trim()) { setError('Subject is required'); return; }
if (!broadcastBody.trim()) { setError('Message is required'); return; }
const body: any = { userIds: selectedUserIds, emails: broadcastEmails, eventId: broadcastEventId || undefined };
const res = await apiFetch(`/api/broadcasts/preview`, { method: 'POST', authToken: token, body });
const body = { userIds: selectedUserIds, emails: broadcastEmails, eventId: broadcastEventId || undefined };
const res = await apiFetch<EmailSendResult>(`/api/broadcasts/preview`, { method: 'POST', authToken: token, body });
setBroadcastPreviewCount(res?.matched ?? 0);
setBroadcastPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
setInfo(`Matched ${res?.matched ?? 0} recipient(s).`);
} catch (e:any) {
setError(e?.message || 'Failed to preview recipients');
} catch (e) {
setError(errorMessage(e) || 'Failed to preview recipients');
}
}}>Preview recipients</button>
@@ -794,14 +797,14 @@ Jane Doe <jane@example.com>
if (!token) { setError('Not authenticated'); return; }
if (!broadcastSubject.trim()) { setError('Subject is required'); return; }
if (!broadcastBody.trim()) { setError('Message is required'); return; }
const payload: any = { subject: broadcastSubject, eventId: broadcastEventId || undefined, userIds: selectedUserIds, emails: broadcastEmails };
const payload: { subject: string; eventId?: string; userIds: string[]; emails: string } & EmailContent = { subject: broadcastSubject, eventId: broadcastEventId || undefined, userIds: selectedUserIds, emails: broadcastEmails };
if (broadcastBody.trim().startsWith('<')) payload.html = broadcastBody; else payload.text = broadcastBody;
const res = await apiFetch(`/api/broadcasts/send`, { method: 'POST', authToken: token, body: payload });
const res = await apiFetch<EmailSendResult>(`/api/broadcasts/send`, { method: 'POST', authToken: token, body: payload });
setInfo(`Sent ${res?.sent ?? 0} out of ${res?.matched ?? 0} recipient(s).`);
// Reset broadcast form
resetBroadcastForm();
} catch (e:any) {
setError(e?.message || 'Failed to send broadcast');
} catch (e) {
setError(errorMessage(e) || 'Failed to send broadcast');
}
}}>Send now</button>
@@ -812,14 +815,14 @@ Jane Doe <jane@example.com>
if (!broadcastSubject.trim()) { setError('Subject is required'); return; }
if (!broadcastBody.trim()) { setError('Message is required'); return; }
const whenIso = new Date(broadcastScheduledAtLocal).toISOString();
const payload: any = { scheduledAt: whenIso, subject: broadcastSubject, eventId: broadcastEventId || undefined, userIds: selectedUserIds, emails: broadcastEmails };
const payload: { scheduledAt: string; subject: string; eventId?: string; userIds: string[]; emails: string } & EmailContent = { scheduledAt: whenIso, subject: broadcastSubject, eventId: broadcastEventId || undefined, userIds: selectedUserIds, emails: broadcastEmails };
if (broadcastBody.trim().startsWith('<')) payload.html = broadcastBody; else payload.text = broadcastBody;
const res = await apiFetch(`/api/broadcasts/schedule`, { method: 'POST', authToken: token, body: payload });
const res = await apiFetch<EmailSendResult>(`/api/broadcasts/schedule`, { method: 'POST', authToken: token, body: payload });
if (res?.job?.id) setInfo('Broadcast scheduled. It will be sent around the specified time.'); else setInfo('Scheduled.');
// Reset broadcast form
resetBroadcastForm();
} catch (e:any) {
setError(e?.message || 'Failed to schedule broadcast');
} catch (e) {
setError(errorMessage(e) || 'Failed to schedule broadcast');
}
}}>Schedule send</button>
@@ -962,9 +965,9 @@ function toLocalInputValue(d: Date) {
return `${y}-${m}-${day}T${hh}:${mm}`;
}
function AutomationsPanel({ events, token, onInfo, onError }:{ events: any[]; token?: string | null; onInfo: (s: string) => void; onError: (s: string) => void }) {
function AutomationsPanel({ events, token, onInfo, onError }:{ events: Event[]; token?: string | null; onInfo: (s: string | null) => void; onError: (s: string | null) => void }) {
const [autoEventId, setAutoEventId] = React.useState<string>('');
const currentEvent = React.useMemo(() => (events || []).find((e:any) => e.id === autoEventId), [events, autoEventId]);
const currentEvent = React.useMemo(() => (events || []).find((e) => e.id === autoEventId), [events, autoEventId]);
// Defaults builders
const preWeekDefault = React.useMemo(() => ({
@@ -1054,37 +1057,38 @@ With gratitude`);
const onSchedule = async () => {
try {
onError(null as any); onInfo(null as any);
onError(null); onInfo(null);
if (!token) { onError('Not authenticated'); return; }
if (!autoEventId) { onError('Please select an event'); return; }
const jobs: any[] = [];
type AutomationJob = { subject: string; scheduledAt: string; audience?: 'sponsors'; promoEventId?: string } & EmailContent;
const jobs: AutomationJob[] = [];
if (enablePre && preSubject.trim() && preBody.trim() && preWhen) {
const payload: any = { subject: preSubject, scheduledAt: new Date(preWhen).toISOString() };
const payload: AutomationJob = { subject: preSubject, scheduledAt: new Date(preWhen).toISOString() };
if (preBody.trim().startsWith('<')) payload.html = preBody; else payload.text = preBody;
jobs.push(payload);
}
if (enableFinal && finalSubject.trim() && finalBody.trim() && finalWhen) {
const payload: any = { subject: finalSubject, scheduledAt: new Date(finalWhen).toISOString() };
const payload: AutomationJob = { subject: finalSubject, scheduledAt: new Date(finalWhen).toISOString() };
if (finalBody.trim().startsWith('<')) payload.html = finalBody; else payload.text = finalBody;
jobs.push(payload);
}
if (enableThanks && thanksSubject.trim() && thanksBody.trim() && thanksWhen) {
const payload: any = { subject: thanksSubject, scheduledAt: new Date(thanksWhen).toISOString() };
const payload: AutomationJob = { subject: thanksSubject, scheduledAt: new Date(thanksWhen).toISOString() };
if (thanksBody.trim().startsWith('<')) payload.html = thanksBody; else payload.text = thanksBody;
jobs.push(payload);
}
if (currentEvent?.allowSponsorships && enableSponsors && sponsorSubject.trim() && sponsorBody.trim() && thanksWhen) {
const payload: any = { subject: sponsorSubject, scheduledAt: new Date(thanksWhen).toISOString(), audience: 'sponsors' };
const payload: AutomationJob = { subject: sponsorSubject, scheduledAt: new Date(thanksWhen).toISOString(), audience: 'sponsors' };
if (sponsorBody.trim().startsWith('<')) payload.html = sponsorBody; else payload.text = sponsorBody;
jobs.push(payload);
}
if (enablePromo && promoSubject.trim() && promoBody.trim() && promoWhen) {
const payload: any = { subject: promoSubject, scheduledAt: new Date(promoWhen).toISOString(), promoEventId: promoEventId || undefined };
const payload: AutomationJob = { subject: promoSubject, scheduledAt: new Date(promoWhen).toISOString(), promoEventId: promoEventId || undefined };
if (promoBody.trim().startsWith('<')) payload.html = promoBody; else payload.text = promoBody;
jobs.push(payload);
}
if (jobs.length === 0) { onError('Please enable at least one automation and fill in details'); return; }
const res = await apiFetch(`/api/automations/schedule`, { method: 'POST', authToken: token, body: { eventId: autoEventId, jobs } });
const res = await apiFetch<{ message?: string }>(`/api/automations/schedule`, { method: 'POST', authToken: token, body: { eventId: autoEventId, jobs } });
onInfo(res?.message || `Scheduled ${jobs.length} automation(s).`);
// Reset to defaults (keep event selection)
setEnablePre(true); setEnableFinal(true); setEnableThanks(true); setEnablePromo(false);
@@ -1092,8 +1096,8 @@ With gratitude`);
setFinalSubject(finalDefault.subject); setFinalBody(finalDefault.body); setFinalHours('24');
setThanksSubject(thanksDefault.subject); setThanksBody(thanksDefault.body);
setPromoSubject(promoDefault.subject); setPromoBody(promoDefault.body); setPromoEventId('');
} catch (e:any) {
onError(e?.message || 'Failed to schedule automations');
} catch (e) {
onError(errorMessage(e) || 'Failed to schedule automations');
}
};
@@ -1103,7 +1107,7 @@ With gratitude`);
<label className="block text-xs text-gray-600 mb-1">Event</label>
<select className="w-full border rounded px-3 py-2 text-sm" value={autoEventId} onChange={e => setAutoEventId(e.target.value)}>
<option value="">Select an event…</option>
{(events||[]).map((ev:any) => (
{(events||[]).map((ev) => (
<option key={ev.id} value={ev.id}>{ev.title}</option>
))}
</select>
@@ -1136,7 +1140,7 @@ With gratitude`);
<input type="checkbox" checked={enableFinal} onChange={e => setEnableFinal(e.target.checked)} /> Enable
</label>
<label className="text-xs text-gray-600">Hours before: </label>
<select className="border rounded px-2 py-1 text-sm" value={finalHours} onChange={e => setFinalHours(e.target.value as any)}>
<select className="border rounded px-2 py-1 text-sm" value={finalHours} onChange={e => setFinalHours(e.target.value as '24'|'48')}>
<option value="24">24</option>
<option value="48">48</option>
</select>
@@ -1200,7 +1204,7 @@ With gratitude`);
<label className="block text-xs text-gray-600 mb-1">Promo Event</label>
<select className="w-full border rounded px-3 py-2 text-sm" value={promoEventId} onChange={e => setPromoEventId(e.target.value)}>
<option value="">Select event to promote…</option>
{(events||[]).map((ev:any) => (
{(events||[]).map((ev) => (
<option key={ev.id} value={ev.id}>{ev.title}</option>
))}
</select>
@@ -298,8 +298,8 @@ export default function FormsBrowserPage() {
setFormDef({ isRequired: false, fields: [] });
}
setFormLoadedFor(eventId);
} catch (e:any) {
setError(e?.message || 'Failed to load form');
} catch (e) {
setError(errorMessage(e) || 'Failed to load form');
} finally {
setFormLoading(false);
}
@@ -318,8 +318,8 @@ export default function FormsBrowserPage() {
const fields = (formDef.fields || []).filter(f => (f.label || '').trim().length > 0).map((f, i) => ({ type: f.type, label: f.label, isRequired: !!f.isRequired && f.type !== 'statement' && f.type !== 'paragraph', order: i, helpText: f.helpText || null, options: f.type === 'multiple_choice' && Array.isArray(f.options) ? f.options.map((o: any) => String(o).trim()).filter(Boolean) : undefined }));
await apiFetch(`/api/events/${encodeURIComponent(selectedEventId)}`, { method: 'PUT', authToken: token, body: { form: { isRequired: !!formDef.isRequired, fields } } });
setInfo('Form saved');
} catch (e:any) {
setError(e?.message || 'Failed to save form');
} catch (e) {
setError(errorMessage(e) || 'Failed to save form');
}
};
@@ -375,8 +375,8 @@ export default function FormsBrowserPage() {
const resList = await apiFetch<any>(`/api/forms/responses?registrationId=${encodeURIComponent(fillRegistrationId)}`, { authToken: token! });
const items = Array.isArray(resList?.items) ? resList.items : (Array.isArray(resList) ? resList : []);
setExistingResponses(items);
} catch (e:any) {
setError(e?.message || 'Failed to load registration/form');
} catch (e) {
setError(errorMessage(e) || 'Failed to load registration/form');
}
})();
}, [fillRegistrationId, mode]);
@@ -435,8 +435,8 @@ export default function FormsBrowserPage() {
const resList = await apiFetch<any>(`/api/forms/responses?registrationId=${encodeURIComponent(fillRegistrationId)}`, { authToken: token! });
const items = Array.isArray(resList?.items) ? resList.items : (Array.isArray(resList) ? resList : []);
setExistingResponses(items);
} catch (e:any) {
setError(e?.message || 'Failed to save responses');
} catch (e) {
setError(errorMessage(e) || 'Failed to save responses');
} finally {
setSavingFill(false);
}
@@ -619,8 +619,8 @@ function PaymentsContent() {
await apiFetch(`/api/yoco-transactions/${encodeURIComponent(tx.id)}/ignore`, { method: 'POST', authToken: token });
setInfo('Transaction ignored');
await loadYocoUnreconciled();
} catch (e:any) {
setError(e?.message || 'Failed to ignore');
} catch (e) {
setError(errorMessage(e) || 'Failed to ignore');
}
}}>Ignore</button>
</td>
@@ -1,6 +1,6 @@
"use client";
import React, { Suspense, useEffect, useMemo, useState } from "react";
import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter, useSearchParams } from "next/navigation";
import { apiFetch, fetchAllUsers } from "@/lib/api";
@@ -8,10 +8,14 @@ import { useDismissingState } from "@/hooks/useDismissingState";
import { MessageCircle, Users, Zap, Send, Clock, type LucideIcon } from "lucide-react";
import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter";
import { errorMessage } from "@/lib/utils";
import type { Event, MessageSendResult, Registration, User } from "@/types";
// Attendee with preference info
type Attendee = { id: string; name: string; phone: string; pref: string };
type UserEntry = { id: string; name: string; phone: string; pref: string };
type TemplateKey = "custom" | "payment_reminder" | "event_reminder" | "tickets";
type StatusFilter = "any" | "paid" | "unpaid" | "partial_paid" | "cancelled";
type MessageFilter = { status?: Exclude<StatusFilter, "any">; attendeeIds?: string[]; allocationGroupId?: string };
const WA_TAB_ICONS: Record<"attendees" | "automations" | "broadcasts" | "scheduled", LucideIcon> = {
attendees: Users,
@@ -161,16 +165,14 @@ function AttendeesCheckboxDropdown({
// ─── Preference warning banner ────────────────────────────────────────────────
function PrefWarning({ attendees, selectedIds, channel }: { attendees: (Attendee|UserEntry)[]; selectedIds: string[]; channel: "whatsapp" | "email" }) {
const prefMatch = (pref: string) =>
channel === "whatsapp" ? pref === "whatsapp" || pref === "both" : pref === "email" || pref === "both";
const mismatched = useMemo(
() => selectedIds.filter((id) => {
const mismatched = useMemo(() => {
const prefMatch = (pref: string) =>
channel === "whatsapp" ? pref === "whatsapp" || pref === "both" : pref === "email" || pref === "both";
return selectedIds.filter((id) => {
const a = attendees.find((x) => x.id === id);
return a && !prefMatch(a.pref);
}),
[attendees, selectedIds, channel]
);
});
}, [attendees, selectedIds, channel]);
if (mismatched.length === 0) return null;
return (
@@ -189,9 +191,9 @@ function PrefWarning({ attendees, selectedIds, channel }: { attendees: (Attendee
}
// ─── WhatsApp Automations Panel ───────────────────────────────────────────────
function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[]; token?: string | null; onInfo: (s: string) => void; onError: (s: string) => void }) {
function WAAutomationsPanel({ events, token, onInfo, onError }: { events: Event[]; token?: string | null; onInfo: (s: string | null) => void; onError: (s: string | null) => void }) {
const [autoEventId, setAutoEventId] = React.useState<string>("");
const currentEvent = React.useMemo(() => (events || []).find((e: any) => e.id === autoEventId), [events, autoEventId]);
const currentEvent = React.useMemo(() => (events || []).find((e) => e.id === autoEventId), [events, autoEventId]);
const preWeekDefault = `Hi {{name}}\n\nJust a friendly reminder that {{event.title}} is one week away!\n\nEvent details: {{event.link}}`;
const finalDefault = `Hi {{name}}\n\nFinal reminder for {{event.title}}.\nPlease have your QR code/ticket ready at entry.\n\nEvent details: {{event.link}}`;
@@ -231,10 +233,10 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[];
const onSchedule = async () => {
try {
onError(null as any); onInfo(null as any);
onError(null); onInfo(null);
if (!token) { onError("Not authenticated"); return; }
if (!autoEventId) { onError("Please select an event"); return; }
const jobs: any[] = [];
const jobs: { message: string; scheduledAt: string; promoEventId?: string }[] = [];
if (enablePre && preBody.trim() && preWhen) jobs.push({ message: preBody, scheduledAt: new Date(preWhen).toISOString() });
if (enableFinal && finalBody.trim() && finalWhen) jobs.push({ message: finalBody, scheduledAt: new Date(finalWhen).toISOString() });
if (enableThanks && thanksBody.trim() && thanksWhen) jobs.push({ message: thanksBody, scheduledAt: new Date(thanksWhen).toISOString() });
@@ -260,7 +262,7 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[];
<label className="block text-xs text-gray-600 mb-1">Event</label>
<select className="w-full border rounded px-3 py-2 text-sm" value={autoEventId} onChange={(e) => setAutoEventId(e.target.value)}>
<option value="">Select an event…</option>
{(events || []).map((ev: any) => (
{(events || []).map((ev) => (
<option key={ev.id} value={ev.id}>{ev.title}</option>
))}
</select>
@@ -287,7 +289,7 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[];
<input type="checkbox" checked={enableFinal} onChange={(e) => setEnableFinal(e.target.checked)} /> Enable
</label>
<label className="text-xs text-gray-600">Hours before:</label>
<select className="border rounded px-2 py-1 text-sm" value={finalHours} onChange={(e) => setFinalHours(e.target.value as any)}>
<select className="border rounded px-2 py-1 text-sm" value={finalHours} onChange={(e) => setFinalHours(e.target.value as "24" | "48")}>
<option value="24">24</option>
<option value="48">48</option>
</select>
@@ -325,7 +327,7 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[];
<label className="block text-xs text-gray-600 mb-1">Promo Event</label>
<select className="w-full border rounded px-3 py-2 text-sm" value={promoEventId} onChange={(e) => setPromoEventId(e.target.value)}>
<option value="">Select event to promote…</option>
{(events || []).map((ev: any) => (
{(events || []).map((ev) => (
<option key={ev.id} value={ev.id}>{ev.title}</option>
))}
</select>
@@ -373,7 +375,7 @@ function WhatsAppAttendeesPageInner() {
const [info, setInfo] = useDismissingState<string | null>(null);
const [tab, setTab] = useState<"attendees" | "automations" | "broadcasts" | "scheduled">("attendees");
const [loadingEvents, setLoadingEvents] = useState(false);
const [allEvents, setAllEvents] = useState<any[]>([]);
const [allEvents, setAllEvents] = useState<Event[]>([]);
const [evIncludePast, setEvIncludePast] = useState(false);
const events = useMemo(() => {
@@ -386,8 +388,8 @@ function WhatsAppAttendeesPageInner() {
const loadEvents = async () => {
try {
setLoadingEvents(true);
const evs = await apiFetch<any[]>("/api/events/all?includePast=true", { authToken: token || undefined });
setAllEvents((evs || []).sort((a: any, b: any) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()));
const evs = await apiFetch<Event[]>("/api/events/all?includePast=true", { authToken: token || undefined });
setAllEvents((evs || []).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()));
} catch (e) {
setError(errorMessage(e) || "Failed to load events");
} finally {
@@ -395,15 +397,17 @@ function WhatsAppAttendeesPageInner() {
}
};
loadEvents();
}, [user, token]);
}, [user, token, setError]);
// ── Attendees tab ──────────────────────────────────────────────────────────
const [eventId, setEventId] = useState<string>(preselectEventId);
useEffect(() => { if (preselectEventId) setEventId(preselectEventId); }, [preselectEventId]);
const [templateKey, setTemplateKey] = useState<"custom" | "payment_reminder" | "event_reminder" | "tickets">("custom");
const [templateKey, setTemplateKey] = useState<TemplateKey>("custom");
const [message, setMessage] = useState("");
const [messageDirty, setMessageDirty] = useState(false);
const [status, setStatus] = useState<"any" | "paid" | "unpaid" | "partial_paid" | "cancelled">("any");
// Set once the supervisor edits the message, so picking a template doesn't overwrite it.
// A ref, not state: it only gates the template effect below and is never rendered.
const messageDirtyRef = useRef(false);
const [status, setStatus] = useState<StatusFilter>("any");
const [groupId, setGroupId] = useState("");
const [attendees, setAttendees] = useState<Attendee[]>([]);
const [selectedAttendeeIds, setSelectedAttendeeIds] = useState<string[]>([]);
@@ -419,11 +423,11 @@ function WhatsAppAttendeesPageInner() {
useEffect(() => {
const title = currentEvent?.title || "the event";
if (templateKey === "payment_reminder") {
if (!messageDirty) setMessage(`Hi {{name}}\n\nFriendly reminder: you have an outstanding balance for ${title}.\n\nPlease settle your balance to secure your tickets. Thank you!`);
if (!messageDirtyRef.current) setMessage(`Hi {{name}}\n\nFriendly reminder: you have an outstanding balance for ${title}.\n\nPlease settle your balance to secure your tickets. Thank you!`);
} else if (templateKey === "event_reminder") {
if (!messageDirty) setMessage(`Hi {{name}}\n\nA quick reminder about ${title}.\nStart: {{event.start}}\n\nWe look forward to seeing you!`);
if (!messageDirtyRef.current) setMessage(`Hi {{name}}\n\nA quick reminder about ${title}.\nStart: {{event.start}}\n\nWe look forward to seeing you!`);
} else if (templateKey === "tickets") {
setMessageDirty(false); setMessage("");
messageDirtyRef.current = false; setMessage("");
}
}, [templateKey, currentEvent]);
@@ -432,10 +436,10 @@ function WhatsAppAttendeesPageInner() {
try {
setLoadingAttendees(true); setAttendees([]); setSelectedAttendeeIds([]);
if (!eventId || !token) return;
const regs = await apiFetch<any[]>(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token });
const regs = await apiFetch<Registration[]>(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token });
const uniq = new Map<string, Attendee>();
(regs || []).forEach((r: any) => {
const u = r?.user;
(regs || []).forEach((r) => {
const u: User | undefined = r?.user;
if (u?.id && u?.phoneNumber && !u.email?.endsWith("@guest.local") && u.isActive !== false) {
uniq.set(u.id, { id: u.id, name: u.name || "", phone: u.phoneNumber, pref: u.notificationPreference || "email" });
}
@@ -451,7 +455,7 @@ function WhatsAppAttendeesPageInner() {
}, [eventId, token]);
const buildPayload = (dryRun?: boolean) => {
const payload: any = {
const payload: { filter: MessageFilter; template: TemplateKey; dryRun?: boolean; message?: string } = {
filter: { status: status !== "any" ? status : undefined, attendeeIds: selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
template: templateKey,
dryRun: dryRun || undefined,
@@ -466,7 +470,7 @@ function WhatsAppAttendeesPageInner() {
if (!token) { setError("Not authenticated"); return; }
if (!eventId) { setError("Please select an event"); return; }
if (templateKey !== "tickets" && !message.trim()) { setError("Message is required"); return; }
const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload(true) });
const res = await apiFetch<MessageSendResult>(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload(true) });
setPreviewCount(res?.matched ?? 0);
setPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
setInfo(`Matched ${res?.matched ?? 0} recipient(s) with a phone number.`);
@@ -474,7 +478,7 @@ function WhatsAppAttendeesPageInner() {
};
const resetAttendeesForm = () => {
setTemplateKey("custom"); setMessage(""); setMessageDirty(false);
setTemplateKey("custom"); setMessage(""); messageDirtyRef.current = false;
setStatus("any"); setScheduledAtLocal(""); setPreviewCount(null); setPreviewSample(null);
setSelectedAttendeeIds(attendees.map((a) => a.id));
};
@@ -486,7 +490,7 @@ function WhatsAppAttendeesPageInner() {
if (!eventId) { setError("Please select an event"); return; }
if (templateKey !== "tickets" && !message.trim()) { setError("Message is required"); return; }
setSending(true);
const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload() });
const res = await apiFetch<MessageSendResult>(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload() });
setInfo(`Queued ${res?.queued ?? res?.matched ?? 0} recipient(s) for sending.`);
resetAttendeesForm();
} catch (e) { setError(errorMessage(e) || "Failed to send"); } finally { setSending(false); }
@@ -500,12 +504,12 @@ function WhatsAppAttendeesPageInner() {
if (templateKey !== "tickets" && !message.trim()) { setError("Message is required"); return; }
if (!scheduledAtLocal) { setError("Scheduled time is required"); return; }
const whenIso = new Date(scheduledAtLocal).toISOString();
const payload: any = {
const payload: { message?: string; filter: MessageFilter; template: TemplateKey; scheduledAt: string } = {
message: message || undefined,
filter: { status: status !== "any" ? status : undefined, attendeeIds: selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
template: templateKey, scheduledAt: whenIso,
};
const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees/schedule`, { method: "POST", authToken: token, body: payload });
const res = await apiFetch<MessageSendResult>(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees/schedule`, { method: "POST", authToken: token, body: payload });
setInfo(res?.job?.id ? "WhatsApp scheduled. It will be sent around the specified time." : "Scheduled.");
resetAttendeesForm();
} catch (e) { setError(errorMessage(e) || "Failed to schedule"); }
@@ -529,9 +533,9 @@ function WhatsAppAttendeesPageInner() {
setLoadingUsers(true);
const allUsers = await fetchAllUsers(token);
const mapped = allUsers
.filter((u: any) => u.isActive !== false && !u.email?.endsWith("@guest.local") && u.phoneNumber)
.map((u: any) => ({ id: u.id, name: u.name || "", phone: u.phoneNumber, pref: u.notificationPreference || "email" }))
.sort((a: any, b: any) => (a.name || "").localeCompare(b.name || "", undefined, { sensitivity: "base" }));
.filter((u) => u.isActive !== false && !u.email?.endsWith("@guest.local") && u.phoneNumber)
.map((u) => ({ id: u.id, name: u.name || "", phone: u.phoneNumber || "", pref: u.notificationPreference || "email" }))
.sort((a, b) => (a.name || "").localeCompare(b.name || "", undefined, { sensitivity: "base" }));
setUsers(mapped);
} catch { } finally { setLoadingUsers(false); }
};
@@ -553,23 +557,23 @@ function WhatsAppAttendeesPageInner() {
const [editWhen, setEditWhen] = useState<string>("");
const [savingEdit, setSavingEdit] = useState(false);
const loadScheduled = async () => {
const loadScheduled = useCallback(async () => {
try {
if (!token) return;
setLoadingScheduled(true);
const res = await apiFetch<{ jobs: ScheduledJob[] }>(`/api/scheduled-emails?channel=whatsapp`, { authToken: token });
setScheduled(Array.isArray(res?.jobs) ? res.jobs : []);
} catch { } finally { setLoadingScheduled(false); }
};
}, [token]);
useEffect(() => { if (tab === "scheduled") loadScheduled(); }, [tab, token]);
useEffect(() => { if (tab === "scheduled") loadScheduled(); }, [tab, loadScheduled]);
const saveEdit = async () => {
if (!editing) return;
try {
setSavingEdit(true);
if (!token) { setError("Not authenticated"); return; }
const body: any = {};
const body: { scheduledAt?: string; message?: string } = {};
if (editWhen) body.scheduledAt = new Date(editWhen).toISOString();
if (editMessage.trim()) body.message = editMessage;
await apiFetch(`/api/scheduled-emails/${encodeURIComponent(editing.id)}`, { method: "PATCH", authToken: token, body });
@@ -664,7 +668,7 @@ function WhatsAppAttendeesPageInner() {
Info
</button>
</div>
<select className="w-full border rounded px-3 py-2 text-sm" value={templateKey} onChange={(e) => setTemplateKey(e.target.value as any)}>
<select className="w-full border rounded px-3 py-2 text-sm" value={templateKey} onChange={(e) => setTemplateKey(e.target.value as TemplateKey)}>
<option value="custom">Custom message</option>
<option value="payment_reminder">Payment reminder</option>
<option value="event_reminder">Event reminder</option>
@@ -710,7 +714,7 @@ function WhatsAppAttendeesPageInner() {
<div className="grid sm:grid-cols-2 gap-3">
<div>
<label className="block text-xs text-gray-600 mb-1">Payment status filter</label>
<select className="w-full border rounded px-3 py-2 text-sm" value={status} onChange={(e) => setStatus(e.target.value as any)}>
<select className="w-full border rounded px-3 py-2 text-sm" value={status} onChange={(e) => setStatus(e.target.value as StatusFilter)}>
<option value="any">Any</option>
<option value="paid">Paid</option>
<option value="unpaid">Unpaid (pending or partial)</option>
@@ -725,7 +729,7 @@ function WhatsAppAttendeesPageInner() {
<div>
<label className="block text-xs text-gray-600 mb-1">Message</label>
<textarea className="w-full border rounded px-3 py-2 text-sm" rows={8} value={message}
onChange={(e) => { setMessage(e.target.value); setMessageDirty(true); }}
onChange={(e) => { setMessage(e.target.value); messageDirtyRef.current = true; }}
placeholder="Write your WhatsApp message to attendees..." />
</div>
) : (
@@ -838,7 +842,7 @@ function WhatsAppAttendeesPageInner() {
try {
setError(null); setInfo(null); setBroadcastPreviewCount(null); setBroadcastPreviewSample(null);
if (!token) { setError("Not authenticated"); return; }
const res = await apiFetch(`/api/whatsapp-broadcasts/preview`, { method: "POST", authToken: token, body: { userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
const res = await apiFetch<MessageSendResult>(`/api/whatsapp-broadcasts/preview`, { method: "POST", authToken: token, body: { userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
setBroadcastPreviewCount(res?.matched ?? 0);
setBroadcastPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
setInfo(`Matched ${res?.matched ?? 0} recipient(s).`);
@@ -850,7 +854,7 @@ function WhatsAppAttendeesPageInner() {
setError(null); setInfo(null);
if (!token) { setError("Not authenticated"); return; }
if (!broadcastMessage.trim()) { setError("Message is required"); return; }
const res = await apiFetch(`/api/whatsapp-broadcasts/send`, { method: "POST", authToken: token, body: { message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
const res = await apiFetch<MessageSendResult>(`/api/whatsapp-broadcasts/send`, { method: "POST", authToken: token, body: { message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
setInfo(`Sent ${res?.sent ?? 0} out of ${res?.matched ?? 0} recipient(s).`);
resetBroadcastForm();
} catch (e) { setError(errorMessage(e) || "Failed to send"); }
@@ -862,7 +866,7 @@ function WhatsAppAttendeesPageInner() {
if (!token) { setError("Not authenticated"); return; }
if (!broadcastMessage.trim()) { setError("Message is required"); return; }
const whenIso = new Date(broadcastScheduledAtLocal).toISOString();
const res = await apiFetch(`/api/whatsapp-broadcasts/schedule`, { method: "POST", authToken: token, body: { scheduledAt: whenIso, message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
const res = await apiFetch<MessageSendResult>(`/api/whatsapp-broadcasts/schedule`, { method: "POST", authToken: token, body: { scheduledAt: whenIso, message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
if (res?.job?.id) setInfo("WhatsApp broadcast scheduled."); else setInfo("Scheduled.");
resetBroadcastForm();
} catch (e) { setError(errorMessage(e) || "Failed to schedule broadcast"); }
+17 -5
View File
@@ -257,8 +257,11 @@ export type RegistrationOption = {
quantity: number;
variantId?: string | null;
priceSnapshot?: number | null;
appliedTierId?: string | null;
eventOption?: EventOption;
variant?: OptionVariant | null;
// One entry per price the line was bought at (e.g. some before an early-bird tier expired).
tranches?: { id: string; quantity: number; priceSnapshot: number; appliedTierId?: string | null }[];
};
// A named person on a group registration, for one main-ticket place.
@@ -270,8 +273,8 @@ export type Attendee = {
consentRequests?: { id: string; status: "pending" | "given" | "declined" }[];
};
export type FormAnswer = { id: string; responseId?: string; fieldId: string; value: string };
export type FormResponse = { id: string; registrationId?: string; attendeeId?: string | null; createdAt?: string; answers?: FormAnswer[] };
export type FormAnswer = { id: string; responseId?: string; fieldId: string; value: string; field?: { label: string } | null };
export type FormResponse = { id: string; registrationId?: string; attendeeId?: string | null; createdAt: string; answers?: FormAnswer[] };
export type Registration = {
id: string;
@@ -280,7 +283,7 @@ export type Registration = {
status: RegistrationStatus;
discountTotal?: number;
ticketDelivery?: "payer" | "each";
createdAt?: string;
createdAt: string;
updatedAt?: string;
user?: UserSummary;
event?: Event;
@@ -303,7 +306,7 @@ export type Ticket = {
emailSent?: boolean;
attendeeId?: string | null;
holderUserId?: string | null;
createdAt?: string;
createdAt: string;
updatedAt?: string;
user?: UserSummary;
attendee?: { id: string; name: string; email?: string | null; phone?: string | null } | null;
@@ -325,7 +328,7 @@ export type Payment = {
status?: string | null;
externalId?: string | null;
originalPaymentId?: string | null;
createdAt?: string;
createdAt: string;
user?: UserSummary;
recordedBy?: UserSummary | null;
event?: Pick<Event, "id" | "title"> | null;
@@ -376,6 +379,15 @@ export type DashboardStats = {
activeEventsCount: number;
};
// What the email/WhatsApp send, preview and schedule endpoints return.
export type MessageSendResult<Recipient = { phone: string; name?: string }> = {
matched?: number;
queued?: number;
sent?: number;
recipients?: Recipient[];
job?: { id: string };
};
// A scanning section (e.g. "Main hall") and the ticket options valid at it.
export type Section = {
id: string;