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/SeasonPassOffers.tsx
T

142 lines
7.7 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 { 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 };
/**
* 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(() => {
(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 (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]);
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 (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 {
setBusy(null);
}
};
const pay = async (purchaseId: string) => {
setBusy(purchaseId); setError(null); setNotice(null);
try {
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 {
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>
);
}