Series: year on year report (1.47.2)

New report (Reports -> Other, or "Compare" on the Event series page):
each event in a series side by side, oldest first - registrations,
tickets, income (dashboard definition), people checked in (average per
session on multi-session events) and attendance rate, with the change
from the event before. Exports like the other reports; campus-scoped
staff see only their campuses' events. GET /api/series/:id/compare.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 10:57:04 +02:00
co-authored by Claude Opus 5.5
parent e221d83ff8
commit bc8021cde0
24 changed files with 320 additions and 28 deletions
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "hope-events-frontend",
"version": "1.47.1",
"version": "1.47.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "hope-events-frontend",
"version": "1.47.1",
"version": "1.47.2",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@hookform/resolvers": "^5.2.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hope-events-frontend",
"version": "1.47.1",
"version": "1.47.2",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
@@ -3,7 +3,7 @@
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Layers, ExternalLink, Users } from "lucide-react";
import { Layers, ExternalLink, Users, BarChart3 } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
@@ -151,6 +151,11 @@ export default function SeriesPage() {
{s.description && <p className="text-sm text-gray-600 mt-1 whitespace-pre-line">{s.description}</p>}
</div>
<div className="flex gap-2 shrink-0">
{s.events.length > 0 && (
<Link href={`/dashboard/supervisor/reports?report=seriesComparison&series=${s.id}`} className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded border bg-white hover:bg-gray-50">
<BarChart3 className="w-3.5 h-3.5" /> Compare
</Link>
)}
<button type="button" className="text-xs px-3 py-1.5 rounded border bg-white hover:bg-gray-50"
onClick={() => { setDraft({ id: s.id, name: s.name, slug: s.slug, description: s.description || "", picture: s.picture || "" }); setNotice(null); }}>Edit</button>
{isAdmin && <button type="button" className="text-xs px-3 py-1.5 rounded bg-red-50 text-red-700 border border-red-200" onClick={() => remove(s)}>Delete</button>}
@@ -18,6 +18,7 @@ import {
HeartPulse,
MessageSquareHeart,
Filter,
Layers,
} from "lucide-react";
export type ReportCategory = "Financial" | "Registration" | "Ticketing" | "Donations" | "Cashup" | "Other";
@@ -42,6 +43,7 @@ export const REPORTS = [
{ key: "funnel", label: "Registration funnel", description: "Event page views → started → submitted → paid, with trend and sources", category: "Registration", icon: Filter, fields: 5 },
{ key: "feedbackSummary", label: "Feedback summary", description: "Post-event feedback: ratings, choices and comments; compare events", category: "Registration", icon: MessageSquareHeart, fields: 4 },
{ key: "medicalList", label: "Medical & emergency list", description: "Youth events: confidential list for leaders (audited)", category: "Registration", icon: HeartPulse, fields: 5 },
{ key: "seriesComparison", label: "Series: year on year", description: "Registrations, income and attendance compared across the events in a series", category: "Other", icon: Layers, fields: 6 },
{ key: "discounts", label: "Discounts (codes & bundles)", description: "Uses and value given away per code, bundle deal and event", category: "Financial", icon: TicketPercent, fields: 4 },
] as const satisfies ReadonlyArray<{
key: string;
@@ -5,7 +5,7 @@ import { useSearchParams } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch, API_BASE } 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 } from "lucide-react";
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";
@@ -15,7 +15,7 @@ import { AreaTrendChart } from "@/components/charts/AreaTrendChart";
import { errorMessage } from "@/lib/utils";
import { registrationOptionUnitPrice } from "@/lib/pricing";
import { CampusFilter, matchesCampus } from "@/components/shared/CampusFilter";
import type { ConsentRow, Event, EventCashup, EventFinancials, MedicalRow, Payment, Registration, Ticket, UserSummary } from "@/types";
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<string, string> = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" };
@@ -147,6 +147,9 @@ type FunnelReport = {
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();
@@ -241,6 +244,18 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
const [feedbackRows, setFeedbackRows] = useState<FeedbackEventSummary[]>([]);
// Registration funnel for the selected events (null until viewed).
const [funnel, setFunnel] = useState<FunnelReport | null>(null);
// Series: year on year — picked by series, not by the events selection.
const [seriesList, setSeriesList] = useState<EventSeries[]>([]);
const [compareSeriesId, setCompareSeriesId] = useState<string>("");
const [comparison, setComparison] = useState<SeriesComparison | null>(null);
useEffect(() => {
if (!token) return;
apiFetch<EventSeries[]>("/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=<key>&range=trailing_month to jump
// straight into a specific report, pre-filtered to every currently-visible event and the
@@ -259,6 +274,8 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
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);
@@ -527,6 +544,10 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
setFeedbackRows(await loadFeedback(selectedEventIds));
} else if (report === "medicalList") {
setMedicalRows(await loadConsent(selectedEventIds, "medical"));
} else if (report === "seriesComparison") {
setComparison(compareSeriesId && token
? await apiFetch<SeriesComparison>(`/api/series/${encodeURIComponent(compareSeriesId)}/compare`, { authToken: token }).catch(() => null)
: null);
}
setReady(true);
} finally {
@@ -959,6 +980,24 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
// 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',
@@ -1372,6 +1411,7 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
discounts: "Discounts Report",
consentStatus: "Parental Consent Status",
medicalList: "Medical & Emergency List",
seriesComparison: "Series: year on year",
};
const doPrintPdf = async () => {
@@ -1412,7 +1452,18 @@ export default function ReportsV2({ backHref }: { backHref?: 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.
const reportSpecificFilters = report === "attendees" ? (
const reportSpecificFilters = report === "seriesComparison" ? (
<div className="flex flex-wrap items-center gap-3">
<label className="text-sm">
<span className="mr-2">Series</span>
<select className="border rounded px-2 py-1 text-sm" value={compareSeriesId} onChange={e => setCompareSeriesId(e.target.value)} aria-label="Series">
{seriesList.length === 0 && <option value="">No series yet</option>}
{seriesList.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</label>
<span className="text-xs text-gray-500">Press refresh after changing the series. The events selection on the left doesn&apos;t apply.</span>
</div>
) : report === "attendees" ? (
<div className="flex flex-wrap items-center gap-3">
<label className="text-sm">
<span className="mr-2">Event</span>
@@ -1869,6 +1920,60 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
})()}
</div>
)}
{report === "seriesComparison" && (
<div data-testid="series-comparison">
{!comparison ? (
<div className="text-sm text-gray-500">{seriesList.length === 0 ? "No series yet — make one on the Event series page and put events in it." : "Choose a series above."}</div>
) : comparison.events.length === 0 ? (
<div className="text-sm text-gray-500">{comparison.series.name} has no events yet (or none at your campuses).</div>
) : (() => {
const last = comparison.events[comparison.events.length - 1];
const change = (c: number | null | undefined) => c == null ? null : <span className={`ml-1 text-xs ${c > 0 ? "text-green-700" : c < 0 ? "text-rose-700" : "text-gray-500"}`}>{changeLabel(c)}</span>;
return (
<>
<StatTileRow>
<StatTile icon={Users} label={`Registrations, ${last.title}`} value={`${last.registrations}${last.change?.registrations != null ? ` (${changeLabel(last.change.registrations)})` : ""}`} tone="violet" />
<StatTile icon={TrendingUp} label="Income" value={`R ${last.income.toFixed(2)}${last.change?.income != null ? ` (${changeLabel(last.change.income)})` : ""}`} tone="green" />
<StatTile icon={TicketIcon} label="Attendance" value={last.attendanceRate != null ? `${last.attendanceRate}%` : "—"} tone="blue" />
</StatTileRow>
{comparison.events.length > 1 && (
<div className="mt-4 grid md:grid-cols-2 gap-4">
<div className="border border-gray-100 rounded-xl p-4">
<div className="text-xs text-gray-500 mb-3">Registrations, by event</div>
<HorizontalBarChart data={comparison.events.map(e => ({ label: e.title, value: e.registrations }))} valueFormatter={v => String(v)} />
</div>
<div className="border border-gray-100 rounded-xl p-4">
<div className="text-xs text-gray-500 mb-3">Income, by event</div>
<HorizontalBarChart data={comparison.events.map(e => ({ label: e.title, value: e.income }))} valueFormatter={v => `R ${v.toFixed(2)}`} />
</div>
</div>
)}
<div className="mt-4 overflow-x-auto">
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-gray-500 border-b">
<th className="py-2 pr-3">Event</th><th className="py-2 pr-3">Date</th><th className="py-2 pr-3">Registrations</th><th className="py-2 pr-3">Tickets</th><th className="py-2 pr-3">Income</th><th className="py-2 pr-3">Checked in</th><th className="py-2">Attendance</th>
</tr></thead>
<tbody>
{comparison.events.map(e => (
<tr key={e.eventId} className="border-b last:border-0" data-testid="comparison-row">
<td className="py-2 pr-3 font-medium">{e.title}{e.campus && <span className="ml-1 text-[10px] text-gray-500">· {e.campus.name}</span>}</td>
<td className="py-2 pr-3 text-gray-600">{new Date(e.startDate).toLocaleDateString()}</td>
<td className="py-2 pr-3">{e.registrations}{change(e.change?.registrations)}</td>
<td className="py-2 pr-3">{e.tickets}{change(e.change?.tickets)}</td>
<td className="py-2 pr-3">R {e.income.toFixed(2)}{change(e.change?.income)}</td>
<td className="py-2 pr-3">{e.checkedIn}{e.sessions > 0 && <span className="text-[10px] text-gray-500"> avg/session</span>}{change(e.change?.checkedIn)}</td>
<td className="py-2">{e.attendanceRate != null ? `${e.attendanceRate}%` : "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
<p className="text-xs text-gray-500 mt-3">Each change is against the event before. Income leaves out donations applied to orders (they count when they were given).</p>
</>
);
})()}
</div>
)}
{report === "feedbackSummary" && (
<div>
{feedbackSummary.perEvent.length === 0 ? (
@@ -29,7 +29,7 @@ export const reportsHelpContent: HelpContent = {
Preview your report, adjust filters, and choose how you want the data to appear.
</GuideItem>
<GuideItem icon={Download} title="Export or email" tone="amber">
Export your report to Excel, PDF, or send it by email or WhatsApp. Tip: select several events in the Feedback summary to compare their ratings (e.g. Camp 2025 vs Camp 2026). The Registration funnel shows where people drop off between viewing an event and paying, by source and device. The source comes from short links and utm_source links, else the site the visitor came from (Facebook, Instagram, Google…). The event page&apos;s Share and Save QR buttons tag their links as &quot;share&quot; and &quot;qr&quot;. WhatsApp doesn&apos;t say where a click came from, so add ?utm_source=whatsapp to links you post there, or they show as &quot;direct&quot;. It counts only visitors who allowed cookies.
Export your report to Excel, PDF, or send it by email or WhatsApp. Tip: select several events in the Feedback summary to compare their ratings (e.g. Camp 2025 vs Camp 2026), or use Series: year on year to compare a whole series&apos; registrations, income and attendance. The Registration funnel shows where people drop off between viewing an event and paying, by source and device. The source comes from short links and utm_source links, else the site the visitor came from (Facebook, Instagram, Google…). The event page&apos;s Share and Save QR buttons tag their links as &quot;share&quot; and &quot;qr&quot;. WhatsApp doesn&apos;t say where a click came from, so add ?utm_source=whatsapp to links you post there, or they show as &quot;direct&quot;. It counts only visitors who allowed cookies.
</GuideItem>
</div>
</div>
@@ -1,5 +1,5 @@
import React from "react";
import { Layers, Calendar, Bell, MapPin, Copy } from "lucide-react";
import { Layers, Calendar, Bell, MapPin, Copy, BarChart3 } from "lucide-react";
import { GuideItem } from "@/components/shared/GuideItem";
import type { HelpContent } from "./types";
@@ -28,6 +28,9 @@ export const seriesHelpContent: HelpContent = {
<GuideItem icon={Bell} title="Following" tone="amber">
People with an account can follow a series on its page. When a new event in the series goes live (and before it starts) followers get one email. It counts as <strong>News &amp; announcements</strong>, so only people who chose to get news receive it, with an unsubscribe link.
</GuideItem>
<GuideItem icon={BarChart3} title="Year on year" tone="green">
&quot;Compare&quot; opens Reports → Series: year on year — each event in the series side by side (registrations, tickets, income, how many came) with how much it went up or down from the one before.
</GuideItem>
<GuideItem icon={MapPin} title="Campuses" tone="gray">
A series can have events at different campuses. Supervisors limited to some campuses see the series, but only their campuses&apos; events in it.
</GuideItem>
+9
View File
@@ -203,6 +203,15 @@ export type EventSeries = EventSeriesRef & {
events: { id: string; title: string; startDate: string; endDate: string; isActive: boolean; isHidden: boolean; campus?: Event["campus"] }[];
};
/** GET /api/series/:id/compare — one row per event in the series, oldest first. */
export type SeriesComparisonRow = {
eventId: string; title: string; startDate: string; endDate: string; campus?: Event["campus"]; isActive: boolean;
sessions: number; registrations: number; tickets: number; income: number; checkedIn: number; attendanceRate: number | null;
// % up or down from the event before (null on the first, or when the one before had none).
change: { registrations: number | null; tickets: number | null; income: number | null; checkedIn: number | null } | null;
};
export type SeriesComparison = { series: EventSeriesRef; events: SeriesComparisonRow[] };
export type EventSession = {
id: string;
eventId?: string;