WIP 1.51.9: frontend on v2 for series, passes, bundles, coupons, campuses

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
This commit is contained in:
2026-10-29 12:34:49 +02:00
co-authored by Claude Opus 5.5
parent 0498ee1854
commit 684560119f
18 changed files with 81 additions and 58 deletions
@@ -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 ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-400">Loading…</p>;
@@ -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");
@@ -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<string, string> = { 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<SeriesComparison | null>(null);
useEffect(() => {
if (!token) return;
apiFetch<EventSeries[]>("/api/series", { authToken: token }).then(l => {
(apiV2Data("get", "/series", { authToken: token }) as Promise<EventSeries[]>).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<DiscountRow[]>(`/api/coupons/redemptions?${query.toString()}`, { authToken: token });
return await (apiV2Data("get", "/coupons/redemptions", { query: Object.fromEntries(query.entries()), authToken: token }) as Promise<DiscountRow[]>);
} 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<SeriesComparison>(`/api/series/${encodeURIComponent(compareSeriesId)}/compare`, { authToken: token }).catch(() => null)
? await (apiV2Data("get", "/series/{id}/compare", { params: { id: compareSeriesId }, authToken: token }) as Promise<SeriesComparison>).catch(() => null)
: null);
}
setReady(true);
@@ -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<SeasonPassView[]>(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<SeasonPassPurchase[]>("/api/season-passes/mine", { authToken: token }).catch(() => []);
const list = await (apiV2Data("get", "/me/season-passes", { authToken: token }) as Promise<SeasonPassPurchase[]>).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<BuyResult>(`/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<BuyResult>));
} 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 {
@@ -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<SeasonPassView[]>(`/api/season-passes?seriesId=${encodeURIComponent(seriesId)}`, { authToken: token }).catch(() => []),
(apiV2Data("get", "/season-passes", { query: { seriesId }, authToken: token }) as Promise<SeasonPassView[]>).catch(() => [] as SeasonPassView[]),
fetchManagedEvents<Event>(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");
@@ -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<string, unknown> = { eventId, options };
if (forUserId !== undefined) body.forUserId = forUserId;
const res = await apiFetch<BundleQuote>("/api/bundles/quote", { method: "POST", authToken: token || undefined, body });
const res = await (apiV2Data("post", "/bundles/quote", { authToken: token, body: body as never }) as Promise<BundleQuote>);
if (!cancelled) setQuote(res.bundleDiscount > 0 ? res : null);
} catch {
if (!cancelled) setQuote(null);
@@ -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);
@@ -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<string, unknown> = { code: trimmed, eventId, options: items };
if (forUserId !== undefined) body.forUserId = forUserId;
const res = await apiFetch<AppliedCoupon & { valid: boolean }>("/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);