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/app/dashboard/supervisor/events/page.tsx
T

2150 lines
122 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, useLayoutEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { API_BASE, fetchManagedEvents, fetchEvent } from "@/lib/api";
import { ApiImage } from "@/components/shared/ApiImage";
import { useDismissingState } from "@/hooks/useDismissingState";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { useMyCampuses } from "@/hooks/useCampuses";
import { CampusBadge, CampusFilter, matchesCampus } from "@/components/shared/CampusFilter";
import { SavedFilters } from "@/components/shared/SavedFilters";
import { Calendar, Copy } from "lucide-react";
import { ChoicesEditor } from "@/components/shared/FormFieldExtras";
import { errorMessage } from "@/lib/utils";
import type { Event, EventAttachment, EventFormField, EventOption, EventSeries, Paginated, Section } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import {
SessionsEditor, AttendanceSettings, keyed, sortSessions, sessionsProblem, defaultCertificate,
type KeyedSession, type AttendanceDraft,
} from "@/components/events/ScheduleEditor";
import { toSessionDraft, scheduleSummary } from "@/lib/sessions";
import { fetchApiFile, openBlob } from "@/lib/export";
import { apiV2, apiV2Data } from "@/lib/apiV2";
import { createTicketOption, updateTicketOption, listSections, createSection, updateSection, deleteSection, listAttachments, uploadAttachment, deleteAttachment, uploadImage } from "@/lib/eventSetup";
// ─── helpers ────────────────────────────────────────────────────────────────
const cleanChoices = (opts: unknown): string[] => (Array.isArray(opts) ? opts.map(o => String(o).trim()).filter(Boolean) : []);
function toLocalDT(input: string | Date | null | undefined): string {
if (!input) return "";
const d = new Date(input);
if (isNaN(d.getTime())) return "";
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
const hh = String(d.getHours()).padStart(2, "0");
const mm = String(d.getMinutes()).padStart(2, "0");
return `${y}-${m}-${day}T${hh}:${mm}`;
}
const DT_MIN = "2000-01-01T00:00";
const DT_MAX = "2099-12-31T23:59";
function DTInput({ label, value, onChange, hint, required }: { label: string; value: string; onChange: (v: string) => void; hint?: string; required?: boolean }) {
return (
<div>
<label className="block text-xs text-gray-600 mb-1">{label} {required && <span className="text-red-500">*</span>}</label>
<input type="datetime-local" min={DT_MIN} max={DT_MAX} required={required}
className="w-full border rounded px-3 py-2 text-sm"
value={value} onChange={e => onChange(e.target.value)} />
{hint && <p className="text-[10px] text-gray-400 mt-0.5">{hint}</p>}
</div>
);
}
// ─── types ───────────────────────────────────────────────────────────────────
type FormFieldType = "yes_no" | "text" | "date" | "numeric" | "statement" | "paragraph" | "rating" | "multiple_choice";
type EventFormDef = { isRequired: boolean; fields: { id?: string; type: FormFieldType; label: string; isRequired?: boolean; order?: number; helpText?: string | null; options?: unknown }[] };
type FieldDef = EventFormDef["fields"][number];
// What PATCH /api/v2/ticket-options/{id} takes as earlyBirdTiers (variantId null = option-level).
type TierPayload = { id?: string; deadline: string; price: number; stockLimit: number; order: number; variantId: string | null };
// GET /api/feedback/event/:id — the event's post-event feedback form, if it has one.
type FeedbackFormResponse = {
fields?: EventFormField[];
sendAt?: string | null;
audience?: string;
anonymous?: boolean;
intro?: string | null;
sentAt: string | null;
invited: number;
responses: number;
};
const toFieldDefs = (fields: EventFormField[] | undefined): FieldDef[] =>
(fields || []).map((x) => ({ id: x.id, type: x.type, label: x.label, isRequired: !!x.isRequired, helpText: x.helpText || "", options: x.options || undefined }));
type Tier = { id?: string; deadline: string; price: string; stockLimit: string; order?: number };
type Variant = {
id?: string;
name: string;
price: string; // empty → use option base price
stockLimit: string;
staffPrice?: string; // empty → use the option's staff price
earlyBirdTiers: Tier[];
};
type OptionDraft = {
id?: string;
name: string;
price: string;
isMainTicket: boolean;
stockLimit: string;
staffPrice?: string; // empty → no staff price
earlyBirdTiers: Tier[]; // option-level (used only when no variants)
variants: Variant[];
sessionMode?: "all" | "pick"; // "pick sessions" events only
};
type SectionDraft = {
name: string;
optionIndices: number[];
};
// ─── sub-components ─────────────────────────────────────────────────────────
function UploadImageButton({ onUploaded, label = "Upload image" }: { onUploaded: (url: string) => void; label?: string }) {
const { token } = useAuth();
const [uploading, setUploading] = useState(false);
const ref = useRef<HTMLInputElement | null>(null);
return (
<div className="inline-flex items-center">
<input ref={ref} type="file" accept="image/*" className="hidden" onChange={async e => {
const file = e.target.files?.[0];
if (!file || !token) return;
setUploading(true);
try {
const uploaded = await uploadImage(token, "event-image", file);
if (uploaded) onUploaded(uploaded);
} finally { setUploading(false); if (ref.current) ref.current.value = ""; }
}} />
<button type="button" onClick={() => ref.current?.click()} disabled={uploading}
className="px-3 py-1.5 text-sm rounded border border-brand-200 bg-brand-50 text-brand-700 hover:bg-brand-100 disabled:opacity-50">
{uploading ? "Uploading…" : label}
</button>
</div>
);
}
function FormBuilder({ value, onChange, title = "Registration Form Fields", gateLabel = "Required before tickets generate" }: {
value: EventFormDef;
onChange: (v: EventFormDef) => void;
title?: string;
/** Label of the "form must be filled in" switch; null hides it (feedback forms). */
gateLabel?: string | null;
}) {
const fields = value.fields || [];
const add = (type: FormFieldType) => onChange({ ...value, fields: [...fields, { type, label: "", isRequired: false, helpText: "" }] });
const upd = (idx: number, patch: Partial<FieldDef>) => { const c = fields.slice(); c[idx] = { ...c[idx], ...patch }; onChange({ ...value, fields: c }); };
const rem = (idx: number) => { const c = fields.slice(); c.splice(idx, 1); onChange({ ...value, fields: c }); };
const mov = (idx: number, dir: -1 | 1) => {
const c = fields.slice(); const t = idx + dir;
if (t < 0 || t >= c.length) return;
[c[idx], c[t]] = [c[t], c[idx]]; onChange({ ...value, fields: c });
};
const typeLabel = (t: FormFieldType) => ({ text: "Text", numeric: "Number", date: "Date", yes_no: "Yes/No", statement: "Statement", paragraph: "Heading", rating: "Rating", multiple_choice: "Multiple choice" }[t] || t);
return (
<div className="border rounded-lg p-3 bg-gray-50">
<div className="flex items-center justify-between mb-3">
<div className="text-sm font-semibold">{title}</div>
{gateLabel && (
<label className="text-xs flex items-center gap-1.5 cursor-pointer">
<input type="checkbox" checked={!!value.isRequired} onChange={e => onChange({ ...value, isRequired: e.target.checked })} />
{gateLabel}
</label>
)}
</div>
{fields.length === 0
? <p className="text-xs text-gray-500 italic mb-3">No fields yet.</p>
: (
<ul className="space-y-2 mb-3">
{fields.map((f, idx) => (
<li key={idx} className="bg-white border rounded p-2">
<div className="flex items-center gap-1 mb-1.5">
<span className="text-[10px] px-1.5 py-0.5 rounded bg-brand-50 text-brand-700 font-medium">{typeLabel(f.type)}</span>
<span className="text-xs text-gray-400">#{idx + 1}</span>
<div className="flex-1" />
<button type="button" className="text-gray-400 hover:text-gray-700 px-1" onClick={() => mov(idx, -1)} disabled={idx === 0}>↑</button>
<button type="button" className="text-gray-400 hover:text-gray-700 px-1" onClick={() => mov(idx, 1)} disabled={idx === fields.length - 1}>↓</button>
<button type="button" className="text-xs px-2 py-0.5 rounded bg-red-50 text-red-700 border border-red-200" onClick={() => rem(idx)}>Remove</button>
</div>
<div className="flex flex-wrap gap-2 mb-1.5">
<select className="border rounded px-2 py-1 text-xs" value={f.type} onChange={e => upd(idx, { type: e.target.value as FormFieldType })}>
<option value="text">Text</option><option value="numeric">Number</option><option value="date">Date</option>
<option value="yes_no">Yes/No</option><option value="rating">Rating (1–5 stars)</option><option value="multiple_choice">Multiple choice</option>
<option value="statement">Statement</option><option value="paragraph">Heading+para</option>
</select>
{f.type !== "statement" && f.type !== "paragraph" && (
<label className="text-xs flex items-center gap-1 cursor-pointer">
<input type="checkbox" checked={!!f.isRequired} onChange={e => upd(idx, { isRequired: e.target.checked })} /> Required
</label>
)}
</div>
<input className="border rounded px-2 py-1 text-sm w-full mb-1" placeholder={f.type === "paragraph" ? "Heading text" : "Label"} value={f.label} onChange={e => upd(idx, { label: e.target.value })} />
{f.type === "multiple_choice" && <ChoicesEditor options={f.options} onChange={opts => upd(idx, { options: opts })} />}
{f.type === "paragraph"
? <textarea className="border rounded px-2 py-1 text-xs w-full" rows={2} placeholder="Body text" value={f.helpText || ""} onChange={e => upd(idx, { helpText: e.target.value })} />
: f.type !== "statement"
? <input className="border rounded px-2 py-1 text-xs w-full" placeholder="Help text (optional)" value={f.helpText || ""} onChange={e => upd(idx, { helpText: e.target.value })} />
: null}
</li>
))}
</ul>
)}
<div className="flex gap-2 flex-wrap">
<button type="button" className="text-xs px-3 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700" onClick={() => add("text")}>+ Question</button>
<button type="button" className="text-xs px-3 py-1.5 rounded bg-gray-200 text-gray-700" onClick={() => add("rating")}>+ Rating</button>
<button type="button" className="text-xs px-3 py-1.5 rounded bg-gray-200 text-gray-700" onClick={() => add("multiple_choice")}>+ Multiple choice</button>
<button type="button" className="text-xs px-3 py-1.5 rounded bg-gray-200 text-gray-700" onClick={() => add("statement")}>+ Statement</button>
<button type="button" className="text-xs px-3 py-1.5 rounded bg-gray-200 text-gray-700" onClick={() => add("paragraph")}>+ Heading</button>
</div>
</div>
);
}
// ─── Items & Pricing substep editors ────────────────────────────────────────
/** Substep 0 — bare option rows */
function OptionsEditor({ options, onChange, required, pickMode }: { options: OptionDraft[]; onChange: (o: OptionDraft[]) => void; required?: boolean; pickMode?: boolean }) {
const upd = (i: number, patch: Partial<OptionDraft>) => { const c = options.slice(); c[i] = { ...c[i], ...patch }; onChange(c); };
const rem = (i: number) => { const c = options.slice(); c.splice(i, 1); onChange(c); };
const add = () => {
const hasMain = options.some(o => o.isMainTicket);
onChange([...options, { name: "", price: "", isMainTicket: !hasMain, stockLimit: "0", earlyBirdTiers: [], variants: [] }]);
};
return (
<div className="space-y-2">
{options.map((opt, i) => {
const priceMissing = required && opt.price.trim() === "";
return (
<div key={i} className="border rounded-lg p-3 bg-white space-y-2">
<div className="flex flex-wrap items-end gap-2">
<div className="flex-1 min-w-36">
<label className="block text-[10px] text-gray-500 mb-0.5">Option name</label>
<input className="border rounded px-2 py-1.5 text-sm w-full" placeholder="e.g. Ticket, Hoodie, Meal"
value={opt.name} onChange={e => upd(i, { name: e.target.value })} />
</div>
<div>
<label className="block text-[10px] text-gray-500 mb-0.5">Base price (R) {required && <span className="text-red-500">*</span>}</label>
<input type="number" step="1" min="0" required={required}
className={`border rounded px-2 py-1.5 text-sm w-28 ${priceMissing ? "border-red-300 bg-red-50" : ""}`}
value={opt.price} onChange={e => upd(i, { price: e.target.value })} />
</div>
<div>
<label className="block text-[10px] text-gray-500 mb-0.5">Stock (0=∞)</label>
<input type="number" step="1" min="0" className="border rounded px-2 py-1.5 text-sm w-24"
value={opt.stockLimit} onChange={e => upd(i, { stockLimit: e.target.value })} />
</div>
<div>
<label className="block text-[10px] text-gray-500 mb-0.5" title="Staff and above pay this automatically when it's lower than the price they'd otherwise pay">Staff price (R)</label>
<input type="number" step="1" min="0" className="border rounded px-2 py-1.5 text-sm w-24" placeholder="(none)"
value={opt.staffPrice ?? ""} onChange={e => upd(i, { staffPrice: e.target.value })} />
</div>
{pickMode && (
<div>
<label className="block text-[10px] text-gray-500 mb-0.5" title="Pick sessions: bought per session — the price and stock are per session">Sessions</label>
<select className="border rounded px-2 py-1.5 text-sm" value={opt.sessionMode || "all"} onChange={e => upd(i, { sessionMode: e.target.value as "all" | "pick" })}>
<option value="all">All sessions</option>
<option value="pick">Pick sessions (price per session)</option>
</select>
</div>
)}
<div className="flex items-center gap-3 pb-1">
<label className="text-xs flex items-center gap-1 cursor-pointer whitespace-nowrap">
<input type="checkbox" checked={opt.isMainTicket} onChange={e => upd(i, { isMainTicket: e.target.checked })} /> Main ticket
</label>
{options.length > 1 && (
<button type="button" className="text-xs px-2 py-1 rounded bg-red-50 text-red-700 border border-red-200 hover:bg-red-100 whitespace-nowrap" onClick={() => rem(i)}>Remove</button>
)}
</div>
</div>
{priceMissing && <p className="text-[10px] text-red-500">Price is required — enter 0 for a free option.</p>}
</div>
);
})}
<button type="button" className="text-xs px-3 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700" onClick={add}>+ Add option</button>
</div>
);
}
/** Substep 1 — variants per option */
function VariantsEditor({ options, onChange }: { options: OptionDraft[]; onChange: (o: OptionDraft[]) => void }) {
const updVariants = (optIdx: number, variants: Variant[]) => {
const c = options.slice(); c[optIdx] = { ...c[optIdx], variants }; onChange(c);
};
if (options.length === 0) return <p className="text-sm text-gray-500">Add options first.</p>;
return (
<div className="space-y-4">
{options.map((opt, optIdx) => {
const variants = opt.variants;
const addVariant = () => updVariants(optIdx, [...variants, { name: "", price: "", stockLimit: "0", earlyBirdTiers: [] }]);
const updVariant = (vi: number, patch: Partial<Variant>) => {
const c = variants.slice(); c[vi] = { ...c[vi], ...patch }; updVariants(optIdx, c);
};
const remVariant = (vi: number) => {
const c = variants.slice(); c.splice(vi, 1); updVariants(optIdx, c);
};
return (
<div key={optIdx} className="border rounded-lg overflow-hidden">
<div className="px-3 py-2 bg-gray-50 border-b text-sm font-medium text-gray-700">{opt.name || <span className="italic text-gray-400">Unnamed option</span>}</div>
<div className="p-3 space-y-2">
{variants.length === 0
? <p className="text-xs text-gray-400 italic">No variants — uses base price (R{opt.price || "0"}).</p>
: variants.map((v, vi) => (
<div key={vi} className="flex flex-wrap items-end gap-2 bg-white border rounded p-2">
<div className="flex-1 min-w-28">
<label className="block text-[10px] text-gray-500 mb-0.5">Variant name</label>
<input className="border rounded px-2 py-1 text-xs w-full" placeholder="e.g. Adult, Child, Large"
value={v.name} onChange={e => updVariant(vi, { name: e.target.value })} />
</div>
<div>
<label className="block text-[10px] text-gray-500 mb-0.5">Price (blank=base)</label>
<input type="number" step="1" min="0" className="border rounded px-2 py-1 text-xs w-24" placeholder="(optional)"
value={v.price} onChange={e => updVariant(vi, { price: e.target.value })} />
</div>
<div>
<label className="block text-[10px] text-gray-500 mb-0.5">Stock (0=∞)</label>
<input type="number" step="1" min="0" className="border rounded px-2 py-1 text-xs w-20"
value={v.stockLimit} onChange={e => updVariant(vi, { stockLimit: e.target.value })} />
</div>
<div>
<label className="block text-[10px] text-gray-500 mb-0.5">Staff price</label>
<input type="number" step="1" min="0" className="border rounded px-2 py-1 text-xs w-20" placeholder="(option)"
value={v.staffPrice ?? ""} onChange={e => updVariant(vi, { staffPrice: e.target.value })} />
</div>
<button type="button" className="text-xs px-2 py-1 rounded bg-red-50 text-red-700 border border-red-200 hover:bg-red-100 self-end" onClick={() => remVariant(vi)}>✕</button>
</div>
))}
<button type="button" className="text-xs px-3 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700" onClick={addVariant}>+ Add variant</button>
</div>
</div>
);
})}
</div>
);
}
/** Single tier row editor */
function TierRow({ tier, onChange, onRemove }: { tier: Tier; onChange: (t: Tier) => void; onRemove: () => void }) {
return (
<div className="flex flex-wrap items-end gap-2 bg-white border rounded p-2">
<div>
<div className="text-[10px] text-gray-500 mb-0.5">Deadline</div>
<input type="datetime-local" min={DT_MIN} max={DT_MAX} className="border rounded px-2 py-1 text-xs"
value={tier.deadline} onChange={e => onChange({ ...tier, deadline: e.target.value })} />
</div>
<div>
<div className="text-[10px] text-gray-500 mb-0.5">Price (R)</div>
<input type="number" step="1" min="0" className="border rounded px-2 py-1 text-xs w-24"
value={tier.price} onChange={e => onChange({ ...tier, price: e.target.value })} />
</div>
<div>
<div className="text-[10px] text-gray-500 mb-0.5">Stock (0=∞)</div>
<input type="number" step="1" min="0" className="border rounded px-2 py-1 text-xs w-20"
value={tier.stockLimit} onChange={e => onChange({ ...tier, stockLimit: e.target.value })} />
</div>
<button type="button" className="text-xs px-2 py-1 rounded bg-red-50 text-red-700 border border-red-200 self-end" onClick={onRemove}>✕</button>
</div>
);
}
/** Substep 2 — early birds per variant (or per option when no variants) */
function EarlyBirdsEditor({ options, onChange }: { options: OptionDraft[]; onChange: (o: OptionDraft[]) => void }) {
if (options.length === 0) return <p className="text-sm text-gray-500">Add options first.</p>;
return (
<div className="space-y-4">
{options.map((opt, optIdx) => {
const hasVariants = opt.variants.length > 0;
if (!hasVariants) {
// Option-level tiers
const updTiers = (tiers: Tier[]) => {
const c = options.slice(); c[optIdx] = { ...c[optIdx], earlyBirdTiers: tiers }; onChange(c);
};
const addTier = () => updTiers([...opt.earlyBirdTiers, { deadline: "", price: "", stockLimit: "0" }]);
return (
<div key={optIdx} className="border rounded-lg overflow-hidden">
<div className="px-3 py-2 bg-gray-50 border-b text-sm font-medium text-gray-700">
{opt.name || <span className="italic text-gray-400">Unnamed option</span>}
<span className="ml-2 text-[10px] text-gray-400">base R{opt.price || "0"}</span>
</div>
<div className="p-3 space-y-2">
{opt.earlyBirdTiers.length === 0 && <p className="text-xs text-gray-400 italic">No early-bird tiers.</p>}
{opt.earlyBirdTiers.map((t, ti) => (
<TierRow key={ti} tier={t}
onChange={updated => { const c = opt.earlyBirdTiers.slice(); c[ti] = updated; updTiers(c); }}
onRemove={() => { const c = opt.earlyBirdTiers.slice(); c.splice(ti, 1); updTiers(c); }} />
))}
<button type="button" className="text-xs px-3 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700" onClick={addTier}>+ Add tier</button>
</div>
</div>
);
}
// Per-variant tiers
return (
<div key={optIdx} className="border rounded-lg overflow-hidden">
<div className="px-3 py-2 bg-gray-50 border-b text-sm font-medium text-gray-700">
{opt.name || <span className="italic text-gray-400">Unnamed option</span>}
</div>
<div className="divide-y">
{opt.variants.map((v, vi) => {
const basePrice = v.price !== "" ? v.price : opt.price;
const updVTiers = (tiers: Tier[]) => {
const co = options.slice();
const cv = co[optIdx].variants.slice();
cv[vi] = { ...cv[vi], earlyBirdTiers: tiers };
co[optIdx] = { ...co[optIdx], variants: cv };
onChange(co);
};
const addTier = () => updVTiers([...v.earlyBirdTiers, { deadline: "", price: "", stockLimit: "0" }]);
return (
<div key={vi} className="p-3 space-y-2">
<div className="text-xs font-medium text-gray-600">
{v.name || <span className="italic text-gray-400">Unnamed variant</span>}
<span className="ml-2 text-gray-400">base R{basePrice || "0"}</span>
</div>
{v.earlyBirdTiers.length === 0 && <p className="text-[10px] text-gray-400 italic">No tiers for this variant.</p>}
{v.earlyBirdTiers.map((t, ti) => (
<TierRow key={ti} tier={t}
onChange={updated => { const c = v.earlyBirdTiers.slice(); c[ti] = updated; updVTiers(c); }}
onRemove={() => { const c = v.earlyBirdTiers.slice(); c.splice(ti, 1); updVTiers(c); }} />
))}
<button type="button" className="text-xs px-3 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700" onClick={addTier}>+ Add tier</button>
</div>
);
})}
</div>
</div>
);
})}
</div>
);
}
// ─── Sections editors ─────────────────────────────────────────────────────────
/** Create-mode: draft sections using option indices */
function SectionsDraftEditor({ sections, options, onChange }: {
sections: SectionDraft[];
options: OptionDraft[];
onChange: (s: SectionDraft[]) => void;
}) {
const [newName, setNewName] = useState("");
const [newIndices, setNewIndices] = useState<number[]>([]);
const create = () => {
if (!newName.trim()) return;
onChange([...sections, { name: newName.trim(), optionIndices: newIndices }]);
setNewName(""); setNewIndices([]);
};
const del = (i: number) => { const c = sections.slice(); c.splice(i, 1); onChange(c); };
return (
<div className="space-y-3">
{sections.length === 0 && <p className="text-xs text-gray-500">No sections yet.</p>}
{sections.map((sec, i) => (
<div key={i} className="border rounded p-3 bg-white flex items-start justify-between gap-3">
<div>
<div className="text-sm font-medium">{sec.name}</div>
<div className="text-xs text-gray-500 mt-0.5">
{sec.optionIndices.length === 0
? "All options"
: sec.optionIndices.map(idx => options[idx]?.name || `Option ${idx + 1}`).join(", ")}
</div>
</div>
<button type="button" className="text-xs px-2 py-1 rounded bg-red-50 text-red-700 border border-red-200 shrink-0" onClick={() => del(i)}>Delete</button>
</div>
))}
<div className="border rounded p-3 bg-gray-50">
<div className="text-xs font-medium mb-2">Create section</div>
<input className="border rounded px-2 py-1 text-sm w-full mb-2" placeholder="Section name"
value={newName} onChange={e => setNewName(e.target.value)} />
{options.length > 0 && (
<>
<div className="text-xs text-gray-600 mb-1">Options in this section:</div>
<div className="flex flex-wrap gap-2 mb-2">
{options.map((opt, idx) => (
<label key={idx} className="text-xs flex items-center gap-1 cursor-pointer">
<input type="checkbox" checked={newIndices.includes(idx)}
onChange={e => setNewIndices(e.target.checked ? [...newIndices, idx] : newIndices.filter(x => x !== idx))} />
{opt.name || `Option ${idx + 1}`}
</label>
))}
</div>
</>
)}
<button type="button" className="text-xs px-3 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700" onClick={create}>Create section</button>
</div>
</div>
);
}
/** Edit-mode: live sections manager (DB-backed) */
function SectionsManager({ eventId }: { eventId: string }) {
const { token } = useAuth();
const [sections, setSections] = useState<Section[]>([]);
const [eventOptions, setEventOptions] = useState<EventOption[]>([]);
const [loading, setLoading] = useState(false);
const [newName, setNewName] = useState("");
const [newOptionIds, setNewOptionIds] = useState<string[]>([]);
const load = useCallback(async () => {
setLoading(true);
try {
const [secList, evFull] = await Promise.all([
listSections<Section>(token),
fetchEvent<Event>(eventId)
]);
setSections((secList || []).filter(s => s.eventId === eventId));
setEventOptions(evFull?.eventOptions || []);
} catch {} finally { setLoading(false); }
}, [eventId, token]);
useEffect(() => { if (eventId) load(); }, [eventId, load]);
const create = async () => {
if (!newName.trim() || !token) return;
await createSection(token, { eventId, name: newName.trim(), allowedOptionIds: newOptionIds });
setNewName(""); setNewOptionIds([]); load();
};
const del = async (id: string) => {
if (!token) return;
await deleteSection(token, id);
load();
};
const update = async (id: string, name: string, optionIds: string[]) => {
if (!token) return;
await updateSection(token, id, { name, allowedOptionIds: optionIds });
load();
};
if (loading) return <div className="text-xs text-gray-500">Loading sections…</div>;
return (
<div className="space-y-3">
{sections.length === 0 && <p className="text-xs text-gray-500">No sections yet.</p>}
{sections.map(sec => (
<SectionRow key={sec.id} sec={sec} options={eventOptions} onDelete={() => del(sec.id)} onUpdate={update} />
))}
<div className="border rounded p-3 bg-gray-50">
<div className="text-xs font-medium mb-2">Create section</div>
<input className="border rounded px-2 py-1 text-sm w-full mb-2" placeholder="Section name" value={newName} onChange={e => setNewName(e.target.value)} />
<div className="text-xs text-gray-600 mb-1">Options in this section:</div>
<div className="flex flex-wrap gap-2 mb-2">
{eventOptions.map(opt => (
<label key={opt.id} className="text-xs flex items-center gap-1 cursor-pointer">
<input type="checkbox" checked={newOptionIds.includes(opt.id)}
onChange={e => setNewOptionIds(e.target.checked ? [...newOptionIds, opt.id] : newOptionIds.filter(id => id !== opt.id))} />
{opt.name}
</label>
))}
</div>
<button type="button" className="text-xs px-3 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700" onClick={create}>Create section</button>
</div>
</div>
);
}
function SectionRow({ sec, options, onDelete, onUpdate }: {
sec: Section;
options: EventOption[];
onDelete: () => void;
onUpdate: (id: string, name: string, optionIds: string[]) => void;
}) {
const [name, setName] = useState(sec.name || "");
const [optIds, setOptIds] = useState<string[]>((sec.allowedOptions || []).map((o) => o.eventOptionId));
return (
<div className="border rounded p-3 bg-white">
<input className="border rounded px-2 py-1 text-sm w-full mb-2" value={name} onChange={e => setName(e.target.value)} />
<div className="flex flex-wrap gap-2 mb-2">
{options.map((opt) => (
<label key={opt.id} className="text-xs flex items-center gap-1 cursor-pointer">
<input type="checkbox" checked={optIds.includes(opt.id)}
onChange={e => setOptIds(e.target.checked ? [...optIds, opt.id] : optIds.filter(id => id !== opt.id))} />
{opt.name}
</label>
))}
</div>
<div className="flex gap-2">
<button type="button" className="text-xs px-2 py-1 rounded bg-brand-600 text-white" onClick={() => onUpdate(sec.id, name, optIds)}>Save</button>
<button type="button" className="text-xs px-2 py-1 rounded bg-red-50 text-red-700 border border-red-200" onClick={onDelete}>Delete</button>
</div>
</div>
);
}
// ─── Attachments ─────────────────────────────────────────────────────────────
function AttachmentsManager({ eventId }: { eventId: string }) {
const { token } = useAuth();
const [items, setItems] = useState<EventAttachment[]>([]);
const [uploading, setUploading] = useState(false);
const ref = useRef<HTMLInputElement | null>(null);
const load = useCallback(async () => {
setItems(await listAttachments(eventId));
}, [eventId]);
useEffect(() => { load(); }, [load]);
const upload: React.ChangeEventHandler<HTMLInputElement> = async e => {
const file = e.target.files?.[0];
if (!file || !token) return;
setUploading(true);
try {
await uploadAttachment(token, eventId, file);
await load();
} finally { setUploading(false); if (ref.current) ref.current.value = ""; }
};
const del = async (id: string) => {
if (!token || !confirm("Delete this attachment?")) return;
await deleteAttachment(token, eventId, id);
await load();
};
return (
<div>
<div className="flex items-center justify-between mb-2">
<div className="text-sm font-medium">Attachments</div>
<div>
<input ref={ref} type="file" className="hidden" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv,.zip" onChange={upload} />
<button type="button" onClick={() => ref.current?.click()} disabled={uploading} className="text-xs px-2 py-1 rounded border bg-white hover:bg-gray-50">
{uploading ? "Uploading…" : "Upload file"}
</button>
</div>
</div>
{items.length === 0
? <p className="text-xs text-gray-500">No attachments.</p>
: (
<ul className="space-y-1">
{items.map(it => (
<li key={it.id} className="flex items-center justify-between text-xs">
<a href={it.url} target="_blank" rel="noreferrer" className="text-brand-600 hover:underline truncate max-w-xs">{it.originalName}</a>
<button type="button" className="text-red-600 hover:underline ml-2" onClick={() => del(it.id)}>Delete</button>
</li>
))}
</ul>
)}
</div>
);
}
// ─── Notification recipients ───────────────────────────────────────────────
type NotifyUser = { id: string; name: string; email: string };
/** Tracks an anchor element's viewport rect while `active`, updating on any scroll
* (capture-phase, so it catches scrolling inside the modal's clipped containers too)
* or resize. Used to position the search-results dropdown outside the modal's overflow clip. */
function useAnchorRect(anchorRef: React.RefObject<HTMLElement | null>, active: boolean) {
const [rect, setRect] = useState<{ top: number; left: number; width: number; bottom: number } | null>(null);
useLayoutEffect(() => {
if (!active) { setRect(null); return; }
const update = () => {
const el = anchorRef.current;
if (!el) return;
const r = el.getBoundingClientRect();
setRect({ top: r.top, left: r.left, width: r.width, bottom: r.bottom });
};
update();
window.addEventListener("scroll", update, true);
window.addEventListener("resize", update);
return () => {
window.removeEventListener("scroll", update, true);
window.removeEventListener("resize", update);
};
}, [anchorRef, active]);
return rect;
}
/** Presentational picker — pure controlled component, no API persistence of its own.
* Used directly for create-mode staging, and wrapped by NotifyRecipientsManager for edit mode. */
function NotifyRecipientsPicker({ selected, onChange, disabled }: { selected: NotifyUser[]; onChange: (next: NotifyUser[]) => void; disabled?: boolean }) {
const { token } = useAuth();
const [search, setSearch] = useState("");
const [results, setResults] = useState<NotifyUser[]>([]);
const [searching, setSearching] = useState(false);
const anchorRef = useRef<HTMLDivElement>(null);
const visibleResults = results.filter(u => !selected.some(s => s.id === u.id));
const dropdownOpen = visibleResults.length > 0;
const rect = useAnchorRect(anchorRef, dropdownOpen);
useEffect(() => {
if (!search.trim()) { setResults([]); return; }
let cancelled = false;
setSearching(true);
const t = setTimeout(async () => {
try {
const res = await (apiV2Data("get", "/users", { query: { search: search.trim(), limit: "10" }, authToken: token }) as Promise<Paginated<NotifyUser>>);
if (!cancelled) setResults(Array.isArray(res?.data) ? res.data : []);
} catch {
if (!cancelled) setResults([]);
} finally {
if (!cancelled) setSearching(false);
}
}, 300);
return () => { cancelled = true; clearTimeout(t); };
}, [search, token]);
const add = (u: NotifyUser) => {
if (selected.some(s => s.id === u.id)) return;
onChange([...selected, u]);
setSearch(""); setResults([]);
};
const remove = (id: string) => onChange(selected.filter(s => s.id !== id));
return (
<div className="space-y-3">
{selected.length === 0 ? (
<p className="text-xs text-gray-400 italic">No recipients selected — falling back to the event creator.</p>
) : (
<ul className="space-y-1">
{selected.map(u => (
<li key={u.id} className="flex items-center justify-between text-sm bg-white border rounded px-3 py-1.5">
<span>{u.name} <span className="text-xs text-gray-400">{u.email}</span></span>
<button type="button" className="text-red-600 hover:underline text-xs" onClick={() => remove(u.id)} disabled={disabled}>Remove</button>
</li>
))}
</ul>
)}
<div ref={anchorRef}>
<input
className="border rounded px-3 py-2 text-sm w-full"
placeholder="Search staff by name or email…"
value={search}
onChange={e => setSearch(e.target.value)}
disabled={disabled}
/>
{searching && <div className="text-xs text-gray-400 mt-1">Searching…</div>}
</div>
{dropdownOpen && rect && typeof document !== "undefined" && createPortal(
<ul
style={{
position: "fixed",
top: rect.bottom + 4,
left: rect.left,
width: rect.width,
maxHeight: Math.max(160, Math.min(360, window.innerHeight - rect.bottom - 16)),
zIndex: 9999,
}}
className="border rounded bg-white shadow-lg overflow-y-auto"
>
{visibleResults.map(u => (
<li key={u.id} className="px-3 py-1.5 text-sm hover:bg-brand-50 cursor-pointer" onClick={() => add(u)}>
{u.name} <span className="text-xs text-gray-400">{u.email}</span>
</li>
))}
</ul>,
document.body
)}
</div>
);
}
/** Edit-mode manager — persists each change via PUT. Uses `initialRecipients` (already
* loaded by the parent's GET /api/events/:id call) when available so opening this step
* is instant; only falls back to its own (lightweight) GET when that wasn't provided. */
function NotifyRecipientsManager({ eventId, creator, initialRecipients }: { eventId: string; creator?: NotifyUser | null; initialRecipients?: NotifyUser[] | null }) {
const { token } = useAuth();
const hasInitial = Array.isArray(initialRecipients);
const [selected, setSelected] = useState<NotifyUser[]>(initialRecipients || []);
const [loading, setLoading] = useState(!hasInitial);
const [saving, setSaving] = useState(false);
const [error, setError] = useDismissingState<string | null>(null);
useEffect(() => {
if (hasInitial) return; // already have the data — skip the network round trip entirely
let cancelled = false;
(async () => {
setLoading(true);
try {
const { data: res } = await apiV2("get", "/events/{id}/notify-recipients", { params: { id: eventId }, authToken: token });
if (!cancelled) setSelected(res);
} catch (e) {
if (!cancelled) setError(errorMessage(e) || "Failed to load notification recipients");
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [eventId]);
const persist = async (next: NotifyUser[]) => {
const prev = selected;
setSelected(next);
setSaving(true);
setError(null);
try {
await apiV2("put", "/events/{id}/notify-recipients", { params: { id: eventId }, authToken: token, body: { userIds: next.map(u => u.id) } });
} catch (e) {
setSelected(prev);
setError(errorMessage(e) || "Failed to save notification recipients");
} finally {
setSaving(false);
}
};
if (loading) return <div className="text-xs text-gray-500">Loading…</div>;
return (
<div className="space-y-3">
<p className="text-xs text-gray-500">
Choose who receives new registration, payment, and daily summary emails for this event.
Leave empty to send them to the event creator{creator ? <> (<strong>{creator.name}</strong>, {creator.email})</> : null} instead.
</p>
{error && <div className="p-2 border rounded bg-red-50 text-red-700 text-xs">{error}</div>}
<NotifyRecipientsPicker selected={selected} onChange={persist} disabled={saving} />
</div>
);
}
// ─── steps ───────────────────────────────────────────────────────────────────
const STEPS = ["Basic Details", "Items & Pricing", "Sections", "Form", "Visibility", "Notifications", "Attachments", "Feedback", "Attendance"] as const;
type StepIdx = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
const PRICING_SUBSTEPS = ["Options", "Variants", "Early Birds"] as const;
type PricingSubstep = 0 | 1 | 2;
interface EventDraft {
title: string; description: string; startDate: string; endDate: string;
registrationDeadline: string; goLiveAt: string; price: string; picture: string;
redirectUrl: string; isActive: boolean; isHidden: boolean; requiresAuth: boolean;
requiresRegistration: boolean; contactName: string; contactPhone: string; contactEmail: string;
location: string; allowNamedAttendees: boolean;
campusId: string; // "" = all campuses
seriesId: string; // "" = not in a series
requiresParentalConsent: boolean; consentText: string;
consentCollectMedical: boolean; consentCollectEmergency: boolean; consentCollectPhoto: boolean;
waitlistEnabled: boolean; waitlistOfferHours: string; waitlistPartialOffers: boolean;
allowTicketTransfer: boolean; collectGender: boolean;
allowSponsorships: boolean; sponsorshipGoalSpots: string; showSponsorshipProgress: boolean;
scheduleType: "single" | "sessions";
attendanceMode: "whole" | "pick";
}
const blankDraft = (location = ""): EventDraft => ({
title: "", description: "", startDate: "", endDate: "",
registrationDeadline: "", goLiveAt: "", price: "", picture: "",
redirectUrl: "", isActive: true, isHidden: false, requiresAuth: true,
requiresRegistration: true, contactName: "", contactPhone: "", contactEmail: "",
location, allowNamedAttendees: false,
campusId: "",
seriesId: "",
requiresParentalConsent: false, consentText: "",
consentCollectMedical: true, consentCollectEmergency: true, consentCollectPhoto: true,
waitlistEnabled: false, waitlistOfferHours: "24", waitlistPartialOffers: true,
allowTicketTransfer: true, collectGender: false,
allowSponsorships: false, sponsorshipGoalSpots: "", showSponsorshipProgress: true,
scheduleType: "single",
attendanceMode: "whole",
});
// "YYYY-MM-DDTHH:MM" (local) → ISO
const isoOf = (local: string) => new Date(local).toISOString();
const blankOptions = (): OptionDraft[] => [
{ name: "Ticket", price: "", isMainTicket: true, stockLimit: "0", earlyBirdTiers: [], variants: [] }
];
// ─── EventModal ───────────────────────────────────────────────────────────────
interface EventModalProps {
mode: "create" | "edit";
event?: Event | null;
// Create mode: start from a copy of this event (cloning).
source?: Event | null;
onClose: () => void;
onSuccess: () => void;
}
/** A source event's ticket options as drafts for a copy — no ids, and without the staff-only
* kids and volunteer tickets (kids check-in and rosters aren't copied). `sourceIds` lines up
* with `drafts`, to map the source's sections onto the copy. */
function cloneOptions(source: Event): { drafts: OptionDraft[]; sourceIds: string[] } {
const staffOnly = new Set([source.kidsOptionId, source.volunteerOptionId].filter(Boolean));
const kept = (source.eventOptions || []).filter(o => !staffOnly.has(o.id));
const tier = (t: { deadline: string; price: number; stockLimit?: number | null }): Tier => ({ deadline: toLocalDT(t.deadline), price: String(t.price ?? ""), stockLimit: String(t.stockLimit ?? "0") });
return {
sourceIds: kept.map(o => o.id),
drafts: kept.map(o => ({
name: o.name,
price: String(o.price ?? ""),
isMainTicket: !!o.isMainTicket,
stockLimit: String(o.stockLimit ?? "0"),
staffPrice: o.staffPrice !== null && o.staffPrice !== undefined ? String(o.staffPrice) : "",
sessionMode: o.sessionMode || "all",
earlyBirdTiers: (o.earlyBirdTiers || []).filter(t => !t.variantId).map(tier),
variants: (o.variants || []).map(v => ({
name: v.name,
price: v.price !== null && v.price !== undefined ? String(v.price) : "",
stockLimit: String(v.stockLimit ?? "0"),
staffPrice: v.staffPrice !== null && v.staffPrice !== undefined ? String(v.staffPrice) : "",
earlyBirdTiers: (o.earlyBirdTiers || []).filter(t => t.variantId === v.id).map(tier),
})),
})),
};
}
const withoutIds = (fields: FieldDef[]): FieldDef[] => fields.map(f => ({ ...f, id: undefined }));
function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalProps) {
const { token } = useAuth();
const { settings } = useSiteSettings();
const campusInfo = useMyCampuses();
// Cloning fills "New event" from the source; everything can still be changed before saving.
const cloning = mode === "create" && !!source;
const base = mode === "edit" ? ev : source;
// Campus-scoped: events for all campuses (and other campuses') are set up by admins and
// supervisors for every campus — the server refuses changes, so the editor says so up front.
const campusReadOnly = mode === "edit" && campusInfo.scoped && !campusInfo.campuses.some(c => c.id === ev?.campusId);
const [step, setStep] = useState<StepIdx>(0);
const [pricingSubstep, setPricingSubstep] = useState<PricingSubstep>(0);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
// ── event draft ──
// New events default their location to the organisation's address (settings.org_address);
// editing an existing event always reflects its own saved location instead. A copy keeps the
// source's, but not its short link (those are unique) or its go-live time.
const [draft, setDraft] = useState<EventDraft>(() => base ? {
title: base.title || "", description: base.description || "",
startDate: toLocalDT(base.startDate), endDate: toLocalDT(base.endDate),
registrationDeadline: toLocalDT(base.registrationDeadline), goLiveAt: cloning ? "" : toLocalDT(base.goLiveAt),
price: String(base.price ?? ""), picture: base.picture || "", redirectUrl: cloning ? "" : base.redirectUrl || "",
isActive: cloning || base.isActive !== false, isHidden: !!base.isHidden, requiresAuth: base.requiresAuth !== false,
requiresRegistration: base.requiresRegistration !== false,
allowNamedAttendees: !!base.allowNamedAttendees,
requiresParentalConsent: !!base.requiresParentalConsent, consentText: base.consentText || "",
consentCollectMedical: !!base.consentCollectMedical, consentCollectEmergency: !!base.consentCollectEmergency, consentCollectPhoto: !!base.consentCollectPhoto,
waitlistEnabled: !!base.waitlistEnabled, waitlistOfferHours: String(base.waitlistOfferHours ?? 24), waitlistPartialOffers: base.waitlistPartialOffers !== false,
allowTicketTransfer: base.allowTicketTransfer !== false,
collectGender: !!base.collectGender,
allowSponsorships: !!base.allowSponsorships, sponsorshipGoalSpots: base.sponsorshipGoalSpots ? String(base.sponsorshipGoalSpots) : "", showSponsorshipProgress: base.showSponsorshipProgress !== false,
contactName: base.contactName || "", contactPhone: base.contactPhone || "", contactEmail: base.contactEmail || "",
location: base.location || "",
campusId: base.campusId || "",
seriesId: base.seriesId || "",
scheduleType: base.scheduleType === "sessions" ? "sessions" : "single",
attendanceMode: base.attendanceMode === "pick" ? "pick" : "whole",
} : blankDraft(settings.org_address || ""));
// A campus-scoped person's new event starts at their (first) campus — they can't make
// events for all campuses — with that campus's default location if the field is still default.
useEffect(() => {
if (mode !== "create" || !campusInfo.scoped || !campusInfo.campuses.length) return;
setDraft(d => {
if (d.campusId) return d;
const first = campusInfo.campuses[0];
const isDefault = !d.location.trim() || d.location === (settings.org_address || "");
return { ...d, campusId: first.id, ...(first.defaultLocation && isDefault ? { location: first.defaultLocation } : {}) };
});
}, [mode, campusInfo.scoped, campusInfo.campuses, settings.org_address]);
// Series to choose from (Basic Details).
const [seriesList, setSeriesList] = useState<EventSeries[]>([]);
useEffect(() => {
if (!token) return;
(apiV2Data("get", "/series", { authToken: token }) as Promise<EventSeries[]>).then(l => setSeriesList(l)).catch(() => {});
}, [token]);
// ── multi-day schedule + attendance settings ──
// A copy leaves out cancelled sessions and saves the rest as new ones; each keeps the source
// session's id as its key so "late joining until" still points at the same session.
const [sessions, setSessions] = useState<KeyedSession[]>(() => cloning
? (base?.sessions || []).filter(s => !(s.cancelled || s.cancelledAt)).map(s => ({ ...toSessionDraft(s), id: undefined, hasCheckIns: false, key: s.id }))
: (base?.sessions || []).map(s => keyed(toSessionDraft(s))));
const [attendance, setAttendance] = useState<AttendanceDraft>(() => ({
lateJoinEnabled: !!base?.lateJoinEnabled,
lateJoinUntilKey: base?.lateJoinUntilSessionId || "",
latePricing: base?.latePricing || "full",
lateFixedPrice: base?.lateFixedPrice !== null && base?.lateFixedPrice !== undefined ? String(base.lateFixedPrice) : "",
checkInWindow: base?.checkInWindow || "whole_day",
remindersEnabled: !!base?.sessionReminders,
reminderOffsets: base?.sessionReminders?.offsets || [180],
reminderChannels: base?.sessionReminders?.channels || ["email", "whatsapp"],
certificatesEnabled: !!base?.certificatesEnabled,
certificate: { ...defaultCertificate(), ...(base?.certificateConfig || {}) },
}));
const updAttendance = (patch: Partial<AttendanceDraft>) => setAttendance(a => ({ ...a, ...patch }));
const multi = draft.scheduleType === "sessions";
const pickMode = multi && draft.attendanceMode === "pick";
// A multi-session event's dates come from its sessions.
const scheduleBounds = useMemo(() => {
const active = sortSessions(sessions).filter(s => !s.cancelled && s.startsAt && s.endsAt);
if (!active.length) return null;
const end = active.reduce((m, s) => (s.endsAt > m ? s.endsAt : m), active[0].endsAt);
return { start: active[0].startsAt, end };
}, [sessions]);
// Shown after saving when sessions moved or were cancelled, to offer telling registrants.
const [changedNotice, setChangedNotice] = useState<{ eventId: string; moved: number; cancelled: number } | null>(null);
// ── options (with per-variant tiers) ──
const [cloned] = useState(() => (cloning && source ? cloneOptions(source) : null));
const [options, setOptions] = useState<OptionDraft[]>(() => {
if (cloned) {
if (!cloned.drafts.length) return blankOptions();
return cloned.drafts.some(o => o.isMainTicket) ? cloned.drafts : cloned.drafts.map((o, i) => ({ ...o, isMainTicket: i === 0 }));
}
if (!ev?.eventOptions?.length) return blankOptions();
return ev.eventOptions.map((o) => {
const allTiers = o.earlyBirdTiers || [];
return {
id: o.id,
name: o.name,
price: String(o.price ?? ""),
isMainTicket: !!o.isMainTicket,
stockLimit: String(o.stockLimit ?? "0"),
staffPrice: o.staffPrice !== null && o.staffPrice !== undefined ? String(o.staffPrice) : "",
sessionMode: o.sessionMode || "all",
// Option-level tiers only (no variantId)
earlyBirdTiers: allTiers
.filter((t) => !t.variantId)
.map((t) => ({ id: t.id, deadline: toLocalDT(t.deadline), price: String(t.price ?? ""), stockLimit: String(t.stockLimit ?? "0") })),
variants: (o.variants || []).map((v) => ({
id: v.id, name: v.name,
price: v.price !== null && v.price !== undefined ? String(v.price) : "",
stockLimit: String(v.stockLimit ?? "0"),
staffPrice: v.staffPrice !== null && v.staffPrice !== undefined ? String(v.staffPrice) : "",
// Variant-level tiers — filter by variantId
earlyBirdTiers: allTiers
.filter((t) => t.variantId === v.id)
.map((t) => ({ id: t.id, deadline: toLocalDT(t.deadline), price: String(t.price ?? ""), stockLimit: String(t.stockLimit ?? "0") })),
})),
};
});
});
// ── sections (staged for create mode) ──
const [sectionDrafts, setSectionDrafts] = useState<SectionDraft[]>([]);
// A copy takes the source's sections onto the copied options. A section whose options were all
// left out (the kids or volunteer ticket) is dropped rather than widened to "all options".
useEffect(() => {
if (!cloned || !source?.id || !token) return;
listSections<Section>(token, source.id).then(list => {
const drafts: SectionDraft[] = [];
for (const sec of list || []) {
const ids = (sec.allowedOptions || []).map(o => o.eventOptionId);
const optionIndices = ids.map(id => cloned.sourceIds.indexOf(id)).filter(i => i >= 0);
if (ids.length && !optionIndices.length) continue;
drafts.push({ name: sec.name, optionIndices });
}
setSectionDrafts(drafts);
}).catch(() => {});
}, [cloned, source?.id, token]);
// ── attachments (staged for create mode; uploaded after event is created) ──
const [stagedFiles, setStagedFiles] = useState<File[]>([]);
// ── notify recipients (staged for create mode; saved after event is created) ──
const [notifyRecipientDrafts, setNotifyRecipientDrafts] = useState<NotifyUser[]>(() => (cloning ? source?.notifyRecipients || [] : []));
// ── form ──
const [formDef, setFormDef] = useState<EventFormDef>(() => (cloning && source?.form
? { isRequired: !!source.form.isRequired, fields: withoutIds(toFieldDefs(source.form.fields)) }
: { isRequired: false, fields: [] }));
const formLoadedRef = useRef(false);
useEffect(() => {
if (mode !== "edit" || !ev?.id || formLoadedRef.current) return;
fetchEvent<Event>(ev.id).then(full => {
const f = full?.form;
if (f) setFormDef({ isRequired: !!f.isRequired, fields: toFieldDefs(f.fields) });
}).catch(() => {}).finally(() => { formLoadedRef.current = true; });
}, [mode, ev?.id]);
// ── post-event feedback ──
const [fbEnabled, setFbEnabled] = useState(false);
const [fbDef, setFbDef] = useState<EventFormDef>({ isRequired: false, fields: [] });
const [fbSettings, setFbSettings] = useState({ sendAt: "", audience: "checked_in", anonymous: false, intro: "" });
const [fbMeta, setFbMeta] = useState<{ sentAt: string | null; invited: number; responses: number } | null>(null);
// How far a copy's dates have been moved so far, for the source's feedback date if it arrives
// after the move.
const shiftedRef = useRef(0);
const feedbackFrom = mode === "edit" ? ev?.id : cloning ? source?.id : undefined;
useEffect(() => {
if (!feedbackFrom || !token) return;
(apiV2Data("get", "/events/{id}/feedback", { params: { id: feedbackFrom }, authToken: token }) as Promise<FeedbackFormResponse | null>).then(f => {
if (!f) return;
setFbEnabled(true);
if (cloning) {
// The questions and settings only — not whether it was sent or who answered.
setFbDef({ isRequired: false, fields: withoutIds(toFieldDefs(f.fields)) });
setFbSettings({ sendAt: f.sendAt ? toLocalDT(new Date(new Date(f.sendAt).getTime() + shiftedRef.current)) : "", audience: f.audience || "checked_in", anonymous: !!f.anonymous, intro: f.intro || "" });
return;
}
setFbDef({ isRequired: false, fields: toFieldDefs(f.fields) });
setFbSettings({ sendAt: toLocalDT(f.sendAt), audience: f.audience || "checked_in", anonymous: !!f.anonymous, intro: f.intro || "" });
setFbMeta({ sentAt: f.sentAt, invited: f.invited, responses: f.responses });
}).catch(() => {});
}, [feedbackFrom, cloning, token]);
const enableFeedback = (on: boolean) => {
setFbEnabled(on);
if (on && fbDef.fields.length === 0) {
setFbDef({ isRequired: false, fields: [
{ type: "rating", label: "Overall, how would you rate the event?", isRequired: true, helpText: "" },
{ type: "rating", label: "How would you rate the organisation?", isRequired: false, helpText: "" },
{ type: "text", label: "What did you enjoy most?", isRequired: false, helpText: "" },
{ type: "text", label: "What could we do better?", isRequired: false, helpText: "" },
] });
}
const endForFeedback = multi ? scheduleBounds?.end : draft.endDate;
if (on && !fbSettings.sendAt && endForFeedback) {
const next = new Date(endForFeedback);
next.setDate(next.getDate() + 1);
next.setHours(9, 0, 0, 0);
setFbSettings(s => ({ ...s, sendAt: toLocalDT(next) }));
}
};
const saveFeedback = async (eventId: string) => {
if (fbEnabled) {
await apiV2Data("put", "/events/{id}/feedback", {
params: { id: eventId },
authToken: token,
body: {
sendAt: fbSettings.sendAt ? new Date(fbSettings.sendAt).toISOString() : null,
audience: fbSettings.audience, anonymous: fbSettings.anonymous, intro: fbSettings.intro || null,
fields: fbDef.fields.filter(f => f.label?.trim()).map((f, i) => ({ type: f.type, label: f.label, isRequired: !!f.isRequired, order: i, helpText: f.helpText || null, options: f.type === "multiple_choice" ? cleanChoices(f.options) : undefined })),
},
});
} else if (fbMeta) {
await apiV2Data("delete", "/events/{id}/feedback", { params: { id: eventId }, authToken: token });
}
};
const upd = (patch: Partial<EventDraft>) => setDraft(d => ({ ...d, ...patch }));
// ── copy: move every date by the same amount (sessions, deadline, early birds, feedback) ──
const copyStart = multi ? scheduleBounds?.start || "" : draft.startDate;
const moveAllDates = (newStart: string) => {
const ms = newStart && copyStart ? new Date(newStart).getTime() - new Date(copyStart).getTime() : NaN;
if (!ms || isNaN(ms)) return;
shiftedRef.current += ms;
const sh = (v: string) => (v ? toLocalDT(new Date(new Date(v).getTime() + ms)) : v);
const shTiers = (tiers: Tier[]) => tiers.map(t => ({ ...t, deadline: sh(t.deadline) }));
setDraft(d => ({ ...d, startDate: sh(d.startDate), endDate: sh(d.endDate), registrationDeadline: sh(d.registrationDeadline), goLiveAt: sh(d.goLiveAt) }));
setSessions(list => list.map(s => ({ ...s, startsAt: sh(s.startsAt), endsAt: sh(s.endsAt) })));
setOptions(list => list.map(o => ({ ...o, earlyBirdTiers: shTiers(o.earlyBirdTiers), variants: o.variants.map(v => ({ ...v, earlyBirdTiers: shTiers(v.earlyBirdTiers) })) })));
setFbSettings(s => ({ ...s, sendAt: sh(s.sendAt) }));
};
// ── auto-fill first option's price from the event base price (create mode only, until the
// user directly edits that option's price — then it becomes independent). A copy keeps its
// own option prices. ──
const [mainPriceTouched, setMainPriceTouched] = useState(cloning);
useEffect(() => {
if (mode !== "create" || mainPriceTouched) return;
setOptions(prev => {
if (prev.length === 0 || prev[0].price === draft.price) return prev;
const next = prev.slice();
next[0] = { ...next[0], price: draft.price };
return next;
});
}, [draft.price, mode, mainPriceTouched]);
const handleOptionsChange = (next: OptionDraft[]) => {
if (mode === "create" && next[0] && options[0] && next[0].price !== options[0].price) {
setMainPriceTouched(true);
}
setOptions(next);
};
const isPriceInvalid = (p: string) => p.trim() === "" || isNaN(parseFloat(p)) || parseFloat(p) < 0;
// Closed (cashed-up) events reject every mutating edit endpoint server-side — show that
// upfront and disable Save rather than letting staff fill out the whole form only to have
// it rejected on submit.
const isClosed = mode === "edit" && ev?.cashupStatus === "closed";
// ── save helpers ──
const saveOptions = async (eventId: string) => {
if (!draft.requiresRegistration) {
// Contact-only events have no ticket options to save — but a form (if any) still needs
// saving in edit mode; for create mode the form is already included in the POST body.
if (mode === "edit") {
await apiV2("patch", "/events/{id}", {
params: { id: eventId }, authToken: token,
body: { form: { isRequired: !!formDef.isRequired, fields: formDef.fields.filter(f => f.label?.trim()).map((f, i) => ({ type: f.type, label: f.label, isRequired: !!f.isRequired, order: i, helpText: f.helpText || null, options: f.type === "multiple_choice" ? cleanChoices(f.options) : undefined })) } }
});
}
return;
}
if (mode === "edit") {
for (const opt of options) {
// Build flat tier array: option-level + all variant tiers
const allTiers: TierPayload[] = [
...opt.earlyBirdTiers
.filter(t => t.deadline && t.price !== "")
.map((t, i) => ({ id: t.id, deadline: new Date(t.deadline).toISOString(), price: parseFloat(t.price), stockLimit: parseInt(t.stockLimit || "0"), order: i, variantId: null })),
];
const variantsPayload = opt.variants.map((v, vi) => ({
id: v.id, name: v.name,
price: v.price !== "" ? parseFloat(v.price) : null,
stockLimit: parseInt(v.stockLimit || "0"), order: vi,
staffPrice: v.staffPrice ? parseFloat(v.staffPrice) : null,
}));
if (opt.id) {
// Update option + variants first to get/confirm variant IDs
const updated = await updateTicketOption(token, opt.id, { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all", variants: variantsPayload });
// Build variant tiers with confirmed IDs from response
const serverVariants = updated?.variants || [];
for (let vi = 0; vi < opt.variants.length; vi++) {
const v = opt.variants[vi];
const serverVariant = serverVariants[vi] || serverVariants.find((sv) => sv.name === v.name);
if (!serverVariant) continue;
for (let ti = 0; ti < v.earlyBirdTiers.length; ti++) {
const t = v.earlyBirdTiers[ti];
if (!t.deadline || t.price === "") continue;
allTiers.push({ deadline: new Date(t.deadline).toISOString(), price: parseFloat(t.price), stockLimit: parseInt(t.stockLimit || "0"), order: ti, variantId: serverVariant.id });
}
}
if (allTiers.length > 0 || opt.earlyBirdTiers.length > 0 || opt.variants.some(v => v.earlyBirdTiers.length > 0)) {
await updateTicketOption(token, opt.id, { earlyBirdTiers: allTiers });
}
// Handle form save (edit only)
await apiV2("patch", "/events/{id}", {
params: { id: eventId }, authToken: token,
body: { form: { isRequired: !!formDef.isRequired, fields: formDef.fields.filter(f => f.label?.trim()).map((f, i) => ({ type: f.type, label: f.label, isRequired: !!f.isRequired, order: i, helpText: f.helpText || null, options: f.type === "multiple_choice" ? cleanChoices(f.options) : undefined })) } }
});
} else {
// New option added during edit
const created = await createTicketOption(token, eventId, { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" });
if (created?.id) {
const updated = await updateTicketOption(token, created.id, { variants: variantsPayload });
const serverVariants = updated?.variants || [];
for (let vi = 0; vi < opt.variants.length; vi++) {
const v = opt.variants[vi];
const sv = serverVariants[vi] || serverVariants.find((x) => x.name === v.name);
if (!sv) continue;
for (let ti = 0; ti < v.earlyBirdTiers.length; ti++) {
const t = v.earlyBirdTiers[ti];
if (!t.deadline || t.price === "") continue;
allTiers.push({ deadline: new Date(t.deadline).toISOString(), price: parseFloat(t.price), stockLimit: parseInt(t.stockLimit || "0"), order: ti, variantId: sv.id });
}
}
if (allTiers.length > 0) {
await updateTicketOption(token, created.id, { earlyBirdTiers: allTiers });
}
}
}
}
} else {
// Create mode — backend auto-creates a "Main Ticket" option; replace/create from draft
let createdEvent: Event | null = null;
try { createdEvent = await fetchEvent<Event>(eventId); } catch {}
const existingMain = (createdEvent?.eventOptions || []).find((o) => !!o.isMainTicket);
const uiMainIdx = options.findIndex(o => o.isMainTicket);
for (let i = 0; i < options.length; i++) {
const opt = options[i];
const variantsPayload = opt.variants.map((v, vi) => ({
name: v.name, price: v.price !== "" ? parseFloat(v.price) : null,
stockLimit: parseInt(v.stockLimit || "0"), order: vi,
staffPrice: v.staffPrice ? parseFloat(v.staffPrice) : null,
}));
let optId: string;
if (i === uiMainIdx && existingMain) {
// Update the auto-created main ticket
await updateTicketOption(token, existingMain.id, { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: true, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" });
optId = existingMain.id;
} else {
const created = await createTicketOption(token, eventId, { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" });
optId = created?.id;
}
if (!optId) continue;
// Save variants, then build tiers with resolved IDs
const allTiers: TierPayload[] = opt.earlyBirdTiers
.filter(t => t.deadline && t.price !== "")
.map((t, ti) => ({ deadline: new Date(t.deadline).toISOString(), price: parseFloat(t.price), stockLimit: parseInt(t.stockLimit || "0"), order: ti, variantId: null }));
if (variantsPayload.length > 0 || opt.variants.some(v => v.earlyBirdTiers.length > 0)) {
const updated = await updateTicketOption(token, optId, { variants: variantsPayload });
const serverVariants = updated?.variants || [];
for (let vi = 0; vi < opt.variants.length; vi++) {
const v = opt.variants[vi];
const sv = serverVariants[vi] || serverVariants.find((x) => x.name === v.name);
if (!sv) continue;
for (let ti = 0; ti < v.earlyBirdTiers.length; ti++) {
const t = v.earlyBirdTiers[ti];
if (!t.deadline || t.price === "") continue;
allTiers.push({ deadline: new Date(t.deadline).toISOString(), price: parseFloat(t.price), stockLimit: parseInt(t.stockLimit || "0"), order: ti, variantId: sv.id });
}
}
}
if (allTiers.length > 0) {
await updateTicketOption(token, optId, { earlyBirdTiers: allTiers });
}
}
}
};
const saveStagedSections = async (eventId: string, createdOptions: EventOption[]) => {
for (const sec of sectionDrafts) {
if (!sec.name.trim()) continue;
const optionIds = sec.optionIndices
.map(idx => createdOptions[idx]?.id)
.filter(Boolean);
try {
await createSection(token, { eventId, name: sec.name.trim(), allowedOptionIds: optionIds as string[] });
} catch {}
}
};
const handleSave = async () => {
if (!draft.title.trim()) { setError("Title is required"); setStep(0); return; }
if (multi) {
const problem = sessionsProblem(sessions);
if (problem) { setError(problem); setStep(0); return; }
if (attendance.lateJoinEnabled && !attendance.lateJoinUntilKey) { setError("Choose until which session late joining is allowed"); setStep(8); return; }
if (attendance.lateJoinEnabled && attendance.latePricing === "fixed" && attendance.lateFixedPrice.trim() === "") { setError("Enter the fixed late price"); setStep(8); return; }
} else if (!draft.startDate || !draft.endDate) { setError("Start and end dates are required"); setStep(0); return; }
if (mode === "create" && draft.requiresRegistration) {
if (isPriceInvalid(draft.price)) { setError("Base price is required (enter 0 for a free event)"); setStep(0); return; }
if (options.some(o => isPriceInvalid(o.price))) { setError("Every option needs a price (enter 0 for a free option)"); setStep(1); setPricingSubstep(0); return; }
}
setSaving(true); setError(null);
try {
const sortedSessions = sortSessions(sessions);
const body: Record<string, unknown> = {
title: draft.title.trim(), description: draft.description || undefined,
startDate: multi && scheduleBounds ? isoOf(scheduleBounds.start) : new Date(draft.startDate).toISOString(),
endDate: multi && scheduleBounds ? isoOf(scheduleBounds.end) : new Date(draft.endDate).toISOString(),
scheduleType: draft.scheduleType,
...(multi ? {
attendanceMode: draft.attendanceMode,
sessions: sortedSessions.map(s => ({ id: s.id, label: s.label.trim() || null, startsAt: isoOf(s.startsAt), endsAt: isoOf(s.endsAt), location: s.location.trim() || null, cancelled: s.cancelled, capacity: pickMode && s.capacity.trim() ? parseInt(s.capacity, 10) : null })),
lateJoinEnabled: attendance.lateJoinEnabled,
lateJoinUntilSessionIndex: attendance.lateJoinEnabled ? sortedSessions.findIndex(s => s.key === attendance.lateJoinUntilKey) : -1,
latePricing: attendance.latePricing,
lateFixedPrice: attendance.latePricing === "fixed" ? attendance.lateFixedPrice : null,
checkInWindow: attendance.checkInWindow,
sessionReminders: attendance.remindersEnabled ? { offsets: attendance.reminderOffsets, channels: attendance.reminderChannels } : null,
} : {}),
certificatesEnabled: attendance.certificatesEnabled,
certificateConfig: attendance.certificate,
registrationDeadline: draft.registrationDeadline ? new Date(draft.registrationDeadline).toISOString() : undefined,
goLiveAt: draft.goLiveAt ? new Date(draft.goLiveAt).toISOString() : undefined,
price: draft.requiresRegistration ? (draft.price ? parseFloat(draft.price) : 0) : 0,
picture: draft.picture || undefined, isHidden: draft.isHidden, requiresAuth: draft.requiresAuth,
redirectUrl: draft.redirectUrl?.trim().replace(/\s+/g, "-") || undefined,
requiresRegistration: draft.requiresRegistration,
allowNamedAttendees: draft.allowNamedAttendees || draft.requiresParentalConsent,
requiresParentalConsent: draft.requiresParentalConsent,
consentText: draft.consentText,
consentCollectMedical: draft.consentCollectMedical,
consentCollectEmergency: draft.consentCollectEmergency,
consentCollectPhoto: draft.consentCollectPhoto,
waitlistEnabled: draft.waitlistEnabled,
allowTicketTransfer: draft.allowTicketTransfer,
collectGender: draft.collectGender,
allowSponsorships: draft.allowSponsorships,
sponsorshipGoalSpots: draft.allowSponsorships && draft.sponsorshipGoalSpots ? parseInt(draft.sponsorshipGoalSpots, 10) || null : null,
showSponsorshipProgress: draft.showSponsorshipProgress,
waitlistOfferHours: parseInt(draft.waitlistOfferHours, 10) || 24,
waitlistPartialOffers: draft.waitlistPartialOffers,
contactName: draft.contactName || undefined,
contactPhone: draft.contactPhone || undefined,
contactEmail: draft.contactEmail || undefined,
location: draft.location.trim(),
// Only sent while campuses are on; the server ignores it otherwise.
...(campusInfo.enabled ? { campusId: draft.campusId || null } : {}),
seriesId: draft.seriesId || null,
};
let notice: { eventId: string; moved: number; cancelled: number } | null = null;
if (mode === "edit") {
body.isActive = draft.isActive;
if (!ev) throw new Error("No event loaded to save");
const { data: saved } = await apiV2("patch", "/events/{id}", { params: { id: ev.id }, authToken: token, body });
await saveOptions(ev.id);
// Form is saved inside saveOptions for edit mode; avoid double call
await saveFeedback(ev.id);
const ch = saved.sessionChanges;
if (ch && ((ch.moved ?? 0) > 0 || (ch.cancelled ?? 0) > 0)) notice = { eventId: ev.id, moved: ch.moved ?? 0, cancelled: ch.cancelled ?? 0 };
} else {
if (formDef.isRequired || formDef.fields.length > 0) {
body.form = { isRequired: !!formDef.isRequired, fields: formDef.fields.filter(f => f.label?.trim()).map((f, i) => ({ type: f.type, label: f.label, isRequired: !!f.isRequired, order: i, helpText: f.helpText || null, options: f.type === "multiple_choice" ? cleanChoices(f.options) : undefined })) };
}
if (cloning) body.clonedFromId = source!.id;
const { data: created } = await apiV2("post", "/events", { authToken: token, body: body as typeof body & { title: string; startDate: string; endDate: string } });
if (created?.id) {
await saveOptions(created.id);
await saveFeedback(created.id);
// Groups (and planned costs, for admins) aren't in this form; the server copies them.
if (cloning) {
await apiV2("post", "/events/{id}/copy-from", { params: { id: created.id }, authToken: token, body: { fromEventId: source!.id } });
}
// Fetch event to get final option IDs for sections
const fullEvent = await fetchEvent<Event>(created.id).catch(() => null);
const createdOptions = fullEvent?.eventOptions || [];
if (sectionDrafts.length > 0) await saveStagedSections(created.id, createdOptions);
// Upload staged attachments
for (const file of stagedFiles) {
await uploadAttachment(token, created.id, file);
}
// Save staged notify recipients
if (notifyRecipientDrafts.length > 0) {
await apiV2("put", "/events/{id}/notify-recipients", { params: { id: created.id }, authToken: token, body: { userIds: notifyRecipientDrafts.map(u => u.id) } }).catch(() => {});
}
}
}
onSuccess();
if (notice) setChangedNotice(notice);
else onClose();
} catch (e) {
setError(errorMessage(e) || "Failed to save event");
} finally {
setSaving(false);
}
};
// ── footer navigation ──
const handleBack = () => {
setError(null);
if (step === 1 && pricingSubstep > 0) {
setPricingSubstep((pricingSubstep - 1) as PricingSubstep);
} else {
setStep((step - 1) as StepIdx);
if (step - 1 === 1) setPricingSubstep(2); // entering from right → land on last substep
}
};
const handleNext = () => {
setError(null);
if (step === 1 && pricingSubstep < 2) {
setPricingSubstep((pricingSubstep + 1) as PricingSubstep);
} else {
setStep((step + 1) as StepIdx);
if (step + 1 === 1) setPricingSubstep(0); // entering from left → land on first substep
}
};
const isFirstStep = step === 0;
const isLastStep = step === STEPS.length - 1;
const isOnLastSubstep = step !== 1 || pricingSubstep === 2;
// Basic Details step requires title, start/end dates, and a base price before moving on
// (mirrors handleSave's own checks). Base price is only compulsory when creating a new event.
const basicDetailsIncomplete = step === 0 && (!draft.title.trim() || (multi ? !!sessionsProblem(sessions) : (!draft.startDate || !draft.endDate)) || (mode === "create" && draft.requiresRegistration && isPriceInvalid(draft.price)));
// Items & Pricing: every option needs a valid price before leaving the step (checked across
// all pricing substeps so switching to Variants/Early Birds can't be used to skip the gate).
// Not applicable to contact-only events, which have no ticket options at all.
const optionsIncomplete = mode === "create" && draft.requiresRegistration && step === 1 && options.some(o => isPriceInvalid(o.price));
const nextDisabled = basicDetailsIncomplete || optionsIncomplete;
// ── render ──
return (
<div className="fixed inset-0 z-50 flex items-start justify-center overflow-auto py-6 px-4">
<div className="absolute inset-0 bg-black/40" onClick={onClose} />
<div className="relative bg-white rounded-xl shadow-2xl w-full max-w-2xl">
{/* Header */}
<div className="flex items-center justify-between px-5 pt-5 pb-3 border-b">
<h2 className="text-lg font-semibold">{cloning ? "Copy Event" : mode === "create" ? "New Event" : "Edit Event"}</h2>
<button type="button" className="text-gray-400 hover:text-gray-700 text-xl leading-none" onClick={onClose}>×</button>
</div>
{/* Step bar */}
<div className="flex items-center gap-1 px-5 py-3 border-b overflow-x-auto">
{STEPS.map((s, i) => {
const clickable = mode === "edit" || cloning;
return (
<button key={i} type="button"
onClick={clickable ? () => { setStep(i as StepIdx); if (i === 1) setPricingSubstep(0); } : undefined}
className={`px-3 py-1.5 text-xs rounded border whitespace-nowrap transition-colors ${
step === i ? "bg-brand-600 text-white border-brand-600"
: clickable ? "bg-white text-gray-700 border-gray-200 hover:bg-gray-50 cursor-pointer"
: "bg-white text-gray-400 border-gray-100 cursor-default"
}`}
>{s}</button>
);
})}
</div>
{/* Pricing substep bar */}
{step === 1 && (
<div className="flex items-center gap-1 px-5 py-2 border-b bg-gray-50 overflow-x-auto">
{PRICING_SUBSTEPS.map((s, i) => (
<button key={i} type="button"
onClick={() => setPricingSubstep(i as PricingSubstep)}
className={`px-3 py-1 text-xs rounded border whitespace-nowrap transition-colors ${
pricingSubstep === i ? "bg-brand-100 text-brand-700 border-brand-300 font-medium" : "bg-white text-gray-600 border-gray-200 hover:bg-gray-50"
}`}
>{s}</button>
))}
</div>
)}
<div className="p-5 space-y-4 max-h-[65vh] overflow-y-auto">
{isClosed && (
<div className="p-3 border rounded bg-rose-50 text-rose-800 text-sm">
This event is closed — it can&apos;t be edited until it&apos;s reopened from the cashup page (admin only).
</div>
)}
{campusReadOnly && (
<div className="p-3 border rounded bg-amber-50 border-amber-200 text-amber-900 text-sm">
{ev?.campusId ? "This event belongs to another campus" : "This is an event for all campuses"} — only admins and supervisors for every campus can change it. You can still work with its registrations, payments and tickets.
</div>
)}
{error && <div className="p-3 border rounded bg-red-50 text-red-700 text-sm">{error}</div>}
{changedNotice && (
<div className="p-3 border rounded bg-amber-50 border-amber-200 text-amber-900 text-sm space-y-2">
<p>
Saved. You {[changedNotice.moved ? `moved ${changedNotice.moved} session${changedNotice.moved === 1 ? "" : "s"}` : "", changedNotice.cancelled ? `cancelled ${changedNotice.cancelled}` : ""].filter(Boolean).join(" and ")}.
Tickets and calendar files show the new schedule, but people who registered aren&apos;t told automatically.
</p>
<div className="flex gap-2">
<a href={`/dashboard/supervisor/email-attendees?eventId=${changedNotice.eventId}`} className="px-3 py-1.5 text-xs rounded bg-brand-600 text-white hover:bg-brand-700">Message attendees</a>
<button type="button" onClick={onClose} className="px-3 py-1.5 text-xs rounded border bg-white hover:bg-gray-50">Done</button>
</div>
</div>
)}
{/* ── Step 0: Basic Details ── */}
{step === 0 && (
<div className="space-y-3">
{cloning && (
<div className="p-3 border rounded bg-brand-50 border-brand-200 text-sm space-y-2" data-testid="copy-panel">
<p className="text-gray-700">
A copy of <span className="font-medium">{source?.title}</span> — check each step before saving. Registrations, coupons,
attachments, kids check-in and volunteer roles aren&apos;t copied.
</p>
<DTInput label="New start" value={copyStart} onChange={moveAllDates}
hint={`Moves every date with it: the end${multi ? ", the sessions" : ""}, registration deadline, early-bird deadlines and feedback date.`} />
{copyStart && new Date(copyStart) < new Date() && <p className="text-xs text-amber-700">This copy still starts in the past.</p>}
</div>
)}
<div>
<label className="block text-xs text-gray-600 mb-1">Title <span className="text-red-500">*</span></label>
<input className="w-full border rounded px-3 py-2 text-sm" value={draft.title} onChange={e => upd({ title: e.target.value })} placeholder="Event title" />
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">Description</label>
<textarea className="w-full border rounded px-3 py-2 text-sm" rows={3} value={draft.description} onChange={e => upd({ description: e.target.value })} />
</div>
<div>
<div className="block text-xs text-gray-600 mb-1">When <span className="text-red-500">*</span></div>
<div className="inline-flex rounded-lg border p-0.5 bg-gray-50">
{([["single", "One date"], ["sessions", "Multiple sessions"]] as const).map(([v, label]) => (
<button key={v} type="button" onClick={() => upd({ scheduleType: v })}
className={`px-3 py-1.5 text-xs rounded-md ${draft.scheduleType === v ? "bg-white shadow-sm text-brand-700 font-medium" : "text-gray-600 hover:text-gray-900"}`}>{label}</button>
))}
</div>
{multi && <p className="text-[10px] text-gray-400 mt-1">One registration and one ticket for every session, e.g. every Wednesday for 5 weeks. Check-in is per session.</p>}
</div>
{multi ? (
<>
<SessionsEditor sessions={sessions} onChange={setSessions} defaultLocation={draft.location} showCapacity={pickMode} />
<div>
<div className="block text-xs text-gray-600 mb-1">How people book</div>
<div className="space-y-1">
<label className="flex items-start gap-2 text-sm"><input type="radio" className="mt-1" name="attendance-mode" checked={draft.attendanceMode === "whole"} onChange={() => upd({ attendanceMode: "whole" })} /><span><span className="font-medium">The whole course</span><span className="block text-xs text-gray-500">One ticket for every session.</span></span></label>
<label className="flex items-start gap-2 text-sm"><input type="radio" className="mt-1" name="attendance-mode" disabled={draft.requiresParentalConsent} checked={draft.attendanceMode === "pick"} onChange={() => upd({ attendanceMode: "pick" })} /><span><span className="font-medium">Pick sessions</span><span className="block text-xs text-gray-500">People choose which sessions to come to (e.g. day passes or a drop-in class). Set which tickets are per session in Items &amp; Pricing, and an optional capacity per session above.{draft.requiresParentalConsent ? " Not available on youth events." : ""}</span></span></label>
</div>
</div>
</>
) : (
<div className="grid sm:grid-cols-2 gap-3">
<DTInput label="Start" required value={draft.startDate} onChange={v => upd({ startDate: v })} />
<DTInput label="End" required value={draft.endDate} onChange={v => upd({ endDate: v })} />
</div>
)}
<div className="grid sm:grid-cols-2 gap-3">
<DTInput label="Registration Deadline (optional)" value={draft.registrationDeadline} onChange={v => upd({ registrationDeadline: v })} hint={multi ? "Registration closes when the first session starts unless late joining is on (Attendance step)" : undefined} />
<DTInput label="Go Live At (optional)" value={draft.goLiveAt} onChange={v => upd({ goLiveAt: v })} hint="Leave blank to show immediately" />
</div>
{campusInfo.enabled && (
<div>
<label className="block text-xs text-gray-600 mb-1" htmlFor="event-campus">Campus</label>
<select
id="event-campus"
className="w-full border rounded px-3 py-2 text-sm bg-white"
value={draft.campusId}
onChange={e => {
const next = campusInfo.campuses.find(c => c.id === e.target.value);
const prev = campusInfo.campuses.find(c => c.id === draft.campusId);
// Swap in the campus's default location while the field still holds a default.
const isDefault = !draft.location.trim() || draft.location === (settings.org_address || "") || draft.location === (prev?.defaultLocation || "");
upd({ campusId: e.target.value, ...(next?.defaultLocation && isDefault ? { location: next.defaultLocation } : {}) });
}}
>
{campusInfo.scoped ? <option value="" disabled>Choose your campus…</option> : <option value="">All campuses</option>}
{campusInfo.campuses.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
{/* An archived campus stays on events that already have it. */}
{base?.campus && !campusInfo.campuses.some(c => c.id === base.campus!.id) && <option value={base.campus.id}>{base.campus.name} (archived)</option>}
</select>
<p className="text-[10px] text-gray-400 mt-0.5">&quot;All campuses&quot; events show at every campus — for church-wide conferences and camps.</p>
</div>
)}
<div>
<label className="block text-xs text-gray-600 mb-1" htmlFor="event-series">Series</label>
<select id="event-series" className="w-full border rounded px-3 py-2 text-sm bg-white" value={draft.seriesId} onChange={e => upd({ seriesId: e.target.value })}>
<option value="">Not in a series</option>
{seriesList.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
<p className="text-[10px] text-gray-400 mt-0.5">Groups separate events, like every year&apos;s camp, on one page with &quot;Next in this series&quot;. <a href="/dashboard/supervisor/series" target="_blank" className="underline">Manage series</a></p>
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">Location</label>
<input className="w-full border rounded px-3 py-2 text-sm" value={draft.location} onChange={e => upd({ location: e.target.value })} placeholder="e.g. 123 Church St, City" />
<p className="text-[10px] text-gray-400 mt-0.5">Defaults to your organisation&apos;s address — shown to attendees with a map link.</p>
</div>
<div className="flex items-start gap-2 p-3 border rounded bg-gray-50">
<input
type="checkbox"
id="contact-only-toggle"
className="mt-0.5"
checked={!draft.requiresRegistration}
onChange={e => upd({ requiresRegistration: !e.target.checked, price: e.target.checked ? "0" : draft.price })}
/>
<label htmlFor="contact-only-toggle" className="text-xs text-gray-700">
<span className="font-medium">This is a contact-only event</span> (e.g. baptism) — no online registration or payment. Shows a &quot;Contact us&quot; button on the public site instead of &quot;Register&quot;.
</label>
</div>
{draft.requiresRegistration ? (
<div>
<label className="block text-xs text-gray-600 mb-1">Base Price (R) {mode === "create" && <span className="text-red-500">*</span>}</label>
<input type="number" step="1" min="0" required={mode === "create"} className="w-full border rounded px-3 py-2 text-sm" value={draft.price} onChange={e => upd({ price: e.target.value })} placeholder="0" />
{mode === "create" && <p className="text-[10px] text-gray-400 mt-0.5">Auto-fills the first ticket option below — enter 0 for a free event.</p>}
</div>
) : (
<div className="space-y-3 p-3 border rounded">
<div>
<label className="block text-xs text-gray-600 mb-1">Contact Name</label>
<input className="w-full border rounded px-3 py-2 text-sm" value={draft.contactName} onChange={e => upd({ contactName: e.target.value })} placeholder="e.g. Pastor John" />
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">Contact Phone</label>
<input className="w-full border rounded px-3 py-2 text-sm" value={draft.contactPhone} onChange={e => upd({ contactPhone: e.target.value })} placeholder="e.g. 082 123 4567" />
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">Contact Email</label>
<input type="email" className="w-full border rounded px-3 py-2 text-sm" value={draft.contactEmail} onChange={e => upd({ contactEmail: e.target.value })} placeholder="e.g. info@hopefamilychurch.org" />
</div>
</div>
)}
<div>
<label className="block text-xs text-gray-600 mb-1">Picture</label>
<ApiImage src={draft.picture} className="h-20 w-20 object-cover rounded border mb-2" />
<div className="flex items-center gap-2">
<input className="flex-1 border rounded px-3 py-2 text-sm" placeholder="/uploads/... or https://" value={draft.picture} onChange={e => upd({ picture: e.target.value })} />
<UploadImageButton onUploaded={url => upd({ picture: url })} label="Upload" />
</div>
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">URL Alias (optional)</label>
<input className="w-full border rounded px-3 py-2 text-sm" placeholder="e.g. camp-2025, movie-night" value={draft.redirectUrl} onChange={e => upd({ redirectUrl: e.target.value })} />
</div>
</div>
)}
{/* ── Step 1: Items & Pricing (3 substeps) ── */}
{step === 1 && pricingSubstep === 0 && (
<div>
<p className="text-xs text-gray-500 mb-3">Define your ticket types or purchasable items. Variants and early-bird pricing are configured in the next two steps.</p>
<OptionsEditor options={options} onChange={handleOptionsChange} required={mode === "create"} pickMode={pickMode} />
</div>
)}
{step === 1 && pricingSubstep === 1 && (
<div>
<p className="text-xs text-gray-500 mb-3">Add variants per option (e.g. Adult / Child, or t-shirt sizes). Leave blank if an option has only one price.</p>
<VariantsEditor options={options} onChange={setOptions} />
</div>
)}
{step === 1 && pricingSubstep === 2 && (
<div>
<p className="text-xs text-gray-500 mb-3">Set early-bird prices per variant (if variants exist) or per option. The cheapest applicable tier is used at registration time.</p>
<EarlyBirdsEditor options={options} onChange={setOptions} />
</div>
)}
{/* ── Step 8: Attendance (late joining, check-in, reminders, certificates) ── */}
{step === 8 && (
<AttendanceSettings
value={attendance}
onChange={updAttendance}
multi={multi}
sessions={sessions}
mainPrice={parseFloat(options.find(o => o.isMainTicket)?.price || draft.price || "0") || 0}
uploadButton={(onUploaded) => <UploadImageButton onUploaded={onUploaded} label="Upload" />}
onPreview={async () => {
if (!token) return;
openBlob(await fetchApiFile(API_BASE, token, "/api/v2/certificates/preview", { method: "POST", body: { title: draft.title || "Your event", config: attendance.certificate } }));
}}
/>
)}
{/* ── Step 2: Sections ── */}
{step === 2 && (
<div>
<p className="text-xs text-gray-500 mb-3">Group ticket options into named sections shown on the registration page (e.g. &quot;Tickets&quot;, &quot;Add-ons&quot;, &quot;Accommodation&quot;).</p>
{mode === "edit" && ev?.id
? <SectionsManager eventId={ev.id} />
: <SectionsDraftEditor sections={sectionDrafts} options={options} onChange={setSectionDrafts} />
}
</div>
)}
{/* ── Step 3: Form ── */}
{step === 3 && (
<div>
<p className="text-xs text-gray-500 mb-3">Collect extra information from registrants (e.g. dietary requirements, t-shirt size, emergency contact).</p>
<FormBuilder value={formDef} onChange={setFormDef} />
</div>
)}
{step === 7 && (
<div className="space-y-3">
<p className="text-xs text-gray-500">Ask people what they thought, automatically after the event. Responses appear in Reports → Feedback summary.</p>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={fbEnabled} onChange={e => enableFeedback(e.target.checked)} />
<span><strong>Send a feedback form after the event</strong></span>
</label>
{fbEnabled && (
<>
{fbMeta?.sentAt && (
<div className="text-xs rounded bg-green-50 text-green-800 p-2">Sent {new Date(fbMeta.sentAt).toLocaleString()} to {fbMeta.invited} {fbMeta.invited === 1 ? "person" : "people"} · {fbMeta.responses} response(s).{fbMeta.responses > 0 ? " The questions can't be changed now that people have answered." : ""}</div>
)}
<div className="grid sm:grid-cols-2 gap-3">
<div>
<label className="block text-xs text-gray-600 mb-1">Send at</label>
<input type="datetime-local" className="border rounded px-2 py-1.5 text-sm w-full" value={fbSettings.sendAt} disabled={!!fbMeta?.sentAt} onChange={e => setFbSettings(s => ({ ...s, sendAt: e.target.value }))} />
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">Send to</label>
<select className="border rounded px-2 py-1.5 text-sm w-full" value={fbSettings.audience} onChange={e => setFbSettings(s => ({ ...s, audience: e.target.value }))}>
<option value="checked_in">Everyone who checked in</option>
<option value="all">Everyone registered</option>
</select>
</div>
</div>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={fbSettings.anonymous} onChange={e => setFbSettings(s => ({ ...s, anonymous: e.target.checked }))} />
<span>Anonymous — answers aren&apos;t linked to people&apos;s names</span>
</label>
<div>
<label className="block text-xs text-gray-600 mb-1">Intro (optional)</label>
<textarea className="border rounded px-2 py-1.5 text-sm w-full" rows={2} value={fbSettings.intro} onChange={e => setFbSettings(s => ({ ...s, intro: e.target.value }))} placeholder="Thanks for coming! Tell us how it went." />
</div>
<p className="text-xs text-gray-500">Anyone who hasn&apos;t answered gets one reminder 3 days later.</p>
<FormBuilder value={fbDef} onChange={setFbDef} title="Feedback questions" gateLabel={null} />
</>
)}
</div>
)}
{/* ── Step 4: Visibility ── */}
{step === 4 && (
<div className="space-y-3">
<div className="border rounded-lg p-4 bg-gray-50 space-y-3">
<div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Visibility & Access</div>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.isHidden} onChange={e => upd({ isHidden: e.target.checked })} />
<span><strong>Hidden</strong> — not shown in the public event listing; still accessible via direct link</span>
</label>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={!draft.requiresAuth} onChange={e => upd({ requiresAuth: !e.target.checked })} />
<span><strong>Allow guest registration</strong> — attendees can register without creating an account</span>
</label>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.allowNamedAttendees} onChange={e => upd({ allowNamedAttendees: e.target.checked })} />
<span><strong>Named attendees (group tickets)</strong> — someone registering several people can give each a name, so each gets their own ticket and attendee form</span>
</label>
{(draft.allowNamedAttendees || draft.requiresParentalConsent) && (
<label className="flex items-start gap-2 text-sm cursor-pointer ml-6">
<input type="checkbox" className="mt-0.5" checked={draft.collectGender} onChange={e => upd({ collectGender: e.target.checked })} />
<span><strong>Ask each person&apos;s gender</strong> — needed to split rooms or cabins by gender (Rooms &amp; groups)</span>
</label>
)}
{mode === "edit" && (
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.isActive} onChange={e => upd({ isActive: e.target.checked })} />
<span><strong>Active</strong> — when unchecked, the event is hidden everywhere including staff views</span>
</label>
)}
</div>
<div className="border rounded-lg p-4 bg-gray-50 space-y-3">
<div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Waitlist</div>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.waitlistEnabled} onChange={e => upd({ waitlistEnabled: e.target.checked })} />
<span><strong>Waitlist for sold-out tickets</strong> — people can join a queue; when places free up, the next person is offered them and has a set time to claim</span>
</label>
{draft.waitlistEnabled && (
<>
<label className="flex items-center gap-2 text-sm">
Hold offered places for
<input type="number" min="1" max="168" className="border rounded px-2 py-1 text-sm w-20" value={draft.waitlistOfferHours} onChange={e => upd({ waitlistOfferHours: e.target.value })} />
hours
</label>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.waitlistPartialOffers} onChange={e => upd({ waitlistPartialOffers: e.target.checked })} />
<span>When fewer places free up than someone asked for, offer them what&apos;s free (otherwise skip to the next person who fits)</span>
</label>
</>
)}
</div>
<div className="border rounded-lg p-4 bg-gray-50 space-y-3">
<div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Sponsor a spot</div>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.allowSponsorships} onChange={e => upd({ allowSponsorships: e.target.checked })} />
<span><strong>Allow sponsorships</strong> — a &quot;Sponsor a spot&quot; button on the event page lets people pay for spots (or any amount) for those who can&apos;t afford to come. The money goes into a sponsorship pool you assign under Payments → Donations</span>
</label>
{draft.allowSponsorships && (
<>
<label className="flex items-center gap-2 text-sm">
Goal
<input type="number" min="1" className="border rounded px-2 py-1 text-sm w-20" value={draft.sponsorshipGoalSpots} onChange={e => upd({ sponsorshipGoalSpots: e.target.value })} placeholder="—" />
spots (optional)
</label>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.showSponsorshipProgress} onChange={e => upd({ showSponsorshipProgress: e.target.checked })} />
<span>Show progress on the event page (&quot;12 of 20 spots sponsored&quot;)</span>
</label>
</>
)}
</div>
<div className="border rounded-lg p-4 bg-gray-50 space-y-3">
<div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Ticket transfer</div>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.allowTicketTransfer} onChange={e => upd({ allowTicketTransfer: e.target.checked })} />
<span><strong>Let people transfer their tickets</strong> — before the event, a ticket that hasn&apos;t been scanned can be handed to someone else, who gets a new QR code (supervisors can always transfer)</span>
</label>
</div>
<div className="border rounded-lg p-4 bg-gray-50 space-y-3">
<div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Youth event</div>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.requiresParentalConsent} onChange={e => upd({ requiresParentalConsent: e.target.checked, ...(e.target.checked ? { allowNamedAttendees: true } : {}) })} />
<span><strong>Requires parental consent</strong> — every attendee gives a date of birth; for anyone under 18, a parent or guardian is asked by email and WhatsApp to give consent before they can be checked in</span>
</label>
{draft.requiresParentalConsent && (
<>
<div>
<label className="block text-xs text-gray-600 mb-1">Consent text (shown to the parent)</label>
<textarea className="w-full border rounded px-2 py-1.5 text-sm" rows={6} value={draft.consentText} onChange={e => upd({ consentText: e.target.value })}
placeholder="e.g. I give permission for my child to take part in all activities, including transport, and for leaders to arrange medical treatment in an emergency." />
{mode === "edit" && <p className="text-[11px] text-gray-500 mt-1">Changing this starts a new version. Parents who already agreed keep their record; use &quot;Re-request consent&quot; on the Parental consent page to ask them again.</p>}
</div>
<div className="text-xs text-gray-600">Also ask the parent for:</div>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={draft.consentCollectMedical} onChange={e => upd({ consentCollectMedical: e.target.checked })} /> Medical info (allergies, medication, conditions, medical aid)</label>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={draft.consentCollectEmergency} onChange={e => upd({ consentCollectEmergency: e.target.checked })} /> An emergency contact</label>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={draft.consentCollectPhoto} onChange={e => upd({ consentCollectPhoto: e.target.checked })} /> Photo consent (yes/no)</label>
</>
)}
</div>
</div>
)}
{/* ── Step 5: Notifications ── */}
{step === 5 && (
<div>
{mode === "edit" && ev?.id ? (
<NotifyRecipientsManager eventId={ev.id} creator={ev.createdBy || null} initialRecipients={ev.notifyRecipients} />
) : (
<div className="space-y-3">
<p className="text-xs text-gray-500">
Choose who receives new registration, payment, and daily summary emails for this event.
Leave empty to send them to you (the event creator) instead.
</p>
<NotifyRecipientsPicker selected={notifyRecipientDrafts} onChange={setNotifyRecipientDrafts} />
</div>
)}
</div>
)}
{/* ── Step 6: Attachments ── */}
{step === 6 && (
<div>
<p className="text-xs text-gray-500 mb-3">Upload documents for attendees to download (e.g. waiver forms, info sheets, maps, schedules).</p>
{mode === "edit" && ev?.id
? <AttachmentsManager eventId={ev.id} />
: (
<div>
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium">Files to attach</span>
<label className="cursor-pointer text-xs px-2 py-1 rounded border bg-white hover:bg-gray-50">
<input
type="file"
className="hidden"
accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv,.zip"
onChange={e => {
const file = e.target.files?.[0];
if (file) setStagedFiles(prev => [...prev, file]);
e.target.value = "";
}}
/>
Add file
</label>
</div>
{stagedFiles.length === 0
? <p className="text-xs text-gray-400">No files added. Files will be uploaded when the event is created.</p>
: (
<ul className="space-y-1">
{stagedFiles.map((f, i) => (
<li key={i} className="flex items-center justify-between text-xs">
<span className="truncate max-w-xs text-gray-700">{f.name}</span>
<button
type="button"
className="text-red-600 hover:underline ml-2"
onClick={() => setStagedFiles(prev => prev.filter((_, j) => j !== i))}
>Remove</button>
</li>
))}
</ul>
)
}
</div>
)
}
</div>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-between px-5 py-3 border-t bg-gray-50 rounded-b-xl">
<button type="button" disabled={isFirstStep} onClick={handleBack}
className="px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50 disabled:opacity-40">← Back</button>
<div className="flex items-center gap-2">
{mode === "create" ? (
isLastStep && isOnLastSubstep ? (
<button type="button" disabled={saving} onClick={handleSave}
className="px-5 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50 font-medium">
{saving ? "Creating…" : "Create Event"}
</button>
) : (
<button type="button" disabled={nextDisabled} onClick={handleNext}
title={basicDetailsIncomplete ? "Fill in title, start, end date, and base price to continue" : optionsIncomplete ? "Every option needs a price before continuing" : undefined}
className="px-4 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 font-medium disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-brand-600">Next →</button>
)
) : (
<>
{!(isLastStep && isOnLastSubstep) && (
<button type="button" onClick={handleNext}
className="px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50">Next →</button>
)}
<button type="button" disabled={saving || isClosed || campusReadOnly} onClick={handleSave}
title={isClosed ? "This event is closed — reopen it first to make changes" : campusReadOnly ? "Only admins and supervisors for every campus can change this event" : undefined}
className="px-5 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50 font-medium">
{saving ? "Saving…" : "Save Changes"}
</button>
</>
)}
</div>
</div>
</div>
</div>
);
}
// ─── event card ───────────────────────────────────────────────────────────────
function EventCard({ ev, onEdit, onCopy }: { ev: Event; onEdit: () => void; onCopy: () => void }) {
const isPast = ev.endDate && new Date(ev.endDate) < new Date();
const isInactive = ev.isActive === false;
const isClosed = ev.cashupStatus === "closed";
return (
<li className="border rounded-lg p-3 bg-white hover:bg-brand-50/40 cursor-pointer transition-colors flex items-start justify-between gap-3" onClick={onEdit}>
<div className="min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium text-sm">{ev.title}</span>
{isInactive && <span className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">Inactive</span>}
{isPast && !isInactive && <span className="text-[10px] px-1.5 py-0.5 rounded bg-amber-50 text-amber-700">Past</span>}
{ev.isHidden && <span className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">Hidden</span>}
{isClosed && <span className="text-[10px] px-1.5 py-0.5 rounded bg-rose-50 text-rose-700">Closed</span>}
<CampusBadge campus={ev.campus} />
{ev.series && <span className="text-[10px] px-1.5 py-0.5 rounded bg-brand-50 text-brand-700">{ev.series.name}</span>}
</div>
<div className="text-xs text-gray-500 mt-0.5">
{scheduleSummary(ev) || <>{ev.startDate ? new Date(ev.startDate).toLocaleDateString() : ""}{ev.endDate ? ` – ${new Date(ev.endDate).toLocaleDateString()}` : ""}</>}
{ev.price != null ? <span className="ml-2">R{Number(ev.price).toFixed(0)}</span> : ""}
</div>
</div>
<div className="flex items-center gap-3 shrink-0 mt-0.5">
<button type="button" title="Make a new event from this one" className="inline-flex items-center gap-1 text-xs text-gray-600 hover:text-brand-700"
onClick={e => { e.stopPropagation(); onCopy(); }}>
<Copy className="w-3.5 h-3.5" /> Copy
</button>
<span className="text-xs text-brand-600">Edit →</span>
</div>
</li>
);
}
// ─── main page ────────────────────────────────────────────────────────────────
export default function ManageEventsPage() {
const { user, loading, token } = useAuth();
const router = useRouter();
const canView = useMemo(() => {
const role = user?.role;
return role === "admin" || role === "supervisor";
}, [user]);
useEffect(() => {
if (loading) return;
if (!user) router.replace("/login");
}, [user, loading, router]);
const [events, setEvents] = useState<Event[]>([]);
const [loadingEvents, setLoadingEvents] = useState(false);
const [error, setError] = useDismissingState<string | null>(null);
const loadEvents = useCallback(async () => {
if (!token) return;
setLoadingEvents(true);
try {
const evs = await fetchManagedEvents<Event>(token, { past: true, inactive: true });
setEvents(Array.isArray(evs) ? evs.sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()) : []);
} catch (e) {
setError(errorMessage(e) || "Failed to load events");
} finally {
setLoadingEvents(false);
}
}, [token, setError]);
// Reload when the signed-in user changes too (e.g. after an impersonation switch).
useEffect(() => { loadEvents(); }, [user, loadEvents]);
const [modalMode, setModalMode] = useState<"create" | "edit" | null>(null);
const [editingEvent, setEditingEvent] = useState<Event | null>(null);
const [includePast, setIncludePast] = useState(false);
const [showInactive, setShowInactive] = useState(false);
const [showClosed, setShowClosed] = useState(false);
const [search, setSearch] = useState("");
const [campus, setCampus] = useState("");
const isAdmin = user?.role === "admin";
const now = Date.now();
const filtered = useMemo(() => events.filter(ev => {
if (!showInactive && ev.isActive === false) return false;
if (!showClosed && ev.cashupStatus === "closed") return false;
if (!includePast && ev.endDate && new Date(ev.endDate).getTime() < now) return false;
if (search && !ev.title?.toLowerCase().includes(search.toLowerCase())) return false;
if (!matchesCampus(ev, campus)) return false;
return true;
}), [events, includePast, showInactive, showClosed, search, campus, now]);
const openCreate = () => { setEditingEvent(null); setModalMode("create"); };
const openEdit = async (ev: Event) => {
try {
const full = await fetchEvent<Event>(ev.id, { authToken: token || undefined });
setEditingEvent(full);
} catch { setEditingEvent(ev); }
setModalMode("edit");
};
// A copy needs the whole source event (options, tiers, form, recipients).
const [copyFrom, setCopyFrom] = useState<Event | null>(null);
const openCopy = async (ev: Event) => {
try {
const full = await fetchEvent<Event>(ev.id, { authToken: token || undefined });
setEditingEvent(null);
setCopyFrom(full);
setModalMode("create");
} catch (e) {
setError(errorMessage(e) || "Couldn't load the event to copy");
}
};
const closeModal = () => { setModalMode(null); setEditingEvent(null); setCopyFrom(null); };
// Deep links (the Ctrl+K palette): ?edit=<eventId> opens that event, ?new=1 a new one.
const deepLinked = useRef(false);
useEffect(() => {
if (deepLinked.current || !token) return;
deepLinked.current = true;
const params = new URLSearchParams(window.location.search);
const edit = params.get("edit");
if (edit) openEdit({ id: edit } as Event);
else if (params.get("new") === "1") openCreate();
if (edit || params.get("new")) window.history.replaceState(null, "", window.location.pathname);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [token]);
return (
<div className="max-w-4xl mx-auto w-full p-6">
<div className="flex items-center justify-between mb-6 flex-wrap gap-3">
<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">
<Calendar 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">Events</h1>
<p className="text-sm text-gray-500 mt-0.5">Manage and create events</p>
</div>
</div>
<div className="flex items-center gap-2">
<button type="button" className="px-4 py-2 text-sm rounded-lg bg-brand-600 text-white hover:bg-brand-700 shadow-sm font-medium" onClick={openCreate}>+ Add Event</button>
</div>
</div>
{!canView && <div className="p-3 border rounded bg-yellow-50 text-yellow-800 text-sm mb-4">You need supervisor or admin access.</div>}
{error && <div className="p-3 mb-3 border rounded bg-red-50 text-red-700 text-sm">{error}</div>}
<div className="flex flex-wrap items-center gap-3 mb-4 text-sm">
<input className="border rounded px-3 py-1.5 text-sm w-48" placeholder="Search by title…" value={search} onChange={e => setSearch(e.target.value)} />
<CampusFilter value={campus} onChange={setCampus} withChurchWide mine />
<label className="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked={includePast} onChange={e => setIncludePast(e.target.checked)} /> Include past
</label>
<label className={`flex items-center gap-2 cursor-pointer ${!isAdmin ? "opacity-50 cursor-not-allowed" : ""}`}>
<input type="checkbox" disabled={!isAdmin} checked={showInactive && isAdmin} onChange={e => setShowInactive(e.target.checked)} /> Show inactive
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked={showClosed} onChange={e => setShowClosed(e.target.checked)} /> Show closed
</label>
<SavedFilters
page="events"
value={{ q: search, campus, past: includePast, inactive: showInactive, closed: showClosed }}
onApply={p => {
setSearch(String(p.q || "")); setCampus(String(p.campus || ""));
setIncludePast(p.past === true); setShowInactive(p.inactive === true); setShowClosed(p.closed === true);
}}
/>
{loadingEvents && <span className="text-xs text-gray-500">Loading…</span>}
</div>
<div className="border rounded-xl bg-white shadow-sm p-4">
{filtered.length === 0
? <p className="text-sm text-gray-500">{events.length === 0 ? 'No events yet. Click "+ Add Event" to create one.' : "No events match the current filters."}</p>
: <ul className="space-y-2">{filtered.map(ev => <EventCard key={ev.id} ev={ev} onEdit={() => openEdit(ev)} onCopy={() => openCopy(ev)} />)}</ul>
}
</div>
{modalMode && (
<EventModal mode={modalMode} event={editingEvent} source={copyFrom}
onClose={closeModal}
onSuccess={loadEvents} />
)}
</div>
);
}