This repository has been archived on 2026-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
hope-events/frontend/src/components/series/SeasonPassesPanel.tsx
T

210 lines
13 KiB
TypeScript

"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<SeasonPassView[]>([]);
const [events, setEvents] = useState<Event[]>([]);
// The series' events have arrived (the pass form needs them before it can be saved).
const [loaded, setLoaded] = useState(false);
const [draft, setDraft] = useState<Draft | null>(null);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
if (!token) return;
const [p, all] = await Promise.all([
(apiV2Data("get", "/season-passes", { query: { seriesId }, authToken: token }) as Promise<SeasonPassView[]>).catch(() => [] as SeasonPassView[]),
fetchManagedEvents<Event>(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<ItemDraft>) => setDraft(d => d && ({ ...d, items: [...d.items.filter(i => i.eventId !== ev.id), { ...itemFor(d, ev), ...patch }] }));
return (
<div className="mt-3 border-t pt-3" data-testid="season-passes">
<div className="flex items-center justify-between gap-2 mb-2">
<div className="text-xs font-medium text-gray-700 flex items-center gap-1"><Ticket className="w-3.5 h-3.5" /> Season passes</div>
{!draft && <button type="button" className="text-xs px-2.5 py-1 rounded border bg-white hover:bg-gray-50" onClick={openNew}>+ New pass</button>}
</div>
{error && <div className="p-2 mb-2 border rounded bg-red-50 text-red-700 text-xs">{error}</div>}
{passes.length === 0 && !draft && <p className="text-xs text-gray-500">No passes. A pass sells a ticket for several events in this series at one price.</p>}
<ul className="space-y-2">
{passes.map(p => (
<li key={p.id} className="border rounded-lg p-3 text-sm bg-gray-50/50" data-testid="season-pass">
<div className="flex items-start justify-between gap-2 flex-wrap">
<div>
<span className="font-medium">{p.name}</span> · {rand(p.price)}
{p.saving > 0 && <span className="text-xs text-green-700"> (saves {rand(p.saving)})</span>}
{!p.isActive && <span className="ml-1 text-[10px] px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">Off</span>}
<div className="text-xs text-gray-500 mt-0.5">{p.sold || 0} sold{p.unpaid ? ` · ${p.unpaid} not paid yet` : ""}{p.unavailable && p.isActive ? ` · ${p.unavailable}` : ""}</div>
</div>
<div className="flex gap-2">
<a href={`/series/${seriesSlug}`} target="_blank" rel="noreferrer" className="text-xs px-2 py-1 rounded border bg-white hover:bg-gray-50">View</a>
<button type="button" className="text-xs px-2 py-1 rounded border bg-white hover:bg-gray-50" onClick={() => openEdit(p)}>Edit</button>
{!(p.sold || p.unpaid) && <button type="button" className="text-xs px-2 py-1 rounded bg-red-50 text-red-700 border border-red-200" onClick={() => remove(p)}>Delete</button>}
</div>
</div>
<ul className="mt-2 text-xs text-gray-600 space-y-0.5">
{p.items.map(i => (
<li key={i.id}>{i.eventTitle} ({new Date(i.startDate).toLocaleDateString()}) — {i.ticket}: normally {rand(i.normalPrice)}, share {rand(i.share)}</li>
))}
</ul>
</li>
))}
</ul>
{draft && (
<div className="border rounded-lg p-3 bg-white space-y-3 mt-2" data-testid="season-pass-form">
<div className="grid sm:grid-cols-3 gap-3">
<div className="sm:col-span-2">
<label className="block text-xs text-gray-600 mb-1" htmlFor="pass-name">Pass name</label>
<input id="pass-name" className="w-full border rounded px-2 py-1.5 text-sm" value={draft.name} onChange={e => setDraft({ ...draft, name: e.target.value })} placeholder="e.g. All 2027 breakfasts" />
</div>
<div>
<label className="block text-xs text-gray-600 mb-1" htmlFor="pass-price">Price (R)</label>
<input id="pass-price" type="number" min="0" step="1" disabled={locked} className="w-full border rounded px-2 py-1.5 text-sm disabled:bg-gray-50" value={draft.price} onChange={e => setDraft({ ...draft, price: e.target.value })} />
</div>
</div>
<div>
<label className="block text-xs text-gray-600 mb-1" htmlFor="pass-description">Description (optional)</label>
<input id="pass-description" className="w-full border rounded px-2 py-1.5 text-sm" value={draft.description} onChange={e => setDraft({ ...draft, description: e.target.value })} />
</div>
<div>
<div className="text-xs text-gray-600 mb-1">Events on the pass</div>
{locked && <p className="text-[11px] text-amber-700 mb-1">People have bought this pass, so its events and price can&apos;t change — switch it off and make a new one.</p>}
{!loaded ? <p className="text-xs text-gray-500">Loading events…</p> : events.length === 0 ? <p className="text-xs text-gray-500">This series has no events that take registrations yet.</p> : (
<ul className="space-y-1.5">
{events.map(ev => {
const item = itemFor(draft, ev);
const opts = sellable(ev);
const variants = opts.find(o => o.id === item.eventOptionId)?.variants || [];
return (
<li key={ev.id} className="flex flex-wrap items-center gap-2 text-sm">
<label className="flex items-center gap-1.5 min-w-0 flex-1">
<input type="checkbox" disabled={locked} checked={item.on} onChange={e => updItem(ev, { on: e.target.checked })} />
<span className="truncate">{ev.title}</span>
<span className="text-xs text-gray-500">{new Date(ev.startDate).toLocaleDateString()}</span>
</label>
{item.on && (
<>
<select aria-label={`Ticket for ${ev.title}`} disabled={locked} className="border rounded px-2 py-1 text-xs" value={item.eventOptionId} onChange={e => updItem(ev, { eventOptionId: e.target.value, variantId: "" })}>
{opts.map(o => <option key={o.id} value={o.id}>{o.name} (R{Number(o.price).toFixed(0)})</option>)}
</select>
{variants.length > 0 && (
<select aria-label={`Variant for ${ev.title}`} disabled={locked} className="border rounded px-2 py-1 text-xs" value={item.variantId} onChange={e => updItem(ev, { variantId: e.target.value })}>
<option value="">Any / none</option>
{variants.map(v => <option key={v.id} value={v.id}>{v.name}</option>)}
</select>
)}
</>
)}
</li>
);
})}
</ul>
)}
{!locked && normalValue > 0 && (
<p className="text-[11px] text-gray-500 mt-1">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&apos;s cashup.</p>
)}
</div>
<div className="grid sm:grid-cols-2 gap-3 items-end">
<div>
<label className="block text-xs text-gray-600 mb-1" htmlFor="pass-sale-ends">Stop selling at (optional)</label>
<input id="pass-sale-ends" type="datetime-local" className="w-full border rounded px-2 py-1.5 text-sm" value={draft.saleEndsAt} onChange={e => setDraft({ ...draft, saleEndsAt: e.target.value })} />
<p className="text-[10px] text-gray-400 mt-0.5">It always stops when the first event on it starts.</p>
</div>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={draft.isActive} onChange={e => setDraft({ ...draft, isActive: e.target.checked })} /> On sale</label>
</div>
<div className="flex gap-2">
<button type="button" onClick={save} disabled={saving || !loaded || !draft.name.trim() || (!locked && draft.price === "")} className="px-3 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50 font-medium">
{saving ? "Saving…" : draft.id ? "Save pass" : "Create pass"}
</button>
<button type="button" onClick={() => setDraft(null)} className="px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50">Cancel</button>
</div>
</div>
)}
</div>
);
}