Files
crosscode-platform/apps/events/frontend/src/components/series/SeasonPassOffers.tsx
T
joshuaandClaude Opus 5.5 cf7d00bdf3 Season passes (1.47.3)
A pass sells a ticket at each of several events in a series for one
price. Supervisors set passes up on the Event series page (events and
ticket per event; fixed once sold). Buying on the series page registers
the buyer at every event at once with one checkout (free passes give
tickets straight away; Pay now if online payment isn't possible). The
price is split over the events in proportion to their normal prices:
each registration line is priced at its share and the webhook records
one Payment per event, so cashups stay per event. Pass registrations
aren't repriced, take no coupons and can't be edited. Migration
20261028150000_season_pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:19:58 +02:00

142 lines
7.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
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";
const rand = (n: number) => `R ${n.toFixed(2)}`;
type BuyResult = { purchaseId: string; total: number; paid: boolean; redirectUrl: string | null; message: string | null };
/**
* The season passes on a series page: what each includes and costs, Buy (registers you for every
* event on it, then one payment), and your own passes for this series with "Pay now" when unpaid.
*/
export function SeasonPassOffers({ slug, passes: initial }: { slug: string; passes: SeasonPassView[] }) {
const { user, token, loading } = useAuth();
const params = useSearchParams();
const [qty, setQty] = useState<Record<string, number>>({});
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [mine, setMine] = useState<SeasonPassPurchase[]>([]);
// 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(() => {});
}, [slug]);
const loadMine = useCallback(async () => {
if (!token) return;
const list = await apiFetch<SeasonPassPurchase[]>("/api/season-passes/mine", { authToken: token }).catch(() => []);
setMine(list.filter(p => p.pass.series.slug === slug && p.status !== "cancelled"));
}, [token, slug]);
useEffect(() => { loadMine(); }, [loadMine]);
const returned = params.get("pass");
const go = (res: BuyResult | { redirectUrl: string | null; message: string | null }) => {
if (res.redirectUrl) { window.location.href = res.redirectUrl; return; }
setNotice(res.message || "Done.");
loadMine();
};
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 } }));
} catch (e) {
setError(errorMessage(e) || "Couldn't buy the pass");
} finally {
setBusy(null);
}
};
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 }));
} catch (e) {
setError(errorMessage(e) || "Couldn't start the payment");
} finally {
setBusy(null);
}
};
if (passes.length === 0 && mine.length === 0) return null;
return (
<section className="mb-10" data-testid="season-pass-offers">
<h2 className="text-xl font-semibold text-gray-900 mb-1 flex items-center gap-2"><Ticket className="w-5 h-5 text-brand-600" /> Season passes</h2>
<p className="text-sm text-gray-500 mb-4">One payment, a ticket for every event on the pass.</p>
{returned === "paid" && <div className="p-3 mb-3 border rounded bg-green-50 text-green-800 text-sm">Thank you! Your tickets are on their way by email once the payment comes through.</div>}
{(returned === "cancelled" || returned === "failed") && <div className="p-3 mb-3 border rounded bg-amber-50 text-amber-800 text-sm">The payment didn&apos;t go through. Your places are kept — use &quot;Pay now&quot; below to try again.</div>}
{notice && <div className="p-3 mb-3 border rounded bg-green-50 text-green-800 text-sm" role="status">{notice}</div>}
{error && <div className="p-3 mb-3 border rounded bg-red-50 text-red-700 text-sm">{error}</div>}
{mine.length > 0 && (
<div className="border rounded-xl bg-white p-4 mb-4" data-testid="my-passes">
<div className="text-sm font-medium text-gray-900 mb-2">Your passes</div>
<ul className="space-y-2">
{mine.map(m => (
<li key={m.id} className="flex flex-wrap items-center justify-between gap-2 text-sm">
<span>{m.quantity} × {m.pass.name} · {rand(m.total)} · {m.status === "paid" ? <span className="text-green-700 inline-flex items-center gap-1"><CheckCircle2 className="w-3.5 h-3.5" /> paid — tickets in My events</span> : <span className="text-amber-700">not paid yet</span>}</span>
{m.status === "pending" && (
<button type="button" disabled={busy === m.id} onClick={() => pay(m.id)} className="px-3 py-1.5 text-xs rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50">Pay now</button>
)}
</li>
))}
</ul>
</div>
)}
<div className="grid gap-4 md:grid-cols-2">
{passes.map(p => (
<div key={p.id} className="border rounded-xl bg-white shadow-sm p-5" data-testid="season-pass-offer">
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="font-semibold text-gray-900">{p.name}</h3>
{p.description && <p className="text-sm text-gray-600 mt-0.5">{p.description}</p>}
</div>
<div className="text-right shrink-0">
<div className="text-lg font-bold text-gray-900">{p.price === 0 ? "Free" : rand(p.price)}</div>
{p.saving > 0 && <div className="text-xs text-green-700">save {rand(p.saving)}</div>}
</div>
</div>
<ul className="mt-3 space-y-1 text-sm text-gray-700">
{p.items.map(i => (
<li key={i.id} className="flex justify-between gap-2">
<span className="min-w-0"><span className="font-medium">{i.eventTitle}</span> <span className="text-gray-500 text-xs">· {formatDateTimeRange(i.startDate, i.endDate)} · {i.ticket}</span></span>
</li>
))}
</ul>
<div className="mt-4">
{p.unavailable ? (
<p className="text-sm text-gray-500">{p.unavailable}</p>
) : loading ? null : !user ? (
<a href={`/login?redirect=/series/${slug}`} className="inline-block px-4 py-2 text-sm rounded-lg border bg-white hover:bg-gray-50">Log in to buy</a>
) : (
<div className="flex items-center gap-2">
<label className="text-sm text-gray-600 flex items-center gap-1.5">
How many
<select aria-label={`How many of ${p.name}`} className="border rounded px-2 py-1 text-sm" value={qty[p.id] || 1} onChange={e => setQty({ ...qty, [p.id]: Number(e.target.value) })}>
{Array.from({ length: 10 }, (_, k) => k + 1).map(n => <option key={n} value={n}>{n}</option>)}
</select>
</label>
<button type="button" disabled={busy === p.id} onClick={() => buy(p)} className="px-4 py-2 text-sm rounded-lg bg-brand-600 text-white hover:bg-brand-700 font-medium disabled:opacity-50">
{busy === p.id ? "Booking…" : p.price === 0 ? "Get the pass" : `Buy · ${rand(p.price * (qty[p.id] || 1))}`}
</button>
</div>
)}
</div>
</div>
))}
</div>
</section>
);
}