"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 } from "lucide-react"; import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table"; type CouponType = "percent" | "fixed" | "comp"; type Role = "user" | "staff" | "supervisor" | "admin"; type EventLite = { id: string; title: string; startDate: 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) => (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"; function couponStatus(c: Coupon): { label: string; cls: string } { const now = Date.now(); if (!c.active) return { label: "Off", cls: "bg-gray-100 text-gray-600" }; if (c.validUntil && new Date(c.validUntil).getTime() < now) return { label: "Expired", cls: "bg-gray-100 text-gray-600" }; if (c.validFrom && new Date(c.validFrom).getTime() > now) return { label: "Scheduled", cls: "bg-amber-100 text-amber-800" }; if (c.maxUses && c.uses >= c.maxUses) return { label: "Used up", cls: "bg-gray-100 text-gray-600" }; return { 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 [showOff, setShowOff] = 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: any) { setError(e?.message || "Failed to load coupons"); } finally { setFetching(false); } }, [token, setError]); useEffect(() => { if (token && canView) load(); }, [token, canView, load]); const visible = useMemo(() => { const q = query.trim().toLowerCase(); return coupons.filter(c => (showOff || c.active) && (!q || c.code.toLowerCase().includes(q) || (c.description || "").toLowerCase().includes(q))); }, [coupons, query, showOff]); 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: any) { setError(e?.message || "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: any) { setError(e?.message || "Failed to load uses"); } }; 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)} />
Code Discount Events Uses Valid Status Actions {visible.map(c => { const status = couponStatus(c); return (
{c.code}
{c.description &&
{c.description}
} {(c.restrictRoles.length > 0 || c.allowedUsers.length > 0 || c.restrictDomain) && (
Restricted: {c.allowedUsers.length ? `${c.allowedUsers.length} person${c.allowedUsers.length === 1 ? "" : "s"}` : c.restrictRoles.length ? c.restrictRoles.join(", ") : `@${c.restrictDomain}`}
)}
{c.summary}
{c.options.length > 0 &&
{c.options.map(o => o.eventOption.name + (o.variant ? ` (${o.variant.name})` : "")).join(", ")}
}
{c.events.length ? c.events.map(e => e.event.title).join(", ") : All events} {c.uses}{c.maxUses ? ` / ${c.maxUses}` : ""}
{fmtRand(c.totalDiscount)} given
{c.validFrom || c.validUntil ? `${c.validFrom ? fmtDate(c.validFrom) : "Now"} – ${c.validUntil ? fmtDate(c.validUntil) : "no end"}` : "Always"} {status.label}
); })} {!fetching && visible.length === 0 && ( No coupon codes yet. )}
)} {editing && ( setEditing(null)} onSaved={(msg) => { setEditing(null); setInfo(msg); load(); }} /> )} {viewing && (
setViewing(null)}>
e.stopPropagation()}>

Uses of {viewing.coupon.code}

{viewing.redemptions.length === 0 ? (

This code hasn't been used yet.

) : ( PersonEventDiscountWhen {viewing.redemptions.map(r => (
{r.user.name}
{r.user.email}
{r.appliedBy &&
Applied by {r.appliedBy.name}
}
{r.registration.event.title} {fmtRand(r.discountAmount)} {r.releasedAt &&
Released (cancelled)
}
{fmtDate(r.createdAt)}
))}
)}
)}
); } 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 set = (key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value })); // 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: any) { setError(err?.message || "Failed to save"); } finally { setSaving(false); } }; return (
e.stopPropagation()}>

{couponId ? "Edit code" : "New coupon code"}

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" />
{d.type !== "comp" && (
set("value", e.target.value)} required />
)}

Leave all unticked for every event.

{events.map(ev => ( ))} {events.length === 0 &&

No 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}
}
); }