From 684560119f33e4da66e8ffb57f72766813cc1faa Mon Sep 17 00:00:00 2001 From: joshua Date: Thu, 29 Oct 2026 12:34:49 +0200 Subject: [PATCH] WIP 1.51.9: frontend on v2 for series, passes, bundles, coupons, campuses Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot --- .../frontend/src/app/campus/[slug]/page.tsx | 5 +++-- .../app/dashboard/supervisor/bundles/page.tsx | 13 +++++++------ .../app/dashboard/supervisor/coupons/page.tsx | 11 ++++++----- .../app/dashboard/supervisor/events/page.tsx | 4 ++-- .../app/dashboard/supervisor/series/page.tsx | 9 +++++---- .../frontend/src/app/series/[slug]/page.tsx | 5 +++-- apps/events/frontend/src/app/sitemap.ts | 3 ++- .../src/components/admin/CampusesTab.tsx | 17 +++++++++-------- .../components/events/FollowSeriesButton.tsx | 6 +++--- .../src/components/reports/ReportsV2.tsx | 9 +++++---- .../src/components/series/SeasonPassOffers.tsx | 10 +++++----- .../src/components/series/SeasonPassesPanel.tsx | 10 ++++++---- .../src/components/shared/BundleDeals.tsx | 6 +++--- .../components/shared/CampusAudiencePicker.tsx | 4 ++-- .../src/components/shared/CouponCodeField.tsx | 9 ++++++--- apps/events/frontend/src/hooks/useCampuses.ts | 4 ++-- apps/events/frontend/src/lib/apiV2.ts | 10 ++++++++++ apps/events/frontend/src/types/index.ts | 4 ++-- 18 files changed, 81 insertions(+), 58 deletions(-) diff --git a/apps/events/frontend/src/app/campus/[slug]/page.tsx b/apps/events/frontend/src/app/campus/[slug]/page.tsx index fa495f3..6ae8acb 100644 --- a/apps/events/frontend/src/app/campus/[slug]/page.tsx +++ b/apps/events/frontend/src/app/campus/[slug]/page.tsx @@ -5,10 +5,11 @@ import { Navbar } from "@/components/layout/Navbar"; import { Footer } from "@/components/layout/Footer"; import { EventCard } from "@/components/events/EventCard"; import { ApiImage } from "@/components/shared/ApiImage"; -import { apiFetch, apiFetchListForPrerender, ApiError } from "@/lib/api"; +import { apiFetchListForPrerender, ApiError } from "@/lib/api"; import { mapsSearchUrl } from "@/lib/maps"; import { CalendarX, MapPin, Mail, Phone, User, ArrowLeft } from "lucide-react"; import type { Campus } from "@/hooks/useCampuses"; +import { apiV2Data } from "@/lib/apiV2"; export const revalidate = 60; @@ -16,7 +17,7 @@ type Event = React.ComponentProps["event"] & { cashupStatus?: async function loadCampus(slug: string): Promise { try { - return await apiFetch(`/api/campuses/by-slug/${encodeURIComponent(slug)}`, { nextOptions: { next: { revalidate } } }); + return await (apiV2Data("get", "/campuses/by-slug/{slug}", { params: { slug }, nextOptions: { next: { revalidate } } }) as Promise); } catch (e) { // 404: no such campus, archived, or campuses are off. if (e instanceof ApiError && e.status === 404) return null; diff --git a/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx index 467ddc5..ff74667 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx @@ -3,13 +3,14 @@ import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; -import { apiFetch, fetchManagedEvents } from "@/lib/api"; +import { fetchManagedEvents } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { Gift, Plus, X, Trash2, Pencil, Power, CalendarClock } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import type { BundleGroupPricing, BundleKind, EventBundle } from "@/types"; import { EventPicker, defaultEventId } from "@/components/shared/EventPicker"; +import { apiV2Data } from "@/lib/apiV2"; type OptionLite = { id: string; name: string; price: number; variants?: { id: string; name: string; price?: number | null }[] }; type EventLite = { id: string; title: string; startDate: string; endDate?: string; eventOptions: OptionLite[] }; @@ -118,7 +119,7 @@ export default function BundlesPage() { if (!token || !eventId) { setBundles([]); return; } setFetching(true); try { - setBundles(await apiFetch(`/api/bundles/event/${eventId}`, { authToken: token }) || []); + setBundles(await (apiV2Data("get", "/events/{id}/bundles", { params: { id: eventId }, authToken: token }) as Promise)); } catch (e) { setError(errorMessage(e) || "Failed to load bundles"); } finally { @@ -130,7 +131,7 @@ export default function BundlesPage() { const toggleActive = async (b: EventBundle) => { try { - await apiFetch(`/api/bundles/${b.id}`, { method: "PUT", authToken: token!, body: { isActive: !b.isActive } }); + await apiV2Data("patch", "/bundles/{id}", { params: { id: b.id }, authToken: token, body: { isActive: !b.isActive } }); setInfo(`${b.name} turned ${b.isActive ? "off" : "on"}.`); load(); } catch (e) { @@ -141,7 +142,7 @@ export default function BundlesPage() { const remove = async (b: EventBundle) => { if (!window.confirm(`Delete "${b.name}"?`)) return; try { - const res = await apiFetch<{ message: string }>(`/api/bundles/${b.id}`, { method: "DELETE", authToken: token! }); + const res = await (apiV2Data("delete", "/bundles/{id}", { params: { id: b.id }, authToken: token }) as Promise<{ message: string }>); setInfo(res?.message || "Bundle deleted"); load(); } catch (e) { @@ -357,10 +358,10 @@ function BundleModal({ token, event, bundleId, initial, onClose, onSaved }: { isActive: d.isActive, }; if (bundleId) { - await apiFetch(`/api/bundles/${bundleId}`, { method: "PUT", authToken: token, body }); + await apiV2Data("patch", "/bundles/{id}", { params: { id: bundleId }, authToken: token, body: body as never }); onSaved(`${body.name} saved.`); } else { - await apiFetch(`/api/bundles/event/${event.id}`, { method: "POST", authToken: token, body }); + await apiV2Data("post", "/events/{id}/bundles", { params: { id: event.id }, authToken: token, body: body as never }); onSaved(`${body.name} created.`); } } catch (err) { diff --git a/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx index 578fde5..d24637f 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx @@ -8,6 +8,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { TicketPercent, Plus, X, Search, Pencil, Power, Users, CalendarClock, ListChecks } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; +import { apiV2Data } from "@/lib/apiV2"; type CouponType = "percent" | "fixed" | "comp"; type Role = "user" | "staff" | "supervisor" | "admin"; @@ -163,7 +164,7 @@ export default function CouponsPage() { setFetching(true); try { const [c, ev] = await Promise.all([ - apiFetch("/api/coupons", { authToken: token }), + (apiV2Data("get", "/coupons", { authToken: token }) as Promise), fetchManagedEvents(token, { past: true }), ]); setCoupons(c || []); @@ -191,7 +192,7 @@ export default function CouponsPage() { const toggleActive = async (c: Coupon) => { try { - await apiFetch(`/api/coupons/${c.id}`, { method: "PUT", authToken: token!, body: { active: !c.active } }); + await apiV2Data("patch", "/coupons/{id}", { params: { id: c.id }, authToken: token, body: { active: !c.active } }); setInfo(`${c.code} turned ${c.active ? "off" : "on"}.`); load(); } catch (e) { @@ -201,7 +202,7 @@ export default function CouponsPage() { const openUses = async (c: Coupon) => { try { - const full = await apiFetch(`/api/coupons/${c.id}`, { authToken: token! }); + const full = await (apiV2Data("get", "/coupons/{id}", { params: { id: c.id }, authToken: token }) as Promise); setViewing({ coupon: c, redemptions: full.redemptions || [] }); } catch (e) { setError(errorMessage(e) || "Failed to load uses"); @@ -473,10 +474,10 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: { try { const body = bodyFromDraft(d); if (couponId) { - await apiFetch(`/api/coupons/${couponId}`, { method: "PUT", authToken: token, body }); + await apiV2Data("patch", "/coupons/{id}", { params: { id: couponId }, authToken: token, body: body as never }); onSaved(`${body.code.toUpperCase()} saved.`); } else { - await apiFetch(`/api/coupons`, { method: "POST", authToken: token, body }); + await apiV2Data("post", "/coupons", { authToken: token, body: body as never }); onSaved(`${body.code.toUpperCase()} created.`); } } catch (err) { diff --git a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx index c8446d8..d9a81a0 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx @@ -22,7 +22,7 @@ import { } from "@/components/events/ScheduleEditor"; import { toSessionDraft, scheduleSummary } from "@/lib/sessions"; import { fetchApiFile, openBlob } from "@/lib/export"; -import { apiV2 } from "@/lib/apiV2"; +import { apiV2, apiV2Data } from "@/lib/apiV2"; import { createTicketOption, updateTicketOption, listSections, createSection, updateSection, deleteSection, listAttachments, uploadAttachment, deleteAttachment, uploadImage } from "@/lib/eventSetup"; // ─── helpers ──────────────────────────────────────────────────────────────── @@ -959,7 +959,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP const [seriesList, setSeriesList] = useState([]); useEffect(() => { if (!token) return; - apiFetch("/api/series", { authToken: token }).then(l => setSeriesList(Array.isArray(l) ? l : [])).catch(() => {}); + (apiV2Data("get", "/series", { authToken: token }) as Promise).then(l => setSeriesList(l)).catch(() => {}); }, [token]); // ── multi-day schedule + attendance settings ── diff --git a/apps/events/frontend/src/app/dashboard/supervisor/series/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/series/page.tsx index 4773cba..3728fab 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/series/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/series/page.tsx @@ -5,12 +5,12 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import { Layers, ExternalLink, Users, BarChart3 } from "lucide-react"; import { useAuth } from "@/hooks/useAuth"; -import { apiFetch } from "@/lib/api"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { CampusBadge } from "@/components/shared/CampusFilter"; import { SeasonPassesPanel } from "@/components/series/SeasonPassesPanel"; import type { EventSeries } from "@/types"; +import { apiV2Data } from "@/lib/apiV2"; type Draft = { id?: string; name: string; slug: string; description: string; picture: string }; const blank: Draft = { name: "", slug: "", description: "", picture: "" }; @@ -69,7 +69,7 @@ export default function SeriesPage() { const load = useCallback(async () => { if (!token) return; try { - setList(await apiFetch("/api/series", { authToken: token })); + setList(await (apiV2Data("get", "/series", { authToken: token }) as Promise)); } catch (e) { setError(errorMessage(e) || "Couldn't load the series"); } @@ -81,7 +81,8 @@ export default function SeriesPage() { setSaving(true); setError(null); setNotice(null); try { const body = { name: draft.name, slug: draft.slug || undefined, description: draft.description, picture: draft.picture }; - await apiFetch(draft.id ? `/api/series/${draft.id}` : "/api/series", { method: draft.id ? "PUT" : "POST", authToken: token || undefined, body }); + if (draft.id) await apiV2Data("patch", "/series/{id}", { params: { id: draft.id }, authToken: token, body: body as never }); + else await apiV2Data("post", "/series", { authToken: token, body: body as never }); setNotice(draft.id ? "Series saved." : `"${draft.name.trim()}" created — choose it in the event editor to add events.`); setDraft(null); await load(); @@ -96,7 +97,7 @@ export default function SeriesPage() { if (!window.confirm(`Delete "${s.name}"? Its ${s.eventCount} event${s.eventCount === 1 ? "" : "s"} stay, just without a series, and ${s.followers} follower${s.followers === 1 ? "" : "s"} won't hear about new ones.`)) return; setError(null); setNotice(null); try { - await apiFetch(`/api/series/${s.id}`, { method: "DELETE", authToken: token || undefined }); + await apiV2Data("delete", "/series/{id}", { params: { id: s.id }, authToken: token }); setNotice(`"${s.name}" deleted.`); await load(); } catch (e) { diff --git a/apps/events/frontend/src/app/series/[slug]/page.tsx b/apps/events/frontend/src/app/series/[slug]/page.tsx index 0681181..822f856 100644 --- a/apps/events/frontend/src/app/series/[slug]/page.tsx +++ b/apps/events/frontend/src/app/series/[slug]/page.tsx @@ -9,10 +9,11 @@ import { CampusBadge } from "@/components/shared/CampusFilter"; import { FollowSeriesButton } from "@/components/events/FollowSeriesButton"; import { SeasonPassOffers } from "@/components/series/SeasonPassOffers"; import { Suspense } from "react"; -import { apiFetch, apiFetchListForPrerender, ApiError } from "@/lib/api"; +import { apiFetchListForPrerender, ApiError } from "@/lib/api"; import { formatDateTimeRange } from "@/lib/date"; import { ArrowLeft, CalendarX, Layers } from "lucide-react"; import type { Event as FullEvent, SeasonPassView } from "@/types"; +import { apiV2Data } from "@/lib/apiV2"; export const revalidate = 60; @@ -22,7 +23,7 @@ type Series = { id: string; name: string; slug: string; description: string | nu async function loadSeries(slug: string): Promise { try { - return await apiFetch(`/api/series/by-slug/${encodeURIComponent(slug)}`, { nextOptions: { next: { revalidate } } }); + return await (apiV2Data("get", "/series/by-slug/{slug}", { params: { slug }, nextOptions: { next: { revalidate } } }) as Promise); } catch (e) { if (e instanceof ApiError && e.status === 404) return null; throw e; diff --git a/apps/events/frontend/src/app/sitemap.ts b/apps/events/frontend/src/app/sitemap.ts index 6385ecd..0c069b7 100644 --- a/apps/events/frontend/src/app/sitemap.ts +++ b/apps/events/frontend/src/app/sitemap.ts @@ -1,6 +1,7 @@ import type { MetadataRoute } from "next"; import { apiFetch } from "@/lib/api"; import { appUrl } from "@/lib/siteConfig"; +import { apiV2Data } from "@/lib/apiV2"; type Event = { id: string; updatedAt?: string; startDate: string }; @@ -26,7 +27,7 @@ export default async function sitemap(): Promise { // Campus pages, while campuses are on (the list is empty otherwise). let campuses: { slug: string }[] = []; try { - campuses = (await apiFetch<{ campuses: { slug: string }[] }>("/api/campuses", { nextOptions: { next: { revalidate } } })).campuses || []; + campuses = (await (apiV2Data("get", "/campuses", { nextOptions: { next: { revalidate } } }) as Promise<{ campuses: { slug: string }[] }>)).campuses || []; } catch { // Same as events above. } diff --git a/apps/events/frontend/src/components/admin/CampusesTab.tsx b/apps/events/frontend/src/components/admin/CampusesTab.tsx index 1835663..b508d38 100644 --- a/apps/events/frontend/src/components/admin/CampusesTab.tsx +++ b/apps/events/frontend/src/components/admin/CampusesTab.tsx @@ -8,6 +8,7 @@ import { useAuth } from "@/hooks/useAuth"; import { useDismissingState } from "@/hooks/useDismissingState"; import { reloadCampuses, type Campus } from "@/hooks/useCampuses"; import { errorMessage } from "@/lib/utils"; +import { apiV2Data } from "@/lib/apiV2"; type Person = { id: string; name: string; email: string }; type AdminCampus = Campus & { @@ -129,7 +130,7 @@ export function CampusesTab({ active }: { active: boolean }) { const load = useCallback(async () => { if (!token) return; try { - const res = await apiFetch<{ enabled: boolean; campuses: AdminCampus[] }>("/api/campuses/admin", { authToken: token }); + const res = await (apiV2Data("get", "/campuses/admin", { authToken: token }) as Promise<{ enabled: boolean; campuses: AdminCampus[] }>); setEnabled(res.enabled); setCampuses(res.campuses); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Could not load campuses." }); } @@ -154,28 +155,28 @@ export function CampusesTab({ active }: { active: boolean }) { // Limits are ignored while campuses are off, so limited staff would see every campus. const limited = (campuses || []).reduce((n, c) => n + (c._count.scopedStaff || 0), 0); if (!on && limited > 0 && !window.confirm(`Some staff are limited to campuses (${limited} limit${limited === 1 ? "" : "s"} set). While campuses are off those limits are ignored and they'll see every campus. Turn campuses off?`)) return; - return run(() => apiFetch("/api/campuses/settings", { method: "PUT", authToken: token, body: { enabled: on } }), on ? "Campuses are on." : "Campuses are off — campus fields are hidden, nothing is deleted."); + return run(() => apiV2Data("put", "/campuses/enabled", { authToken: token, body: { enabled: on } }), on ? "Campuses are on." : "Campuses are off — campus fields are hidden, nothing is deleted."); }; const save = async (d: Draft, id?: string) => { const body = { ...d, notifyRecipients: undefined, notifyRecipientIds: d.notifyRecipients.map(p => p.id) }; const ok = await run(() => id - ? apiFetch(`/api/campuses/${id}`, { method: "PUT", authToken: token, body }) - : apiFetch("/api/campuses", { method: "POST", authToken: token, body }).then((c) => { + ? apiV2Data("patch", "/campuses/{id}", { params: { id }, authToken: token, body: body as never }) + : apiV2Data("post", "/campuses", { authToken: token, body: body as never }).then((c) => { const created = c as AdminCampus; // Recipients are set with an update, so a new campus gets them too. - return d.notifyRecipients.length ? apiFetch(`/api/campuses/${created.id}`, { method: "PUT", authToken: token, body: { notifyRecipientIds: body.notifyRecipientIds } }) : created; + return d.notifyRecipients.length ? apiV2Data("patch", "/campuses/{id}", { params: { id: created.id }, authToken: token, body: { notifyRecipientIds: body.notifyRecipientIds } }) : created; }), id ? "Campus saved." : "Campus added."); if (ok) setEditing(null); }; const move = (list: AdminCampus[], i: number, dir: -1 | 1) => { const ids = list.map(c => c.id); [ids[i], ids[i + dir]] = [ids[i + dir], ids[i]]; - return run(() => apiFetch("/api/campuses/order", { method: "PUT", authToken: token, body: { ids } })); + return run(() => apiV2Data("put", "/campuses/order", { authToken: token, body: { ids } })); }; - const setArchived = (c: AdminCampus, archived: boolean) => run(() => apiFetch(`/api/campuses/${c.id}`, { method: "PUT", authToken: token, body: { archived } }), archived ? `${c.name} archived.` : `${c.name} restored.`); + const setArchived = (c: AdminCampus, archived: boolean) => run(() => apiV2Data("patch", "/campuses/{id}", { params: { id: c.id }, authToken: token, body: { archived } }), archived ? `${c.name} archived.` : `${c.name} restored.`); const remove = (c: AdminCampus) => { if (!window.confirm(`Delete ${c.name}? This can't be undone.`)) return; - run(() => apiFetch(`/api/campuses/${c.id}`, { method: "DELETE", authToken: token }), `${c.name} deleted.`); + run(() => apiV2Data("delete", "/campuses/{id}", { params: { id: c.id }, authToken: token }), `${c.name} deleted.`); }; if (!campuses) return msg ?

{msg.text}

:

Loading…

; diff --git a/apps/events/frontend/src/components/events/FollowSeriesButton.tsx b/apps/events/frontend/src/components/events/FollowSeriesButton.tsx index b45e492..79a57bb 100644 --- a/apps/events/frontend/src/components/events/FollowSeriesButton.tsx +++ b/apps/events/frontend/src/components/events/FollowSeriesButton.tsx @@ -3,8 +3,8 @@ import { useEffect, useState } from "react"; import { Bell, BellOff } from "lucide-react"; import { useAuth } from "@/hooks/useAuth"; -import { apiFetch } from "@/lib/api"; import { errorMessage } from "@/lib/utils"; +import { apiV2Data } from "@/lib/apiV2"; /** Follow / unfollow a series. Signed out, it links to the login page and back. */ export function FollowSeriesButton({ slug }: { slug: string }) { @@ -18,7 +18,7 @@ export function FollowSeriesButton({ slug }: { slug: string }) { // is now) is asked separately. useEffect(() => { if (!token) return; - apiFetch<{ id: string; following: boolean }>(`/api/series/by-slug/${encodeURIComponent(slug)}`, { authToken: token }) + (apiV2Data("get", "/series/by-slug/{slug}", { params: { slug }, authToken: token }) as Promise<{ id: string; following: boolean }>) .then(s => { setSeriesId(s.id); setFollowing(!!s.following); }) .catch(() => setFollowing(null)); }, [slug, token]); @@ -35,7 +35,7 @@ export function FollowSeriesButton({ slug }: { slug: string }) { const toggle = async () => { setBusy(true); setError(null); try { - const res = await apiFetch<{ following: boolean }>(`/api/series/${seriesId}/follow`, { method: following ? "DELETE" : "POST", authToken: token || undefined }); + const res = await (apiV2Data(following ? "delete" : "put", "/series/{id}/follow", { params: { id: seriesId! }, authToken: token }) as Promise<{ following: boolean }>); setFollowing(res.following); } catch (e) { setError(errorMessage(e) || "Couldn't change that"); diff --git a/apps/events/frontend/src/components/reports/ReportsV2.tsx b/apps/events/frontend/src/components/reports/ReportsV2.tsx index 95ec38a..afecacf 100644 --- a/apps/events/frontend/src/components/reports/ReportsV2.tsx +++ b/apps/events/frontend/src/components/reports/ReportsV2.tsx @@ -17,6 +17,7 @@ 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"; +import { apiV2Data } from "@/lib/apiV2"; const METHOD_KEYS = ["cash", "card", "eft", "other"] as const; const METHOD_LABEL: Record = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" }; @@ -97,7 +98,7 @@ type AuditRow = EventCashup & { _previousCloseAt?: string; }; -// GET /api/coupons/redemptions — active coupon uses and bundle deals, with a readable summary. +// GET /api/v2/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; @@ -251,7 +252,7 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) { const [comparison, setComparison] = useState(null); useEffect(() => { if (!token) return; - apiFetch("/api/series", { authToken: token }).then(l => { + (apiV2Data("get", "/series", { authToken: token }) as Promise).then(l => { const list = Array.isArray(l) ? l : []; setSeriesList(list); setCompareSeriesId(id => id || list[0]?.id || ""); @@ -395,7 +396,7 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) { 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 (apiV2Data("get", "/coupons/redemptions", { query: Object.fromEntries(query.entries()), authToken: token }) as Promise); } catch { return []; } @@ -547,7 +548,7 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) { setMedicalRows(await loadConsent(selectedEventIds, "medical")); } else if (report === "seriesComparison") { setComparison(compareSeriesId && token - ? await apiFetch(`/api/series/${encodeURIComponent(compareSeriesId)}/compare`, { authToken: token }).catch(() => null) + ? await (apiV2Data("get", "/series/{id}/compare", { params: { id: compareSeriesId }, authToken: token }) as Promise).catch(() => null) : null); } setReady(true); diff --git a/apps/events/frontend/src/components/series/SeasonPassOffers.tsx b/apps/events/frontend/src/components/series/SeasonPassOffers.tsx index 0742c56..1ce8445 100644 --- a/apps/events/frontend/src/components/series/SeasonPassOffers.tsx +++ b/apps/events/frontend/src/components/series/SeasonPassOffers.tsx @@ -4,10 +4,10 @@ import React, { useCallback, useEffect, useState } from "react"; import { Ticket, CheckCircle2 } from "lucide-react"; import { useSearchParams } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; -import { apiFetch } from "@/lib/api"; import { errorMessage } from "@/lib/utils"; import { formatDateTimeRange } from "@/lib/date"; import type { SeasonPassPurchase, SeasonPassView } from "@/types"; +import { apiV2Data } from "@/lib/apiV2"; const rand = (n: number) => `R ${n.toFixed(2)}`; type BuyResult = { purchaseId: string; total: number; paid: boolean; redirectUrl: string | null; message: string | null }; @@ -27,12 +27,12 @@ export function SeasonPassOffers({ slug, passes: initial }: { slug: string; pass // The page is cached for everyone; ask for the passes as they are now. const [passes, setPasses] = useState(initial); useEffect(() => { - apiFetch<{ passes?: SeasonPassView[] }>(`/api/series/by-slug/${encodeURIComponent(slug)}`).then(s => setPasses(s.passes || [])).catch(() => {}); + (apiV2Data("get", "/series/by-slug/{slug}", { params: { slug } }) as Promise<{ passes?: SeasonPassView[] }>).then(s => setPasses(s.passes || [])).catch(() => {}); }, [slug]); const loadMine = useCallback(async () => { if (!token) return; - const list = await apiFetch("/api/season-passes/mine", { authToken: token }).catch(() => []); + const list = await (apiV2Data("get", "/me/season-passes", { authToken: token }) as Promise).catch(() => [] as SeasonPassPurchase[]); setMine(list.filter(p => p.pass.series.slug === slug && p.status !== "cancelled")); }, [token, slug]); useEffect(() => { loadMine(); }, [loadMine]); @@ -48,7 +48,7 @@ export function SeasonPassOffers({ slug, passes: initial }: { slug: string; pass const buy = async (p: SeasonPassView) => { setBusy(p.id); setError(null); setNotice(null); try { - go(await apiFetch(`/api/season-passes/${p.id}/buy`, { method: "POST", authToken: token || undefined, body: { quantity: qty[p.id] || 1 } })); + go(await (apiV2Data("post", "/season-passes/{id}/buy", { params: { id: p.id }, authToken: token, body: { quantity: qty[p.id] || 1 } }) as Promise)); } catch (e) { setError(errorMessage(e) || "Couldn't buy the pass"); } finally { @@ -59,7 +59,7 @@ export function SeasonPassOffers({ slug, passes: initial }: { slug: string; pass const pay = async (purchaseId: string) => { setBusy(purchaseId); setError(null); setNotice(null); try { - go(await apiFetch<{ redirectUrl: string | null; message: string | null }>(`/api/season-passes/purchases/${purchaseId}/checkout`, { method: "POST", authToken: token || undefined })); + go(await (apiV2Data("post", "/season-pass-purchases/{id}/checkout", { params: { id: purchaseId }, authToken: token, body: {} }) as Promise<{ redirectUrl: string | null; message: string | null }>)); } catch (e) { setError(errorMessage(e) || "Couldn't start the payment"); } finally { diff --git a/apps/events/frontend/src/components/series/SeasonPassesPanel.tsx b/apps/events/frontend/src/components/series/SeasonPassesPanel.tsx index c2ac442..d5854c7 100644 --- a/apps/events/frontend/src/components/series/SeasonPassesPanel.tsx +++ b/apps/events/frontend/src/components/series/SeasonPassesPanel.tsx @@ -3,9 +3,10 @@ import React, { useCallback, useEffect, useMemo, useState } from "react"; import { Ticket } from "lucide-react"; import { useAuth } from "@/hooks/useAuth"; -import { apiFetch, fetchManagedEvents } from "@/lib/api"; +import { fetchManagedEvents } from "@/lib/api"; import { errorMessage } from "@/lib/utils"; import type { Event, SeasonPassView } from "@/types"; +import { apiV2Data } from "@/lib/apiV2"; type ItemDraft = { eventId: string; on: boolean; eventOptionId: string; variantId: string }; type Draft = { id?: string; name: string; description: string; price: string; saleEndsAt: string; isActive: boolean; items: ItemDraft[] }; @@ -32,7 +33,7 @@ export function SeasonPassesPanel({ seriesId, seriesSlug }: { seriesId: string; const load = useCallback(async () => { if (!token) return; const [p, all] = await Promise.all([ - apiFetch(`/api/season-passes?seriesId=${encodeURIComponent(seriesId)}`, { authToken: token }).catch(() => []), + (apiV2Data("get", "/season-passes", { query: { seriesId }, authToken: token }) as Promise).catch(() => [] as SeasonPassView[]), fetchManagedEvents(token, { inactive: true }).catch(() => []), ]); setPasses(p); @@ -76,7 +77,8 @@ export function SeasonPassesPanel({ seriesId, seriesSlug }: { seriesId: string; items: events.map(ev => itemFor(draft, ev)).filter(i => i.on).map(i => ({ eventId: i.eventId, eventOptionId: i.eventOptionId, variantId: i.variantId || null })), }), }; - await apiFetch(draft.id ? `/api/season-passes/${draft.id}` : "/api/season-passes", { method: draft.id ? "PUT" : "POST", authToken: token || undefined, body }); + if (draft.id) await apiV2Data("patch", "/season-passes/{id}", { params: { id: draft.id }, authToken: token, body: body as never }); + else await apiV2Data("post", "/season-passes", { authToken: token, body: body as never }); setDraft(null); await load(); } catch (e) { @@ -89,7 +91,7 @@ export function SeasonPassesPanel({ seriesId, seriesSlug }: { seriesId: string; const remove = async (p: SeasonPassView) => { if (!window.confirm(`Delete "${p.name}"?`)) return; try { - await apiFetch(`/api/season-passes/${p.id}`, { method: "DELETE", authToken: token || undefined }); + await apiV2Data("delete", "/season-passes/{id}", { params: { id: p.id }, authToken: token }); await load(); } catch (e) { setError(errorMessage(e) || "Couldn't delete the pass"); diff --git a/apps/events/frontend/src/components/shared/BundleDeals.tsx b/apps/events/frontend/src/components/shared/BundleDeals.tsx index 13049bd..92aa2af 100644 --- a/apps/events/frontend/src/components/shared/BundleDeals.tsx +++ b/apps/events/frontend/src/components/shared/BundleDeals.tsx @@ -2,14 +2,14 @@ import React, { useEffect, useState } from "react"; import { Gift } from "lucide-react"; -import { apiFetch } from "@/lib/api"; import type { BundleItem, BundleQuote, PublicBundle } from "@/types"; import type { BasketItem } from "@/components/shared/CouponCodeField"; +import { apiV2Data } from "@/lib/apiV2"; const fmt = (n: number) => `R${n.toFixed(2)}`; /** - * The bundle deals a basket gets, from POST /api/bundles/quote (the server prices the + * The bundle deals a basket gets, from POST /api/v2/bundles/quote (the server prices the * basket the same way registration will). Null while there's nothing to show. Pass * `enabled={false}` when the event has no bundles to skip the request. * @@ -35,7 +35,7 @@ export function useBundleQuote({ eventId, basket, token, forUserId, enabled = tr try { const body: Record = { eventId, options }; if (forUserId !== undefined) body.forUserId = forUserId; - const res = await apiFetch("/api/bundles/quote", { method: "POST", authToken: token || undefined, body }); + const res = await (apiV2Data("post", "/bundles/quote", { authToken: token, body: body as never }) as Promise); if (!cancelled) setQuote(res.bundleDiscount > 0 ? res : null); } catch { if (!cancelled) setQuote(null); diff --git a/apps/events/frontend/src/components/shared/CampusAudiencePicker.tsx b/apps/events/frontend/src/components/shared/CampusAudiencePicker.tsx index 26284a7..ad46414 100644 --- a/apps/events/frontend/src/components/shared/CampusAudiencePicker.tsx +++ b/apps/events/frontend/src/components/shared/CampusAudiencePicker.tsx @@ -2,10 +2,10 @@ import React, { useState } from "react"; import { Users } from "lucide-react"; -import { apiFetch } from "@/lib/api"; import { useAuth } from "@/hooks/useAuth"; import { useMyCampuses } from "@/hooks/useCampuses"; import { errorMessage } from "@/lib/utils"; +import { apiV2Data } from "@/lib/apiV2"; /** * "Everyone at campus X" for the email/WhatsApp broadcast composers: adds the people whose @@ -27,7 +27,7 @@ export function CampusAudiencePicker({ selectedIds, onChange }: { selectedIds: s setBusy(true); setNote(null); try { - const res = await apiFetch<{ campus: { name: string }; users: { id: string }[] }>(`/api/campuses/${campusId}/audience${registrants ? "?registrants=true" : ""}`, { authToken: token }); + const res = await (apiV2Data("get", "/campuses/{id}/audience", { params: { id: campusId }, query: { registrants: registrants ? "true" : "false" }, authToken: token }) as Promise<{ campus: { name: string }; users: { id: string }[] }>); const ids = res.users.map(u => u.id); const merged = Array.from(new Set([...selectedIds, ...ids])); onChange(merged); diff --git a/apps/events/frontend/src/components/shared/CouponCodeField.tsx b/apps/events/frontend/src/components/shared/CouponCodeField.tsx index 1e301cd..adfaf23 100644 --- a/apps/events/frontend/src/components/shared/CouponCodeField.tsx +++ b/apps/events/frontend/src/components/shared/CouponCodeField.tsx @@ -2,7 +2,8 @@ import React, { useEffect, useRef, useState } from "react"; import { TicketPercent, X } from "lucide-react"; -import { apiFetch, ApiError } from "@/lib/api"; +import { ApiError } from "@/lib/api"; +import { apiV2Data } from "@/lib/apiV2"; export type BasketItem = { eventOptionId: string; variantId?: string | null; quantity: number }; @@ -16,7 +17,7 @@ export type AppliedCoupon = { /** * "Have a code?" field. Checks the code against the current basket with - * POST /api/coupons/validate and reports the result through `onChange` — the parent + * POST /api/v2/coupons/check and reports the result through `onChange` — the parent * sends `applied.code` as `couponCode` when it registers. Re-checks automatically when * the basket changes, since the discount (or whether the code applies at all) can change. * @@ -58,7 +59,9 @@ export function CouponCodeField({ try { const body: Record = { code: trimmed, eventId, options: items }; if (forUserId !== undefined) body.forUserId = forUserId; - const res = await apiFetch("/api/coupons/validate", { method: "POST", authToken: token || undefined, body }); + const res = await (apiV2Data("post", "/coupons/check", { authToken: token, body: body as never }) as Promise<(AppliedCoupon & { valid: true }) | { valid: false; message: string }>); + // A code that doesn't apply is an answer, not an error. + if (!res.valid) { onChange(null); setError(res.message); return; } onChange({ code: res.code, summary: res.summary, discount: res.discount, subtotal: res.subtotal, total: res.total }); } catch (e) { onChange(null); diff --git a/apps/events/frontend/src/hooks/useCampuses.ts b/apps/events/frontend/src/hooks/useCampuses.ts index e77db3b..ab53430 100644 --- a/apps/events/frontend/src/hooks/useCampuses.ts +++ b/apps/events/frontend/src/hooks/useCampuses.ts @@ -1,8 +1,8 @@ "use client"; import { useEffect, useState } from "react"; -import { apiFetch } from "@/lib/api"; import { useAuth } from "@/hooks/useAuth"; +import { apiV2Data } from "@/lib/apiV2"; export type Campus = { id: string; @@ -28,7 +28,7 @@ let cache: Promise | null = null; function load(): Promise { if (!cache) { - cache = apiFetch("/api/campuses").catch(() => { + cache = (apiV2Data("get", "/campuses") as Promise).catch(() => { cache = null; // try again next time return { enabled: false, campuses: [] }; }); diff --git a/apps/events/frontend/src/lib/apiV2.ts b/apps/events/frontend/src/lib/apiV2.ts index ee51c13..fec15e1 100644 --- a/apps/events/frontend/src/lib/apiV2.ts +++ b/apps/events/frontend/src/lib/apiV2.ts @@ -45,3 +45,13 @@ export function apiV2>(method: M, path: /** The JSON body a v2 endpoint takes. */ export type V2Body

= Body>; + +/** + * `apiV2` for screens that keep their own record types: the path, parameters and body are still + * checked against the API, and the answer's `data` comes back untyped — cast it: + * `await (apiV2Data("get", "/coupons", { authToken }) as Promise)`. + */ +export async function apiV2Data>(method: M, path: P, ...rest: object extends V2Options ? [V2Options?] : [V2Options]): Promise { + const res = (await apiV2(method, path, ...(rest as [V2Options]))) as { data?: unknown }; + return res.data; +} diff --git a/apps/events/frontend/src/types/index.ts b/apps/events/frontend/src/types/index.ts index 21f820d..b7bcc46 100644 --- a/apps/events/frontend/src/types/index.ts +++ b/apps/events/frontend/src/types/index.ts @@ -194,7 +194,7 @@ export type Event = { export type EventSeriesRef = { id: string; name: string; slug: string }; export type NextInSeries = { id: string; title: string; startDate: string; endDate: string; location?: string | null }; -/** GET /api/series (supervisors): a series with its events and number of followers. */ +/** GET /api/v2/series (supervisors): a series with its events and number of followers. */ export type EventSeries = EventSeriesRef & { description: string | null; picture: string | null; @@ -225,7 +225,7 @@ export type SeasonPassPurchase = { registrations: { id: string; status: string; event: { id: string; title: string; startDate: string } }[]; }; -/** GET /api/series/:id/compare — one row per event in the series, oldest first. */ +/** GET /api/v2/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;