"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { Ticket } from "lucide-react"; import { useAuth } from "@/hooks/useAuth"; 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[] }; const rand = (n: number) => `R ${n.toFixed(2)}`; /** The staff-only kids and volunteer tickets aren't sold on a pass. */ const sellable = (ev: Event) => (ev.eventOptions || []).filter(o => o.id !== ev.kidsOptionId && o.id !== ev.volunteerOptionId && !(ev.attendanceMode === "pick" && o.sessionMode === "pick")); /** * A series' season passes on the Event series page: what's on each, sold so far, and a form to * make or change one (events and price are fixed once someone has bought it). */ export function SeasonPassesPanel({ seriesId, seriesSlug }: { seriesId: string; seriesSlug: string }) { const { token } = useAuth(); const [passes, setPasses] = useState([]); const [events, setEvents] = useState([]); // The series' events have arrived (the pass form needs them before it can be saved). const [loaded, setLoaded] = useState(false); const [draft, setDraft] = useState(null); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const load = useCallback(async () => { if (!token) return; const [p, all] = await Promise.all([ (apiV2Data("get", "/season-passes", { query: { seriesId }, authToken: token }) as Promise).catch(() => [] as SeasonPassView[]), fetchManagedEvents(token, { inactive: true }).catch(() => []), ]); setPasses(p); // Upcoming events in this series that take registrations, not youth events. setEvents((all || []).filter(e => e.seriesId === seriesId && e.requiresRegistration !== false && !e.requiresParentalConsent).sort((a, b) => a.startDate.localeCompare(b.startDate))); setLoaded(true); }, [token, seriesId]); useEffect(() => { load(); }, [load]); // A pass's own events; events without a row yet (a new pass, or still loading) take the default: // ticked on a new pass, with the first ticket that can be sold. const passItems = (p: SeasonPassView): ItemDraft[] => p.items.map(i => ({ eventId: i.eventId, on: true, eventOptionId: i.eventOptionId, variantId: i.variantId || "" })); const itemFor = (d: Draft, ev: Event): ItemDraft => d.items.find(i => i.eventId === ev.id) || { eventId: ev.id, on: !d.id, eventOptionId: sellable(ev)[0]?.id || "", variantId: "" }; const openNew = () => { setError(null); setDraft({ name: "", description: "", price: "", saleEndsAt: "", isActive: true, items: [] }); }; const openEdit = (p: SeasonPassView) => { setError(null); setDraft({ id: p.id, name: p.name, description: p.description || "", price: String(p.price), saleEndsAt: p.saleEndsAt ? p.saleEndsAt.slice(0, 16) : "", isActive: p.isActive, items: passItems(p) }); }; const editing = draft?.id ? passes.find(p => p.id === draft.id) : null; const locked = !!editing && ((editing.sold || 0) + (editing.unpaid || 0)) > 0; // What the chosen tickets cost separately, to show the saving while typing the price. const normalValue = useMemo(() => (draft ? events.map(ev => itemFor(draft, ev)) : []).filter(i => i.on).reduce((s, i) => { const ev = events.find(e => e.id === i.eventId); const opt = ev?.eventOptions?.find(o => o.id === i.eventOptionId); const v = opt?.variants?.find(x => x.id === i.variantId); return s + Number(v?.price ?? opt?.price ?? 0); }, 0), [draft, events]); const save = async () => { if (!draft) return; setSaving(true); setError(null); try { const body = { seriesId, name: draft.name, description: draft.description, isActive: draft.isActive, saleEndsAt: draft.saleEndsAt ? new Date(draft.saleEndsAt).toISOString() : null, ...(locked ? {} : { price: Number(draft.price), items: events.map(ev => itemFor(draft, ev)).filter(i => i.on).map(i => ({ eventId: i.eventId, eventOptionId: i.eventOptionId, variantId: i.variantId || null })), }), }; 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) { setError(errorMessage(e) || "Couldn't save the pass"); } finally { setSaving(false); } }; const remove = async (p: SeasonPassView) => { if (!window.confirm(`Delete "${p.name}"?`)) return; try { await apiV2Data("delete", "/season-passes/{id}", { params: { id: p.id }, authToken: token }); await load(); } catch (e) { setError(errorMessage(e) || "Couldn't delete the pass"); } }; const updItem = (ev: Event, patch: Partial) => setDraft(d => d && ({ ...d, items: [...d.items.filter(i => i.eventId !== ev.id), { ...itemFor(d, ev), ...patch }] })); return (
Season passes
{!draft && }
{error &&
{error}
} {passes.length === 0 && !draft &&

No passes. A pass sells a ticket for several events in this series at one price.

}
    {passes.map(p => (
  • {p.name} · {rand(p.price)} {p.saving > 0 && (saves {rand(p.saving)})} {!p.isActive && Off}
    {p.sold || 0} sold{p.unpaid ? ` · ${p.unpaid} not paid yet` : ""}{p.unavailable && p.isActive ? ` · ${p.unavailable}` : ""}
    View {!(p.sold || p.unpaid) && }
      {p.items.map(i => (
    • {i.eventTitle} ({new Date(i.startDate).toLocaleDateString()}) — {i.ticket}: normally {rand(i.normalPrice)}, share {rand(i.share)}
    • ))}
  • ))}
{draft && (
setDraft({ ...draft, name: e.target.value })} placeholder="e.g. All 2027 breakfasts" />
setDraft({ ...draft, price: e.target.value })} />
setDraft({ ...draft, description: e.target.value })} />
Events on the pass
{locked &&

People have bought this pass, so its events and price can't change — switch it off and make a new one.

} {!loaded ?

Loading events…

: events.length === 0 ?

This series has no events that take registrations yet.

: (
    {events.map(ev => { const item = itemFor(draft, ev); const opts = sellable(ev); const variants = opts.find(o => o.id === item.eventOptionId)?.variants || []; return (
  • {item.on && ( <> {variants.length > 0 && ( )} )}
  • ); })}
)} {!locked && normalValue > 0 && (

Bought separately: {rand(normalValue)}{draft.price !== "" && Number(draft.price) < normalValue ? ` — the pass saves ${rand(normalValue - Number(draft.price))}` : ""}. The price is split over the events in proportion to these prices for each event's cashup.

)}
setDraft({ ...draft, saleEndsAt: e.target.value })} />

It always stops when the first event on it starts.

)}
); }