Archived
Percentage, fixed-amount and comp codes, limited by event, ticket option or variant, dates, use counts, minimum quantity, and people, roles or an email domain. The discount is locked in on the registration (mirrored on Registration.discountTotal so every total sees it), shows on invoices, receipts, emails and the Yoco checkout, and is released on cancellation. Use limits are enforced under an advisory lock. Ticket options and variants can also carry a staff price that Staff and above get automatically. Adds a Supervisor > Coupon codes page, code fields on registration, My Events, manual registration, at the door and the kiosk, a Discounts report, and audit log entries. Also fixes Yoco line items and the free-registration check for lines spanning several price tranches. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
597 lines
30 KiB
TypeScript
597 lines
30 KiB
TypeScript
"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,
|
||
});
|
||
|
||
// <input type="datetime-local"> 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<Coupon[]>([]);
|
||
const [events, setEvents] = useState<EventLite[]>([]);
|
||
const [fetching, setFetching] = useState(false);
|
||
const [error, setError] = useDismissingState<string | null>(null);
|
||
const [info, setInfo] = useDismissingState<string | null>(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<Coupon[]>("/api/coupons", { authToken: token }),
|
||
apiFetch<EventLite[]>("/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<Coupon & { redemptions: Redemption[] }>(`/api/coupons/${c.id}`, { authToken: token! });
|
||
setViewing({ coupon: c, redemptions: full.redemptions || [] });
|
||
} catch (e: any) {
|
||
setError(e?.message || "Failed to load uses");
|
||
}
|
||
};
|
||
|
||
return (
|
||
<div className="max-w-6xl mx-auto w-full p-6">
|
||
<div className="flex items-center justify-between gap-3 mb-4 flex-wrap">
|
||
<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">
|
||
<TicketPercent className="w-5 h-5 text-brand-600" />
|
||
</div>
|
||
<div>
|
||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard")}>← Back to dashboard</button>
|
||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Coupon codes</h1>
|
||
<p className="text-sm text-gray-500">Discounts for staff, leaders, volunteers and promotions</p>
|
||
</div>
|
||
</div>
|
||
{canView && (
|
||
<button
|
||
onClick={() => setEditing({ id: null, draft: blankDraft() })}
|
||
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700"
|
||
>
|
||
<Plus className="w-4 h-4" /> New code
|
||
</button>
|
||
)}
|
||
</div>
|
||
|
||
{!canView && (
|
||
<div className="p-3 border rounded bg-yellow-50 text-yellow-800 text-sm mb-4">You need supervisor access to manage coupon codes.</div>
|
||
)}
|
||
{error && <div className="mb-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
|
||
{info && <div className="mb-3 p-3 border rounded bg-green-50 text-green-800 text-sm">{info}</div>}
|
||
|
||
{canView && (
|
||
<div className="border rounded-xl p-4 bg-white shadow-sm">
|
||
<div className="flex flex-wrap items-center gap-3 mb-3">
|
||
<div className="relative w-full sm:w-64">
|
||
<Search className="w-4 h-4 text-gray-400 absolute left-2.5 top-2.5" />
|
||
<input className={`${inputCls} pl-8`} placeholder="Search codes" value={query} onChange={e => setQuery(e.target.value)} />
|
||
</div>
|
||
<label className="flex items-center gap-2 text-sm text-gray-700">
|
||
<input type="checkbox" checked={showOff} onChange={e => setShowOff(e.target.checked)} /> Show codes that are off
|
||
</label>
|
||
</div>
|
||
|
||
<div className="overflow-x-auto">
|
||
<Table>
|
||
<TableHeader>
|
||
<TableRow>
|
||
<TableHead>Code</TableHead>
|
||
<TableHead>Discount</TableHead>
|
||
<TableHead>Events</TableHead>
|
||
<TableHead>Uses</TableHead>
|
||
<TableHead>Valid</TableHead>
|
||
<TableHead>Status</TableHead>
|
||
<TableHead className="text-right">Actions</TableHead>
|
||
</TableRow>
|
||
</TableHeader>
|
||
<TableBody>
|
||
{visible.map(c => {
|
||
const status = couponStatus(c);
|
||
return (
|
||
<TableRow key={c.id}>
|
||
<TableCell>
|
||
<div className="font-mono font-semibold text-gray-900">{c.code}</div>
|
||
{c.description && <div className="text-xs text-gray-500">{c.description}</div>}
|
||
{(c.restrictRoles.length > 0 || c.allowedUsers.length > 0 || c.restrictDomain) && (
|
||
<div className="text-xs text-amber-700 mt-0.5">
|
||
Restricted: {c.allowedUsers.length ? `${c.allowedUsers.length} person${c.allowedUsers.length === 1 ? "" : "s"}` : c.restrictRoles.length ? c.restrictRoles.join(", ") : `@${c.restrictDomain}`}
|
||
</div>
|
||
)}
|
||
</TableCell>
|
||
<TableCell>
|
||
<div>{c.summary}</div>
|
||
{c.options.length > 0 && <div className="text-xs text-gray-500">{c.options.map(o => o.eventOption.name + (o.variant ? ` (${o.variant.name})` : "")).join(", ")}</div>}
|
||
</TableCell>
|
||
<TableCell className="text-sm">{c.events.length ? c.events.map(e => e.event.title).join(", ") : <span className="text-gray-500">All events</span>}</TableCell>
|
||
<TableCell className="text-sm">
|
||
{c.uses}{c.maxUses ? ` / ${c.maxUses}` : ""}
|
||
<div className="text-xs text-gray-500">{fmtRand(c.totalDiscount)} given</div>
|
||
</TableCell>
|
||
<TableCell className="text-xs text-gray-600">
|
||
{c.validFrom || c.validUntil ? `${c.validFrom ? fmtDate(c.validFrom) : "Now"} – ${c.validUntil ? fmtDate(c.validUntil) : "no end"}` : "Always"}
|
||
</TableCell>
|
||
<TableCell><span className={`text-xs px-2 py-0.5 rounded-full font-medium ${status.cls}`}>{status.label}</span></TableCell>
|
||
<TableCell className="text-right whitespace-nowrap">
|
||
<button className="px-2 py-1 text-xs rounded border hover:bg-gray-50 mr-1" onClick={() => openUses(c)}>Uses</button>
|
||
<button className="px-2 py-1 text-xs rounded border hover:bg-gray-50 mr-1" onClick={() => setEditing({ id: c.id, draft: draftFromCoupon(c) })}>Edit</button>
|
||
<button className={`px-2 py-1 text-xs rounded text-white ${c.active ? "bg-amber-500 hover:bg-amber-600" : "bg-green-600 hover:bg-green-700"}`} onClick={() => toggleActive(c)}>
|
||
{c.active ? "Turn off" : "Turn on"}
|
||
</button>
|
||
</TableCell>
|
||
</TableRow>
|
||
);
|
||
})}
|
||
{!fetching && visible.length === 0 && (
|
||
<TableRow><TableCell colSpan={7} className="text-center text-sm text-gray-500 py-8">No coupon codes yet.</TableCell></TableRow>
|
||
)}
|
||
</TableBody>
|
||
</Table>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
{editing && (
|
||
<CouponModal
|
||
token={token!}
|
||
events={events}
|
||
couponId={editing.id}
|
||
initial={editing.draft}
|
||
onClose={() => setEditing(null)}
|
||
onSaved={(msg) => { setEditing(null); setInfo(msg); load(); }}
|
||
/>
|
||
)}
|
||
|
||
{viewing && (
|
||
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" onClick={() => setViewing(null)}>
|
||
<div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[85vh] flex flex-col" onClick={e => e.stopPropagation()}>
|
||
<div className="flex items-center justify-between p-4 border-b">
|
||
<h2 className="font-semibold">Uses of <span className="font-mono">{viewing.coupon.code}</span></h2>
|
||
<button onClick={() => setViewing(null)} aria-label="Close"><X className="w-5 h-5 text-gray-500" /></button>
|
||
</div>
|
||
<div className="p-4 overflow-y-auto">
|
||
{viewing.redemptions.length === 0 ? (
|
||
<p className="text-sm text-gray-500">This code hasn't been used yet.</p>
|
||
) : (
|
||
<Table>
|
||
<TableHeader>
|
||
<TableRow><TableHead>Person</TableHead><TableHead>Event</TableHead><TableHead>Discount</TableHead><TableHead>When</TableHead></TableRow>
|
||
</TableHeader>
|
||
<TableBody>
|
||
{viewing.redemptions.map(r => (
|
||
<TableRow key={r.id} className={r.releasedAt ? "opacity-60" : ""}>
|
||
<TableCell>
|
||
<div className="text-sm">{r.user.name}</div>
|
||
<div className="text-xs text-gray-500">{r.user.email}</div>
|
||
{r.appliedBy && <div className="text-xs text-gray-500">Applied by {r.appliedBy.name}</div>}
|
||
</TableCell>
|
||
<TableCell className="text-sm">{r.registration.event.title}</TableCell>
|
||
<TableCell className="text-sm">
|
||
{fmtRand(r.discountAmount)}
|
||
{r.releasedAt && <div className="text-xs text-gray-500">Released (cancelled)</div>}
|
||
</TableCell>
|
||
<TableCell className="text-xs text-gray-600">{fmtDate(r.createdAt)}</TableCell>
|
||
</TableRow>
|
||
))}
|
||
</TableBody>
|
||
</Table>
|
||
)}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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<Draft>(initial);
|
||
const [saving, setSaving] = useState(false);
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [userQuery, setUserQuery] = useState("");
|
||
const [userResults, setUserResults] = useState<{ id: string; name: string; email: string }[]>([]);
|
||
const set = <K extends keyof Draft>(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 (
|
||
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" onClick={onClose}>
|
||
<form onSubmit={save} className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col" onClick={e => e.stopPropagation()}>
|
||
<div className="flex items-center justify-between p-4 border-b">
|
||
<h2 className="font-semibold">{couponId ? "Edit code" : "New coupon code"}</h2>
|
||
<button type="button" onClick={onClose} aria-label="Close"><X className="w-5 h-5 text-gray-500" /></button>
|
||
</div>
|
||
|
||
<div className="p-4 space-y-5 overflow-y-auto">
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Code</label>
|
||
<input className={`${inputCls} font-mono uppercase`} value={d.code} onChange={e => set("code", e.target.value.toUpperCase().replace(/[^A-Z0-9_-]/g, ""))} placeholder="STAFF50" required maxLength={32} />
|
||
<p className="text-xs text-gray-500 mt-1">Letters, numbers, - and _. Not case-sensitive when entered.</p>
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Description (internal)</label>
|
||
<input className={inputCls} value={d.description} onChange={e => set("description", e.target.value)} placeholder="Staff discount for Camp 2026" />
|
||
</div>
|
||
</div>
|
||
|
||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Discount type</label>
|
||
<select className={inputCls} value={d.type} onChange={e => set("type", e.target.value as CouponType)}>
|
||
<option value="percent">Percentage</option>
|
||
<option value="fixed">Fixed amount (R)</option>
|
||
<option value="comp">Free (100%)</option>
|
||
</select>
|
||
</div>
|
||
{d.type !== "comp" && (
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">{d.type === "percent" ? "Percent off" : "Amount off (R)"}</label>
|
||
<input type="number" min="0" step={d.type === "percent" ? "1" : "0.01"} max={d.type === "percent" ? 100 : undefined} className={inputCls} value={d.value} onChange={e => set("value", e.target.value)} required />
|
||
</div>
|
||
)}
|
||
<div className="flex items-end">
|
||
<label className="flex items-start gap-2 text-sm text-gray-700">
|
||
<input type="checkbox" className="mt-0.5" checked={d.stackEarlyBird} onChange={e => set("stackEarlyBird", e.target.checked)} />
|
||
<span>Also apply on top of early-bird prices <span className="block text-xs text-gray-500">Off: the better of the two prices wins.</span></span>
|
||
</label>
|
||
</div>
|
||
</div>
|
||
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Events</label>
|
||
<p className="text-xs text-gray-500 mb-2">Leave all unticked for every event.</p>
|
||
<div className="max-h-40 overflow-y-auto border rounded-lg divide-y">
|
||
{events.map(ev => (
|
||
<label key={ev.id} className="flex items-center gap-2 px-3 py-2 text-sm">
|
||
<input type="checkbox" checked={d.eventIds.includes(ev.id)} onChange={() => toggleEvent(ev.id)} />
|
||
<span>{ev.title}</span>
|
||
<span className="text-xs text-gray-500 ml-auto">{fmtDate(ev.startDate)}</span>
|
||
</label>
|
||
))}
|
||
{events.length === 0 && <p className="px-3 py-2 text-sm text-gray-500">No events.</p>}
|
||
</div>
|
||
</div>
|
||
|
||
{scopedEvents.length > 0 && (
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Only these tickets / items</label>
|
||
<p className="text-xs text-gray-500 mb-2">Leave all unticked to discount the whole registration.</p>
|
||
<div className="space-y-2">
|
||
{scopedEvents.map(ev => (
|
||
<div key={ev.id} className="border rounded-lg p-3">
|
||
<div className="text-xs font-semibold text-gray-600 mb-1">{ev.title}</div>
|
||
{ev.eventOptions.map(o => (
|
||
<div key={o.id}>
|
||
<label className="flex items-center gap-2 text-sm">
|
||
<input type="checkbox" checked={d.options.some(s => scopeKey(s) === scopeKey({ eventOptionId: o.id, variantId: null }))} onChange={() => toggleScope(o.id, null)} />
|
||
{o.name}{(o.variants || []).length > 0 && <span className="text-xs text-gray-500">(all variants)</span>}
|
||
</label>
|
||
{(o.variants || []).map(v => (
|
||
<label key={v.id} className="flex items-center gap-2 text-sm ml-6">
|
||
<input type="checkbox" checked={d.options.some(s => scopeKey(s) === scopeKey({ eventOptionId: o.id, variantId: v.id }))} onChange={() => toggleScope(o.id, v.id)} />
|
||
{v.name}
|
||
</label>
|
||
))}
|
||
</div>
|
||
))}
|
||
</div>
|
||
))}
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Valid from</label>
|
||
<input type="datetime-local" className={inputCls} value={d.validFrom} onChange={e => set("validFrom", e.target.value)} />
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Valid until</label>
|
||
<input type="datetime-local" className={inputCls} value={d.validUntil} onChange={e => set("validUntil", e.target.value)} />
|
||
</div>
|
||
</div>
|
||
|
||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Max total uses</label>
|
||
<input type="number" min="1" className={inputCls} value={d.maxUses} onChange={e => set("maxUses", e.target.value)} placeholder="Unlimited" />
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Max uses per person</label>
|
||
<input type="number" min="1" className={inputCls} value={d.maxUsesPerUser} onChange={e => set("maxUsesPerUser", e.target.value)} placeholder="Unlimited" />
|
||
</div>
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Minimum tickets</label>
|
||
<input type="number" min="1" className={inputCls} value={d.minQuantity} onChange={e => set("minQuantity", e.target.value)} placeholder="None" />
|
||
</div>
|
||
</div>
|
||
|
||
<div>
|
||
<label className="block text-sm font-medium text-gray-700 mb-1">Who can use it</label>
|
||
<select className={inputCls} value={d.restrictTo} onChange={e => set("restrictTo", e.target.value as Draft["restrictTo"])}>
|
||
<option value="anyone">Anyone with the code</option>
|
||
<option value="roles">People with certain roles</option>
|
||
<option value="users">Specific people</option>
|
||
<option value="domain">An email domain</option>
|
||
</select>
|
||
{d.restrictTo !== "anyone" && (
|
||
<p className="text-xs text-gray-500 mt-1">Restricted codes need the person to be logged in (or registered by staff), so they can't be shared in group chats.</p>
|
||
)}
|
||
|
||
{d.restrictTo === "roles" && (
|
||
<div className="flex flex-wrap gap-4 mt-2">
|
||
{(["user", "staff", "supervisor", "admin"] as Role[]).map(r => (
|
||
<label key={r} className="flex items-center gap-2 text-sm capitalize">
|
||
<input type="checkbox" checked={d.restrictRoles.includes(r)} onChange={() => set("restrictRoles", d.restrictRoles.includes(r) ? d.restrictRoles.filter(x => x !== r) : [...d.restrictRoles, r])} />
|
||
{r === "user" ? "Member" : r}
|
||
</label>
|
||
))}
|
||
</div>
|
||
)}
|
||
|
||
{d.restrictTo === "domain" && (
|
||
<input className={`${inputCls} mt-2`} value={d.restrictDomain} onChange={e => set("restrictDomain", e.target.value)} placeholder="church.org" required />
|
||
)}
|
||
|
||
{d.restrictTo === "users" && (
|
||
<div className="mt-2">
|
||
<div className="flex flex-wrap gap-2 mb-2">
|
||
{d.users.map(u => (
|
||
<span key={u.id} className="inline-flex items-center gap-1 text-xs bg-brand-50 text-brand-800 rounded-full px-2 py-1">
|
||
{u.name}
|
||
<button type="button" onClick={() => set("users", d.users.filter(x => x.id !== u.id))} aria-label={`Remove ${u.name}`}><X className="w-3 h-3" /></button>
|
||
</span>
|
||
))}
|
||
</div>
|
||
<input className={inputCls} value={userQuery} onChange={e => setUserQuery(e.target.value)} placeholder="Search by name, email or phone" />
|
||
{userResults.length > 0 && (
|
||
<div className="border rounded-lg mt-1 divide-y max-h-40 overflow-y-auto">
|
||
{userResults.filter(r => !d.users.some(u => u.id === r.id)).map(r => (
|
||
<button type="button" key={r.id} className="w-full text-left px-3 py-2 text-sm hover:bg-gray-50" onClick={() => { set("users", [...d.users, r]); setUserQuery(""); }}>
|
||
{r.name} <span className="text-xs text-gray-500">{r.email}</span>
|
||
</button>
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
<label className="flex items-center gap-2 text-sm text-gray-700">
|
||
<input type="checkbox" checked={d.active} onChange={e => set("active", e.target.checked)} /> Active
|
||
</label>
|
||
|
||
{error && <div className="p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
|
||
</div>
|
||
|
||
<div className="flex justify-end gap-3 p-4 border-t">
|
||
<button type="button" onClick={onClose} className="px-4 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">Cancel</button>
|
||
<button type="submit" disabled={saving} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
|
||
{saving ? "Saving…" : couponId ? "Save changes" : "Create code"}
|
||
</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
);
|
||
}
|