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