"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import { apiFetch } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { TicketPercent, Plus, X, Search, Pencil, Power, Users, CalendarClock, ListChecks } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; type CouponType = "percent" | "fixed" | "comp"; type Role = "user" | "staff" | "supervisor" | "admin"; type EventLite = { id: string; title: string; startDate: string; endDate?: string; eventOptions: { id: string; name: string; variants?: { id: string; name: string }[] }[]; }; type Coupon = { id: string; code: string; description: string | null; type: CouponType; value: number; stackEarlyBird: boolean; validFrom: string | null; validUntil: string | null; maxUses: number | null; maxUsesPerUser: number | null; minQuantity: number | null; restrictRoles: Role[]; restrictDomain: string | null; active: boolean; summary: string; uses: number; totalDiscount: number; events: { eventId: string; event: { id: string; title: string } }[]; options: { eventOptionId: string; variantId: string | null; eventOption: { name: string; eventId: string }; variant: { name: string } | null }[]; allowedUsers: { userId: string; user: { id: string; name: string; email: string } }[]; }; type Redemption = { id: string; discountAmount: number; createdAt: string; releasedAt: string | null; user: { name: string; email: string }; appliedBy: { name: string } | null; registration: { status: string; event: { title: string } }; }; type Draft = { code: string; description: string; type: CouponType; value: string; stackEarlyBird: boolean; validFrom: string; validUntil: string; maxUses: string; maxUsesPerUser: string; minQuantity: string; eventIds: string[]; options: { eventOptionId: string; variantId: string | null }[]; restrictTo: "anyone" | "roles" | "users" | "domain"; restrictRoles: Role[]; restrictDomain: string; users: { id: string; name: string; email: string }[]; active: boolean; }; const blankDraft = (): Draft => ({ code: "", description: "", type: "percent", value: "", stackEarlyBird: false, validFrom: "", validUntil: "", maxUses: "", maxUsesPerUser: "1", minQuantity: "", eventIds: [], options: [], restrictTo: "anyone", restrictRoles: ["staff", "supervisor", "admin"], restrictDomain: "", users: [], active: true, }); // wants local "YYYY-MM-DDTHH:mm". const toLocalInput = (iso: string | null) => { if (!iso) return ""; const d = new Date(iso); const pad = (n: number) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; }; function draftFromCoupon(c: Coupon): Draft { const restrictTo: Draft["restrictTo"] = c.allowedUsers.length ? "users" : c.restrictRoles.length ? "roles" : c.restrictDomain ? "domain" : "anyone"; return { code: c.code, description: c.description || "", type: c.type, value: c.type === "comp" ? "" : String(c.value), stackEarlyBird: c.stackEarlyBird, validFrom: toLocalInput(c.validFrom), validUntil: toLocalInput(c.validUntil), maxUses: c.maxUses ? String(c.maxUses) : "", maxUsesPerUser: c.maxUsesPerUser ? String(c.maxUsesPerUser) : "", minQuantity: c.minQuantity ? String(c.minQuantity) : "", eventIds: c.events.map(e => e.eventId), options: c.options.map(o => ({ eventOptionId: o.eventOptionId, variantId: o.variantId })), restrictTo, restrictRoles: c.restrictRoles.length ? c.restrictRoles : ["staff", "supervisor", "admin"], restrictDomain: c.restrictDomain || "", users: c.allowedUsers.map(u => u.user), active: c.active, }; } function bodyFromDraft(d: Draft) { return { code: d.code.trim(), description: d.description.trim() || null, type: d.type, value: d.type === "comp" ? 0 : Number(d.value), stackEarlyBird: d.stackEarlyBird, validFrom: d.validFrom ? new Date(d.validFrom).toISOString() : null, validUntil: d.validUntil ? new Date(d.validUntil).toISOString() : null, maxUses: d.maxUses || null, maxUsesPerUser: d.maxUsesPerUser || null, minQuantity: d.minQuantity || null, eventIds: d.eventIds, options: d.options, restrictRoles: d.restrictTo === "roles" ? d.restrictRoles : [], restrictDomain: d.restrictTo === "domain" ? d.restrictDomain.trim() : null, userIds: d.restrictTo === "users" ? d.users.map(u => u.id) : [], active: d.active, }; } const fmtDate = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : ""); const fmtRand = (n: number) => `R ${(n || 0).toFixed(2)}`; const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"; const isPast = (ev: EventLite) => new Date(ev.endDate || ev.startDate).getTime() < Date.now(); type Status = { key: "active" | "scheduled" | "off" | "expired" | "used"; label: string; cls: string }; function couponStatus(c: Coupon): Status { const now = Date.now(); if (!c.active) return { key: "off", label: "Off", cls: "bg-gray-100 text-gray-600" }; if (c.validUntil && new Date(c.validUntil).getTime() < now) return { key: "expired", label: "Expired", cls: "bg-gray-100 text-gray-600" }; if (c.maxUses && c.uses >= c.maxUses) return { key: "used", label: "Used up", cls: "bg-gray-100 text-gray-600" }; if (c.validFrom && new Date(c.validFrom).getTime() > now) return { key: "scheduled", label: "Scheduled", cls: "bg-amber-100 text-amber-800" }; return { key: "active", label: "Active", cls: "bg-green-100 text-green-800" }; } export default function CouponsPage() { const { user, loading, token } = useAuth(); const router = useRouter(); const canView = useMemo(() => user?.role === "admin" || user?.role === "supervisor", [user]); useEffect(() => { if (loading) return; if (!user) router.replace("/login"); }, [user, loading, router]); const [coupons, setCoupons] = useState([]); const [events, setEvents] = useState([]); const [fetching, setFetching] = useState(false); const [error, setError] = useDismissingState(null); const [info, setInfo] = useDismissingState(null); const [query, setQuery] = useState(""); const [showInactive, setShowInactive] = useState(false); const [editing, setEditing] = useState<{ id: string | null; draft: Draft } | null>(null); const [viewing, setViewing] = useState<{ coupon: Coupon; redemptions: Redemption[] } | null>(null); const load = useCallback(async () => { if (!token) return; setFetching(true); try { const [c, ev] = await Promise.all([ apiFetch("/api/coupons", { authToken: token }), apiFetch("/api/events/all?includePast=true", { authToken: token }), ]); setCoupons(c || []); setEvents(ev || []); } catch (e) { setError(errorMessage(e) || "Failed to load coupons"); } finally { setFetching(false); } }, [token, setError]); useEffect(() => { if (token && canView) load(); }, [token, canView, load]); // Codes that can still be used first; off, expired and used-up ones only when asked for. const visible = useMemo(() => { const q = query.trim().toLowerCase(); const order: Record = { active: 0, scheduled: 1, used: 2, expired: 3, off: 4 }; return coupons .map(c => ({ c, status: couponStatus(c) })) .filter(({ c, status }) => (showInactive || status.key === "active" || status.key === "scheduled") && (!q || c.code.toLowerCase().includes(q) || (c.description || "").toLowerCase().includes(q) || c.events.some(e => e.event.title.toLowerCase().includes(q)))) .sort((a, b) => order[a.status.key] - order[b.status.key]); }, [coupons, query, showInactive]); const hiddenCount = coupons.filter(c => !["active", "scheduled"].includes(couponStatus(c).key)).length; const toggleActive = async (c: Coupon) => { try { await apiFetch(`/api/coupons/${c.id}`, { method: "PUT", authToken: token!, body: { active: !c.active } }); setInfo(`${c.code} turned ${c.active ? "off" : "on"}.`); load(); } catch (e) { setError(errorMessage(e) || "Failed to update coupon"); } }; const openUses = async (c: Coupon) => { try { const full = await apiFetch(`/api/coupons/${c.id}`, { authToken: token! }); setViewing({ coupon: c, redemptions: full.redemptions || [] }); } catch (e) { setError(errorMessage(e) || "Failed to load uses"); } }; const startNew = () => setEditing({ id: null, draft: blankDraft() }); return (

Coupon codes

Discounts for staff, leaders, volunteers and promotions

{canView && ( )}
{!canView && (
You need supervisor access to manage coupon codes.
)} {error &&
{error}
} {info &&
{info}
} {canView && (
setQuery(e.target.value)} />
{!fetching && visible.length === 0 && (

{coupons.length === 0 ? "No coupon codes yet" : "No codes match"}

e.g. "STAFF50": 50% off for staff, or "WELCOME20": R20 off for first-time visitors.

{coupons.length === 0 && ( )}
)} {visible.length > 0 && (
{visible.map(({ c, status }) => ( openUses(c)} onEdit={() => setEditing({ id: c.id, draft: draftFromCoupon(c) })} onToggle={() => toggleActive(c)} /> ))}
)}
)} {editing && ( setEditing(null)} onSaved={(msg) => { setEditing(null); setInfo(msg); load(); }} /> )} {viewing && ( Uses of {viewing.coupon.code}} onClose={() => setViewing(null)}> {viewing.redemptions.length === 0 ? (

This code hasn't been used yet.

) : (
    {viewing.redemptions.map(r => (
  • {r.user.name}
    {r.user.email}
    {r.registration.event.title} · {fmtDate(r.createdAt)}
    {r.appliedBy &&
    Applied by {r.appliedBy.name}
    }
    {fmtRand(r.discountAmount)}
    {r.releasedAt &&
    Released (cancelled)
    }
  • ))}
)}
)}
); } /** A dialog that slides up full-width on phones and sits centred on bigger screens. */ function Sheet({ title, subtitle, onClose, children, footer, onSubmit }: { title: React.ReactNode; subtitle?: React.ReactNode; onClose: () => void; children: React.ReactNode; footer?: React.ReactNode; onSubmit?: (e: React.FormEvent) => void; }) { const Box = onSubmit ? "form" : "div"; return (
e.stopPropagation()}>

{title}

{subtitle &&

{subtitle}

}
{children}
{footer &&
{footer}
}
); } function CouponCard({ coupon: c, status, onUses, onEdit, onToggle }: { coupon: Coupon; status: Status; onUses: () => void; onEdit: () => void; onToggle: () => void }) { const restricted = c.allowedUsers.length ? `${c.allowedUsers.length} ${c.allowedUsers.length === 1 ? "person" : "people"}` : c.restrictRoles.length ? c.restrictRoles.map(r => (r === "user" ? "members" : r)).join(", ") : c.restrictDomain ? `@${c.restrictDomain}` : null; const dates = c.validFrom || c.validUntil ? `${c.validFrom ? fmtDate(c.validFrom) : "Now"} – ${c.validUntil ? fmtDate(c.validUntil) : "no end date"}` : null; const limits = [ c.maxUses ? `${c.maxUses} uses in total` : null, c.maxUsesPerUser ? `${c.maxUsesPerUser} per person` : null, c.minQuantity ? `min ${c.minQuantity} tickets` : null, ].filter(Boolean).join(" · "); const live = status.key === "active" || status.key === "scheduled"; return (
{c.code}
{c.description &&
{c.description}
}
{status.label}
{c.summary} {c.options.length > 0 && ( on {c.options.map(o => o.eventOption.name + (o.variant ? ` (${o.variant.name})` : "")).join(", ")} )}
{c.events.length === 0 ? All events : c.events.map(e => ( {e.event.title} ))}
Used {c.uses}{c.maxUses ? ` / ${c.maxUses}` : ""}× · {fmtRand(c.totalDiscount)} given
{restricted &&
Only for {restricted}
} {dates &&
{dates}
} {limits &&
{limits}
}
); } function CouponModal({ token, events, couponId, initial, onClose, onSaved }: { token: string; events: EventLite[]; couponId: string | null; initial: Draft; onClose: () => void; onSaved: (message: string) => void; }) { const [d, setD] = useState(initial); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const [userQuery, setUserQuery] = useState(""); const [userResults, setUserResults] = useState<{ id: string; name: string; email: string }[]>([]); const [eventQuery, setEventQuery] = useState(""); const [showPast, setShowPast] = useState(false); const set = (key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value })); // Upcoming events soonest first. Past events only when asked for, but ones already // picked always stay in the list so they can be unticked. const eventChoices = useMemo(() => { const q = eventQuery.trim().toLowerCase(); const upcoming = events.filter(e => !isPast(e)).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()); const past = events.filter(isPast).sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()); return [...upcoming, ...past] .filter(e => showPast || !isPast(e) || d.eventIds.includes(e.id)) .filter(e => !q || e.title.toLowerCase().includes(q)); }, [events, eventQuery, showPast, d.eventIds]); const pastCount = events.filter(isPast).length; // Ticket options only make sense within the chosen events. const scopedEvents = useMemo(() => events.filter(e => d.eventIds.includes(e.id)), [events, d.eventIds]); useEffect(() => { if (d.restrictTo !== "users" || userQuery.trim().length < 2) { setUserResults([]); return; } const t = setTimeout(async () => { try { const res = await apiFetch<{ data: { id: string; name: string; email: string }[] }>(`/api/users?search=${encodeURIComponent(userQuery.trim())}&limit=8`, { authToken: token }); setUserResults(res?.data || []); } catch { setUserResults([]); } }, 300); return () => clearTimeout(t); }, [userQuery, d.restrictTo, token]); const toggleEvent = (id: string) => { const eventIds = d.eventIds.includes(id) ? d.eventIds.filter(x => x !== id) : [...d.eventIds, id]; // Drop scoped options from events that are no longer selected. const keepOptionIds = new Set(events.filter(e => eventIds.includes(e.id)).flatMap(e => e.eventOptions.map(o => o.id))); setD(prev => ({ ...prev, eventIds, options: prev.options.filter(o => keepOptionIds.has(o.eventOptionId)) })); }; const scopeKey = (o: { eventOptionId: string; variantId: string | null }) => `${o.eventOptionId}::${o.variantId || ""}`; const toggleScope = (eventOptionId: string, variantId: string | null) => { const key = scopeKey({ eventOptionId, variantId }); set("options", d.options.some(o => scopeKey(o) === key) ? d.options.filter(o => scopeKey(o) !== key) : [...d.options, { eventOptionId, variantId }]); }; const save = async (e: React.FormEvent) => { e.preventDefault(); setError(null); if (d.restrictTo === "users" && d.users.length === 0) { setError("Add at least one person, or choose another restriction."); return; } setSaving(true); try { const body = bodyFromDraft(d); if (couponId) { await apiFetch(`/api/coupons/${couponId}`, { method: "PUT", authToken: token, body }); onSaved(`${body.code.toUpperCase()} saved.`); } else { await apiFetch(`/api/coupons`, { method: "POST", authToken: token, body }); onSaved(`${body.code.toUpperCase()} created.`); } } catch (err) { setError(errorMessage(err) || "Failed to save"); } finally { setSaving(false); } }; const label = "block text-sm font-medium text-gray-700 mb-1"; const optional = (optional); return ( )} >
set("code", e.target.value.toUpperCase().replace(/[^A-Z0-9_-]/g, ""))} placeholder="STAFF50" required maxLength={32} />

