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 b2439a781e
commit b560d0d340
6 changed files with 196 additions and 174 deletions
@@ -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>