"use client"; import React, { useEffect, useMemo, useRef, useState } from "react"; import { useSearchParams } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; import { apiFetch, API_BASE, fetchManagedEvents } from "@/lib/api"; import { downloadReportExcel, emailReportPdf, whatsappReportPdf, viewReportPdf, type ReportPdfPayload } from "@/lib/export"; import { Printer, Mail, FileSpreadsheet, MessageCircle, ShoppingCart, CreditCard, Gift, Clock, HandHeart, Search, TrendingUp, TicketPercent, ShieldCheck, Star, MessageSquareHeart, Send, Eye, MousePointerClick, BadgeCheck, Users, Ticket as TicketIcon } from "lucide-react"; import { REPORTS, type ReportKey } from "./ReportCatalog"; import ReportsShell from "./ReportsShell"; import ReportViewerModal, { ReportActionButton } from "./ReportViewerModal"; import { StatTile, StatTileRow } from "./StatTile"; import { HorizontalBarChart } from "./charts/HorizontalBarChart"; import { AreaTrendChart } from "@/components/charts/AreaTrendChart"; import { errorMessage } from "@/lib/utils"; import { registrationOptionUnitPrice } from "@/lib/pricing"; import { CampusFilter, matchesCampus } from "@/components/shared/CampusFilter"; import { SavedFilters } from "@/components/shared/SavedFilters"; import type { ConsentRow, Event, EventCashup, EventFinancials, EventSeries, MedicalRow, Payment, Registration, SeriesComparison, Ticket, UserSummary } from "@/types"; const METHOD_KEYS = ["cash", "card", "eft", "other"] as const; const METHOD_LABEL: Record = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" }; const WRITE_OFF_LABEL: Record = { card_fees: "Card / online fees", bank_charges: "Bank charges", cash_shortfall: "Cash shortfall", other: "Other" }; function denomLabel(v: number): string { return v >= 1 ? `R${v}` : `${Math.round(v * 100)}c`; } function money2(n: number | null | undefined): string { return `R${Number(n || 0).toFixed(2)}`; } // A donation is never mutated once created — assigning it to a registration creates a separate // "leg" Payment row (isDonation:false, originalPaymentId -> the donation, amount > 0) instead. // That leg is not new money: it just re-labels part of an already-counted donation as applied // to a registration. Aggregate revenue/received totals must count each real inflow exactly // once, so legs are excluded — the money was already counted via the original donation row. // (Refunds also set originalPaymentId, but always with a negative amount, so they're unaffected.) function isDonationLeg(p: Payment): boolean { return !p?.isDonation && !!p?.originalPaymentId && (p?.amount || 0) > 0; } function actionLabel(action: string): string { return action === "closed" ? "Closed (full cashup)" : action === "quick_closed" ? "Quick closed" : "Reopened"; } // Annotates closed/quick_closed audit rows with the per-method delta versus the previous // close for the same event, so the audit trail shows differences between successive cashups. function computeAuditDeltas(rows: AuditRow[]): AuditRow[] { const byEvent: Record = {}; rows.forEach(r => { (byEvent[r.eventId] = byEvent[r.eventId] || []).push(r); }); Object.values(byEvent).forEach(list => { list.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()); let prevClose: AuditRow | null = null; list.forEach(r => { if (r.action === "closed" || r.action === "quick_closed") { if (prevClose) { const delta: Record = {}; METHOD_KEYS.forEach(m => { const curLine = (r.lines || []).find((l) => l.method === m); const prevLine = (prevClose?.lines || []).find((l) => l.method === m); const curActual = curLine?.actualAmount; const prevActual = prevLine?.actualAmount; delta[m] = (curActual != null && prevActual != null) ? curActual - prevActual : null; }); r._deltaVsPrevious = delta; r._previousCloseAt = prevClose?.createdAt; } prevClose = r; } }); }); return rows; } // Effective per-unit price for a registration option — shared with the Payments page. const optionUnitPrice = registrationOptionUnitPrice; // ─── Rows the reports derive from loaded data ──────────────────────────────── type PaymentRow = { eventId: string; eventTitle: string; userName: string; userEmail?: string; amount: number; method: string; isDonation?: boolean; createdAt: string; recordedByName: string }; type RevenueDetailRow = { eventId: string; eventTitle: string; userName: string; userEmail?: string; totalPaid: number; status?: string; registrationId: string; outstanding: number }; type AttendeeLayerOption = { optionName: string; users: { name: string; email?: string; status: string; qty: number }[] }; type MasterRow = { eventTitle: string; name: string; email?: string; orderTotal: number; totalPaid: number; outstanding: number; paidViaDonation: number; // Quantity and tranche-aware revenue per option name (the table's dynamic columns). qty: Record; revenue: Record; }; // ─── API shapes used only by reports ───────────────────────────────────────── // GET /api/cashups/audit, annotated by computeAuditDeltas with the change since the previous close. type AuditRow = EventCashup & { _deltaVsPrevious?: Record; _previousCloseAt?: string; }; // GET /api/coupons/redemptions — active coupon uses and bundle deals, with a readable summary. // For a bundle, coupon.code is the bundle name and uses is how many times it applied. type DiscountRow = { id: string; kind?: "coupon" | "bundle"; uses?: number; discountAmount: number; createdAt: string; summary?: string; coupon?: { id: string; code: string; type?: string; value?: number } | null; user?: { id: string; name: string; email: string } | null; appliedBy?: { id: string; name: string } | null; registration?: { id: string; status: string; event?: { id: string; title: string } | null } | null; }; // GET /api/feedback/summary — one entry per event with a feedback form. type FeedbackQuestion = { fieldId: string; type: string; label: string; answered: number; average?: number | null; distribution?: { label: string; value: number }[]; counts?: { label: string; value: number }[]; texts?: { value: string; name?: string }[]; }; type FeedbackEventSummary = { eventId: string; title: string; startDate: string; anonymous: boolean; sentAt: string | null; invited: number; responses: number; responseRate: number | null; questions: FeedbackQuestion[]; }; // GET /api/analytics/funnel — session counts per stage. type FunnelCounts = { view: number; start: number; submit: number; paid: number }; type FunnelConversion = { start: number | null; submit: number | null; paid: number | null; startToSubmit: number | null; submitToPaid: number | null }; type FunnelReport = { totals: FunnelCounts; conversion: FunnelConversion; trend: (FunnelCounts & { day: string })[]; bySource: (FunnelCounts & { key: string; conversion: number | null })[]; byDevice: (FunnelCounts & { key: string; conversion: number | null })[]; byOption: { key: string; submitted: number; paid: number }[]; perEvent?: { eventId: string; title: string; totals: FunnelCounts; conversion: FunnelConversion }[]; }; /** "+12%", "−5%", "no change" — a year-on-year change. */ const changeLabel = (c: number) => (c > 0 ? `+${c}%` : c < 0 ? `−${Math.abs(c)}%` : "no change"); // Simple MultiSelect control used in filters export default function ReportsV2({ backHref }: { backHref?: string } = {}) { const { token, user } = useAuth(); const role = user?.role || "user"; const canView = role === "admin" || role === "supervisor"; const searchParams = useSearchParams(); // Events list const [events, setEvents] = useState([]); const [error, setError] = useState(null); const [showPastEvents, setShowPastEvents] = useState(false); const [showInactiveEvents, setShowInactiveEvents] = useState(false); // Unlike past/inactive, closed (cashed-up) events are shown by default — they're normal // historical data for most reports (Payments, Attendees, Revenue, etc.), and the // Cashup/Finance/Profit reports specifically exist to review already-closed events, so // hiding them by default would work against those reports' whole purpose. This toggle // lets staff exclude them when they only want currently-open events. const [showClosedEvents, setShowClosedEvents] = useState(true); // Multi-campus: one campus's events, church-wide ones, or all (the church-wide total). const [campus, setCampus] = useState(""); const isAdmin = role === "admin"; const filteredEvents = useMemo(() => { const now = new Date(); return events.filter(ev => { if (!showPastEvents && ev.endDate && new Date(ev.endDate) < now) return false; if (!showInactiveEvents && ev.isActive === false) return false; if (!showClosedEvents && ev.cashupStatus === "closed") return false; if (!matchesCampus(ev, campus)) return false; return true; }); }, [events, showPastEvents, showInactiveEvents, showClosedEvents, campus]); useEffect(() => { (async () => { try { const evs = await fetchManagedEvents(token || undefined, { past: true, inactive: true }); setEvents(Array.isArray(evs) ? evs : []); } catch (e) { setError(errorMessage(e) || "Failed to load events"); } })(); }, [token, role]); // General state for UI flow const [report, setReport] = useState("payments"); const [ready, setReady] = useState(false); // toggled by View button const [busy, setBusy] = useState(false); const [popupOpen, setPopupOpen] = useState(false); // Universal filters — apply to every report's onView loader (per-report filters below stay // report-specific). A single events selection replaces what used to be ~10 separate // per-report "Events" multi-selects, and a single date range replaces payFrom/payTo and // auditFrom/auditTo — both now live in the sidebar (ReportsShell) instead of being re-picked // per report. const [selectedEventIds, setSelectedEventIds] = useState([]); const [dateFrom, setDateFrom] = useState(""); const [dateTo, setDateTo] = useState(""); // Back-compat aliases so the many existing date-filtered useMemo/CSV/PDF/email blocks below // (written against payFrom/payTo/auditFrom/auditTo) don't all need renaming. const payFrom = dateFrom, payTo = dateTo, auditFrom = dateFrom, auditTo = dateTo; // Attendees (single-event report — defaults to the first universally-selected event, with // its own picker in the popup if more than one event is selected) const [attEventId, setAttEventId] = useState(""); const [attIncludeCancelled, setAttIncludeCancelled] = useState(false); // Master orders breakdown — in-popup search boxes for the Orders / Donations made tables const [masterOrderSearch, setMasterOrderSearch] = useState(""); const [masterDonationSearch, setMasterDonationSearch] = useState(""); // Registration status breakdown const [statusIncludeCancelled, setStatusIncludeCancelled] = useState(true); const [statusCountMode, setStatusCountMode] = useState<'registrations' | 'tickets'>('registrations'); // 'registrations' mode: one count per registration row. 'tickets' mode: sum of ticket // quantity across the registration's options, so someone with 3 tickets counts as 3. const countForStatus = (r: Registration) => statusCountMode === 'tickets' ? (r.registrationOptions || []).reduce((s, ro) => s + (ro.quantity || 0), 0) : 1; // Data stores const [paymentsByEvent, setPaymentsByEvent] = useState>({}); const [registrationsByEvent, setRegistrationsByEvent] = useState>({}); const [ticketUsage, setTicketUsage] = useState>({}); const [financialsByEvent, setFinancialsByEvent] = useState>({}); const [auditRows, setAuditRows] = useState([]); const [discountRows, setDiscountRows] = useState([]); // Youth events (one row per attendee), each tagged with its event title. const [consentRows, setConsentRows] = useState<(ConsentRow & { eventTitle: string })[]>([]); const [medicalRows, setMedicalRows] = useState<(MedicalRow & { eventTitle: string })[]>([]); // Post-event feedback, one entry per event that had a feedback form. const [feedbackRows, setFeedbackRows] = useState([]); // Registration funnel for the selected events (null until viewed). const [funnel, setFunnel] = useState(null); // Series: year on year — picked by series, not by the events selection. const [seriesList, setSeriesList] = useState([]); const [compareSeriesId, setCompareSeriesId] = useState(""); const [comparison, setComparison] = useState(null); useEffect(() => { if (!token) return; apiFetch("/api/series", { authToken: token }).then(l => { const list = Array.isArray(l) ? l : []; setSeriesList(list); setCompareSeriesId(id => id || list[0]?.id || ""); }).catch(() => {}); }, [token]); // Deep-linking: dashboards link here with ?report=&range=trailing_month to jump // straight into a specific report, pre-filtered to every currently-visible event and the // trailing month (today back one month, matching the dashboard KPI window — see // trailingMonthRanges in backend/src/controllers/statsController.js), instead of landing // on the plain report grid. deepLinkHandledRef is a ref (not state) so it updates // synchronously — the "Initialize default selection" effect right below reads it in the // same commit to skip its own single-event default. const deepLinkHandledRef = useRef(false); const [autoViewPending, setAutoViewPending] = useState(false); useEffect(() => { if (deepLinkHandledRef.current) return; if (filteredEvents.length === 0) return; const reportParam = searchParams.get("report"); if (!reportParam || !REPORTS.some(r => r.key === reportParam)) return; deepLinkHandledRef.current = true; setReport(reportParam as ReportKey); setSelectedEventIds(filteredEvents.map((e) => e.id)); const seriesParam = searchParams.get("series"); if (seriesParam) setCompareSeriesId(seriesParam); if (searchParams.get("range") === "trailing_month") { const now = new Date(); const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 30); const iso = (d: Date) => d.toISOString().slice(0, 10); setDateFrom(iso(start)); setDateTo(iso(now)); } setPopupOpen(true); setAutoViewPending(true); }, [filteredEvents, searchParams]); // Fires once the state set above has actually committed (selectedEventIds reflects the // deep-link's full event list), so onView() below closes over the updated values instead // of the stale defaults from the render that scheduled it. useEffect(() => { if (!autoViewPending || selectedEventIds.length === 0) return; setAutoViewPending(false); onView(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [autoViewPending, selectedEventIds, report]); // Initialize default selection when events load (functional updates, so this only // reacts to the event list changing and never overrides a choice already made). useEffect(() => { if (filteredEvents.length === 0) return; if (!deepLinkHandledRef.current) setSelectedEventIds(ids => ids.length === 0 ? filteredEvents.slice(0, 1).map((e) => e.id) : ids); setAttEventId(id => id || filteredEvents[0].id); }, [filteredEvents]); // Attendees' single-event picker defaults to (and stays within) the universal selection. useEffect(() => { setAttEventId(id => selectedEventIds.length > 0 && !selectedEventIds.includes(id) ? selectedEventIds[0] : id); }, [selectedEventIds]); // Loaders const loadPayments = async (eventIds: string[]) => { if (!token || !eventIds.length) return {} as Record; const byEv: Record = {}; for (const id of eventIds) { try { const list = await apiFetch(`/api/payments/event/${encodeURIComponent(id)}`, { authToken: token }); byEv[id] = Array.isArray(list) ? list : []; } catch { byEv[id] = []; } } return byEv; }; const loadRegistrations = async (eventIds: string[]) => { if (!token || !eventIds.length) return {} as Record; const byEv: Record = {}; for (const id of eventIds) { try { const list = await apiFetch(`/api/registrations/event/${encodeURIComponent(id)}`, { authToken: token }); byEv[id] = Array.isArray(list) ? list : []; } catch { byEv[id] = []; } } return byEv; }; const loadTicketUsage = async (eventIds: string[]) => { if (!token || !eventIds.length) return {} as Record; const result: Record = {}; for (const id of eventIds) { try { const tickets = await apiFetch(`/api/tickets/event/${encodeURIComponent(id)}`, { authToken: token }); result[id] = { used: tickets.filter(t => t.isUsed).length, unused: tickets.filter(t => !t.isUsed).length }; } catch { result[id] = { used: 0, unused: 0 }; } } return result; }; const loadFinancials = async (eventIds: string[]) => { if (!token || !eventIds.length) return {} as Record; const byEv: Record = {}; for (const id of eventIds) { try { byEv[id] = await apiFetch(`/api/cashups/event/${encodeURIComponent(id)}`, { authToken: token }); } catch { byEv[id] = null; } } return byEv; }; const loadFunnel = async (eventIds: string[]) => { if (!token || !eventIds.length) return null; const query = new URLSearchParams({ eventIds: eventIds.join(",") }); if (dateFrom) query.set("from", dateFrom); if (dateTo) query.set("to", dateTo); try { return await apiFetch(`/api/analytics/funnel?${query.toString()}`, { authToken: token }); } catch { return null; } }; const loadFeedback = async (eventIds: string[]) => { if (!token || !eventIds.length) return []; try { return await apiFetch(`/api/feedback/summary?eventIds=${encodeURIComponent(eventIds.join(","))}`, { authToken: token }); } catch { return []; } }; // Coupon uses (active redemptions on non-cancelled registrations) for the Discounts report. const loadDiscounts = async (eventIds: string[]) => { if (!token || !eventIds.length) return []; const query = new URLSearchParams({ eventIds: eventIds.join(",") }); if (dateFrom) query.set("from", dateFrom); if (dateTo) query.set("to", dateTo); try { return await apiFetch(`/api/coupons/redemptions?${query.toString()}`, { authToken: token }); } catch { return []; } }; // Rows of one kind (consent status or medical details) for every youth event selected. async function loadConsent(eventIds: string[], kind: "status"): Promise<(ConsentRow & { eventTitle: string })[]>; async function loadConsent(eventIds: string[], kind: "medical"): Promise<(MedicalRow & { eventTitle: string })[]>; async function loadConsent(eventIds: string[], kind: "status" | "medical") { if (!token) return []; const out: ((ConsentRow | MedicalRow) & { eventTitle: string })[] = []; for (const id of eventIds) { const ev = filteredEvents.find((e) => e.id === id); if (!ev?.requiresParentalConsent) continue; try { const res = await apiFetch<{ rows?: (ConsentRow | MedicalRow)[] }>(`/api/consent/events/${encodeURIComponent(id)}${kind === "medical" ? "/medical" : ""}`, { authToken: token }); (res?.rows || []).forEach((r) => out.push({ ...r, eventTitle: ev.title })); } catch { /* not allowed or not found — skip */ } } return out; } const loadCashupAudit = async (eventIds: string[]) => { if (!token) return []; const query = new URLSearchParams(); if (auditFrom) query.set("from", auditFrom); if (auditTo) query.set("to", auditTo); if (eventIds.length === 1) query.set("eventId", eventIds[0]); try { const rows = await apiFetch(`/api/cashups/audit?${query.toString()}`, { authToken: token }); const idSet = new Set(eventIds); const filtered = eventIds.length > 1 ? (rows || []).filter(r => idSet.has(r.eventId)) : (rows || []); return computeAuditDeltas(filtered).sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()); } catch { return []; } }; // Discounts report: one row per code per event. const discountSummary = useMemo(() => { const byKey = new Map(); for (const r of discountRows) { const event = r.registration?.event?.title || "—"; const isBundle = r.kind === "bundle"; const code = isBundle ? `Bundle: ${r.coupon?.code || "?"}` : r.coupon?.code || "?"; const key = `${code}__${event}`; const row = byKey.get(key) || { code, isBundle, summary: r.summary || "", event, uses: 0, total: 0 }; row.uses += r.uses ?? 1; row.total += Number(r.discountAmount || 0); byKey.set(key, row); } const rows = Array.from(byKey.values()).sort((a, b) => b.total - a.total); const byCode = new Map(); rows.forEach(r => byCode.set(r.code, (byCode.get(r.code) || 0) + r.total)); return { rows, totalUses: rows.reduce((s, r) => s + r.uses, 0), totalValue: rows.reduce((s, r) => s + r.total, 0), codes: byCode.size, chart: Array.from(byCode.entries()).map(([label, value]) => ({ label, value })), }; }, [discountRows]); // Feedback summary: overall numbers, and the average star rating per event (for comparing events). const feedbackSummary = useMemo(() => { const invited = feedbackRows.reduce((s, f) => s + (f.invited || 0), 0); const responses = feedbackRows.reduce((s, f) => s + (f.responses || 0), 0); const ratingOf = (f: FeedbackEventSummary) => { const avgs = (f.questions || []).filter((q) => q.type === "rating" && q.average != null).map((q) => q.average as number); return avgs.length ? Math.round((avgs.reduce((s, n) => s + n, 0) / avgs.length) * 10) / 10 : null; }; const perEvent = feedbackRows.map(f => ({ ...f, rating: ratingOf(f) })); const rated = perEvent.filter(f => f.rating != null); return { perEvent, invited, responses, rate: invited ? Math.round((responses / invited) * 100) : null, rating: rated.length ? Math.round((rated.reduce((s, f) => s + (f.rating ?? 0), 0) / rated.length) * 10) / 10 : null, chart: rated.map(f => ({ label: f.title, value: f.rating ?? 0 })), }; }, [feedbackRows]); const feedbackResult = (q: FeedbackQuestion) => q.type === "rating" ? (q.average != null ? `${q.average} / 5` : "—") : q.type === "numeric" ? (q.average != null ? `average ${q.average}` : "—") : q.counts ? q.counts.map((c) => `${c.label}: ${c.value}`).join(" · ") : `${(q.texts || []).length} answer(s)`; // View handler according to selected report const onView = async () => { setBusy(true); setReady(false); try { if (report === "payments") { const byEv = await loadPayments(selectedEventIds); setPaymentsByEvent(byEv); } else if (report === "attendees") { const byEv = await loadRegistrations([attEventId || selectedEventIds[0]].filter(Boolean)); setRegistrationsByEvent(byEv); } else if (report === "regTypes") { const byEv = await loadRegistrations(selectedEventIds); setRegistrationsByEvent(byEv); } else if (report === "usage") { const usage = await loadTicketUsage(selectedEventIds); setTicketUsage(usage); } else if (report === "revenue") { const byEv = await loadPayments(selectedEventIds); setPaymentsByEvent(byEv); } else if (report === "revenueDetailed") { const [byEvP, byEvR] = await Promise.all([ loadPayments(selectedEventIds), loadRegistrations(selectedEventIds) ]); setPaymentsByEvent(byEvP); setRegistrationsByEvent(byEvR); } else if (report === "regStatus") { const byEv = await loadRegistrations(selectedEventIds); setRegistrationsByEvent(byEv); } else if (report === "masterOrders") { const [byEvP, byEvR] = await Promise.all([ loadPayments(selectedEventIds), loadRegistrations(selectedEventIds) ]); setPaymentsByEvent(byEvP); setRegistrationsByEvent(byEvR); } else if (report === "donations") { const byEv = await loadPayments(selectedEventIds); setPaymentsByEvent(byEv); } else if (report === "cashup") { const byEv = await loadFinancials(selectedEventIds); setFinancialsByEvent(byEv); } else if (report === "financeReport") { const byEv = await loadFinancials(selectedEventIds); setFinancialsByEvent(byEv); } else if (report === "profitReport") { const byEv = await loadFinancials(selectedEventIds); setFinancialsByEvent(byEv); } else if (report === "cashupAudit") { const rows = await loadCashupAudit(selectedEventIds); setAuditRows(rows); } else if (report === "discounts") { setDiscountRows(await loadDiscounts(selectedEventIds)); } else if (report === "consentStatus") { setConsentRows(await loadConsent(selectedEventIds, "status")); } else if (report === "funnel") { setFunnel(await loadFunnel(selectedEventIds)); } else if (report === "feedbackSummary") { setFeedbackRows(await loadFeedback(selectedEventIds)); } else if (report === "medicalList") { setMedicalRows(await loadConsent(selectedEventIds, "medical")); } else if (report === "seriesComparison") { setComparison(compareSeriesId && token ? await apiFetch(`/api/series/${encodeURIComponent(compareSeriesId)}/compare`, { authToken: token }).catch(() => null) : null); } setReady(true); } finally { setBusy(false); } }; // Payment method label mapping — bucket into the same 4 categories used by the finance/cashup // reports (cash, card, eft, other). Card-network wallets (Apple Pay, Google Pay) and Yoco // checkout-portal payments settle exactly like a card — no separate float to reconcile — so // they fold into "Card" rather than showing as their own categories. Mirrors bucketForMethod // in backend/src/utils/cashupUtils.js. const getPaymentMethod = (p: Payment) => { const m = String(p?.method || "").toLowerCase(); if (m.includes("cash")) return "Cash"; if (m.includes("eft")) return "EFT"; if (m.includes("card") || m.includes("yoco") || m.includes("pay") || p?.externalId) return "Card"; return "Other"; }; // Derived rows for payments (apply date filter) const paymentRows = useMemo(() => { if (report !== "payments") return [] as PaymentRow[]; const df = payFrom ? new Date(payFrom).getTime() : null; const dt = payTo ? new Date(payTo).getTime() : null; const rows: PaymentRow[] = []; for (const evId of Object.keys(paymentsByEvent)) { const ev = filteredEvents.find(e => e.id === evId); const evTitle = ev?.title || evId; for (const p of paymentsByEvent[evId] || []) { // Exclude donation-application legs — that money was already counted once, as the // donation itself. Only real inflows (payments and donations) belong here. if (isDonationLeg(p)) continue; const t = new Date(p.createdAt).getTime(); if ((df && t < df) || (dt && t > dt)) continue; // Reporting rule: if donation, attribute to payer; otherwise attribute to the registration's assigned user const u: Partial = p.isDonation ? (p.user || {}) : ((p.registration?.user || p.user) || {}); // Self-service (webhook) payments record the payer as recordedBy too — only call it // out when a different staff member actually recorded it, to avoid noise. const recordedByName = (p.recordedBy && String(p.recordedBy.id) !== String(p.userId)) ? (p.recordedBy.name || p.recordedBy.email || "") : ""; rows.push({ eventId: evId, eventTitle: evTitle, userName: u?.name || u?.email || p.userId || "User", userEmail: u?.email, amount: p.amount, method: getPaymentMethod(p), isDonation: p.isDonation, createdAt: p.createdAt, recordedByName, }); } } rows.sort((a,b) => (a.eventTitle.localeCompare(b.eventTitle) || (a.userName || '').localeCompare(b.userName || '') || new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())); return rows; }, [report, paymentsByEvent, payFrom, payTo, filteredEvents]); // Derived rows for revenue detailed (apply date filter) // Outstanding by registration respecting early-bird tiers and last payment lock-in const outstandingByReg = useMemo(() => { const map = new Map(); // Build quick index of payments per registration from all payments loaded per event const paidByReg = new Map(); const lastPaymentAtByReg = new Map(); Object.keys(paymentsByEvent).forEach(evId => { (paymentsByEvent[evId] || []).forEach((p) => { if (p.registrationId) { const regId = p.registrationId; paidByReg.set(regId, (paidByReg.get(regId) || 0) + (p.amount || 0)); const t = new Date(p.createdAt).getTime(); const prev = lastPaymentAtByReg.get(regId)?.getTime() || -Infinity; if (t > prev) lastPaymentAtByReg.set(regId, new Date(t)); } }); }); const now = new Date(); // For each registration in loaded events, compute due and outstanding with lock-in rule Object.keys(registrationsByEvent).forEach(evId => { (registrationsByEvent[evId] || []).forEach((r) => { const lastAt = lastPaymentAtByReg.get(r.id) || null; // Backend attaches a tranche-aware totalDueComputed, which locks each tranche's price // at the time it was purchased — it's already time-invariant, so the "dueNow vs // dueAtLast" lock-in dance below is only needed as a fallback for legacy rows without it. const hasComputed = r.totalDueComputed !== null && r.totalDueComputed !== undefined; const dueNow = hasComputed ? Number(r.totalDueComputed) : (r.registrationOptions || []).reduce((sum, ro) => sum + optionUnitPrice(ro, lastAt, now) * (ro.quantity || 0), 0); const paid = paidByReg.get(r.id) || 0; let outstanding = Math.max(dueNow - paid, 0); if (lastAt && !hasComputed) { const dueAtLast = (r.registrationOptions || []).reduce((sum, ro) => sum + optionUnitPrice(ro, lastAt, lastAt) * (ro.quantity || 0), 0); if (paid >= dueAtLast) outstanding = 0; } map.set(r.id, outstanding); }); }); return map; }, [paymentsByEvent, registrationsByEvent]); // Build payment totals per registration (all payments, no date filter) const paidByReg = useMemo(() => { const map = new Map(); Object.keys(paymentsByEvent).forEach(evId => { (paymentsByEvent[evId] || []).forEach((p) => { if (p.registrationId) { map.set(p.registrationId, (map.get(p.registrationId) || 0) + (p.amount || 0)); } }); }); return map; }, [paymentsByEvent]); // How much of each registration's Total paid (above) came from an assigned donation leg, // rather than a direct cash/card/eft/online payment — this is a subset of paidByReg, not // additional money, and is unambiguous per-registration (unlike "this donor's total // donations", which isn't specific to this order and shouldn't be repeated per row). const paidViaDonationByReg = useMemo(() => { const map = new Map(); Object.keys(paymentsByEvent).forEach(evId => { (paymentsByEvent[evId] || []).forEach((p) => { if (p.registrationId && isDonationLeg(p)) { map.set(p.registrationId, (map.get(p.registrationId) || 0) + (p.amount || 0)); } }); }); return map; }, [paymentsByEvent]); // Donations made (as donor), with used/unused split — independent of any single registration, // shown as its own breakdown so "who gave what" is never conflated with "what this order cost". // Shared by Master Orders and Revenue Detailed — both need to attribute the full donation // amount to the donor, never to whichever registration a portion of it happened to fund. const donationsMadeRows = useMemo(() => { const rows: { eventId: string; eventTitle: string; donor: string; email?: string; amount: number; used: number; unused: number; createdAt: string }[] = []; Object.keys(paymentsByEvent).forEach(evId => { const ev = filteredEvents.find(e => e.id === evId); const evTitle = ev?.title || evId; const evPayments = paymentsByEvent[evId] || []; evPayments.filter((p) => p.isDonation).forEach((donation) => { // A refund of the donation itself also creates a leg (originalPaymentId -> donation), // with a negative amount — Math.abs() so it reduces "used" (money no longer available) // instead of a raw signed sum subtracting a negative and inflating "unused" below. const used = evPayments .filter((leg) => !leg.isDonation && leg.originalPaymentId === donation.id) .reduce((s, leg) => s + Math.abs(leg.amount || 0), 0); rows.push({ eventId: evId, eventTitle: evTitle, donor: donation.user?.name || donation.userId || "Donor", email: donation.user?.email, amount: donation.amount || 0, used, unused: Math.max((donation.amount || 0) - used, 0), createdAt: donation.createdAt, }); }); }); rows.sort((a, b) => a.eventTitle.localeCompare(b.eventTitle) || a.donor.localeCompare(b.donor)); return rows; }, [paymentsByEvent, filteredEvents]); const revDetRows = useMemo(() => { if (report !== "revenueDetailed") return [] as RevenueDetailRow[]; const df = payFrom ? new Date(payFrom).getTime() : null; const dt = payTo ? new Date(payTo).getTime() : null; const rows: RevenueDetailRow[] = []; // Iterate registrations to include those with zero payments and show each once. "Total paid" // is what THIS person actually paid directly — money that reached them via an assigned // donation is not their payment, so it's excluded here and attributed to the donor instead // (below). Outstanding still reflects the full picture (direct + donation-funded), since // that's genuinely how much of the order remains unsettled. Object.keys(registrationsByEvent).forEach(evId => { const ev = filteredEvents.find(e => e.id === evId); const evTitle = ev?.title || evId; (registrationsByEvent[evId] || []).forEach((r) => { const created = r.createdAt ? new Date(r.createdAt).getTime() : null; if (df && created && created < df) return; if (dt && created && created > dt) return; const directPaid = Math.max((paidByReg.get(r.id) || 0) - (paidViaDonationByReg.get(r.id) || 0), 0); const outstanding = outstandingByReg.get(r.id) || 0; rows.push({ eventId: evId, eventTitle: evTitle, userName: r.user?.name || r.userId || "User", userEmail: r.user?.email, totalPaid: directPaid, status: r.status, registrationId: r.id, outstanding, }); }); }); // Every donation is real money received from the donor, whether or not (or how much of) it // has since been assigned to fund someone else's registration — so it's attributed here in // full, under the donor, never under whichever registration it happened to fund. donationsMadeRows.forEach(d => { const created = d.createdAt ? new Date(d.createdAt).getTime() : null; if (df && created && created < df) return; if (dt && created && created > dt) return; rows.push({ eventId: d.eventId, eventTitle: d.eventTitle, userName: d.donor, userEmail: d.email, totalPaid: d.amount, status: d.used <= 0.000001 ? "donation (unassigned)" : (d.unused > 0.000001 ? "donation (partly assigned)" : "donation (fully assigned)"), registrationId: "", outstanding: 0, }); }); rows.sort((a,b) => (a.eventTitle.localeCompare(b.eventTitle) || (a.userName || '').localeCompare(b.userName || ''))); return rows; }, [report, registrationsByEvent, filteredEvents, payFrom, payTo, paidByReg, paidViaDonationByReg, outstandingByReg, donationsMadeRows]); // Derived for attendees (layered) for a single event const attendeesLayer = useMemo(() => { if (report !== "attendees") return { eventTitle: "", options: [] as AttendeeLayerOption[] }; const regs = registrationsByEvent[attEventId] || []; const ev = filteredEvents.find(e => e.id === attEventId); // Option -> users const byOption = new Map(); for (const r of regs) { if (!attIncludeCancelled && r.status === "cancelled") continue; const baseUser = { name: r.user?.name || r.userId, email: r.user?.email, status: r.status, }; const options = (r.registrationOptions || []); if (options.length === 0) { const key = "(No option)"; if (!byOption.has(key)) byOption.set(key, { optionName: key, users: [] }); byOption.get(key)!.users.push({ ...baseUser, qty: 0 }); } else { for (const ro of options) { const key = ro.eventOption?.name || "Option"; if (!byOption.has(key)) { byOption.set(key, { optionName: key, users: [] }); } byOption.get(key)!.users.push({ ...baseUser, qty: ro.quantity || 0 }); } } } const options = Array.from(byOption.values()).sort((a,b) => a.optionName.localeCompare(b.optionName)); options.forEach(o => o.users.sort((a,b) => (a.name || '').localeCompare(b.name || ''))); return { eventTitle: ev?.title || attEventId, options }; }, [report, registrationsByEvent, attEventId, attIncludeCancelled, filteredEvents]); // Derived for reg type counts const regTypeRows = useMemo(() => { if (report !== "regTypes") return [] as { eventTitle: string; type: string; qty: number }[]; const rows: { eventTitle: string; type: string; qty: number }[] = []; for (const evId of Object.keys(registrationsByEvent)) { const ev = filteredEvents.find(e => e.id === evId); const title = ev?.title || evId; const regs = registrationsByEvent[evId] || []; const counts: Record = {}; for (const r of regs) { if (r.status === "cancelled") continue; for (const ro of (r.registrationOptions || [])) { const name = ro.eventOption?.name || "Option"; counts[name] = (counts[name] || 0) + (ro.quantity || 0); } } for (const type of Object.keys(counts)) rows.push({ eventTitle: title, type, qty: counts[type] }); } rows.sort((a,b) => (a.eventTitle.localeCompare(b.eventTitle) || a.type.localeCompare(b.type))); return rows; }, [report, registrationsByEvent, filteredEvents]); //Master report options const masterOptions = useMemo(() => { if (report !== "masterOrders") return []; const map = new Map(); Object.values(registrationsByEvent).forEach((regs) => { regs.forEach((r) => { (r.registrationOptions || []).forEach((ro) => { const id = ro.eventOption?.id; const name = ro.eventOption?.name; if (id && name) { map.set(id, name); } }); }); }); return Array.from(map.entries()) .map(([id, name]) => ({ id, name })) .sort((a, b) => a.name.localeCompare(b.name)); }, [report, registrationsByEvent]); //Master Report Data Rows const masterRows = useMemo(() => { if (report !== "masterOrders") return []; const rows: MasterRow[] = []; Object.keys(registrationsByEvent).forEach(evId => { const ev = filteredEvents.find(e => e.id === evId); const eventTitle = ev?.title || evId; (registrationsByEvent[evId] || []).forEach((r) => { if (r.status === "cancelled") return; const optionQtyMap = new Map(); (r.registrationOptions || []).forEach((ro) => { const id = ro.eventOption?.id; const qty = ro.quantity || 0; if (id) { optionQtyMap.set(id, (optionQtyMap.get(id) || 0) + qty); } }); // "Paid" is what this person actually paid directly — money that reached this // registration via an assigned donation is the donor's money, not theirs, so it's // excluded here and shown separately in "Paid via donation" instead. const paidViaDonation = paidViaDonationByReg.get(r.id) || 0; const directPaid = Math.max((paidByReg.get(r.id) || 0) - paidViaDonation, 0); const baseRow: MasterRow = { eventTitle, name: r.user?.name || "User", email: r.user?.email, orderTotal: 0, totalPaid: directPaid, outstanding: outstandingByReg.get(r.id) || 0, paidViaDonation, qty: {}, revenue: {}, }; // 👇 Dynamic columns masterOptions.forEach(opt => { const qty = optionQtyMap.get(opt.id) || 0; baseRow.qty[opt.name] = qty; const ro = (r.registrationOptions || []) .find((x) => x.eventOption?.id === opt.id); // Backend attaches a tranche-aware lineTotal (exact even when this line spans // multiple early-bird prices) — fall back to the old blended-price estimate // otherwise. `revenue` carries the real total used for aggregation below. const lineTotal = ro ? (ro.lineTotal !== null && ro.lineTotal !== undefined ? ro.lineTotal : optionUnitPrice(ro, null, new Date()) * qty) : 0; baseRow.revenue[opt.name] = lineTotal; baseRow.orderTotal += lineTotal; }); rows.push(baseRow); }); }); rows.sort((a,b) => a.eventTitle.localeCompare(b.eventTitle) || a.name.localeCompare(b.name) ); return rows; }, [report, registrationsByEvent, filteredEvents, masterOptions, paidByReg, outstandingByReg, paidViaDonationByReg]); //Master Report Totals const masterTotals = useMemo(() => { if (report !== "masterOrders") return null; const totals: Record = { orderTotal: 0, totalPaid: 0, outstanding: 0, paidViaDonation: 0, }; // 👇 initialise dynamic option totals masterOptions.forEach(opt => { totals[opt.name] = 0; // qty total totals[`${opt.name}_revenue`] = 0; // revenue total }); masterRows.forEach(row => { totals.orderTotal += row.orderTotal; totals.totalPaid += row.totalPaid; totals.outstanding += row.outstanding; totals.paidViaDonation += row.paidViaDonation || 0; masterOptions.forEach(opt => { const qty = row.qty[opt.name] || 0; totals[opt.name] += qty; // revenue per option — use the tranche-aware per-row total computed above rather // than re-deriving qty*price from a blended average price. totals[`${opt.name}_revenue`] += Number(row.revenue[opt.name] ?? 0); }); }); // Donations logged for these events that haven't (fully) been applied to any order yet — // real money already received, sitting unused, distinct from what orders actually cost. totals.unassignedDonations = donationsMadeRows.reduce((s, d) => s + d.unused, 0); return totals; }, [masterRows, masterOptions, report, donationsMadeRows]); // Export/print/email handlers per report // Builds the export payload for the current report — one shared builder consumed by Print, // Email, WhatsApp, and Excel, so all four channels always show identical data/styling instead // of four independently-maintained copies drifting apart. Stats/chart data (when present) // mirror exactly what the on-screen report shows above its table, computed the same way. const buildReportPayload = (): ReportPdfPayload | null => { const subtitle = `Generated ${new Date().toLocaleString()}`; if (report === "seriesComparison") { if (!comparison) return null; const withChange = (v: string, c: number | null | undefined) => (c == null ? v : `${v} (${changeLabel(c)})`); return { title: `${comparison.series.name}: year on year`, subtitle, kind: "table", orientation: "landscape", note: "Each change is against the event before. Checked in on a multi-session event is the average per session. Income leaves out donations applied to orders (counted when they were given).", ...(comparison.events.length > 1 ? { chart: { title: "Income, by event", data: comparison.events.map(e => ({ label: e.title, value: e.income, displayValue: `R ${e.income.toFixed(2)}` })) } } : {}), table: { columns: ["Event", "Date", "Registrations", "Tickets", "Income", "Checked in", "Attendance"], rows: comparison.events.map(e => [ e.title, new Date(e.startDate).toLocaleDateString(), withChange(String(e.registrations), e.change?.registrations), withChange(String(e.tickets), e.change?.tickets), withChange(`R ${e.income.toFixed(2)}`, e.change?.income), withChange(String(e.checkedIn), e.change?.checkedIn), e.attendanceRate != null ? `${e.attendanceRate}%` : "—", ]), }, }; } if (report === "payments") { return { title: 'Payments Report', subtitle, kind: 'table', orientation: 'portrait', table: { columns: ["Event","User","Email","Amount","Method","Donation","Recorded by","Date"], rows: paymentRows.map(r => [r.eventTitle, r.userName, r.userEmail || "", `R ${Number(r.amount).toFixed(2)}`, r.method, r.isDonation ? "Yes" : "No", r.recordedByName || "", new Date(r.createdAt).toLocaleString()]) } }; } if (report === "attendees") { const sections = attendeesLayer.options.map(opt => ({ title: opt.optionName, items: opt.users.map((u) => `${u.name}${u.email ? ` (${u.email})` : ''} — ${u.status}${typeof u.qty==='number' ? ` • Qty: ${u.qty}` : ''}`) })); return { title: 'Attendees Report', subtitle, kind: 'layered', orientation: 'portrait', layered: { header: `Event: ${attendeesLayer.eventTitle}`, sections } }; } if (report === "regTypes") { const byType = new Map(); regTypeRows.forEach(r => byType.set(r.type, (byType.get(r.type) || 0) + r.qty)); return { title: 'Registration Types Report', subtitle, kind: 'table', orientation: 'portrait', chart: { title: 'Across all selected events', data: Array.from(byType.entries()).map(([label, value]) => ({ label, value })) }, table: { columns: ["Event","Type","Quantity"], rows: regTypeRows.map(r => [r.eventTitle, r.type, String(r.qty)]) } }; } if (report === "usage") { const rows: (string|number)[][] = []; let totalUsed = 0, totalUnused = 0; Object.keys(ticketUsage).forEach(evId => { const ev = filteredEvents.find(e => e.id === evId); const tu = ticketUsage[evId]; rows.push([ev?.title || evId, tu.used, tu.unused]); totalUsed += tu.used; totalUnused += tu.unused; }); return { title: 'Ticket Usage Report', subtitle, kind: 'table', orientation: 'portrait', chart: { title: 'Used vs. unused, across all selected events', data: [{ label: "Used", value: totalUsed }, { label: "Unused", value: totalUnused }] }, table: { columns: ["Event","Used","Unused"], rows } }; } if (report === "revenue") { const df = payFrom ? new Date(payFrom).getTime() : null; const dt = payTo ? new Date(payTo).getTime() : null; const rows: (string|number)[][] = []; const byMethodTotal: Record = {}; Object.keys(paymentsByEvent).forEach(evId => { const ev = filteredEvents.find(e => e.id === evId); const list = (paymentsByEvent[evId] || []).filter((p) => { if (isDonationLeg(p)) return false; // already counted once, as the source donation const t = new Date(p.createdAt).getTime(); return !(df && t < df) && !(dt && t > dt); }); const byMethod: Record = {}; let total = 0; list.forEach((p) => { const m = getPaymentMethod(p); byMethod[m] = (byMethod[m] || 0) + (p.amount || 0); byMethodTotal[m] = (byMethodTotal[m] || 0) + (p.amount || 0); total += (p.amount || 0); }); if (Object.keys(byMethod).length === 0) rows.push([ev?.title || evId, '-', 0, 0]); Object.keys(byMethod).forEach(m => rows.push([ev?.title || evId, m, Number(byMethod[m].toFixed(2)), Number(total.toFixed(2))])); }); return { title: 'Revenue Summary', subtitle, kind: 'table', orientation: 'portrait', chart: { title: 'By method, across all selected events', data: Object.keys(byMethodTotal).sort().map(m => ({ label: m, value: byMethodTotal[m], displayValue: `R ${byMethodTotal[m].toFixed(2)}` })) }, table: { columns: ["Event","Method","Amount","Event Total"], rows } }; } if (report === "revenueDetailed") { const rows: (string|number)[][] = revDetRows.map(r => [ r.eventTitle, r.userName, r.userEmail || "", r.status || "", Number((r.totalPaid || 0).toFixed(2)), Number((r.outstanding || 0).toFixed(2)), r.registrationId || "", ]); return { title: 'Revenue Detailed', subtitle, kind: 'table', orientation: 'landscape', table: { columns: ["Event","Name","Email","Status","Total paid","Outstanding","RegistrationId"], rows } }; } if (report === "regStatus") { const rows: (string|number)[][] = []; const agg: Record = { pending: 0, partial_paid: 0, paid: 0, cancelled: 0 }; Object.keys(registrationsByEvent).forEach(evId => { const ev = filteredEvents.find(e => e.id === evId); const regs = registrationsByEvent[evId] || []; const counts: Record = { pending: 0, partial_paid: 0, paid: 0, cancelled: 0 }; regs.forEach((r) => { if (!statusIncludeCancelled && r.status === 'cancelled') return; counts[r.status] = (counts[r.status] || 0) + countForStatus(r); agg[r.status] = (agg[r.status] || 0) + countForStatus(r); }); rows.push([ev?.title || evId, counts.pending||0, counts.partial_paid||0, counts.paid||0, counts.cancelled||0]); }); const unit = statusCountMode === 'tickets' ? 'tickets' : 'registrations'; return { title: 'Registration Status Breakdown', subtitle, kind: 'table', chart: { title: `Across all selected events, by ${unit}`, data: [ { label: "Pending", value: agg.pending || 0 }, { label: "Partial", value: agg.partial_paid || 0 }, { label: "Paid", value: agg.paid || 0 }, { label: "Cancelled", value: agg.cancelled || 0 }, ] }, table: { columns: ["Event", statusCountMode === 'tickets' ? "Pending (tickets)" : "Pending", statusCountMode === 'tickets' ? "Partial (tickets)" : "Partial", statusCountMode === 'tickets' ? "Paid (tickets)" : "Paid", statusCountMode === 'tickets' ? "Cancelled (tickets)" : "Cancelled"], rows } }; } if (report === "donations") { // Math.abs(): a refund of the donation itself also creates a leg (originalPaymentId -> // donation) with a negative amount, which must reduce "used" rather than inflate "unused". const usedFor = (evId: string, donationId: string) => (paymentsByEvent[evId] || []).filter((leg) => !leg.isDonation && leg.originalPaymentId === donationId) .reduce((s, leg) => s + Math.abs(leg.amount || 0), 0); const rows: (string|number)[][] = []; let grandTotal = 0, grandUsed = 0; Object.keys(paymentsByEvent).forEach(evId => { const ev = filteredEvents.find(e => e.id === evId); const evPayments = paymentsByEvent[evId] || []; const dons = evPayments.filter((p) => p.isDonation); const total = dons.reduce((s, p) => s + (p.amount || 0), 0); const used = dons.reduce((s, p) => s + usedFor(evId, p.id), 0); const unused = Math.max(total - used, 0); grandTotal += total; grandUsed += used; const pool = dons.filter((p) => p.isSponsorship); const poolIn = pool.reduce((s, p) => s + (p.amount || 0), 0); const poolUsed = pool.reduce((s, p) => s + usedFor(evId, p.id), 0); rows.push([ev?.title || evId, Number(total.toFixed(2)), Number(used.toFixed(2)), Number(unused.toFixed(2)), dons.length, Number(poolIn.toFixed(2)), Number(poolUsed.toFixed(2)), Number(Math.max(poolIn - poolUsed, 0).toFixed(2))]); }); const grandUnused = Math.max(grandTotal - grandUsed, 0); return { title: 'Donations Breakdown', subtitle, kind: 'table', orientation: 'portrait', stats: [ { label: 'Total donated', value: `R ${grandTotal.toFixed(2)}`, tone: 'rose' }, { label: 'Used', value: `R ${grandUsed.toFixed(2)}`, tone: 'violet' }, { label: 'Unused', value: `R ${grandUnused.toFixed(2)}`, tone: 'amber' }, ], chart: { title: 'Used vs. unused, across all selected events', data: [{ label: "Used", value: grandUsed, displayValue: `R ${grandUsed.toFixed(2)}` }, { label: "Unused", value: grandUnused, displayValue: `R ${grandUnused.toFixed(2)}` }] }, table: { columns: ["Event", "Donations (R)", "Used (R)", "Unused (R)", "Count", "Sponsorship pool (R)", "Pool assigned (R)", "Pool remaining (R)"], rows } }; } if (report === "consentStatus") { const minors = consentRows.filter(r => r.minor); const count = (s: string) => minors.filter(r => r.status === s).length; return { title: 'Parental consent status', subtitle, kind: 'table', orientation: 'landscape', stats: [ { label: 'Given', value: String(count('given')), tone: 'green' }, { label: 'Pending', value: String(count('pending')), tone: 'amber' }, { label: 'Declined / missing', value: String(count('declined') + count('missing')), tone: 'rose' }, ], note: 'Under-18 attendees on youth events. Pending, declined or missing consent blocks check-in.', table: { columns: ["Event", "Attendee", "Date of birth", "Parent / guardian", "Consent", "Answered"], rows: minors.map(r => [r.eventTitle, r.name, r.dateOfBirth ? new Date(r.dateOfBirth).toLocaleDateString() : '', [r.parentName, r.parentPhone].filter(Boolean).join(' · '), r.status + (r.request?.outdated ? ' (older text)' : ''), r.request?.respondedAt ? `${r.request.signedName || ''} ${new Date(r.request.respondedAt).toLocaleDateString()}`.trim() : '']), }, }; } if (report === "funnel" && funnel) { const pct = (v: number | null) => (v != null ? `${v}%` : "—"); const line = (label: string, c: FunnelCounts & { conversion?: number | null }) => [label, c.view, c.start, c.submit, c.paid, pct(c.conversion ?? (c.view ? Math.round((c.paid / c.view) * 1000) / 10 : null))]; const rows: (string | number)[][] = [ line("All selected events", funnel.totals), ...(funnel.perEvent || []).length > 1 ? (funnel.perEvent || []).map((p) => line(p.title, p.totals)) : [], ...funnel.bySource.map((s) => line(`Source: ${s.key}`, s)), ...funnel.byDevice.map((d) => line(`Device: ${d.key}`, d)), ...funnel.byOption.map((o) => [`Ticket: ${o.key}`, "", "", o.submitted, o.paid, ""]), ]; return { title: 'Registration funnel', subtitle, kind: 'table', orientation: 'landscape', stats: [ { label: 'Event page visits', value: String(funnel.totals.view), tone: 'blue' }, { label: 'Paid', value: String(funnel.totals.paid), tone: 'green' }, { label: 'Conversion', value: pct(funnel.conversion.paid), tone: 'violet' }, ], chart: { title: 'Visitors reaching each stage', data: [ { label: 'Viewed event', value: funnel.totals.view }, { label: 'Started', value: funnel.totals.start }, { label: 'Submitted', value: funnel.totals.submit }, { label: 'Paid', value: funnel.totals.paid }, ] }, note: 'Counts only visitors who allowed cookies. A visitor counts at a stage if they got that far or further.', table: { columns: ["Breakdown", "Viewed", "Started", "Submitted", "Paid", "Conversion"], rows }, }; } if (report === "feedbackSummary") { const rows: (string | number)[][] = []; for (const f of feedbackSummary.perEvent) { for (const q of f.questions || []) { rows.push([f.title, q.label, q.answered, feedbackResult(q)]); for (const t of q.texts || []) rows.push(["", ` “${t.value}”`, "", t.name || ""]); } } return { title: 'Feedback summary', subtitle, kind: 'table', orientation: 'landscape', stats: [ { label: 'Responses', value: String(feedbackSummary.responses), tone: 'violet' }, { label: 'Response rate', value: feedbackSummary.rate != null ? `${feedbackSummary.rate}%` : '—', tone: 'blue' }, { label: 'Average rating', value: feedbackSummary.rating != null ? `${feedbackSummary.rating} / 5` : '—', tone: 'amber' }, ], ...(feedbackSummary.chart.length > 1 ? { chart: { title: 'Average rating, by event', data: feedbackSummary.chart.map(c => ({ ...c, displayValue: `${c.value} / 5` })) } } : {}), table: { columns: ["Event", "Question", "Answered", "Result"], rows }, }; } if (report === "medicalList") { const fmt = (m: MedicalRow["medical"]) => m ? [m.allergies && `Allergies: ${m.allergies}`, m.medication && `Medication: ${m.medication}`, m.conditions && `Conditions: ${m.conditions}`, m.medicalAid && `Medical aid: ${m.medicalAid}`].filter(Boolean).join('; ') : ''; return { title: 'Medical & emergency list', subtitle, kind: 'table', orientation: 'landscape', note: 'CONFIDENTIAL — for event leaders only. Viewing this list is recorded in the audit log.', table: { columns: ["Event", "Attendee", "Medical", "Emergency contact", "Parent / guardian", "Photos"], rows: medicalRows.map(r => [r.eventTitle, r.name, r.purged ? 'Deleted after the event' : fmt(r.medical), r.emergency ? `${r.emergency.name} ${r.emergency.phone}${r.emergency.relationship ? ` (${r.emergency.relationship})` : ''}` : '', [r.parentName, r.parentPhone].filter(Boolean).join(' · '), r.photoConsent === null || r.photoConsent === undefined ? '' : r.photoConsent ? 'Yes' : 'No']), }, }; } if (report === "discounts") { return { title: 'Discounts (codes and bundles)', subtitle, kind: 'table', orientation: 'portrait', stats: [ { label: 'Value given away', value: `R ${discountSummary.totalValue.toFixed(2)}`, tone: 'rose' }, { label: 'Uses', value: String(discountSummary.totalUses), tone: 'violet' }, { label: 'Codes & bundles used', value: String(discountSummary.codes), tone: 'blue' }, ], chart: { title: 'Value given away, by code or bundle', data: discountSummary.chart.map(c => ({ ...c, displayValue: `R ${c.value.toFixed(2)}` })) }, note: 'Counts codes and bundle deals on registrations that are not cancelled. Cancelling a registration frees its code. Uses for a bundle are how many times it applied.', table: { columns: ["Code / bundle", "Discount", "Event", "Uses", "Value (R)"], rows: [ ...discountSummary.rows.map(r => [r.code, r.summary, r.event, r.uses, Number(r.total.toFixed(2))]), ["Total", "", "", discountSummary.totalUses, Number(discountSummary.totalValue.toFixed(2))], ], }, }; } if (report === "cashup") { const rows: (string | number)[][] = []; const incomeByMethod: Record = {}; Object.keys(financialsByEvent).forEach(evId => { const f = financialsByEvent[evId]; const ev = filteredEvents.find(e => e.id === evId); if (!f) return; const title = ev?.title || evId; METHOD_KEYS.forEach(m => { const r = f.reconciled?.byMethod?.[m]; incomeByMethod[m] = (incomeByMethod[m] || 0) + (f.paymentsByMethod?.[m] || 0); const amount = (v: number | null | undefined) => (v != null && Math.abs(v) >= 0.005 ? Number(v.toFixed(2)) : ""); rows.push([title, METHOD_LABEL[m], Number((f.paymentsByMethod?.[m] || 0).toFixed(2)), Number((f.costsByMethod?.[m] || 0).toFixed(2)), Number((f.expectedCashByMethod?.[m] || 0).toFixed(2)), amount(r?.bank), amount(r?.onHand), amount(r?.pendingOutstanding), amount(r?.writeOffTotal), r?.unaccounted != null ? Number(r.unaccounted.toFixed(2)) : "not reconciled"]); if (m === "cash") { (r?.denominations || []).forEach((d) => rows.push([title, ` ${denomLabel(d.value)} × ${d.count}`, "", "", "", "", Number((d.value * d.count).toFixed(2)), "", "", ""])); } (r?.writeOffs || []).forEach((w) => rows.push([title, ` Write-off: ${WRITE_OFF_LABEL[w.category] || w.category}${w.reason ? ` (${w.reason})` : ""}`, "", "", "", "", "", "", Number(w.amount.toFixed(2)), ""])); }); if ((f.untaggedCostsTotal || 0) > 0) rows.push([title, "Untagged costs", "", Number(f.untaggedCostsTotal.toFixed(2)), "", "", "", "", "", ""]); rows.push([title, "Donations counted as profit", "", "", "", "", "", "", "", Number((f.unallocatedDonationsTotal || 0).toFixed(2))]); }); return { title: 'Cashup Report', subtitle, kind: 'table', orientation: 'landscape', chart: { title: 'Income by method, across all selected events', data: METHOD_KEYS.map(m => ({ label: METHOD_LABEL[m], value: incomeByMethod[m] || 0, displayValue: `R ${(incomeByMethod[m] || 0).toFixed(2)}` })) }, table: { columns: ["Event", "Method", "Income", "Costs from method", "Expected", "In bank", "On hand", "Pending", "Written off", "Unaccounted"], rows } }; } if (report === "financeReport") { const rows: (string | number)[][] = []; let sold = 0, paidByAll = 0, donationsProfit = 0, costsTotal = 0, writeOffsTotal = 0, netProfitTotal = 0; const paidByMethod: Record = {}; Object.keys(financialsByEvent).forEach(evId => { const f = financialsByEvent[evId]; const ev = filteredEvents.find(e => e.id === evId); if (!f) return; const title = ev?.title || evId; sold += (f.salesByOption || []).reduce((s, o) => s + (o.revenue || 0), 0) - (f.discountsTotal || 0); paidByAll += METHOD_KEYS.reduce((s, m) => s + (f.paymentsByMethod?.[m] || 0), 0); METHOD_KEYS.forEach(m => { paidByMethod[m] = (paidByMethod[m] || 0) + (f.paymentsByMethod?.[m] || 0); }); donationsProfit += f.unallocatedDonationsTotal || 0; costsTotal += f.totalCosts || 0; writeOffsTotal += f.totalWriteOffs || 0; netProfitTotal += f.netProfit || 0; // "Sales" is ticket-price revenue for orders that reached 'paid' status — whether that // order was funded directly or via an assigned donation, its full price is already // counted here once. A separate "Donations" line for the full donation total would // double-count the assigned portion; only the still-unassigned remainder is money not // otherwise reflected in Sales, and that's already shown below under "Donations counted // as profit" — no need to repeat it here. rows.push([title, "Sales", "What was sold", ""]); (f.salesByOption || []).forEach((s) => rows.push([title, "", `${s.name} (${s.quantitySold} sold)`, Number(s.revenue.toFixed(2))])); if ((f.discountsTotal ?? 0) > 0) rows.push([title, "", "Less discounts (codes & bundles)", -Number((f.discountsTotal ?? 0).toFixed(2))]); rows.push([title, "Paid by", "", ""]); METHOD_KEYS.forEach(m => rows.push([title, "", METHOD_LABEL[m], Number((f.paymentsByMethod?.[m] || 0).toFixed(2))])); rows.push([title, "Cashup comparison", "", ""]); METHOD_KEYS.forEach(m => { const r = f.reconciled?.byMethod?.[m]; rows.push([title, "", `${METHOD_LABEL[m]} — expected / actual / unaccounted`, `${money2(f.expectedCashByMethod?.[m])} / ${r?.actual != null ? money2(r.actual) : "—"} / ${r?.unaccounted != null ? money2(r.unaccounted) : "—"}`]); }); rows.push([title, "Costs", "", ""]); (f.costs || []).forEach((c) => rows.push([title, "", `${c.label}${c.paidFromMethod ? ` (via ${METHOD_LABEL[c.paidFromMethod]})` : ""}`, Number((-(c.total ?? c.amount)).toFixed(2))])); METHOD_KEYS.forEach(m => (f.reconciled?.byMethod?.[m]?.writeOffs || []).forEach((w) => rows.push([title, "", `${WRITE_OFF_LABEL[w.category] || w.category} (${METHOD_LABEL[m]})${w.reason ? ` — ${w.reason}` : ""}`, -Number(w.amount.toFixed(2))]))); rows.push([title, "", "Donations counted as profit", Number((f.unallocatedDonationsTotal || 0).toFixed(2))]); rows.push([title, "", "Net profit", Number((f.netProfit || 0).toFixed(2))]); }); return { title: 'Finance Report', subtitle, kind: 'table', orientation: 'landscape', stats: [ { label: 'What was sold', value: `R ${sold.toFixed(2)}`, tone: 'green' }, { label: 'Paid by (all methods)', value: `R ${paidByAll.toFixed(2)}`, tone: 'blue' }, { label: 'Donations counted as profit', value: `R ${donationsProfit.toFixed(2)}`, tone: 'rose' }, { label: 'Total costs', value: `R ${costsTotal.toFixed(2)}`, tone: 'amber' }, { label: 'Bank & card charges', value: `R ${writeOffsTotal.toFixed(2)}`, tone: 'amber' }, { label: 'Net profit', value: `R ${netProfitTotal.toFixed(2)}`, tone: 'violet' }, ], chart: { title: 'Paid by, across all selected events', data: METHOD_KEYS.map(m => ({ label: METHOD_LABEL[m], value: paidByMethod[m] || 0, displayValue: `R ${(paidByMethod[m] || 0).toFixed(2)}` })) }, table: { columns: ["Event", "Section", "Detail", "Amount"], rows } }; } if (report === "profitReport") { const evIds = Object.keys(financialsByEvent); const totals = evIds.reduce((acc, evId) => { const f = financialsByEvent[evId]; acc.revenue += f?.effectiveTotalRevenue || 0; acc.costs += f?.totalCosts || 0; acc.charges += f?.totalWriteOffs || 0; acc.profit += f?.netProfit || 0; return acc; }, { revenue: 0, costs: 0, charges: 0, profit: 0 }); const rows: (string | number)[][] = evIds.map(evId => { const f = financialsByEvent[evId]; const ev = filteredEvents.find(e => e.id === evId); return [ev?.title || evId, Number((f?.effectiveTotalRevenue || 0).toFixed(2)), Number((f?.totalCosts || 0).toFixed(2)), Number((f?.totalWriteOffs || 0).toFixed(2)), Number((f?.netProfit || 0).toFixed(2))]; }); return { title: 'Profit Report', subtitle, kind: 'table', orientation: 'portrait', stats: [ { label: 'Revenue', value: `R ${totals.revenue.toFixed(2)}`, tone: 'green' }, { label: 'Costs', value: `R ${totals.costs.toFixed(2)}`, tone: 'amber' }, { label: 'Bank & card charges', value: `R ${totals.charges.toFixed(2)}`, tone: 'amber' }, { label: 'Net profit', value: `R ${totals.profit.toFixed(2)}`, tone: 'violet' }, ], chart: evIds.length > 1 ? { title: 'Net profit by event', data: evIds.map(evId => ({ label: filteredEvents.find(e => e.id === evId)?.title || evId, value: financialsByEvent[evId]?.netProfit || 0, displayValue: `R ${(financialsByEvent[evId]?.netProfit || 0).toFixed(2)}` })) } : undefined, table: { columns: ["Event", "Revenue", "Costs", "Bank & card charges", "Net profit"], rows } }; } if (report === "cashupAudit") { const rows: (string | number)[][] = []; auditRows.forEach((r) => { const base = [r.event?.title || r.eventId, actionLabel(r.action), r.performedBy?.name || "", new Date(r.createdAt).toLocaleString()]; if (r.action === "reopened") { rows.push([...base, "", "", "", "", "", r.notes || ""]); } else { (r.lines || []).forEach((l) => rows.push([...base, METHOD_LABEL[l.method] || l.method, Number((l.expectedAmount || 0).toFixed(2)), l.actualAmount != null ? Number(l.actualAmount.toFixed(2)) : "", l.variance != null ? Number(l.variance.toFixed(2)) : "", r._deltaVsPrevious?.[l.method] != null ? Number(r._deltaVsPrevious[l.method]!.toFixed(2)) : "", l.notes || ""])); if (!r.lines || r.lines.length === 0) rows.push([...base, "", "", "", "", "", `Donations counted as profit: ${money2(r.unallocatedDonationsTotal)}`]); } }); return { title: 'Cashup Audit Trail', subtitle, kind: 'table', orientation: 'landscape', table: { columns: ["Event", "Action", "Performed by", "Date", "Method", "Expected", "Actual", "Variance", "Δ vs previous close", "Notes"], rows } }; } if (report === "masterOrders") { const bodyRows: (string | number)[][] = masterRows.map(r => [ r.eventTitle, r.name, r.email || "", ...masterOptions.map(opt => r.qty[opt.name] ?? 0), Number(r.orderTotal.toFixed(2)), Number(r.totalPaid.toFixed(2)), Number((r.paidViaDonation || 0).toFixed(2)), Number(r.outstanding.toFixed(2)), ]); bodyRows.push([ "TOTAL", "", "", ...masterOptions.map(opt => masterTotals?.[opt.name] ?? 0), Number((masterTotals?.orderTotal ?? 0).toFixed(2)), Number((masterTotals?.totalPaid ?? 0).toFixed(2)), Number((masterTotals?.paidViaDonation ?? 0).toFixed(2)), Number((masterTotals?.outstanding ?? 0).toFixed(2)), ]); bodyRows.push([ "Revenue per Ticket", "", "", ...masterOptions.map(opt => `R ${(masterTotals?.[`${opt.name}_revenue`] ?? 0).toFixed(2)}`), "", "", "", "", ]); bodyRows.push([ "Unassigned donations", "", "", ...masterOptions.map(() => ""), "", "", "", Number((masterTotals?.unassignedDonations ?? 0).toFixed(2)), ]); return { title: "Master Orders Breakdown", subtitle, kind: "table", orientation: "landscape", stats: [ { label: 'Order Total', value: `R ${(masterTotals?.orderTotal ?? 0).toFixed(2)}`, tone: 'green' }, { label: 'Paid', value: `R ${(masterTotals?.totalPaid ?? 0).toFixed(2)}`, tone: 'blue' }, { label: 'Paid via donations', value: `R ${(masterTotals?.paidViaDonation ?? 0).toFixed(2)}`, tone: 'violet' }, { label: 'Outstanding', value: `R ${(masterTotals?.outstanding ?? 0).toFixed(2)}`, tone: 'amber' }, { label: 'Unassigned donations', value: `R ${(masterTotals?.unassignedDonations ?? 0).toFixed(2)}`, tone: 'rose' }, ], note: `"Paid" is only what each person actually paid themselves — money that reached their order via an assigned donation shows separately under "Paid via donation" and is attributed to the donor below, not the registrant. "Unassigned donations" is real money already received that hasn't been applied to any order yet.`, table: { columns: ["Event", "Name", "Email", ...masterOptions.map(o => o.name), "Order Total", "Paid", "Paid via donation", "Outstanding"], rows: bodyRows }, extraTables: donationsMadeRows.length > 0 ? [{ title: "Donations made", columns: ["Event", "Donor", "Email", "Donated", "Used", "Unused"], rows: donationsMadeRows.map(d => [d.eventTitle, d.donor, d.email || "", Number(d.amount.toFixed(2)), Number(d.used.toFixed(2)), Number(d.unused.toFixed(2))]) }] : undefined, }; } return null; }; const doExportExcel = async () => { if (!token) { alert('Please login to export Excel'); return; } try { const payload = buildReportPayload(); if (!payload) return; await downloadReportExcel(API_BASE, token, payload); } catch (e) { alert(errorMessage(e) || 'Failed to generate Excel file'); } }; const REPORT_LABEL: Record = { payments: "Payments Report", attendees: "Attendees Report", regTypes: "Registration Types Report", usage: "Ticket Usage Report", revenue: "Revenue Summary", revenueDetailed: "Revenue Detailed Report", regStatus: "Registration Status Breakdown", masterOrders: "Master Orders Report", donations: "Donations Breakdown", cashup: "Cashup Report", financeReport: "Finance Report", profitReport: "Profit Report", cashupAudit: "Cashup Audit Trail", discounts: "Discounts Report", consentStatus: "Parental Consent Status", medicalList: "Medical & Emergency List", seriesComparison: "Series: year on year", }; const doPrintPdf = async () => { if (!token) { alert('Please login to export PDF'); return; } try { const payload = buildReportPayload(); if (!payload) return; await viewReportPdf(API_BASE, token, payload); } catch (e) { alert(errorMessage(e) || 'Failed to generate PDF'); } }; const doEmail = async () => { if (!token) { alert('Please login to email PDF'); return; } try { const payload = buildReportPayload(); if (!payload) return; await emailReportPdf(API_BASE, token, { ...payload, subject: REPORT_LABEL[report], body: "Report generated on " + new Date().toLocaleString() }); alert('Email sent with PDF attachment'); } catch (e) { alert(errorMessage(e) || 'Failed to email PDF'); } }; const doWhatsApp = async () => { if (!token) { alert('Please login to send via WhatsApp'); return; } try { const payload = buildReportPayload(); if (!payload) return; await whatsappReportPdf(API_BASE, token, { ...payload, caption: REPORT_LABEL[report] }); alert('Report sent to your WhatsApp'); } catch (e) { alert(errorMessage(e) || 'Failed to send via WhatsApp'); } }; // Report-specific filters shown inside the popup — whatever each report had beyond the // universal Events/Date range, which now live in the sidebar (ReportsShell) instead. `null` // when a report has none, so the modal chrome shows its own fallback note. const reportSpecificFilters = report === "seriesComparison" ? (
Press refresh after changing the series. The events selection on the left doesn't apply.
) : report === "attendees" ? (
) : report === "regStatus" ? (
) : null; const reportActions = ready && ( <> ); const activeReportMeta = REPORTS.find(r => r.key === report); // UI return (
{!canView && (
You need supervisor or admin access to view reports.
)} {error &&
{error}
}
{ setCampus(v); setSelectedEventIds([]); }} withChurchWide everyLabel="All campuses (church-wide total)" id="reports-campus" mine /> { if (typeof p.report === "string" && REPORTS.some(r => r.key === p.report)) setReport(p.report as ReportKey); setCampus(String(p.campus || "")); setShowPastEvents(p.past === true); setShowInactiveEvents(p.inactive === true); setShowClosedEvents(p.closed !== false); setSelectedEventIds(Array.isArray(p.events) ? p.events : []); setDateFrom(String(p.from || "")); setDateTo(String(p.to || "")); setReady(false); }} skipDefault={!!searchParams.get("report")} />
{ setReport(r); setReady(false); }} onViewReport={() => { setPopupOpen(true); onView(); }} busy={busy} backHref={backHref} /> {popupOpen && ( setPopupOpen(false)} filters={reportSpecificFilters} actions={reportActions} onRefresh={onView} busy={busy} > {!ready &&
Loading…
} {ready && ( <> {report === "payments" && (
{paymentRows.length === 0 ? (
No payments match the selected filters.
) : (
{Object.entries(paymentRows.reduce>((acc, r) => { acc[r.eventTitle] = acc[r.eventTitle] || []; acc[r.eventTitle].push(r); return acc; }, {})).map(([eventTitle, rows]) => { // group by user const byUser: Record = {}; rows.forEach((r) => { const key = r.userName || 'User'; byUser[key] = byUser[key] || []; byUser[key].push(r); }); const eventTotal = rows.reduce((s, r) => s + (r.amount || 0), 0); return (
{eventTitle}
Total: R {eventTotal.toFixed(2)}
{Object.keys(byUser).sort().map(userName => { const list = byUser[userName]; const userTotal = list.reduce((s, r) => s + (r.amount || 0), 0); const email = list.find((r) => r.userEmail)?.userEmail || ''; return (
{userName} {email ? ({email}) : null}
Subtotal: R {userTotal.toFixed(2)}
    {list.map((r, i) => (
  • {r.method}{r.isDonation ? ' • Donation' : ''}{r.recordedByName ? ` • Recorded by ${r.recordedByName}` : ''} R {Number(r.amount).toFixed(2)} • {new Date(r.createdAt).toLocaleString()}
  • ))}
); })}
); })}
)}
)} {report === "attendees" && (
Event: {attendeesLayer.eventTitle}
{attendeesLayer.options.length === 0 ? (
No attendees for selected filters.
) : (
{attendeesLayer.options.map(opt => (
{opt.optionName}
    {opt.users.map((u, i) => (
  • {u.name} {u.email && ({u.email})} — {u.status} • Qty {u.qty}
  • ))}
))}
)}
)} {report === "regTypes" && (
{regTypeRows.length === 0 ? (
No data available. Select events and view.
) : (() => { const byType = new Map(); regTypeRows.forEach(r => byType.set(r.type, (byType.get(r.type) || 0) + r.qty)); return ( <>
Across all selected events
({ label, value }))} valueFormatter={v => String(v)} />
{regTypeRows.map((r, idx) => ( ))}
Event Registration Type Quantity
{r.eventTitle} {r.type} {r.qty}
); })()}
)} {report === "usage" && (
{Object.keys(ticketUsage).length === 0 ? (
No data available. Select events and view.
) : ( Object.keys(ticketUsage).map(evId => { const ev = events.find(e => e.id === evId); const tu = ticketUsage[evId]; const total = tu.used + tu.unused; return (
{ev?.title || evId}
{total} tickets total
String(v)} />
); }) )}
)} {report === "revenue" && (
{Object.keys(paymentsByEvent).length === 0 ? (
No data available. Select events and view.
) : ( Object.keys(paymentsByEvent).map(evId => { const ev = events.find(e => e.id === evId); const df = payFrom ? new Date(payFrom).getTime() : null; const dt = payTo ? new Date(payTo).getTime() : null; const list = (paymentsByEvent[evId] || []).filter((p) => { if (isDonationLeg(p)) return false; // already counted once, as the source donation const t = new Date(p.createdAt).getTime(); return !(df && t < df) && !(dt && t > dt); }); const byMethod: Record = {}; let total = 0; list.forEach((p) => { const m = getPaymentMethod(p); byMethod[m] = (byMethod[m] || 0) + (p.amount || 0); total += (p.amount || 0); }); const chartData = Object.keys(byMethod).sort().map(m => ({ label: m, value: byMethod[m] })); return (
{ev?.title || evId}
R {total.toFixed(2)}
{chartData.length === 0 ? (
No payments in date range.
) : ( `R ${v.toFixed(2)}`} /> )}
); }) )}
)} {report === "revenueDetailed" && (
{Object.keys(registrationsByEvent).length === 0 ? (
No data available. Select events and view.
) : ( Object.keys(registrationsByEvent).map(evId => { const ev = events.find(e => e.id === evId); const rows = revDetRows.filter(r => r.eventId === evId); const total = rows.reduce((s, r) => s + (r.totalPaid || 0), 0); const regIds = rows.map(r => r.registrationId); const outstandingTotal = regIds.reduce((s, id) => s + (outstandingByReg.get(id) || 0), 0); return (
{ev?.title || evId}
Paid R {total.toFixed(2)} · Outstanding R {outstandingTotal.toFixed(2)}
{rows.length === 0 ? (
No registrations in date range.
) : (
{rows.map((r, idx) => ( ))}
Name Email Status Total paid Outstanding Registration
{r.userName} {r.userEmail || ''} {r.status || ''} R {Number(r.totalPaid || 0).toFixed(2)} R {Number(r.outstanding || 0).toFixed(2)} {r.registrationId || ''}
)}
); }) )}
)} {report === "regStatus" && (
{Object.keys(registrationsByEvent).length === 0 ? (
No data available. Select events and view.
) : ( <> {(() => { const agg: Record = { pending: 0, partial_paid: 0, paid: 0, cancelled: 0 }; Object.values(registrationsByEvent).forEach((regs) => { (regs || []).forEach((r) => { if (!statusIncludeCancelled && r.status === 'cancelled') return; agg[r.status] = (agg[r.status] || 0) + countForStatus(r); }); }); const unit = statusCountMode === 'tickets' ? 'tickets' : 'registrations'; return (
Across all selected events, by {unit}
String(v)} />
); })()}
{Object.keys(registrationsByEvent).map(evId => { const ev = events.find(e => e.id === evId); const regs = registrationsByEvent[evId] || []; const counts: Record = { pending: 0, partial_paid: 0, paid: 0, cancelled: 0 }; regs.forEach((r) => { if (!statusIncludeCancelled && r.status === 'cancelled') return; counts[r.status] = (counts[r.status] || 0) + countForStatus(r); }); return ( ); })}
Event Pending{statusCountMode === 'tickets' ? ' (tickets)' : ''} Partial{statusCountMode === 'tickets' ? ' (tickets)' : ''} Paid{statusCountMode === 'tickets' ? ' (tickets)' : ''} Cancelled{statusCountMode === 'tickets' ? ' (tickets)' : ''}
{ev?.title || evId} {counts.pending || 0} {counts.partial_paid || 0} {counts.paid || 0} {counts.cancelled || 0}
)}
)} {report === "funnel" && (
{!funnel || funnel.totals.view === 0 ? (
No tracked visits for the selected events and dates yet. Only visitors who allow cookies are counted.
) : (() => { const pct = (v: number | null) => (v != null ? `${v}%` : "—"); const stages = [ { label: "Viewed event", value: funnel.totals.view }, { label: `Started (${pct(funnel.conversion.start)})`, value: funnel.totals.start }, { label: `Submitted (${pct(funnel.conversion.submit)})`, value: funnel.totals.submit }, { label: `Paid (${pct(funnel.conversion.paid)})`, value: funnel.totals.paid }, ]; const table = (title: string, rows: (FunnelCounts & { key: string; conversion: number | null })[]) => rows.length === 0 ? null : (
{rows.map((r) => ( ))}
{title}ViewedStarted SubmittedPaidConversion
{r.key}{r.view}{r.start} {r.submit}{r.paid}{pct(r.conversion)}
); return ( <>
Visitors reaching each stage (% of event page visits)
String(v)} />
Started → submitted: {pct(funnel.conversion.startToSubmit)} · Submitted → paid: {pct(funnel.conversion.submitToPaid)}
{funnel.trend.length > 1 && (
Event page visits per day
({ label: t.day.slice(5), value: t.view }))} />
)} {(funnel.perEvent || []).length > 1 && table("Event", (funnel.perEvent || []).map((p) => ({ key: p.title, ...p.totals, conversion: p.conversion.paid })))} {table("Source", funnel.bySource)} {table("Device", funnel.byDevice)} {funnel.byOption.length > 0 && (
{funnel.byOption.map((o) => ( ))}
Ticket optionRegistrationsPaid
{o.key}{o.submitted}{o.paid}
)}

Only visitors who allowed cookies are counted. A visitor counts at a stage if they got that far or further. Sources come from utm_source links and short links.

); })()}
)} {report === "seriesComparison" && (
{!comparison ? (
{seriesList.length === 0 ? "No series yet — make one on the Event series page and put events in it." : "Choose a series above."}
) : comparison.events.length === 0 ? (
{comparison.series.name} has no events yet (or none at your campuses).
) : (() => { const last = comparison.events[comparison.events.length - 1]; const change = (c: number | null | undefined) => c == null ? null : 0 ? "text-green-700" : c < 0 ? "text-rose-700" : "text-gray-500"}`}>{changeLabel(c)}; return ( <> {comparison.events.length > 1 && (
Registrations, by event
({ label: e.title, value: e.registrations }))} valueFormatter={v => String(v)} />
Income, by event
({ label: e.title, value: e.income }))} valueFormatter={v => `R ${v.toFixed(2)}`} />
)}
{comparison.events.map(e => ( ))}
EventDateRegistrationsTicketsIncomeChecked inAttendance
{e.title}{e.campus && · {e.campus.name}} {new Date(e.startDate).toLocaleDateString()} {e.registrations}{change(e.change?.registrations)} {e.tickets}{change(e.change?.tickets)} R {e.income.toFixed(2)}{change(e.change?.income)} {e.checkedIn}{e.sessions > 0 && avg/session}{change(e.change?.checkedIn)} {e.attendanceRate != null ? `${e.attendanceRate}%` : "—"}

Each change is against the event before. Income leaves out donations applied to orders (they count when they were given).

); })()}
)} {report === "feedbackSummary" && (
{feedbackSummary.perEvent.length === 0 ? (
None of the selected events has a feedback form. Add one in the event wizard's Feedback step.
) : ( <> {feedbackSummary.chart.length > 1 && (
Average rating, by event
`${v} / 5`} />
)} {feedbackSummary.perEvent.map((f) => (
{f.title}
{f.sentAt ? `${f.responses} of ${f.invited} responded${f.responseRate != null ? ` (${f.responseRate}%)` : ""}` : "Not sent yet"}{f.anonymous ? " · anonymous" : ""}
{(f.questions || []).map((q) => (
{q.label} · {q.answered} answer(s)
{q.type === "rating" && (
{q.average ?? "—"} / 5
String(v)} />
)} {q.counts &&
String(v)} />
} {q.type === "numeric" &&
Average: {q.average ?? "—"}
} {q.texts && ( q.texts.length === 0 ?
No answers.
: (
    {q.texts.map((t, i) => (
  • {t.value}{t.name && — {t.name}}
  • ))}
) )}
))}
))} )}
)} {(report === "consentStatus" || report === "medicalList") && (() => { const payload = buildReportPayload(); const rows = payload?.table?.rows || []; const cols: string[] = payload?.table?.columns || []; return (
{report === "medicalList" &&
Confidential — for event leaders only. Viewing this list is recorded in the audit log.
} {payload?.stats && ( {payload.stats.map((s) => )} )} {rows.length === 0 ? (
Nothing to show — pick youth events (ones that need parental consent) in the filters.
) : (
{cols.map(c => )} {rows.map((r, i) => ( {r.map((cell, j) => )} ))}
{c}
{String(cell ?? '')}
)}
); })()} {report === "discounts" && (
{discountSummary.rows.length === 0 ? (
No discount codes or bundle deals used for the selected events and dates.
) : ( <>
Value given away, by code or bundle
`R ${v.toFixed(2)}`} />
{discountSummary.rows.map(row => ( ))}
Code / bundle Discount Event Uses Value (R)
{row.code} {row.summary} {row.event} {row.uses} R {row.total.toFixed(2)}
Total {discountSummary.totalUses} R {discountSummary.totalValue.toFixed(2)}
)}
)} {report === "donations" && (
{Object.keys(paymentsByEvent).length === 0 ? (
No data. Select events and view.
) : (() => { // A donation is never mutated once assigned — its "used" amount is the // sum of every leg (isDonation:false, originalPaymentId -> the donation) // referencing it, which — since a donation and its legs share the event // it was logged against in the common case — are already present in the // same per-event payments list. Math.abs(): a refund of the donation itself // also creates such a leg, with a negative amount, which must reduce "used" // rather than inflate "unused" via a raw signed sum. const usedFor = (evId: string, donationId: string) => (paymentsByEvent[evId] || []).filter((leg) => !leg.isDonation && leg.originalPaymentId === donationId) .reduce((s, leg) => s + Math.abs(leg.amount || 0), 0); let grandTotal = 0, grandUsed = 0, grandCount = 0; const perEvent = Object.keys(paymentsByEvent).map(evId => { const ev = filteredEvents.find(e => e.id === evId); const dons = (paymentsByEvent[evId] || []).filter((p) => p.isDonation); const total = dons.reduce((s, p) => s + (p.amount || 0), 0); const used = dons.reduce((s, p) => s + usedFor(evId, p.id), 0); const unused = Math.max(total - used, 0); grandTotal += total; grandUsed += used; grandCount += dons.length; const pool = dons.filter((p) => p.isSponsorship); const poolIn = pool.reduce((s, p) => s + (p.amount || 0), 0); const poolUsed = pool.reduce((s, p) => s + usedFor(evId, p.id), 0); return { evId, title: ev?.title || evId, total, used, unused, count: dons.length, poolIn, poolUsed, poolLeft: Math.max(poolIn - poolUsed, 0) }; }); const grandUnused = Math.max(grandTotal - grandUsed, 0); return ( <>
Used vs. unused, across all selected events
`R ${v.toFixed(2)}`} />
{perEvent.map(row => ( ))}
Event Donations (R) Used (R) Unused (R) Count Avg (R) Sponsorship pool (R) Pool assigned (R) Pool remaining (R)
{row.title} R {row.total.toFixed(2)} R {row.used.toFixed(2)} R {row.unused.toFixed(2)} {row.count} {row.count ? `R ${(row.total / row.count).toFixed(2)}` : '-'} R {row.poolIn.toFixed(2)} R {row.poolUsed.toFixed(2)} R {row.poolLeft.toFixed(2)}
Total R {grandTotal.toFixed(2)} R {grandUsed.toFixed(2)} R {grandUnused.toFixed(2)} {grandCount} R {perEvent.reduce((s, r) => s + r.poolIn, 0).toFixed(2)} R {perEvent.reduce((s, r) => s + r.poolUsed, 0).toFixed(2)} R {perEvent.reduce((s, r) => s + r.poolLeft, 0).toFixed(2)}
); })()}
)} {report === "masterOrders" && (
{masterRows.length === 0 ? (
No registrations found.
) : ( <>
Totals
"Paid" is only what each person actually paid themselves — money that reached their order via an assigned donation shows separately under "Paid via donation" and is attributed to the donor below, not the registrant. "Unassigned donations" is real money already received that hasn't been applied to any order yet.
Orders
setMasterOrderSearch(e.target.value)} />
{masterOptions.map(opt => ( ))} {masterRows .filter(r => { const q = masterOrderSearch.trim().toLowerCase(); if (!q) return true; return [r.eventTitle, r.name, r.email].some((v) => String(v || "").toLowerCase().includes(q)); }) .map((r, idx) => ( {masterOptions.map(opt => ( ))} ))} {masterOptions.map(opt => ( ))} {masterOptions.map(opt => ( ))} {masterOptions.map(opt => )}
Event Name Email{opt.name}Order Total Paid Paid via donation Outstanding
{r.eventTitle} {r.name} {r.email || ""} {r.qty[opt.name] ?? 0} R {r.orderTotal.toFixed(2)} R {r.totalPaid.toFixed(2)} {r.paidViaDonation > 0.000001 ? `R ${r.paidViaDonation.toFixed(2)}` : ''} R {r.outstanding.toFixed(2)}
TOTAL {masterTotals?.[opt.name] ?? 0} R {masterTotals?.orderTotal.toFixed(2)} R {masterTotals?.totalPaid.toFixed(2)} R {masterTotals?.paidViaDonation.toFixed(2)} R {masterTotals?.outstanding.toFixed(2)}
Revenue per Ticket R {(masterTotals?.[`${opt.name}_revenue`] ?? 0).toFixed(2)}
Unassigned donations R {masterTotals?.unassignedDonations.toFixed(2)}
Donations made
setMasterDonationSearch(e.target.value)} />
Every donation logged for these events, who gave it, and how much of it has been applied to an order (Used) versus still available (Unused). This is independent of the orders table above — a donation isn't tied to the donor's own order.
{donationsMadeRows.length === 0 ? (
No donations logged for these events.
) : (
{donationsMadeRows .filter(d => { const q = masterDonationSearch.trim().toLowerCase(); if (!q) return true; return [d.eventTitle, d.donor, d.email].some((v) => String(v || "").toLowerCase().includes(q)); }) .map((d, idx) => ( ))}
Event Donor Email Donated Used Unused
{d.eventTitle} {d.donor} {d.email || ""} R {d.amount.toFixed(2)} R {d.used.toFixed(2)} R {d.unused.toFixed(2)}
)}
)}
)} {report === "cashup" && (
{Object.keys(financialsByEvent).length === 0 ? (
No data available. Select events and view.
) : ( Object.keys(financialsByEvent).map(evId => { const f = financialsByEvent[evId]; const ev = filteredEvents.find(e => e.id === evId); if (!f) return null; return (
{ev?.title || evId}
{f.event?.cashupStatus === "closed" ? "Closed" : "Open"}
Income by method
({ label: METHOD_LABEL[m], value: f.paymentsByMethod?.[m] || 0 }))} valueFormatter={v => `R ${v.toFixed(2)}`} />
{METHOD_KEYS.map(m => { const r = f.reconciled?.byMethod?.[m]; return ( {m === "cash" && (r?.denominations || []).length > 0 && (r?.denominations || []).map((d) => ( ))} ); })}
MethodIncomeCosts from methodExpected cashActualVariance
{METHOD_LABEL[m]} R {(f.paymentsByMethod?.[m] || 0).toFixed(2)} R {(f.costsByMethod?.[m] || 0).toFixed(2)} R {(f.expectedCashByMethod?.[m] || 0).toFixed(2)} {r?.actual != null ? `R ${r.actual.toFixed(2)}` : not reconciled} {r?.variance != null ? `R ${r.variance.toFixed(2)}` : "—"}
{denomLabel(d.value)} × {d.count} R {(d.value * d.count).toFixed(2)}
{(f.untaggedCostsTotal || 0) > 0 && (
Untagged costs (not tied to a method)R {f.untaggedCostsTotal.toFixed(2)}
)}
Donations counted as profitR {(f.unallocatedDonationsTotal || 0).toFixed(2)}
); }) )}
)} {report === "financeReport" && (
{Object.keys(financialsByEvent).length === 0 ? (
No data available. Select events and view.
) : ( Object.keys(financialsByEvent).map(evId => { const f = financialsByEvent[evId]; const ev = filteredEvents.find(e => e.id === evId); if (!f) return null; return (
{ev?.title || evId}
0 ? "What was sold (after discounts)" : "What was sold"} value={`R ${((f.salesByOption || []).reduce((s, o) => s + (o.revenue || 0), 0) - (f.discountsTotal || 0)).toFixed(2)}`} tone="green" /> s + (f.paymentsByMethod?.[m] || 0), 0).toFixed(2)}`} tone="blue" /> {(f.salesByOption || []).length > 0 && (
What was sold
({ label: `${s.name} (${s.quantitySold})`, value: s.revenue }))} valueFormatter={v => `R ${v.toFixed(2)}`} />
)}
Paid by
({ label: METHOD_LABEL[m], value: f.paymentsByMethod?.[m] || 0 }))} valueFormatter={v => `R ${v.toFixed(2)}`} />
Comparison to cashup
{METHOD_KEYS.map(m => { const r = f.reconciled?.byMethod?.[m]; return ( ); })}
MethodExpectedActualVariance
{METHOD_LABEL[m]} R {(f.expectedCashByMethod?.[m] || 0).toFixed(2)} {r?.actual != null ? `R ${r.actual.toFixed(2)}` : not reconciled} {r?.variance != null ? `R ${r.variance.toFixed(2)}` : "—"}
{(f.costs || []).length > 0 && (
Costs
    {(f.costs || []).map((c) => (
  • {c.label}{c.paidFromMethod ? ` (via ${METHOD_LABEL[c.paidFromMethod]})` : ""}-R {(c.total ?? c.amount).toFixed(2)}
  • ))}
)}
); }) )}
)} {report === "profitReport" && (
{Object.keys(financialsByEvent).length === 0 ? (
No data available. Select events and view.
) : (() => { const evIds = Object.keys(financialsByEvent); const totals = evIds.reduce((acc, evId) => { const f = financialsByEvent[evId]; acc.revenue += f?.effectiveTotalRevenue || 0; acc.costs += f?.totalCosts || 0; acc.profit += f?.netProfit || 0; return acc; }, { revenue: 0, costs: 0, profit: 0 }); return ( <> {evIds.length > 1 && (
Net profit by event
({ label: filteredEvents.find(e => e.id === evId)?.title || evId, value: financialsByEvent[evId]?.netProfit || 0 }))} valueFormatter={v => `R ${v.toFixed(2)}`} />
)}
{evIds.map(evId => { const f = financialsByEvent[evId]; const ev = filteredEvents.find(e => e.id === evId); return ( ); })}
EventRevenueCostsNet profit
{ev?.title || evId} R {(f?.effectiveTotalRevenue || 0).toFixed(2)} R {(f?.totalCosts || 0).toFixed(2)} R {(f?.netProfit || 0).toFixed(2)}
); })()}
)} {report === "cashupAudit" && (
{auditRows.length === 0 ? (
No close/reopen actions match the selected filters.
) : ( auditRows.map((r) => (
{r.event?.title || r.eventId} — {actionLabel(r.action)} — {r.performedBy?.name || "Unknown"} — {new Date(r.createdAt).toLocaleString()}
{(r.action === "closed" || r.action === "quick_closed") && ( Donations counted as profit: R {(r.unallocatedDonationsTotal || 0).toFixed(2)} )}
{r.notes &&
Notes: {r.notes}
} {(r.action === "closed" || r.action === "quick_closed") && (
{(r.lines && r.lines.length > 0 ? r.lines : METHOD_KEYS.map(m => ({ method: m, expectedAmount: null, actualAmount: null, variance: null }))).map((l) => ( ))}
MethodExpectedActualVarianceΔ vs previous close
{METHOD_LABEL[l.method] || l.method} {l.expectedAmount != null ? `R ${l.expectedAmount.toFixed(2)}` : "—"} {l.actualAmount != null ? `R ${l.actualAmount.toFixed(2)}` : not reconciled} {l.variance != null ? `R ${l.variance.toFixed(2)}` : "—"} {r._deltaVsPrevious?.[l.method] != null ? `R ${r._deltaVsPrevious[l.method]!.toFixed(2)}` : {r._previousCloseAt ? "n/a" : "no previous close"}}
)}
)) )}
)} )}
)}
); }