Letters, numbers, - and _. Not case-sensitive when entered.

set("description", e.target.value)} placeholder="Staff discount for Camp 2026" />

Only staff see this.

{([["percent", "Percentage", "e.g. 20% off"], ["fixed", "Amount off", "e.g. R50 off"], ["comp", "Free", "100% off"]] as [CouponType, string, string][]).map(([t, name, hint]) => ( ))}
{d.type !== "comp" && (
set("value", e.target.value)} required />
)}

{d.eventIds.length === 0 ? "None picked: the code works for every event." : `${d.eventIds.length} picked. The code only works for ${d.eventIds.length === 1 ? "this event" : "these events"}.`}

setEventQuery(e.target.value)} />
{pastCount > 0 && ( )}
{eventChoices.map(ev => ( ))} {eventChoices.length === 0 &&

{eventQuery ? "No events match." : "No upcoming events."}

}
{scopedEvents.length > 0 && (

Leave all unticked to discount the whole registration.

{scopedEvents.map(ev => (
{ev.title}
{ev.eventOptions.map(o => (
{(o.variants || []).map(v => ( ))}
))}
))}
)}
set("validFrom", e.target.value)} />
set("validUntil", e.target.value)} />
set("maxUses", e.target.value)} placeholder="Unlimited" />
set("maxUsesPerUser", e.target.value)} placeholder="Unlimited" />
set("minQuantity", e.target.value)} placeholder="None" />
{d.restrictTo !== "anyone" && (

Restricted codes need the person to be logged in (or registered by staff), so they can't be shared in group chats.

)} {d.restrictTo === "roles" && (
{(["user", "staff", "supervisor", "admin"] as Role[]).map(r => ( ))}
)} {d.restrictTo === "domain" && ( set("restrictDomain", e.target.value)} placeholder="church.org" required /> )} {d.restrictTo === "users" && (
{d.users.map(u => ( {u.name} ))}
setUserQuery(e.target.value)} placeholder="Search by name, email or phone" /> {userResults.length > 0 && (
{userResults.filter(r => !d.users.some(u => u.id === r.id)).map(r => ( ))}
)}
)}
{error &&
{error}
}
); }