diff --git a/apps/events/frontend/next.config.ts b/apps/events/frontend/next.config.ts index a19a4c9..01bb739 100644 --- a/apps/events/frontend/next.config.ts +++ b/apps/events/frontend/next.config.ts @@ -5,9 +5,6 @@ const nextConfig: NextConfig = { images: { domains: ['images.unsplash.com'], }, - eslint: { - ignoreDuringBuilds: true, - }, compiler: { removeConsole: process.env.NODE_ENV === 'production', }, diff --git a/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx index f69d1be..a774ac0 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx @@ -9,27 +9,8 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { ShieldCheck, Send, RefreshCw, HeartPulse, Printer } from "lucide-react"; import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table"; import { errorMessage } from "@/lib/utils"; -import type { Event } from "@/types"; +import type { Event, ConsentRow, MedicalRow } from "@/types"; -type ConsentRow = { - attendeeId: string; - name: string; - dateOfBirth: string | null; - minor: boolean; - parentName: string | null; - parentEmail: string | null; - parentPhone: string | null; - registrationStatus: string; - bookedBy: { name: string; email: string }; - status: "not_required" | "missing" | "pending" | "given" | "declined"; - request: { id: string; status: string; textVersion: number; signedName: string | null; respondedAt: string | null; lastSentAt: string; remindersSent: number; photoConsent: boolean | null; outdated: boolean } | null; -}; -type MedicalRow = { - name: string; dateOfBirth: string | null; parentName: string | null; parentPhone: string | null; parentEmail: string | null; - medical: { allergies: string; medication: string; conditions: string; medicalAid: string } | null; - emergency: { name: string; phone: string; relationship: string } | null; - photoConsent: boolean | null; purged: boolean; -}; const STATUS_STYLE: Record = { not_required: { label: "Not needed (18+)", cls: "bg-gray-100 text-gray-600" }, diff --git a/apps/events/frontend/src/components/reports/ReportsV2.tsx b/apps/events/frontend/src/components/reports/ReportsV2.tsx index 4756da3..863c23b 100644 --- a/apps/events/frontend/src/components/reports/ReportsV2.tsx +++ b/apps/events/frontend/src/components/reports/ReportsV2.tsx @@ -13,6 +13,8 @@ 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 type { ConsentRow, Event, EventCashup, EventFinancials, MedicalRow, Payment, Registration, 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" }; @@ -28,7 +30,7 @@ function money2(n: number | null | undefined): string { // 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: any): boolean { +function isDonationLeg(p: Payment): boolean { return !p?.isDonation && !!p?.originalPaymentId && (p?.amount || 0) > 0; } function actionLabel(action: string): string { @@ -36,25 +38,25 @@ function actionLabel(action: string): string { } // 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: any[]): any[] { - const byEvent: Record = {}; +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: any = null; + 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: any) => l.method === m); - const prevLine = (prevClose.lines || []).find((l: any) => l.method === 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; + r._previousCloseAt = prevClose?.createdAt; } prevClose = r; } @@ -63,30 +65,82 @@ function computeAuditDeltas(rows: any[]): any[] { return rows; } -// Effective per-unit price for a registration option, honoring an already-locked -// priceSnapshot first, then early-bird tier deadlines, then falling back to the -// base (variant or option) price. Mirrors optionUnitPrice on the Payments page. -function optionUnitPrice(ro: any, referenceTime: any, atTime: Date): number { - if (ro?.priceSnapshot !== null && ro?.priceSnapshot !== undefined) { - return Number(ro.priceSnapshot); - } - const eo = ro?.eventOption; - const variantId = ro?.variantId || null; - const base = (ro?.variant?.price !== null && ro?.variant?.price !== undefined) - ? Number(ro.variant.price) : Number(eo?.price || 0); - const allTiers = Array.isArray(eo?.earlyBirdTiers) ? eo.earlyBirdTiers.slice() : []; - const tiers = variantId ? allTiers.filter((t: any) => t.variantId === variantId) : allTiers.filter((t: any) => !t.variantId); - if (tiers.length === 0) return base; - const t = atTime ? new Date(atTime) : new Date(); - const ref = referenceTime ? new Date(referenceTime) : t; - const applicable = tiers - .map((x: any) => ({ ...x, deadline: new Date(x.deadline) })) - .filter((x: any) => (ref < x.deadline) && (t < x.deadline)) - .sort((a: any, b: any) => a.deadline.getTime() - b.deadline.getTime() || (a.order || 0) - (b.order || 0) || a.price - b.price); - if (applicable.length === 0) return base; - const price = Number(applicable[0].price); - return (price >= 0) ? price : base; -} +// 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, with a readable summary of the code. +type DiscountRow = { + id: string; + 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 }[]; +}; // Simple MultiSelect control used in filters export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { @@ -96,8 +150,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const searchParams = useSearchParams(); // Events list - const [events, setEvents] = useState([]); - const [loadingEvents, setLoadingEvents] = useState(false); + const [events, setEvents] = useState([]); const [error, setError] = useState(null); const [showPastEvents, setShowPastEvents] = useState(false); const [showInactiveEvents, setShowInactiveEvents] = useState(false); @@ -122,13 +175,10 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { useEffect(() => { (async () => { try { - setLoadingEvents(true); - const evs = await apiFetch("/api/events/all?includePast=true&includeInactive=true", { authToken: token || undefined }); + const evs = await apiFetch("/api/events/all?includePast=true&includeInactive=true", { authToken: token || undefined }); setEvents(Array.isArray(evs) ? evs : []); } catch (e) { setError(errorMessage(e) || "Failed to load events"); - } finally { - setLoadingEvents(false); } })(); }, [token, role]); @@ -165,24 +215,24 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { 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: any) => statusCountMode === 'tickets' - ? (r.registrationOptions || []).reduce((s: number, ro: any) => s + (ro.quantity || 0), 0) + 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 [paymentsByEvent, setPaymentsByEvent] = useState>({}); + const [registrationsByEvent, setRegistrationsByEvent] = useState>({}); const [ticketUsage, setTicketUsage] = useState>({}); - const [financialsByEvent, setFinancialsByEvent] = useState>({}); - const [auditRows, setAuditRows] = useState([]); - const [discountRows, setDiscountRows] = 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([]); - const [medicalRows, setMedicalRows] = useState([]); + 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([]); + const [feedbackRows, setFeedbackRows] = useState([]); // Registration funnel for the selected events (null until viewed). - const [funnel, setFunnel] = useState(null); + const [funnel, setFunnel] = useState(null); // 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 @@ -200,7 +250,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { if (!reportParam || !REPORTS.some(r => r.key === reportParam)) return; deepLinkHandledRef.current = true; setReport(reportParam as ReportKey); - setSelectedEventIds(filteredEvents.map((e: any) => e.id)); + setSelectedEventIds(filteredEvents.map((e) => e.id)); if (searchParams.get("range") === "trailing_month") { const now = new Date(); const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 30); @@ -222,27 +272,26 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [autoViewPending, selectedEventIds, report]); - // Initialize default selection when events load + // 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 && selectedEventIds.length === 0) setSelectedEventIds(filteredEvents.slice(0, 1).map((e: any) => e.id)); - if (!attEventId) setAttEventId(filteredEvents[0].id); + 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(() => { - if (selectedEventIds.length > 0 && !selectedEventIds.includes(attEventId)) { - setAttEventId(selectedEventIds[0]); - } + 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 = {}; + 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 }); + const list = await apiFetch(`/api/payments/event/${encodeURIComponent(id)}`, { authToken: token }); byEv[id] = Array.isArray(list) ? list : []; } catch { byEv[id] = []; @@ -252,11 +301,11 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { }; const loadRegistrations = async (eventIds: string[]) => { - if (!token || !eventIds.length) return {} as Record; - const byEv: Record = {}; + 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 }); + const list = await apiFetch(`/api/registrations/event/${encodeURIComponent(id)}`, { authToken: token }); byEv[id] = Array.isArray(list) ? list : []; } catch { byEv[id] = []; @@ -270,7 +319,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const result: Record = {}; for (const id of eventIds) { try { - const tickets = await apiFetch(`/api/tickets/event/${encodeURIComponent(id)}`, { authToken: token }); + 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 }; @@ -280,11 +329,11 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { }; const loadFinancials = async (eventIds: string[]) => { - if (!token || !eventIds.length) return {} as Record; - const byEv: Record = {}; + 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 }); + byEv[id] = await apiFetch(`/api/cashups/event/${encodeURIComponent(id)}`, { authToken: token }); } catch { byEv[id] = null; } @@ -298,16 +347,16 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { if (dateFrom) query.set("from", dateFrom); if (dateTo) query.set("to", dateTo); try { - return await apiFetch(`/api/analytics/funnel?${query.toString()}`, { authToken: token }); + return await apiFetch(`/api/analytics/funnel?${query.toString()}`, { authToken: token }); } catch { return null; } }; const loadFeedback = async (eventIds: string[]) => { - if (!token || !eventIds.length) return [] as any[]; + if (!token || !eventIds.length) return []; try { - return await apiFetch(`/api/feedback/summary?eventIds=${encodeURIComponent(eventIds.join(","))}`, { authToken: token }); + return await apiFetch(`/api/feedback/summary?eventIds=${encodeURIComponent(eventIds.join(","))}`, { authToken: token }); } catch { return []; } @@ -315,39 +364,42 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { // Coupon uses (active redemptions on non-cancelled registrations) for the Discounts report. const loadDiscounts = async (eventIds: string[]) => { - if (!token || !eventIds.length) return [] as any[]; + 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 }); + return await apiFetch(`/api/coupons/redemptions?${query.toString()}`, { authToken: token }); } catch { return []; } }; - const loadConsent = async (eventIds: string[], kind: "status" | "medical") => { - if (!token) return [] as any[]; - const out: any[] = []; + // 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: any) => e.id === id); + const ev = filteredEvents.find((e) => e.id === id); if (!ev?.requiresParentalConsent) continue; try { - const res = await apiFetch(`/api/consent/events/${encodeURIComponent(id)}${kind === "medical" ? "/medical" : ""}`, { authToken: token }); - (res?.rows || []).forEach((r: any) => out.push({ ...r, eventTitle: ev.title })); + 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 [] as any[]; + 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 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()); @@ -383,23 +435,23 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { 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: any) => { - const avgs = (f.questions || []).filter((q: any) => q.type === "rating" && q.average != null).map((q: any) => q.average); - return avgs.length ? Math.round((avgs.reduce((s: number, n: number) => s + n, 0) / avgs.length) * 10) / 10 : null; + 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) / rated.length) * 10) / 10 : null, - chart: rated.map(f => ({ label: f.title, value: f.rating })), + 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: any) => + 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: any) => `${c.label}: ${c.value}`).join(" · ") + : q.counts ? q.counts.map((c) => `${c.label}: ${c.value}`).join(" · ") : `${(q.texts || []).length} answer(s)`; // View handler according to selected report @@ -477,7 +529,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { // 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: any) => { + const getPaymentMethod = (p: Payment) => { const m = String(p?.method || "").toLowerCase(); if (m.includes("cash")) return "Cash"; if (m.includes("eft")) return "EFT"; @@ -487,10 +539,10 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { // Derived rows for payments (apply date filter) const paymentRows = useMemo(() => { - if (report !== "payments") return [] as any[]; + if (report !== "payments") return [] as PaymentRow[]; const df = payFrom ? new Date(payFrom).getTime() : null; const dt = payTo ? new Date(payTo).getTime() : null; - const rows: { eventId: string; eventTitle: string; userName: string; userEmail?: string; amount: number; method: string; isDonation?: boolean; createdAt: string; recordedByName: string }[] = []; + const rows: PaymentRow[] = []; for (const evId of Object.keys(paymentsByEvent)) { const ev = filteredEvents.find(e => e.id === evId); const evTitle = ev?.title || evId; @@ -501,7 +553,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { 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 = p.isDonation ? (p.user || {}) : ((p.registration?.user || p.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)) @@ -532,7 +584,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const paidByReg = new Map(); const lastPaymentAtByReg = new Map(); Object.keys(paymentsByEvent).forEach(evId => { - (paymentsByEvent[evId] || []).forEach((p: any) => { + (paymentsByEvent[evId] || []).forEach((p) => { if (p.registrationId) { const regId = p.registrationId; paidByReg.set(regId, (paidByReg.get(regId) || 0) + (p.amount || 0)); @@ -546,17 +598,17 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { 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: any) => { + (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 ? r.totalDueComputed : (r.registrationOptions || []).reduce((sum: number, ro: any) => sum + optionUnitPrice(ro, lastAt, now) * (ro.quantity || 0), 0); + 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: number, ro: any) => sum + optionUnitPrice(ro, lastAt, lastAt) * (ro.quantity || 0), 0); + 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); @@ -565,25 +617,11 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { return map; }, [paymentsByEvent, registrationsByEvent]); - const donationsByEvent = useMemo(() => { - const map = new Map(); - - Object.keys(paymentsByEvent).forEach(evId => { - const total = (paymentsByEvent[evId] || []) - .filter((p: any) => p.isDonation) - .reduce((sum: number, p: any) => sum + (p.amount || 0), 0); - - map.set(evId, total); - }); - - return map; - }, [paymentsByEvent]); - // 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: any) => { + (paymentsByEvent[evId] || []).forEach((p) => { if (p.registrationId) { map.set(p.registrationId, (map.get(p.registrationId) || 0) + (p.amount || 0)); } @@ -599,7 +637,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const paidViaDonationByReg = useMemo(() => { const map = new Map(); Object.keys(paymentsByEvent).forEach(evId => { - (paymentsByEvent[evId] || []).forEach((p: any) => { + (paymentsByEvent[evId] || []).forEach((p) => { if (p.registrationId && isDonationLeg(p)) { map.set(p.registrationId, (map.get(p.registrationId) || 0) + (p.amount || 0)); } @@ -618,13 +656,13 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const ev = filteredEvents.find(e => e.id === evId); const evTitle = ev?.title || evId; const evPayments = paymentsByEvent[evId] || []; - evPayments.filter((p: any) => p.isDonation).forEach((donation: any) => { + 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: any) => !leg.isDonation && leg.originalPaymentId === donation.id) - .reduce((s: number, leg: any) => s + Math.abs(leg.amount || 0), 0); + .filter((leg) => !leg.isDonation && leg.originalPaymentId === donation.id) + .reduce((s, leg) => s + Math.abs(leg.amount || 0), 0); rows.push({ eventId: evId, eventTitle: evTitle, @@ -642,11 +680,10 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { }, [paymentsByEvent, filteredEvents]); const revDetRows = useMemo(() => { - if (report !== "revenueDetailed") return [] as any[]; + if (report !== "revenueDetailed") return [] as RevenueDetailRow[]; const df = payFrom ? new Date(payFrom).getTime() : null; const dt = payTo ? new Date(payTo).getTime() : null; - type Row = { eventId: string; eventTitle: string; userName: string; userEmail?: string; totalPaid: number; status?: string; registrationId: string; outstanding: number }; - const rows: Row[] = []; + 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 @@ -655,7 +692,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { Object.keys(registrationsByEvent).forEach(evId => { const ev = filteredEvents.find(e => e.id === evId); const evTitle = ev?.title || evId; - (registrationsByEvent[evId] || []).forEach((r: any) => { + (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; @@ -699,11 +736,11 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { // Derived for attendees (layered) for a single event const attendeesLayer = useMemo(() => { - if (report !== "attendees") return { eventTitle: "", options: [] as any[] }; + 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(); + const byOption = new Map(); for (const r of regs) { if (!attIncludeCancelled && r.status === "cancelled") continue; @@ -772,9 +809,9 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const map = new Map(); - Object.values(registrationsByEvent).forEach((regs: any) => { - regs.forEach((r: any) => { - (r.registrationOptions || []).forEach((ro: any) => { + Object.values(registrationsByEvent).forEach((regs) => { + regs.forEach((r) => { + (r.registrationOptions || []).forEach((ro) => { const id = ro.eventOption?.id; const name = ro.eventOption?.name; @@ -795,18 +832,18 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const masterRows = useMemo(() => { if (report !== "masterOrders") return []; - const rows: any[] = []; + 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: any) => { + (registrationsByEvent[evId] || []).forEach((r) => { if (r.status === "cancelled") return; const optionQtyMap = new Map(); - (r.registrationOptions || []).forEach((ro: any) => { + (r.registrationOptions || []).forEach((ro) => { const id = ro.eventOption?.id; const qty = ro.quantity || 0; @@ -820,7 +857,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { // 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: any = { + const baseRow: MasterRow = { eventTitle, name: r.user?.name || "User", email: r.user?.email, @@ -828,29 +865,27 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { totalPaid: directPaid, outstanding: outstandingByReg.get(r.id) || 0, paidViaDonation, - __prices: {} as Record // 👈 hidden helper + qty: {}, + revenue: {}, }; // 👇 Dynamic columns masterOptions.forEach(opt => { const qty = optionQtyMap.get(opt.id) || 0; - baseRow[opt.name] = qty; + baseRow.qty[opt.name] = qty; const ro = (r.registrationOptions || []) - .find((x: any) => x.eventOption?.id === opt.id); + .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. __prices stores an *average* unit price derived from that, purely - // for display; __revenue carries the real total used for aggregation below. + // 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.__prices[opt.name] = qty > 0 ? lineTotal / qty : 0; - baseRow.__revenue = baseRow.__revenue || {}; - baseRow.__revenue[opt.name] = lineTotal; + baseRow.revenue[opt.name] = lineTotal; baseRow.orderTotal += lineTotal; }); @@ -871,7 +906,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const masterTotals = useMemo(() => { if (report !== "masterOrders") return null; - const totals: any = { + const totals: Record = { orderTotal: 0, totalPaid: 0, outstanding: 0, @@ -891,12 +926,12 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { totals.paidViaDonation += row.paidViaDonation || 0; masterOptions.forEach(opt => { - const qty = row[opt.name] || 0; + 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); + totals[`${opt.name}_revenue`] += Number(row.revenue[opt.name] ?? 0); }); }); @@ -926,7 +961,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { if (report === "attendees") { const sections = attendeesLayer.options.map(opt => ({ title: opt.optionName, - items: opt.users.map((u: any) => `${u.name}${u.email ? ` (${u.email})` : ''} — ${u.status}${typeof u.qty==='number' ? ` • Qty: ${u.qty}` : ''}`) + 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 } }; } @@ -961,14 +996,14 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const byMethodTotal: Record = {}; Object.keys(paymentsByEvent).forEach(evId => { const ev = filteredEvents.find(e => e.id === evId); - const list = (paymentsByEvent[evId] || []).filter((p: any) => { + 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: any) => { const m = getPaymentMethod(p); byMethod[m] = (byMethod[m] || 0) + (p.amount || 0); byMethodTotal[m] = (byMethodTotal[m] || 0) + (p.amount || 0); total += (p.amount || 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))])); }); @@ -979,7 +1014,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { }; } if (report === "revenueDetailed") { - const rows: (string|number)[][] = (revDetRows as any[]).map(r => [ + 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 || "", ]); @@ -995,7 +1030,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { 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: any) => { if (!statusIncludeCancelled && r.status === 'cancelled') return; counts[r.status] = (counts[r.status] || 0) + countForStatus(r); agg[r.status] = (agg[r.status] || 0) + countForStatus(r); }); + 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'; @@ -1012,21 +1047,21 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { // 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: any) => !leg.isDonation && leg.originalPaymentId === donationId) - .reduce((s: number, leg: any) => s + Math.abs(leg.amount || 0), 0); + (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: any) => p.isDonation); - const total = dons.reduce((s: number, p: any) => s + (p.amount || 0), 0); - const used = dons.reduce((s: number, p: any) => s + usedFor(evId, p.id), 0); + 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: any) => p.isSponsorship); - const poolIn = pool.reduce((s: number, p: any) => s + (p.amount || 0), 0); - const poolUsed = pool.reduce((s: number, p: any) => s + usedFor(evId, p.id), 0); + 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); @@ -1060,13 +1095,13 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { } if (report === "funnel" && funnel) { const pct = (v: number | null) => (v != null ? `${v}%` : "—"); - const line = (label: string, c: any) => [label, c.view, c.start, c.submit, c.paid, pct(c.conversion ?? (c.view ? Math.round((c.paid / c.view) * 1000) / 10 : null))]; + 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: any) => line(p.title, p.totals)) : [], - ...funnel.bySource.map((s: any) => line(`Source: ${s.key}`, s)), - ...funnel.byDevice.map((d: any) => line(`Device: ${d.key}`, d)), - ...funnel.byOption.map((o: any) => [`Ticket: ${o.key}`, "", "", o.submitted, o.paid, ""]), + ...(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', @@ -1103,7 +1138,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { }; } if (report === "medicalList") { - const fmt = (m: any) => 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('; ') : ''; + 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.', @@ -1145,7 +1180,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { incomeByMethod[m] = (incomeByMethod[m] || 0) + (f.paymentsByMethod?.[m] || 0); 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)), r?.actual != null ? Number(r.actual.toFixed(2)) : "not reconciled", r?.variance != null ? Number(r.variance.toFixed(2)) : ""]); if (m === "cash") { - (r?.denominations || []).forEach((d: any) => rows.push([title, ` ${denomLabel(d.value)} × ${d.count}`, "", "", "", Number((d.value * d.count).toFixed(2)), ""])); + (r?.denominations || []).forEach((d) => rows.push([title, ` ${denomLabel(d.value)} × ${d.count}`, "", "", "", Number((d.value * d.count).toFixed(2)), ""])); } }); if ((f.untaggedCostsTotal || 0) > 0) rows.push([title, "Untagged costs", "", Number(f.untaggedCostsTotal.toFixed(2)), "", "", ""]); @@ -1166,7 +1201,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { const ev = filteredEvents.find(e => e.id === evId); if (!f) return; const title = ev?.title || evId; - sold += (f.salesByOption || []).reduce((s: number, o: any) => s + (o.revenue || 0), 0) - (f.discountsTotal || 0); + 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; @@ -1179,8 +1214,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { // 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: any) => rows.push([title, "", `${s.name} (${s.quantitySold} sold)`, Number(s.revenue.toFixed(2))])); - if (f.discountsTotal > 0) rows.push([title, "", "Less discount codes", -Number(f.discountsTotal.toFixed(2))]); + (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 discount codes", -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", "", ""]); @@ -1189,7 +1224,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { rows.push([title, "", `${METHOD_LABEL[m]} — expected / actual / variance`, `${money2(f.expectedCashByMethod?.[m])} / ${r?.actual != null ? money2(r.actual) : "—"} / ${r?.variance != null ? money2(r.variance) : "—"}`]); }); rows.push([title, "Costs", "", ""]); - (f.costs || []).forEach((c: any) => rows.push([title, "", `${c.label}${c.paidFromMethod ? ` (via ${METHOD_LABEL[c.paidFromMethod]})` : ""}`, Number((-(c.total ?? c.amount)).toFixed(2))])); + (f.costs || []).forEach((c) => rows.push([title, "", `${c.label}${c.paidFromMethod ? ` (via ${METHOD_LABEL[c.paidFromMethod]})` : ""}`, Number((-(c.total ?? c.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))]); }); @@ -1233,12 +1268,12 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { } if (report === "cashupAudit") { const rows: (string | number)[][] = []; - auditRows.forEach((r: any) => { + 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: any) => 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 || ""])); + (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)}`]); } }); @@ -1250,7 +1285,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { if (report === "masterOrders") { const bodyRows: (string | number)[][] = masterRows.map(r => [ r.eventTitle, r.name, r.email || "", - ...masterOptions.map(opt => r[opt.name] ?? 0), + ...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([ @@ -1357,40 +1392,6 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { } }; - // Rendering helpers - function htmlTable(headers: string[], rows: (string | number)[][]) { - const thead = `${headers.map(h => `${escapeHtml(h)}`).join("")}`; - const tbody = rows.map(r => `${r.map(c => `${escapeHtml(String(c ?? ""))}`).join("")}`).join(""); - return `${thead}${tbody}
`; - } - function htmlLayered(eventTitle: string, options: { optionName: string; users: { name: string; email?: string; status: string; qty?: number }[] }[]) { - const optHtml = options.map(opt => ` -
-
${escapeHtml(opt.optionName)}
-
    - ${opt.users.map(u => `
  • ${escapeHtml(u.name || "")}${u.email ? ` ` : ""} — ${escapeHtml(u.status)}${typeof u.qty === 'number' ? ` • Qty: ${u.qty}` : ''}
  • `).join("")} -
-
- `).join(""); - return ` - -
${escapeHtml(eventTitle)}
- ${optHtml} - `; - } - function escapeHtml(s: string) { - return s.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"','\'':'''}[c] as string)); - } - // 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. @@ -1477,19 +1478,19 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
No payments match the selected filters.
) : (
- {Object.entries(paymentRows.reduce((acc: any, r: any) => { + {Object.entries(paymentRows.reduce>((acc, r) => { acc[r.eventTitle] = acc[r.eventTitle] || []; acc[r.eventTitle].push(r); return acc; - }, {})).map(([eventTitle, rows]: any) => { + }, {})).map(([eventTitle, rows]) => { // group by user - const byUser: Record = {}; - rows.forEach((r: any) => { + const byUser: Record = {}; + rows.forEach((r) => { const key = r.userName || 'User'; byUser[key] = byUser[key] || []; byUser[key].push(r); }); - const eventTotal = rows.reduce((s: number, r: any) => s + (r.amount || 0), 0); + const eventTotal = rows.reduce((s, r) => s + (r.amount || 0), 0); return (
@@ -1499,8 +1500,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
{Object.keys(byUser).sort().map(userName => { const list = byUser[userName]; - const userTotal = list.reduce((s: number, r: any) => s + (r.amount || 0), 0); - const email = list.find((r: any) => r.userEmail)?.userEmail || ''; + const userTotal = list.reduce((s, r) => s + (r.amount || 0), 0); + const email = list.find((r) => r.userEmail)?.userEmail || ''; return (
@@ -1508,7 +1509,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
Subtotal: R {userTotal.toFixed(2)}
    - {list.map((r: any, i: number) => ( + {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()} @@ -1538,7 +1539,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
    {opt.optionName}
      - {opt.users.map((u: any, i: number) => ( + {opt.users.map((u, i) => (
    • {u.name} {u.email && ({u.email})} @@ -1628,14 +1629,14 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { 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: any) => { + 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: any) => { const m = getPaymentMethod(p); byMethod[m] = (byMethod[m] || 0) + (p.amount || 0); total += (p.amount || 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 (
      @@ -1662,7 +1663,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { ) : ( Object.keys(registrationsByEvent).map(evId => { const ev = events.find(e => e.id === evId); - const rows = (revDetRows as any[]).filter(r => r.eventId === 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); @@ -1717,8 +1718,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { <> {(() => { const agg: Record = { pending: 0, partial_paid: 0, paid: 0, cancelled: 0 }; - Object.values(registrationsByEvent).forEach((regs: any) => { - (regs || []).forEach((r: any) => { if (!statusIncludeCancelled && r.status === 'cancelled') return; agg[r.status] = (agg[r.status] || 0) + countForStatus(r); }); + 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 ( @@ -1752,7 +1753,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { 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: any) => { if (!statusIncludeCancelled && r.status === 'cancelled') return; counts[r.status] = (counts[r.status] || 0) + countForStatus(r); }); + regs.forEach((r) => { if (!statusIncludeCancelled && r.status === 'cancelled') return; counts[r.status] = (counts[r.status] || 0) + countForStatus(r); }); return ( {ev?.title || evId} @@ -1782,7 +1783,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { { 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: any[]) => rows.length === 0 ? null : ( + const table = (title: string, rows: (FunnelCounts & { key: string; conversion: number | null })[]) => rows.length === 0 ? null : (
      @@ -1792,7 +1793,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { - {rows.map((r: any) => ( + {rows.map((r) => ( @@ -1817,10 +1818,10 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { {funnel.trend.length > 1 && (
      Event page visits per day
      - ({ label: t.day.slice(5), value: t.view }))} /> + ({ label: t.day.slice(5), value: t.view }))} />
      )} - {(funnel.perEvent || []).length > 1 && table("Event", funnel.perEvent.map((p: any) => ({ key: p.title, ...p.totals, conversion: p.conversion.paid })))} + {(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 && ( @@ -1828,7 +1829,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
      {r.key}{r.view}{r.start} {r.submit}{r.paid}{pct(r.conversion)}
      - {funnel.byOption.map((o: any) => ( + {funnel.byOption.map((o) => ( ))} @@ -1858,7 +1859,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { `${v} / 5`} /> )} - {feedbackSummary.perEvent.map((f: any) => ( + {feedbackSummary.perEvent.map((f) => (
      {f.title}
      @@ -1867,13 +1868,13 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
      - {(f.questions || []).map((q: any) => ( + {(f.questions || []).map((q) => (
      {q.label} · {q.answered} answer(s)
      {q.type === "rating" && (
      {q.average ?? "—"} / 5
      - String(v)} /> + String(v)} />
      )} {q.counts &&
      String(v)} />
      } @@ -1881,7 +1882,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { {q.texts && ( q.texts.length === 0 ?
      No answers.
      : (
        - {q.texts.map((t: any, i: number) => ( + {q.texts.map((t, i) => (
      • {t.value}{t.name && — {t.name}}
      • ))}
      @@ -1897,15 +1898,15 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
      )} {(report === "consentStatus" || report === "medicalList") && (() => { - const payload: any = buildReportPayload(); - const rows: any[] = payload?.table?.rows || []; + 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: any) => )} + {payload.stats.map((s) => )} )} {rows.length === 0 ? ( @@ -1921,7 +1922,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
      {rows.map((r, i) => ( - {r.map((cell: any, j: number) => )} + {r.map((cell, j) => )} ))} @@ -1992,19 +1993,19 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { // 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: any) => !leg.isDonation && leg.originalPaymentId === donationId) - .reduce((s: number, leg: any) => s + Math.abs(leg.amount || 0), 0); + (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: any) => p.isDonation); - const total = dons.reduce((s: number, p: any) => s + (p.amount || 0), 0); - const used = dons.reduce((s: number, p: any) => s + usedFor(evId, p.id), 0); + 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: any) => p.isSponsorship); - const poolIn = pool.reduce((s: number, p: any) => s + (p.amount || 0), 0); - const poolUsed = pool.reduce((s: number, p: any) => s + usedFor(evId, p.id), 0); + 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); @@ -2122,7 +2123,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { .filter(r => { const q = masterOrderSearch.trim().toLowerCase(); if (!q) return true; - return [r.eventTitle, r.name, r.email].some((v: any) => String(v || "").toLowerCase().includes(q)); + return [r.eventTitle, r.name, r.email].some((v) => String(v || "").toLowerCase().includes(q)); }) .map((r, idx) => ( @@ -2132,7 +2133,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { {masterOptions.map(opt => ( ))} @@ -2215,7 +2216,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { .filter(d => { const q = masterDonationSearch.trim().toLowerCase(); if (!q) return true; - return [d.eventTitle, d.donor, d.email].some((v: any) => String(v || "").toLowerCase().includes(q)); + return [d.eventTitle, d.donor, d.email].some((v) => String(v || "").toLowerCase().includes(q)); }) .map((d, idx) => ( @@ -2274,7 +2275,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { - {m === "cash" && (r?.denominations || []).length > 0 && (r?.denominations || []).map((d: any) => ( + {m === "cash" && (r?.denominations || []).length > 0 && (r?.denominations || []).map((d) => ( @@ -2311,7 +2312,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
      {ev?.title || evId}
      - 0 ? "What was sold (after discounts)" : "What was sold"} value={`R ${((f.salesByOption || []).reduce((s: number, o: any) => s + (o.revenue || 0), 0) - (f.discountsTotal || 0)).toFixed(2)}`} tone="green" /> + 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" /> @@ -2322,7 +2323,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
      What was sold
      ({ label: `${s.name} (${s.quantitySold})`, value: s.revenue }))} + data={(f.salesByOption || []).map((s) => ({ label: `${s.name} (${s.quantitySold})`, value: s.revenue }))} valueFormatter={v => `R ${v.toFixed(2)}`} />
      @@ -2360,7 +2361,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
      Costs
        - {(f.costs || []).map((c: any) => ( + {(f.costs || []).map((c) => (
      • {c.label}{c.paidFromMethod ? ` (via ${METHOD_LABEL[c.paidFromMethod]})` : ""}-R {(c.total ?? c.amount).toFixed(2)}
      • ))}
      @@ -2432,7 +2433,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) { {auditRows.length === 0 ? (
      No close/reopen actions match the selected filters.
      ) : ( - auditRows.map((r: any) => ( + auditRows.map((r) => (
      @@ -2449,13 +2450,13 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
      Ticket optionRegistrationsPaid
      {o.key}{o.submitted}{o.paid}
      {String(cell ?? '')}{String(cell ?? '')}
      - {r[opt.name] ?? 0} + {r.qty[opt.name] ?? 0}
      {r?.actual != null ? `R ${r.actual.toFixed(2)}` : not reconciled} {r?.variance != null ? `R ${r.variance.toFixed(2)}` : "—"}
      {denomLabel(d.value)} × {d.count}
      - {(r.lines && r.lines.length > 0 ? r.lines : METHOD_KEYS.map(m => ({ method: m, expectedAmount: null, actualAmount: null, variance: null }))).map((l: any) => ( + {(r.lines && r.lines.length > 0 ? r.lines : METHOD_KEYS.map(m => ({ method: m, expectedAmount: null, actualAmount: null, variance: null }))).map((l) => ( - + ))} diff --git a/apps/events/frontend/src/types/index.ts b/apps/events/frontend/src/types/index.ts index ad7dffd..2f5b8e2 100644 --- a/apps/events/frontend/src/types/index.ts +++ b/apps/events/frontend/src/types/index.ts @@ -251,6 +251,8 @@ export type EventFinancials = { effectiveGrossIncomeByMethod: Record; effectiveTotalRevenue: number; netProfit: number; + // Coupon discounts given on the event's registrations. + discountsTotal?: number; unallocatedDonations: Payment[]; unallocatedDonationsTotal: number; totalDonations: number; @@ -273,6 +275,8 @@ export type RegistrationOption = { tranches?: { id: string; quantity: number; priceSnapshot: number; appliedTierId?: string | null }[]; tickets?: { id: string; quantity?: number }[]; registration?: Registration; + // Tranche-aware total for the line, attached by registration list endpoints. + lineTotal?: number | null; }; // A named person on a group registration, for one main-ticket place. @@ -413,6 +417,29 @@ export type MessageSendResult = { job?: { id: string }; }; +// One person's parental-consent status on a youth event (GET /api/consent/events/:id). +export type ConsentRow = { + attendeeId: string; + name: string; + dateOfBirth: string | null; + minor: boolean; + parentName: string | null; + parentEmail: string | null; + parentPhone: string | null; + registrationStatus: string; + bookedBy: { name: string; email: string }; + status: "not_required" | "missing" | "pending" | "given" | "declined"; + request: { id: string; status: string; textVersion: number; signedName: string | null; respondedAt: string | null; lastSentAt: string; remindersSent: number; photoConsent: boolean | null; outdated: boolean } | null; +}; + +// One person's medical/emergency details (GET /api/consent/events/:id/medical). +export type MedicalRow = { + name: string; dateOfBirth: string | null; parentName: string | null; parentPhone: string | null; parentEmail: string | null; + medical: { allergies: string; medication: string; conditions: string; medicalAid: string } | null; + emergency: { name: string; phone: string; relationship: string } | null; + photoConsent: boolean | null; purged: boolean; +}; + // A scanning section (e.g. "Main hall") and the ticket options valid at it. export type Section = { id: string;
      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"}}{r._deltaVsPrevious?.[l.method] != null ? `R ${r._deltaVsPrevious[l.method]!.toFixed(2)}` : {r._previousCloseAt ? "n/a" : "no previous close"}}