diff --git a/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx b/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx index 21e5b5d..9bd901f 100644 --- a/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx @@ -1,12 +1,13 @@ "use client"; -import React, { useEffect, useMemo, useState } from "react"; +import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import { apiFetch } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { ClipboardList } from "lucide-react"; import { errorMessage } from "@/lib/utils"; +import type { Event, FormResponse, Registration } from "@/types"; const STATUS_OPTIONS = ["pending", "confirmed", "partial_paid", "paid", "cancelled"] as const; @@ -18,6 +19,16 @@ function fuzzyMatch(query: string, target: string): boolean { return tokens.every(tok => t.includes(tok)); } +// Backend attaches a tranche-aware totalDueComputed (exact even when a line spans multiple +// early-bird prices) — fall back to the old client-side estimate only for stale payloads. +const totalDueFor = (r: Registration) => r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => { + const unit = (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) + ? Number(opt.priceSnapshot) + : (opt.eventOption?.price || 0); + return sum + unit * (opt.quantity || 0); +}, 0); +const totalPaidFor = (r: Registration) => (r.payments || []).reduce((sum, p) => sum + (p.amount || 0), 0); + export default function AdminRegistrationsPage() { const { user, loading, token } = useAuth(); const router = useRouter(); @@ -29,8 +40,8 @@ export default function AdminRegistrationsPage() { if (!user) router.replace("/login"); }, [user, loading, router]); - const [registrations, setRegistrations] = useState([]); - const [events, setEvents] = useState([]); + const [registrations, setRegistrations] = useState([]); + const [events, setEvents] = useState([]); const [loadingRegs, setLoadingRegs] = useState(false); const [error, setError] = useDismissingState(null); const [info, setInfo] = useDismissingState(null); @@ -44,14 +55,14 @@ export default function AdminRegistrationsPage() { // Expanded rows + form responses cache const [expanded, setExpanded] = useState>(new Set()); - const [formResponses, setFormResponses] = useState>({}); + const [formResponses, setFormResponses] = useState>({}); const [loadingForms, setLoadingForms] = useState>(new Set()); - const loadRegistrations = async () => { + const loadRegistrations = useCallback(async () => { if (!token) return; try { setLoadingRegs(true); - const regs = await apiFetch("/api/registrations", { authToken: token }); + const regs = await apiFetch("/api/registrations", { authToken: token }); const list = Array.isArray(regs) ? regs.sort((a, b) => { const eventCompare = (a.event?.startDate || a.eventId).localeCompare(b.event?.startDate || b.eventId); if (eventCompare !== 0) return eventCompare; @@ -63,29 +74,29 @@ export default function AdminRegistrationsPage() { } finally { setLoadingRegs(false); } - }; + }, [token, setError]); - const loadEvents = async () => { + const loadEvents = useCallback(async () => { if (!token) return; try { const params = new URLSearchParams(); if (includePastEvents) params.set("includePast", "true"); if (includeInactiveEvents) params.set("includeInactive", "true"); const qs = params.toString() ? `?${params.toString()}` : ""; - const evs = await apiFetch(`/api/events/all${qs}`, { authToken: token }); - setEvents(Array.isArray(evs) ? evs.sort((a: any, b: any) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()) : []); + const evs = await apiFetch(`/api/events/all${qs}`, { authToken: token }); + setEvents(Array.isArray(evs) ? evs.sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()) : []); } catch {} - }; + }, [token, includePastEvents, includeInactiveEvents]); useEffect(() => { loadRegistrations(); - }, [token]); + }, [loadRegistrations]); useEffect(() => { loadEvents(); - }, [token, includePastEvents, includeInactiveEvents]); + }, [loadEvents]); - const toggleExpand = async (reg: any) => { + const toggleExpand = async (reg: Registration) => { const id = reg.id; const next = new Set(expanded); if (next.has(id)) { @@ -99,8 +110,8 @@ export default function AdminRegistrationsPage() { if (!formResponses[id] && !loadingForms.has(id)) { setLoadingForms(prev => new Set(prev).add(id)); try { - const res = await apiFetch(`/api/forms/responses?registrationId=${encodeURIComponent(id)}`, { authToken: token! }); - const items = Array.isArray(res?.items) ? res.items : (Array.isArray(res) ? res : []); + const res = await apiFetch<{ items?: FormResponse[] } | FormResponse[]>(`/api/forms/responses?registrationId=${encodeURIComponent(id)}`, { authToken: token! }); + const items = Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []); setFormResponses(prev => ({ ...prev, [id]: items })); } catch { setFormResponses(prev => ({ ...prev, [id]: [] })); @@ -110,7 +121,7 @@ export default function AdminRegistrationsPage() { } }; - const cancelRegistration = async (reg: any) => { + const cancelRegistration = async (reg: Registration) => { if (!token) return; setError(null); setInfo(null); if (!confirm(`Cancel registration #${String(reg.id).slice(0, 8)} for ${reg.user?.name || reg.userId}?`)) return; @@ -123,7 +134,7 @@ export default function AdminRegistrationsPage() { } }; - const updateStatus = async (reg: any, status: string) => { + const updateStatus = async (reg: Registration, status: string) => { if (!token) return; setError(null); setInfo(null); try { @@ -135,10 +146,10 @@ export default function AdminRegistrationsPage() { } }; - const eventIds = useMemo(() => new Set(events.map((ev: any) => ev.id)), [events]); + const eventIds = useMemo(() => new Set(events.map((ev) => ev.id)), [events]); const filtered = useMemo(() => { - return registrations.filter((r: any) => { + return registrations.filter((r) => { if (!eventIds.has(r.eventId)) return false; if (eventFilter && r.eventId !== eventFilter) return false; if (statusFilter && r.status !== statusFilter) return false; @@ -146,10 +157,10 @@ export default function AdminRegistrationsPage() { const haystack = [ r.id, r.user?.name, r.user?.email, r.user?.phoneNumber, r.userId, r.event?.title, r.eventId, r.status, - ].map((x: any) => String(x || "")).join(" "); + ].map((x) => String(x || "")).join(" "); return fuzzyMatch(query.trim(), haystack); }); - }, [registrations, query, eventFilter, statusFilter]); + }, [registrations, query, eventFilter, statusFilter, eventIds]); const statusColor = (s: string) => { if (s === "paid") return "text-green-700 bg-green-50"; @@ -159,15 +170,6 @@ export default function AdminRegistrationsPage() { return "text-gray-700 bg-gray-50"; }; - // Backend attaches a tranche-aware totalDueComputed (exact even when a line spans multiple - // early-bird prices) — fall back to the old client-side estimate only for stale payloads. - const totalDueFor = (r: any) => r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum: number, opt: any) => { - const unit = (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) - ? Number(opt.priceSnapshot) - : (opt.eventOption?.price || 0); - return sum + unit * (opt.quantity || 0); - }, 0); - const totalPaidFor = (r: any) => (r.payments || []).reduce((sum: number, p: any) => sum + (p.amount || 0), 0); // Aggregate stats across the currently filtered registrations — counts by status, plus // revenue/outstanding totals (cancelled registrations are excluded from the money totals @@ -176,7 +178,7 @@ export default function AdminRegistrationsPage() { const counts: Record = {}; let totalRevenue = 0; let totalOutstanding = 0; - filtered.forEach((r: any) => { + filtered.forEach((r) => { counts[r.status] = (counts[r.status] || 0) + 1; if (r.status === "cancelled") return; const due = totalDueFor(r); @@ -276,7 +278,7 @@ export default function AdminRegistrationsPage() {
    - {filtered.map((r: any) => { + {filtered.map((r) => { const totalDue = totalDueFor(r); const totalPaid = totalPaidFor(r); const outstanding = Math.max(totalDue - totalPaid, 0); @@ -337,7 +339,7 @@ export default function AdminRegistrationsPage() {
    Ticket options
    - {r.registrationOptions.map((opt: any) => { + {(r.registrationOptions || []).map((opt) => { // A line can span multiple price tranches (e.g. tickets bought // before and after an early-bird tier expired) — show one row per // tranche so its own price/tier status is accurate, not blended. @@ -357,7 +359,7 @@ export default function AdminRegistrationsPage() { {opt.eventOption?.name || opt.eventOptionId} {opt.variant?.name && ({opt.variant.name})}
    - {tranches.map((t: any, idx: number) => { + {tranches.map((t, idx) => { const unit = Number(t.priceSnapshot || 0); return (
    @@ -383,7 +385,7 @@ export default function AdminRegistrationsPage() {
    No payments recorded.
    ) : (
    - {r.payments.map((p: any) => ( + {(r.payments || []).map((p) => (
    {p.amount < 0 ? '-' : ''}R {Math.abs(p.amount).toFixed(2)} · {p.method || 'payment'} @@ -410,11 +412,11 @@ export default function AdminRegistrationsPage() {
    No form responses submitted.
    ) : (
    - {responses.map((resp: any, idx: number) => ( + {responses.map((resp, idx) => (
    Response #{idx + 1}
    - {(resp.answers || []).map((a: any) => ( + {(resp.answers || []).map((a) => (
    {a.field?.label || a.fieldId}
    {a.value}
    diff --git a/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx index 557ffc9..25549e1 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx @@ -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; 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([]); + const [allEvents, setAllEvents] = useState([]); 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("/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("/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('custom'); const [showInfo, setShowInfo] = useState(false); // Broadcasts state @@ -270,7 +276,7 @@ function EmailAttendeesPageInner() { const [editWhen, setEditWhen] = useState(''); 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("any"); const [groupId, setGroupId] = useState(""); // Attendees list and selection const [attendees, setAttendees] = useState([]); @@ -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(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token }); + const regs = await apiFetch(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token }); const uniq = new Map(); - (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(`/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(`/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
    - setTemplateKey(e.target.value as TemplateKey)}> @@ -600,7 +603,7 @@ function EmailAttendeesPageInner() {
    - setStatus(e.target.value as StatusFilter)}> @@ -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(`/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 {previewCount != null && ( @@ -778,13 +781,13 @@ Jane Doe 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(`/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 @@ -794,14 +797,14 @@ Jane Doe 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(`/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 @@ -812,14 +815,14 @@ Jane Doe 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(`/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 @@ -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(''); - 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`); @@ -1136,7 +1140,7 @@ With gratitude`); setEnableFinal(e.target.checked)} /> Enable - setFinalHours(e.target.value as '24'|'48')}> @@ -1200,7 +1204,7 @@ With gratitude`); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx index 72ac84b..8d4f0c9 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx @@ -298,8 +298,8 @@ export default function FormsBrowserPage() { setFormDef({ isRequired: false, fields: [] }); } setFormLoadedFor(eventId); - } catch (e:any) { - setError(e?.message || 'Failed to load form'); + } catch (e) { + setError(errorMessage(e) || 'Failed to load form'); } finally { setFormLoading(false); } @@ -318,8 +318,8 @@ export default function FormsBrowserPage() { const fields = (formDef.fields || []).filter(f => (f.label || '').trim().length > 0).map((f, i) => ({ type: f.type, label: f.label, isRequired: !!f.isRequired && f.type !== 'statement' && f.type !== 'paragraph', order: i, helpText: f.helpText || null, options: f.type === 'multiple_choice' && Array.isArray(f.options) ? f.options.map((o: any) => String(o).trim()).filter(Boolean) : undefined })); await apiFetch(`/api/events/${encodeURIComponent(selectedEventId)}`, { method: 'PUT', authToken: token, body: { form: { isRequired: !!formDef.isRequired, fields } } }); setInfo('Form saved'); - } catch (e:any) { - setError(e?.message || 'Failed to save form'); + } catch (e) { + setError(errorMessage(e) || 'Failed to save form'); } }; @@ -375,8 +375,8 @@ export default function FormsBrowserPage() { const resList = await apiFetch(`/api/forms/responses?registrationId=${encodeURIComponent(fillRegistrationId)}`, { authToken: token! }); const items = Array.isArray(resList?.items) ? resList.items : (Array.isArray(resList) ? resList : []); setExistingResponses(items); - } catch (e:any) { - setError(e?.message || 'Failed to load registration/form'); + } catch (e) { + setError(errorMessage(e) || 'Failed to load registration/form'); } })(); }, [fillRegistrationId, mode]); @@ -435,8 +435,8 @@ export default function FormsBrowserPage() { const resList = await apiFetch(`/api/forms/responses?registrationId=${encodeURIComponent(fillRegistrationId)}`, { authToken: token! }); const items = Array.isArray(resList?.items) ? resList.items : (Array.isArray(resList) ? resList : []); setExistingResponses(items); - } catch (e:any) { - setError(e?.message || 'Failed to save responses'); + } catch (e) { + setError(errorMessage(e) || 'Failed to save responses'); } finally { setSavingFill(false); } diff --git a/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx index ae48b19..e0d1ced 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx @@ -619,8 +619,8 @@ function PaymentsContent() { await apiFetch(`/api/yoco-transactions/${encodeURIComponent(tx.id)}/ignore`, { method: 'POST', authToken: token }); setInfo('Transaction ignored'); await loadYocoUnreconciled(); - } catch (e:any) { - setError(e?.message || 'Failed to ignore'); + } catch (e) { + setError(errorMessage(e) || 'Failed to ignore'); } }}>Ignore diff --git a/apps/events/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx index a8be25a..8d98cc0 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { Suspense, useEffect, useMemo, useState } from "react"; +import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter, useSearchParams } from "next/navigation"; import { apiFetch, fetchAllUsers } from "@/lib/api"; @@ -8,10 +8,14 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { MessageCircle, Users, Zap, Send, Clock, type LucideIcon } from "lucide-react"; import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter"; import { errorMessage } from "@/lib/utils"; +import type { Event, MessageSendResult, Registration, User } from "@/types"; // Attendee with preference info type Attendee = { id: string; name: string; phone: string; pref: string }; type UserEntry = { id: string; name: string; phone: string; pref: string }; +type TemplateKey = "custom" | "payment_reminder" | "event_reminder" | "tickets"; +type StatusFilter = "any" | "paid" | "unpaid" | "partial_paid" | "cancelled"; +type MessageFilter = { status?: Exclude; attendeeIds?: string[]; allocationGroupId?: string }; const WA_TAB_ICONS: Record<"attendees" | "automations" | "broadcasts" | "scheduled", LucideIcon> = { attendees: Users, @@ -161,16 +165,14 @@ function AttendeesCheckboxDropdown({ // ─── Preference warning banner ──────────────────────────────────────────────── function PrefWarning({ attendees, selectedIds, channel }: { attendees: (Attendee|UserEntry)[]; selectedIds: string[]; channel: "whatsapp" | "email" }) { - const prefMatch = (pref: string) => - channel === "whatsapp" ? pref === "whatsapp" || pref === "both" : pref === "email" || pref === "both"; - - const mismatched = useMemo( - () => selectedIds.filter((id) => { + const mismatched = useMemo(() => { + const prefMatch = (pref: string) => + channel === "whatsapp" ? pref === "whatsapp" || pref === "both" : pref === "email" || pref === "both"; + return selectedIds.filter((id) => { const a = attendees.find((x) => x.id === id); return a && !prefMatch(a.pref); - }), - [attendees, selectedIds, channel] - ); + }); + }, [attendees, selectedIds, channel]); if (mismatched.length === 0) return null; return ( @@ -189,9 +191,9 @@ function PrefWarning({ attendees, selectedIds, channel }: { attendees: (Attendee } // ─── WhatsApp Automations Panel ─────────────────────────────────────────────── -function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[]; token?: string | null; onInfo: (s: string) => void; onError: (s: string) => void }) { +function WAAutomationsPanel({ events, token, onInfo, onError }: { events: Event[]; token?: string | null; onInfo: (s: string | null) => void; onError: (s: string | null) => void }) { const [autoEventId, setAutoEventId] = React.useState(""); - const currentEvent = React.useMemo(() => (events || []).find((e: any) => e.id === autoEventId), [events, autoEventId]); + const currentEvent = React.useMemo(() => (events || []).find((e) => e.id === autoEventId), [events, autoEventId]); const preWeekDefault = `Hi {{name}}\n\nJust a friendly reminder that {{event.title}} is one week away!\n\nEvent details: {{event.link}}`; const finalDefault = `Hi {{name}}\n\nFinal reminder for {{event.title}}.\nPlease have your QR code/ticket ready at entry.\n\nEvent details: {{event.link}}`; @@ -231,10 +233,10 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[]; const onSchedule = async () => { try { - onError(null as any); onInfo(null as any); + onError(null); onInfo(null); if (!token) { onError("Not authenticated"); return; } if (!autoEventId) { onError("Please select an event"); return; } - const jobs: any[] = []; + const jobs: { message: string; scheduledAt: string; promoEventId?: string }[] = []; if (enablePre && preBody.trim() && preWhen) jobs.push({ message: preBody, scheduledAt: new Date(preWhen).toISOString() }); if (enableFinal && finalBody.trim() && finalWhen) jobs.push({ message: finalBody, scheduledAt: new Date(finalWhen).toISOString() }); if (enableThanks && thanksBody.trim() && thanksWhen) jobs.push({ message: thanksBody, scheduledAt: new Date(thanksWhen).toISOString() }); @@ -260,7 +262,7 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[]; @@ -287,7 +289,7 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[]; setEnableFinal(e.target.checked)} /> Enable - setFinalHours(e.target.value as "24" | "48")}> @@ -325,7 +327,7 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[]; @@ -373,7 +375,7 @@ function WhatsAppAttendeesPageInner() { const [info, setInfo] = useDismissingState(null); const [tab, setTab] = useState<"attendees" | "automations" | "broadcasts" | "scheduled">("attendees"); const [loadingEvents, setLoadingEvents] = useState(false); - const [allEvents, setAllEvents] = useState([]); + const [allEvents, setAllEvents] = useState([]); const [evIncludePast, setEvIncludePast] = useState(false); const events = useMemo(() => { @@ -386,8 +388,8 @@ function WhatsAppAttendeesPageInner() { const loadEvents = async () => { try { setLoadingEvents(true); - const evs = await apiFetch("/api/events/all?includePast=true", { authToken: token || undefined }); - setAllEvents((evs || []).sort((a: any, b: any) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime())); + const evs = await apiFetch("/api/events/all?includePast=true", { authToken: token || undefined }); + setAllEvents((evs || []).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime())); } catch (e) { setError(errorMessage(e) || "Failed to load events"); } finally { @@ -395,15 +397,17 @@ function WhatsAppAttendeesPageInner() { } }; loadEvents(); - }, [user, token]); + }, [user, token, setError]); // ── Attendees tab ────────────────────────────────────────────────────────── const [eventId, setEventId] = useState(preselectEventId); useEffect(() => { if (preselectEventId) setEventId(preselectEventId); }, [preselectEventId]); - const [templateKey, setTemplateKey] = useState<"custom" | "payment_reminder" | "event_reminder" | "tickets">("custom"); + const [templateKey, setTemplateKey] = useState("custom"); const [message, setMessage] = useState(""); - const [messageDirty, setMessageDirty] = useState(false); - const [status, setStatus] = useState<"any" | "paid" | "unpaid" | "partial_paid" | "cancelled">("any"); + // Set once the supervisor edits the message, so picking a template doesn't overwrite it. + // A ref, not state: it only gates the template effect below and is never rendered. + const messageDirtyRef = useRef(false); + const [status, setStatus] = useState("any"); const [groupId, setGroupId] = useState(""); const [attendees, setAttendees] = useState([]); const [selectedAttendeeIds, setSelectedAttendeeIds] = useState([]); @@ -419,11 +423,11 @@ function WhatsAppAttendeesPageInner() { useEffect(() => { const title = currentEvent?.title || "the event"; if (templateKey === "payment_reminder") { - if (!messageDirty) setMessage(`Hi {{name}}\n\nFriendly reminder: you have an outstanding balance for ${title}.\n\nPlease settle your balance to secure your tickets. Thank you!`); + if (!messageDirtyRef.current) setMessage(`Hi {{name}}\n\nFriendly reminder: you have an outstanding balance for ${title}.\n\nPlease settle your balance to secure your tickets. Thank you!`); } else if (templateKey === "event_reminder") { - if (!messageDirty) setMessage(`Hi {{name}}\n\nA quick reminder about ${title}.\nStart: {{event.start}}\n\nWe look forward to seeing you!`); + if (!messageDirtyRef.current) setMessage(`Hi {{name}}\n\nA quick reminder about ${title}.\nStart: {{event.start}}\n\nWe look forward to seeing you!`); } else if (templateKey === "tickets") { - setMessageDirty(false); setMessage(""); + messageDirtyRef.current = false; setMessage(""); } }, [templateKey, currentEvent]); @@ -432,10 +436,10 @@ function WhatsAppAttendeesPageInner() { try { setLoadingAttendees(true); setAttendees([]); setSelectedAttendeeIds([]); if (!eventId || !token) return; - const regs = await apiFetch(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token }); + const regs = await apiFetch(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token }); const uniq = new Map(); - (regs || []).forEach((r: any) => { - const u = r?.user; + (regs || []).forEach((r) => { + const u: User | undefined = r?.user; if (u?.id && u?.phoneNumber && !u.email?.endsWith("@guest.local") && u.isActive !== false) { uniq.set(u.id, { id: u.id, name: u.name || "", phone: u.phoneNumber, pref: u.notificationPreference || "email" }); } @@ -451,7 +455,7 @@ function WhatsAppAttendeesPageInner() { }, [eventId, token]); const buildPayload = (dryRun?: boolean) => { - const payload: any = { + const payload: { filter: MessageFilter; template: TemplateKey; dryRun?: boolean; message?: string } = { filter: { status: status !== "any" ? status : undefined, attendeeIds: selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined }, template: templateKey, dryRun: dryRun || undefined, @@ -466,7 +470,7 @@ function WhatsAppAttendeesPageInner() { if (!token) { setError("Not authenticated"); return; } if (!eventId) { setError("Please select an event"); return; } if (templateKey !== "tickets" && !message.trim()) { setError("Message is required"); return; } - const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload(true) }); + const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload(true) }); setPreviewCount(res?.matched ?? 0); setPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null); setInfo(`Matched ${res?.matched ?? 0} recipient(s) with a phone number.`); @@ -474,7 +478,7 @@ function WhatsAppAttendeesPageInner() { }; const resetAttendeesForm = () => { - setTemplateKey("custom"); setMessage(""); setMessageDirty(false); + setTemplateKey("custom"); setMessage(""); messageDirtyRef.current = false; setStatus("any"); setScheduledAtLocal(""); setPreviewCount(null); setPreviewSample(null); setSelectedAttendeeIds(attendees.map((a) => a.id)); }; @@ -486,7 +490,7 @@ function WhatsAppAttendeesPageInner() { if (!eventId) { setError("Please select an event"); return; } if (templateKey !== "tickets" && !message.trim()) { setError("Message is required"); return; } setSending(true); - const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload() }); + const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload() }); setInfo(`Queued ${res?.queued ?? res?.matched ?? 0} recipient(s) for sending.`); resetAttendeesForm(); } catch (e) { setError(errorMessage(e) || "Failed to send"); } finally { setSending(false); } @@ -500,12 +504,12 @@ function WhatsAppAttendeesPageInner() { if (templateKey !== "tickets" && !message.trim()) { setError("Message is required"); return; } if (!scheduledAtLocal) { setError("Scheduled time is required"); return; } const whenIso = new Date(scheduledAtLocal).toISOString(); - const payload: any = { + const payload: { message?: string; filter: MessageFilter; template: TemplateKey; scheduledAt: string } = { message: message || undefined, filter: { status: status !== "any" ? status : undefined, attendeeIds: selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined }, template: templateKey, scheduledAt: whenIso, }; - const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees/schedule`, { method: "POST", authToken: token, body: payload }); + const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees/schedule`, { method: "POST", authToken: token, body: payload }); setInfo(res?.job?.id ? "WhatsApp scheduled. It will be sent around the specified time." : "Scheduled."); resetAttendeesForm(); } catch (e) { setError(errorMessage(e) || "Failed to schedule"); } @@ -529,9 +533,9 @@ function WhatsAppAttendeesPageInner() { setLoadingUsers(true); const allUsers = await fetchAllUsers(token); const mapped = allUsers - .filter((u: any) => u.isActive !== false && !u.email?.endsWith("@guest.local") && u.phoneNumber) - .map((u: any) => ({ id: u.id, name: u.name || "", phone: u.phoneNumber, pref: u.notificationPreference || "email" })) - .sort((a: any, b: any) => (a.name || "").localeCompare(b.name || "", undefined, { sensitivity: "base" })); + .filter((u) => u.isActive !== false && !u.email?.endsWith("@guest.local") && u.phoneNumber) + .map((u) => ({ id: u.id, name: u.name || "", phone: u.phoneNumber || "", pref: u.notificationPreference || "email" })) + .sort((a, b) => (a.name || "").localeCompare(b.name || "", undefined, { sensitivity: "base" })); setUsers(mapped); } catch { } finally { setLoadingUsers(false); } }; @@ -553,23 +557,23 @@ function WhatsAppAttendeesPageInner() { const [editWhen, setEditWhen] = useState(""); const [savingEdit, setSavingEdit] = useState(false); - const loadScheduled = async () => { + const loadScheduled = useCallback(async () => { try { if (!token) return; setLoadingScheduled(true); const res = await apiFetch<{ jobs: ScheduledJob[] }>(`/api/scheduled-emails?channel=whatsapp`, { authToken: token }); setScheduled(Array.isArray(res?.jobs) ? res.jobs : []); } catch { } finally { setLoadingScheduled(false); } - }; + }, [token]); - useEffect(() => { if (tab === "scheduled") loadScheduled(); }, [tab, token]); + useEffect(() => { if (tab === "scheduled") loadScheduled(); }, [tab, loadScheduled]); const saveEdit = async () => { if (!editing) return; try { setSavingEdit(true); if (!token) { setError("Not authenticated"); return; } - const body: any = {}; + const body: { scheduledAt?: string; message?: string } = {}; if (editWhen) body.scheduledAt = new Date(editWhen).toISOString(); if (editMessage.trim()) body.message = editMessage; await apiFetch(`/api/scheduled-emails/${encodeURIComponent(editing.id)}`, { method: "PATCH", authToken: token, body }); @@ -664,7 +668,7 @@ function WhatsAppAttendeesPageInner() { Info
    - setTemplateKey(e.target.value as TemplateKey)}> @@ -710,7 +714,7 @@ function WhatsAppAttendeesPageInner() {
    - setStatus(e.target.value as StatusFilter)}> @@ -725,7 +729,7 @@ function WhatsAppAttendeesPageInner() {