Archived
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
543 lines
29 KiB
TypeScript
543 lines
29 KiB
TypeScript
"use client";
|
||
|
||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||
import { useAuth } from "@/hooks/useAuth";
|
||
import { useRouter } from "next/navigation";
|
||
import { fetchManagedEvents } from "@/lib/api";
|
||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||
import { Gift, Plus, X, Trash2, Pencil, Power, CalendarClock } from "lucide-react";
|
||
import { errorMessage } from "@/lib/utils";
|
||
import { BackLink } from "@/components/shared/BackLink";
|
||
import type { BundleGroupPricing, BundleKind, EventBundle } from "@/types";
|
||
import { EventPicker, defaultEventId } from "@/components/shared/EventPicker";
|
||
import { apiV2Data } from "@/lib/apiV2";
|
||
|
||
type OptionLite = { id: string; name: string; price: number; variants?: { id: string; name: string; price?: number | null }[] };
|
||
type EventLite = { id: string; title: string; startDate: string; endDate?: string; eventOptions: OptionLite[] };
|
||
|
||
type ItemDraft = { eventOptionId: string; variantId: string | null; quantity: string };
|
||
type Draft = {
|
||
name: string;
|
||
description: string;
|
||
kind: BundleKind;
|
||
price: string;
|
||
setSize: string;
|
||
freeCount: string;
|
||
groupPricing: BundleGroupPricing;
|
||
items: ItemDraft[];
|
||
validFrom: string;
|
||
validUntil: string;
|
||
isActive: boolean;
|
||
};
|
||
|
||
const blankDraft = (options: OptionLite[]): Draft => ({
|
||
name: "", description: "", kind: "exact", price: "", setSize: "4", freeCount: "1", groupPricing: "per_ticket",
|
||
items: options.slice(0, 2).map(o => ({ eventOptionId: o.id, variantId: null, quantity: "1" })),
|
||
validFrom: "", validUntil: "", isActive: true,
|
||
});
|
||
|
||
// <input type="datetime-local"> wants local "YYYY-MM-DDTHH:mm".
|
||
const toLocalInput = (iso: string | null | undefined) => {
|
||
if (!iso) return "";
|
||
const d = new Date(iso);
|
||
const pad = (n: number) => String(n).padStart(2, "0");
|
||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||
};
|
||
|
||
const draftFromBundle = (b: EventBundle): Draft => ({
|
||
name: b.name, description: b.description || "", kind: b.kind || "exact",
|
||
price: b.kind === "free" ? "" : String(b.price),
|
||
setSize: b.setSize ? String(b.setSize) : "4", freeCount: b.freeCount ? String(b.freeCount) : "1",
|
||
groupPricing: b.groupPricing || "per_ticket",
|
||
items: b.items.map(i => ({ eventOptionId: i.eventOptionId, variantId: i.variantId || null, quantity: String(i.quantity) })),
|
||
validFrom: toLocalInput(b.validFrom), validUntil: toLocalInput(b.validUntil), isActive: b.isActive,
|
||
});
|
||
|
||
const fmtDate = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : "");
|
||
const fmtRand = (n: number) => `R ${(n || 0).toFixed(2)}`;
|
||
// fieldCls has no width, for fields sized by their row (inputCls is full width).
|
||
const fieldCls = "border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400";
|
||
const inputCls = `w-full ${fieldCls}`;
|
||
|
||
const KIND_INFO: Record<BundleKind, { label: string; hint: string; example: string }> = {
|
||
exact: { label: "Exact set", hint: "These tickets in these numbers", example: "2 adults + 3 kids for R220" },
|
||
mix: { label: "Pick any", hint: "Any mix of the chosen tickets", example: "Any 4 tickets for R250" },
|
||
free: { label: "Buy X get Y free", hint: "Cheapest ones in each set are free", example: "Buy 3, get 1 free" },
|
||
group: { label: "Group discount", hint: "A lower price from a group size up", example: "10+ tickets: R70 each" },
|
||
};
|
||
|
||
/** Standard price of one unit of an item (variant price, else the option's). */
|
||
function unitPrice(options: OptionLite[], item: { eventOptionId: string; variantId: string | null }) {
|
||
const o = options.find(x => x.id === item.eventOptionId);
|
||
if (!o) return 0;
|
||
const v = item.variantId ? (o.variants || []).find(x => x.id === item.variantId) : null;
|
||
return Number(v && v.price !== null && v.price !== undefined ? v.price : o.price) || 0;
|
||
}
|
||
|
||
function bundleStatus(b: EventBundle): { label: string; cls: string } {
|
||
const now = Date.now();
|
||
if (!b.isActive) return { label: "Off", cls: "bg-gray-100 text-gray-600" };
|
||
if (b.validUntil && new Date(b.validUntil).getTime() < now) return { label: "Ended", cls: "bg-gray-100 text-gray-600" };
|
||
if (b.validFrom && new Date(b.validFrom).getTime() > now) return { label: "Scheduled", cls: "bg-amber-100 text-amber-800" };
|
||
return { label: "On sale", cls: "bg-green-100 text-green-800" };
|
||
}
|
||
|
||
export default function BundlesPage() {
|
||
const { user, loading, token } = useAuth();
|
||
const router = useRouter();
|
||
const canView = useMemo(() => user?.role === "admin" || user?.role === "supervisor", [user]);
|
||
|
||
useEffect(() => {
|
||
if (loading) return;
|
||
if (!user) router.replace("/login");
|
||
}, [user, loading, router]);
|
||
|
||
const [allEvents, setAllEvents] = useState<EventLite[]>([]);
|
||
const [eventId, setEventId] = useState("");
|
||
const [bundles, setBundles] = useState<EventBundle[]>([]);
|
||
const [fetching, setFetching] = useState(false);
|
||
const [error, setError] = useDismissingState<string | null>(null);
|
||
const [info, setInfo] = useDismissingState<string | null>(null);
|
||
const [editing, setEditing] = useState<{ id: string | null; draft: Draft } | null>(null);
|
||
|
||
useEffect(() => {
|
||
if (!token || !canView) return;
|
||
fetchManagedEvents<EventLite>(token, { past: true })
|
||
.then(list => setAllEvents(list || []))
|
||
.catch(e => setError(errorMessage(e) || "Failed to load events"));
|
||
}, [token, canView, setError]);
|
||
|
||
// Start on the next upcoming event (or the latest one).
|
||
useEffect(() => {
|
||
if (!allEvents.some(e => e.id === eventId)) setEventId(defaultEventId(allEvents));
|
||
}, [allEvents, eventId]);
|
||
|
||
const event = allEvents.find(e => e.id === eventId) || null;
|
||
const options = event?.eventOptions || [];
|
||
|
||
const load = useCallback(async () => {
|
||
if (!token || !eventId) { setBundles([]); return; }
|
||
setFetching(true);
|
||
try {
|
||
setBundles(await (apiV2Data("get", "/events/{id}/bundles", { params: { id: eventId }, authToken: token }) as Promise<EventBundle[]>));
|
||
} catch (e) {
|
||
setError(errorMessage(e) || "Failed to load bundles");
|
||
} finally {
|
||
setFetching(false);
|
||
}
|
||
}, [token, eventId, setError]);
|
||
|
||
useEffect(() => { load(); }, [load]);
|
||
|
||
const toggleActive = async (b: EventBundle) => {
|
||
try {
|
||
await apiV2Data("patch", "/bundles/{id}", { params: { id: b.id }, authToken: token, body: { isActive: !b.isActive } });
|
||
setInfo(`${b.name} turned ${b.isActive ? "off" : "on"}.`);
|
||
load();
|
||
} catch (e) {
|
||
setError(errorMessage(e) || "Failed to update bundle");
|
||
}
|
||
};
|
||
|
||
const remove = async (b: EventBundle) => {
|
||
if (!window.confirm(`Delete "${b.name}"?`)) return;
|
||
try {
|
||
const res = await (apiV2Data("delete", "/bundles/{id}", { params: { id: b.id }, authToken: token }) as Promise<{ message: string }>);
|
||
setInfo(res?.message || "Bundle deleted");
|
||
load();
|
||
} catch (e) {
|
||
setError(errorMessage(e) || "Failed to delete bundle");
|
||
}
|
||
};
|
||
|
||
const startNew = () => setEditing({ id: null, draft: blankDraft(options) });
|
||
const canAdd = !!event && options.length > 0;
|
||
|
||
return (
|
||
<div className="max-w-6xl mx-auto w-full p-4 sm:p-6">
|
||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-4">
|
||
<div className="flex items-center gap-3">
|
||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||
<Gift className="w-5 h-5 text-brand-600" />
|
||
</div>
|
||
<div>
|
||
<BackLink href="/dashboard" />
|
||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Bundle deals</h1>
|
||
<p className="text-sm text-gray-500">Tickets sold together for one price</p>
|
||
</div>
|
||
</div>
|
||
{canView && (
|
||
<button
|
||
onClick={startNew}
|
||
disabled={!canAdd}
|
||
className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50 w-full sm:w-auto"
|
||
>
|
||
<Plus className="w-4 h-4" /> New bundle
|
||
</button>
|
||
)}
|
||
</div>
|
||
|
||
{!canView && (
|
||
<div className="p-3 border rounded bg-yellow-50 text-yellow-800 text-sm mb-4">You need supervisor access to manage bundle deals.</div>
|
||
)}
|
||
{error && <div className="mb-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
|
||
{info && <div className="mb-3 p-3 border rounded bg-green-50 text-green-800 text-sm">{info}</div>}
|
||
|
||
{canView && (
|
||
<div className="border rounded-xl p-4 bg-white shadow-sm">
|
||
<div className="flex flex-col sm:flex-row sm:items-end gap-3 mb-4">
|
||
<div className="w-full sm:w-auto">
|
||
<label className="block text-xs text-gray-600 mb-1" htmlFor="bundles-event">Event</label>
|
||
<EventPicker id="bundles-event" className="w-full sm:min-w-[20rem]" events={allEvents} value={eventId} onChange={setEventId} placeholder="No events" />
|
||
</div>
|
||
</div>
|
||
|
||
{event && options.length === 0 && (
|
||
<p className="text-sm text-gray-500 py-6 text-center">This event has no tickets yet. Add ticket options to the event first.</p>
|
||
)}
|
||
|
||
{event && options.length > 0 && !fetching && bundles.length === 0 && (
|
||
<div className="text-center py-10">
|
||
<div className="w-12 h-12 rounded-full bg-emerald-50 flex items-center justify-center mx-auto mb-3">
|
||
<Gift className="w-6 h-6 text-emerald-600" />
|
||
</div>
|
||
<p className="text-sm font-medium text-gray-900">No bundle deals for this event yet</p>
|
||
<p className="text-xs text-gray-500 mt-1 max-w-sm mx-auto">e.g. "Family deal: 2 adults + 3 kids for R220". Buyers get it automatically when their tickets match.</p>
|
||
<button onClick={startNew} className="mt-4 inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700">
|
||
<Plus className="w-4 h-4" /> Create a bundle
|
||
</button>
|
||
</div>
|
||
)}
|
||
|
||
{bundles.length > 0 && (
|
||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||
{bundles.map(b => (
|
||
<BundleCard
|
||
key={b.id}
|
||
bundle={b}
|
||
onEdit={() => setEditing({ id: b.id, draft: draftFromBundle(b) })}
|
||
onToggle={() => toggleActive(b)}
|
||
onDelete={() => remove(b)}
|
||
/>
|
||
))}
|
||
</div>
|
||
)}
|
||
|
||
<p className="text-xs text-gray-500 mt-4">
|
||
Bundles apply automatically, as many times as someone's tickets allow, and only when cheaper than the tickets at the prices
|
||
actually charged (early-bird and staff prices included). Coupon codes come off afterwards.
|
||
</p>
|
||
</div>
|
||
)}
|
||
|
||
{editing && event && (
|
||
<BundleModal
|
||
token={token!}
|
||
event={event}
|
||
bundleId={editing.id}
|
||
initial={editing.draft}
|
||
onClose={() => setEditing(null)}
|
||
onSaved={(msg) => { setEditing(null); setInfo(msg); load(); }}
|
||
/>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function BundleCard({ bundle: b, onEdit, onToggle, onDelete }: { bundle: EventBundle; onEdit: () => void; onToggle: () => void; onDelete: () => void }) {
|
||
const status = bundleStatus(b);
|
||
const kind = b.kind || "exact";
|
||
const dates = b.validFrom || b.validUntil
|
||
? `${b.validFrom ? fmtDate(b.validFrom) : "Now"} – ${b.validUntil ? fmtDate(b.validUntil) : "no end date"}`
|
||
: null;
|
||
return (
|
||
<div className={`border rounded-xl p-4 flex flex-col gap-3 ${b.isActive ? "bg-white" : "bg-gray-50"}`}>
|
||
<div className="flex items-start justify-between gap-3">
|
||
<div className="min-w-0">
|
||
<div className="font-semibold text-gray-900 break-words">{b.name}</div>
|
||
{b.description && <div className="text-xs text-gray-500 mt-0.5 break-words">{b.description}</div>}
|
||
</div>
|
||
<span className={`shrink-0 text-xs px-2 py-0.5 rounded-full font-medium ${status.cls}`}>{status.label}</span>
|
||
</div>
|
||
|
||
<div className="text-xs font-medium text-brand-700">{KIND_INFO[kind].label}{kind === "exact" ? "" : ` · ${kind === "group" ? "qualifying" : "any of"}:`}</div>
|
||
|
||
<div className="flex flex-wrap gap-1.5">
|
||
{b.items.map(i => (
|
||
<span key={i.id || `${i.eventOptionId}-${i.variantId}`} className="inline-flex items-center gap-1 rounded-full bg-emerald-50 text-emerald-800 border border-emerald-100 px-2.5 py-1 text-xs">
|
||
{kind === "exact" && <span className="font-semibold">{i.quantity} ×</span>} {i.eventOption?.name || "Ticket"}{i.variant ? ` (${i.variant.name})` : ""}
|
||
</span>
|
||
))}
|
||
</div>
|
||
|
||
<div>
|
||
<div className="flex items-baseline flex-wrap gap-x-2 gap-y-0.5">
|
||
{kind === "exact" || kind === "mix" ? (
|
||
<>
|
||
<span className="text-xl font-semibold text-gray-900">{fmtRand(b.price)}</span>
|
||
<span className="text-sm text-gray-500">{kind === "mix" ? `for any ${b.setSize}` : "for the set"}</span>
|
||
{b.standardValue !== null && <span className="text-sm text-gray-400 line-through">{fmtRand(b.standardValue)}</span>}
|
||
</>
|
||
) : kind === "free" ? (
|
||
<span className="text-xl font-semibold text-gray-900">Buy {(b.setSize || 0) - (b.freeCount || 0)}, get {b.freeCount} free</span>
|
||
) : (
|
||
<>
|
||
<span className="text-xl font-semibold text-gray-900">{b.groupPricing === "percent" ? `${b.price}% off` : `${fmtRand(b.price)} each`}</span>
|
||
<span className="text-sm text-gray-500">from {b.setSize} tickets</span>
|
||
</>
|
||
)}
|
||
</div>
|
||
<div className={`text-xs font-medium ${b.savingText || kind === "free" || (kind === "group" && b.groupPricing === "percent") ? "text-green-700" : "text-amber-700"}`}>
|
||
{b.savingText || (kind === "free" || (kind === "group" && b.groupPricing === "percent") ? "" : "No saving at the standard prices")}
|
||
</div>
|
||
</div>
|
||
|
||
<div className="text-xs text-gray-600 space-y-0.5">
|
||
<div>
|
||
Used <strong>{b.uses || 0}×</strong> on {b.registrations || 0} registration{b.registrations === 1 ? "" : "s"} · {fmtRand(b.totalDiscount || 0)} given
|
||
</div>
|
||
{dates && <div className="flex items-center gap-1"><CalendarClock className="w-3.5 h-3.5" /> {dates}</div>}
|
||
</div>
|
||
|
||
<div className="flex flex-wrap gap-2 pt-1 border-t border-gray-100 mt-auto">
|
||
<button onClick={onEdit} className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border hover:bg-gray-50 mt-2">
|
||
<Pencil className="w-3.5 h-3.5" /> Edit
|
||
</button>
|
||
<button onClick={onToggle} className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border mt-2 ${b.isActive ? "text-amber-700 border-amber-200 hover:bg-amber-50" : "text-green-700 border-green-200 hover:bg-green-50"}`}>
|
||
<Power className="w-3.5 h-3.5" /> {b.isActive ? "Turn off" : "Turn on"}
|
||
</button>
|
||
<button onClick={onDelete} className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border text-red-700 border-red-200 hover:bg-red-50 mt-2 sm:ml-auto">
|
||
<Trash2 className="w-3.5 h-3.5" /> Delete
|
||
</button>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function BundleModal({ token, event, bundleId, initial, onClose, onSaved }: {
|
||
token: string;
|
||
event: EventLite;
|
||
bundleId: string | null;
|
||
initial: Draft;
|
||
onClose: () => void;
|
||
onSaved: (message: string) => void;
|
||
}) {
|
||
const [d, setD] = useState<Draft>(initial);
|
||
const [saving, setSaving] = useState(false);
|
||
const [error, setError] = useState<string | null>(null);
|
||
const set = <K extends keyof Draft>(key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value }));
|
||
const options = event.eventOptions || [];
|
||
|
||
const setItem = (i: number, patch: Partial<ItemDraft>) => set("items", d.items.map((it, j) => (j === i ? { ...it, ...patch } : it)));
|
||
const exact = d.kind === "exact";
|
||
const price = Number(d.price) || 0;
|
||
const size = Math.max(0, Math.floor(Number(d.setSize) || 0));
|
||
const free = Math.max(0, Math.floor(Number(d.freeCount) || 0));
|
||
const dearest = d.items.reduce((m, it) => Math.max(m, unitPrice(options, it)), 0);
|
||
// Exact: what the set costs separately. Pick any: the dearest possible set.
|
||
const standardValue = exact ? d.items.reduce((s, it) => s + unitPrice(options, it) * (Number(it.quantity) || 0), 0) : dearest * size;
|
||
const saving_ = standardValue - price;
|
||
const priceLabel = exact ? "Bundle price (R)" : d.kind === "mix" ? "Price for the set (R)" : d.groupPricing === "percent" ? "Percentage off (%)" : "Price per ticket (R)";
|
||
|
||
const save = async (e: React.FormEvent) => {
|
||
e.preventDefault();
|
||
setError(null);
|
||
setSaving(true);
|
||
try {
|
||
const body = {
|
||
name: d.name.trim(),
|
||
description: d.description.trim() || null,
|
||
kind: d.kind,
|
||
price: d.kind === "free" ? 0 : Number(d.price),
|
||
setSize: exact ? null : Number(d.setSize),
|
||
freeCount: d.kind === "free" ? Number(d.freeCount) : null,
|
||
groupPricing: d.kind === "group" ? d.groupPricing : null,
|
||
items: d.items.map(it => ({ eventOptionId: it.eventOptionId, variantId: it.variantId, quantity: exact ? Number(it.quantity) : 1 })),
|
||
validFrom: d.validFrom ? new Date(d.validFrom).toISOString() : null,
|
||
validUntil: d.validUntil ? new Date(d.validUntil).toISOString() : null,
|
||
isActive: d.isActive,
|
||
};
|
||
if (bundleId) {
|
||
await apiV2Data("patch", "/bundles/{id}", { params: { id: bundleId }, authToken: token, body: body as never });
|
||
onSaved(`${body.name} saved.`);
|
||
} else {
|
||
await apiV2Data("post", "/events/{id}/bundles", { params: { id: event.id }, authToken: token, body: body as never });
|
||
onSaved(`${body.name} created.`);
|
||
}
|
||
} catch (err) {
|
||
setError(errorMessage(err) || "Failed to save");
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
return (
|
||
<div className="fixed inset-0 z-50 bg-black/40 flex items-end sm:items-center justify-center sm:p-4" onClick={onClose}>
|
||
<form onSubmit={save} className="bg-white w-full sm:max-w-2xl max-h-[92vh] sm:max-h-[90vh] rounded-t-2xl sm:rounded-xl shadow-xl flex flex-col" onClick={e => e.stopPropagation()}>
|
||
<div className="flex items-start justify-between gap-3 p-4 border-b">
|
||
<div className="min-w-0">
|
||
<h2 className="font-semibold">{bundleId ? "Edit bundle" : "New bundle deal"}</h2>
|
||
<p className="text-xs text-gray-500 truncate">{event.title}</p>
|
||
</div>
|
||
<button type="button" onClick={onClose} aria-label="Close" className="p-1 -m-1"><X className="w-5 h-5 text-gray-500" /></button>
|
||
</div>
|
||
|
||
<div className="p-4 space-y-5 overflow-y-auto overflow-x-hidden overscroll-contain">
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
|
||
<input className={inputCls} value={d.name} onChange={e => set("name", e.target.value)} placeholder="Family deal" required maxLength={80} />
|
||
<p className="text-xs text-gray-500 mt-1">Shown to buyers and on receipts.</p>
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Description <span className="font-normal text-gray-400">(optional)</span></label>
|
||
<input className={inputCls} value={d.description} onChange={e => set("description", e.target.value)} placeholder="Bring the whole family" />
|
||
</div>
|
||
</div>
|
||
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-2">Type of deal</label>
|
||
<div className="grid grid-cols-2 gap-2">
|
||
{(Object.keys(KIND_INFO) as BundleKind[]).map(k => (
|
||
<button type="button" key={k} onClick={() => set("kind", k)} aria-pressed={d.kind === k}
|
||
className={`text-left rounded-lg border p-2.5 transition-colors ${d.kind === k ? "border-brand-500 bg-brand-50 ring-1 ring-brand-500" : "hover:bg-gray-50"}`}>
|
||
<div className="text-sm font-medium text-gray-900">{KIND_INFO[k].label}</div>
|
||
<div className="text-xs text-gray-500">{KIND_INFO[k].hint}</div>
|
||
<div className="text-[11px] text-gray-400 mt-0.5 hidden sm:block">e.g. {KIND_INFO[k].example}</div>
|
||
</button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-2">{exact ? "Tickets in the bundle" : "Qualifying tickets"}</label>
|
||
{!exact && <p className="text-xs text-gray-500 -mt-1 mb-2">Any of these count towards the deal.</p>}
|
||
<div className="space-y-2">
|
||
{d.items.map((it, i) => {
|
||
const opt = options.find(o => o.id === it.eventOptionId);
|
||
const hasVariants = (opt?.variants || []).length > 0;
|
||
return (
|
||
<div key={i} className="rounded-lg border bg-gray-50 p-2.5">
|
||
<div className="flex items-center gap-2">
|
||
{exact && (
|
||
<>
|
||
<input type="number" min="1" step="1" inputMode="numeric" className={`${fieldCls} w-16 shrink-0 px-2 bg-white text-center`} value={it.quantity} onChange={e => setItem(i, { quantity: e.target.value })} aria-label="Quantity" required />
|
||
<span className="text-sm text-gray-500 shrink-0">×</span>
|
||
</>
|
||
)}
|
||
<select className={`${fieldCls} min-w-0 flex-1 bg-white`} value={it.eventOptionId} onChange={e => setItem(i, { eventOptionId: e.target.value, variantId: null })} aria-label="Ticket">
|
||
{options.map(o => <option key={o.id} value={o.id}>{o.name} ({fmtRand(o.price)})</option>)}
|
||
</select>
|
||
<button type="button" onClick={() => set("items", d.items.filter((_, j) => j !== i))} disabled={d.items.length <= 1}
|
||
className="p-2 shrink-0 rounded-lg text-gray-400 hover:text-red-600 hover:bg-red-50 disabled:opacity-30 disabled:hover:bg-transparent" aria-label="Remove ticket">
|
||
<Trash2 className="w-4 h-4" />
|
||
</button>
|
||
</div>
|
||
{hasVariants && (
|
||
<select className={`${inputCls} mt-2 bg-white`} value={it.variantId || ""} onChange={e => setItem(i, { variantId: e.target.value || null })} aria-label="Variant">
|
||
<option value="">Any {opt?.name.toLowerCase()} variant</option>
|
||
{(opt?.variants || []).map(v => <option key={v.id} value={v.id}>{v.name}</option>)}
|
||
</select>
|
||
)}
|
||
</div>
|
||
);
|
||
})}
|
||
</div>
|
||
<button type="button" onClick={() => set("items", [...d.items, { eventOptionId: options[0]?.id || "", variantId: null, quantity: "1" }])}
|
||
className="mt-2 inline-flex items-center gap-1 text-sm font-medium text-brand-700 hover:underline">
|
||
<Plus className="w-4 h-4" /> Add a ticket type
|
||
</button>
|
||
</div>
|
||
|
||
{!exact && (
|
||
<div className="grid grid-cols-2 gap-4">
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">{d.kind === "group" ? "Minimum tickets" : "Tickets per set"}</label>
|
||
<input type="number" min={d.kind === "free" ? 2 : 2} step="1" inputMode="numeric" className={inputCls} value={d.setSize} onChange={e => set("setSize", e.target.value)} required />
|
||
</div>
|
||
{d.kind === "free" && (
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Free in each set</label>
|
||
<input type="number" min="1" step="1" inputMode="numeric" className={inputCls} value={d.freeCount} onChange={e => set("freeCount", e.target.value)} required />
|
||
</div>
|
||
)}
|
||
{d.kind === "group" && (
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Group price</label>
|
||
<select className={inputCls} value={d.groupPricing} onChange={e => set("groupPricing", e.target.value as BundleGroupPricing)}>
|
||
<option value="per_ticket">Price per ticket</option>
|
||
<option value="percent">Percentage off</option>
|
||
</select>
|
||
</div>
|
||
)}
|
||
</div>
|
||
)}
|
||
|
||
{d.kind === "free" ? (
|
||
<div className="rounded-lg bg-emerald-50 p-3 text-sm text-emerald-900">
|
||
{size > free && free > 0
|
||
? <>Buy {size - free}, get {free} free. In every {size} qualifying tickets, the cheapest {free === 1 ? "one is" : `${free} are`} free.</>
|
||
: <span className="text-amber-700">The set needs more tickets than are free.</span>}
|
||
</div>
|
||
) : (
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">{priceLabel}</label>
|
||
<input type="number" min="0" max={d.kind === "group" && d.groupPricing === "percent" ? 100 : undefined} step="0.01" inputMode="decimal" className={`${inputCls} sm:max-w-[12rem]`} value={d.price} onChange={e => set("price", e.target.value)} required />
|
||
{d.kind === "group" ? (
|
||
<p className="text-xs text-gray-500 mt-2">
|
||
{size >= 2 ? `From ${size} qualifying tickets, every one of them ` : "Every qualifying ticket "}
|
||
{d.groupPricing === "percent" ? `gets ${d.price || "…"}% off.` : `costs ${d.price === "" ? "…" : fmtRand(price)} (tickets already cheaper stay as they are).`}
|
||
</p>
|
||
) : (
|
||
<>
|
||
<div className="mt-2 grid grid-cols-3 gap-2 text-center">
|
||
<div className="rounded-lg bg-gray-50 p-2">
|
||
<div className="text-[11px] uppercase tracking-wide text-gray-500">{exact ? "Separately" : "Dearest set"}</div>
|
||
<div className="text-sm font-semibold text-gray-900">{fmtRand(standardValue)}</div>
|
||
</div>
|
||
<div className="rounded-lg bg-gray-50 p-2">
|
||
<div className="text-[11px] uppercase tracking-wide text-gray-500">Bundle</div>
|
||
<div className="text-sm font-semibold text-gray-900">{d.price === "" ? "—" : fmtRand(price)}</div>
|
||
</div>
|
||
<div className={`rounded-lg p-2 ${d.price !== "" && saving_ <= 0 ? "bg-amber-50" : "bg-emerald-50"}`}>
|
||
<div className="text-[11px] uppercase tracking-wide text-gray-500">Saving</div>
|
||
<div className={`text-sm font-semibold ${d.price !== "" && saving_ <= 0 ? "text-amber-700" : "text-emerald-700"}`}>{d.price === "" ? "—" : fmtRand(Math.max(0, saving_))}</div>
|
||
</div>
|
||
</div>
|
||
{d.price !== "" && saving_ <= 0 && <p className="text-xs text-amber-700 mt-1">The bundle isn't cheaper than the standard prices, so it won't apply unless prices change.</p>}
|
||
{!exact && <p className="text-xs text-gray-500 mt-1">The saving depends on which tickets are picked; it only applies when the set price is cheaper.</p>}
|
||
</>
|
||
)}
|
||
</div>
|
||
)}
|
||
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Available from <span className="font-normal text-gray-400">(optional)</span></label>
|
||
<input type="datetime-local" className={inputCls} value={d.validFrom} onChange={e => set("validFrom", e.target.value)} />
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Available until <span className="font-normal text-gray-400">(optional)</span></label>
|
||
<input type="datetime-local" className={inputCls} value={d.validUntil} onChange={e => set("validUntil", e.target.value)} />
|
||
</div>
|
||
</div>
|
||
|
||
<label className="flex items-start gap-2 text-sm text-gray-700">
|
||
<input type="checkbox" className="mt-0.5" checked={d.isActive} onChange={e => set("isActive", e.target.checked)} />
|
||
<span>On sale <span className="block text-xs text-gray-500">Registrations that already have this bundle keep it if you turn it off later.</span></span>
|
||
</label>
|
||
|
||
{error && <div className="p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
|
||
</div>
|
||
|
||
<div className="flex flex-col-reverse sm:flex-row sm:justify-end gap-2 sm:gap-3 p-4 border-t">
|
||
<button type="button" onClick={onClose} className="px-4 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">Cancel</button>
|
||
<button type="submit" disabled={saving} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
|
||
{saving ? "Saving…" : bundleId ? "Save changes" : "Create bundle"}
|
||
</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
);
|
||
}
|