Add coupon codes and staff pricing
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>
This commit is contained in:
@@ -13,6 +13,7 @@ import {
|
||||
FileBarChart,
|
||||
BarChart3,
|
||||
ClipboardList,
|
||||
TicketPercent,
|
||||
} from "lucide-react";
|
||||
|
||||
export type ReportCategory = "Financial" | "Registration" | "Ticketing" | "Donations" | "Cashup" | "Other";
|
||||
@@ -33,6 +34,7 @@ export const REPORTS = [
|
||||
{ key: "financeReport", label: "Finance report (revenue & costs)", description: "Revenue & costs overview", category: "Financial", icon: FileBarChart, fields: 6 },
|
||||
{ key: "profitReport", label: "Profit report", description: "View profit report", category: "Financial", icon: BarChart3, fields: 5 },
|
||||
{ key: "cashupAudit", label: "Cashup audit trail", description: "Audit trail of cashup actions", category: "Cashup", icon: ClipboardList, fields: 6 },
|
||||
{ key: "discounts", label: "Discounts (coupon codes)", description: "Uses and value given away per code and event", category: "Financial", icon: TicketPercent, fields: 4 },
|
||||
] as const satisfies ReadonlyArray<{
|
||||
key: string;
|
||||
label: string;
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useSearchParams } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch, API_BASE } from "@/lib/api";
|
||||
import { downloadReportExcel, emailReportPdf, whatsappReportPdf, viewReportPdf, type ReportPdfPayload } from "@/lib/export";
|
||||
import { Printer, Mail, FileSpreadsheet, MessageCircle, ShoppingCart, CreditCard, Gift, Clock, HandHeart, Search, TrendingUp } from "lucide-react";
|
||||
import { Printer, Mail, FileSpreadsheet, MessageCircle, ShoppingCart, CreditCard, Gift, Clock, HandHeart, Search, TrendingUp, TicketPercent } from "lucide-react";
|
||||
import { REPORTS, type ReportKey } from "./ReportCatalog";
|
||||
import ReportsShell from "./ReportsShell";
|
||||
import ReportViewerModal, { ReportActionButton } from "./ReportViewerModal";
|
||||
@@ -173,6 +173,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
const [ticketUsage, setTicketUsage] = useState<Record<string, { used: number; unused: number }>>({});
|
||||
const [financialsByEvent, setFinancialsByEvent] = useState<Record<string, any>>({});
|
||||
const [auditRows, setAuditRows] = useState<any[]>([]);
|
||||
const [discountRows, setDiscountRows] = useState<any[]>([]);
|
||||
|
||||
// Deep-linking: dashboards link here with ?report=<key>&range=trailing_month to jump
|
||||
// straight into a specific report, pre-filtered to every currently-visible event and the
|
||||
@@ -282,6 +283,19 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
return byEv;
|
||||
};
|
||||
|
||||
// Coupon uses (active redemptions on non-cancelled registrations) for the Discounts report.
|
||||
const loadDiscounts = async (eventIds: string[]) => {
|
||||
if (!token || !eventIds.length) return [] as any[];
|
||||
const query = new URLSearchParams({ eventIds: eventIds.join(",") });
|
||||
if (dateFrom) query.set("from", dateFrom);
|
||||
if (dateTo) query.set("to", dateTo);
|
||||
try {
|
||||
return await apiFetch<any[]>(`/api/coupons/redemptions?${query.toString()}`, { authToken: token });
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const loadCashupAudit = async (eventIds: string[]) => {
|
||||
if (!token) return [] as any[];
|
||||
const query = new URLSearchParams();
|
||||
@@ -298,6 +312,29 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
}
|
||||
};
|
||||
|
||||
// Discounts report: one row per code per event.
|
||||
const discountSummary = useMemo(() => {
|
||||
const byKey = new Map<string, { code: string; summary: string; event: string; uses: number; total: number }>();
|
||||
for (const r of discountRows) {
|
||||
const event = r.registration?.event?.title || "—";
|
||||
const key = `${r.coupon?.code}__${event}`;
|
||||
const row = byKey.get(key) || { code: r.coupon?.code || "?", summary: r.summary || "", event, uses: 0, total: 0 };
|
||||
row.uses += 1;
|
||||
row.total += Number(r.discountAmount || 0);
|
||||
byKey.set(key, row);
|
||||
}
|
||||
const rows = Array.from(byKey.values()).sort((a, b) => b.total - a.total);
|
||||
const byCode = new Map<string, number>();
|
||||
rows.forEach(r => byCode.set(r.code, (byCode.get(r.code) || 0) + r.total));
|
||||
return {
|
||||
rows,
|
||||
totalUses: rows.reduce((s, r) => s + r.uses, 0),
|
||||
totalValue: rows.reduce((s, r) => s + r.total, 0),
|
||||
codes: byCode.size,
|
||||
chart: Array.from(byCode.entries()).map(([label, value]) => ({ label, value })),
|
||||
};
|
||||
}, [discountRows]);
|
||||
|
||||
// View handler according to selected report
|
||||
const onView = async () => {
|
||||
setBusy(true);
|
||||
@@ -351,6 +388,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
} else if (report === "cashupAudit") {
|
||||
const rows = await loadCashupAudit(selectedEventIds);
|
||||
setAuditRows(rows);
|
||||
} else if (report === "discounts") {
|
||||
setDiscountRows(await loadDiscounts(selectedEventIds));
|
||||
}
|
||||
setReady(true);
|
||||
} finally {
|
||||
@@ -924,6 +963,25 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
table: { columns: ["Event", "Donations (R)", "Used (R)", "Unused (R)", "Count"], rows }
|
||||
};
|
||||
}
|
||||
if (report === "discounts") {
|
||||
return {
|
||||
title: 'Discounts (coupon codes)', subtitle, kind: 'table', orientation: 'portrait',
|
||||
stats: [
|
||||
{ label: 'Value given away', value: `R ${discountSummary.totalValue.toFixed(2)}`, tone: 'rose' },
|
||||
{ label: 'Uses', value: String(discountSummary.totalUses), tone: 'violet' },
|
||||
{ label: 'Codes used', value: String(discountSummary.codes), tone: 'blue' },
|
||||
],
|
||||
chart: { title: 'Value given away, by code', data: discountSummary.chart.map(c => ({ ...c, displayValue: `R ${c.value.toFixed(2)}` })) },
|
||||
note: 'Counts codes on registrations that are not cancelled. Cancelling a registration frees its code.',
|
||||
table: {
|
||||
columns: ["Code", "Discount", "Event", "Uses", "Value (R)"],
|
||||
rows: [
|
||||
...discountSummary.rows.map(r => [r.code, r.summary, r.event, r.uses, Number(r.total.toFixed(2))]),
|
||||
["Total", "", "", discountSummary.totalUses, Number(discountSummary.totalValue.toFixed(2))],
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
if (report === "cashup") {
|
||||
const rows: (string | number)[][] = [];
|
||||
const incomeByMethod: Record<string, number> = {};
|
||||
@@ -958,7 +1016,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
const ev = filteredEvents.find(e => e.id === evId);
|
||||
if (!f) return;
|
||||
const title = ev?.title || evId;
|
||||
sold += (f.salesByOption || []).reduce((s: number, o: any) => s + (o.revenue || 0), 0);
|
||||
sold += (f.salesByOption || []).reduce((s: number, o: any) => s + (o.revenue || 0), 0) - (f.discountsTotal || 0);
|
||||
paidByAll += METHOD_KEYS.reduce((s, m) => s + (f.paymentsByMethod?.[m] || 0), 0);
|
||||
METHOD_KEYS.forEach(m => { paidByMethod[m] = (paidByMethod[m] || 0) + (f.paymentsByMethod?.[m] || 0); });
|
||||
donationsProfit += f.unallocatedDonationsTotal || 0;
|
||||
@@ -972,6 +1030,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
// as profit" — no need to repeat it here.
|
||||
rows.push([title, "Sales", "What was sold", ""]);
|
||||
(f.salesByOption || []).forEach((s: any) => rows.push([title, "", `${s.name} (${s.quantitySold} sold)`, Number(s.revenue.toFixed(2))]));
|
||||
if (f.discountsTotal > 0) rows.push([title, "", "Less discount codes", -Number(f.discountsTotal.toFixed(2))]);
|
||||
rows.push([title, "Paid by", "", ""]);
|
||||
METHOD_KEYS.forEach(m => rows.push([title, "", METHOD_LABEL[m], Number((f.paymentsByMethod?.[m] || 0).toFixed(2))]));
|
||||
rows.push([title, "Cashup comparison", "", ""]);
|
||||
@@ -1108,6 +1167,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
financeReport: "Finance Report",
|
||||
profitReport: "Profit Report",
|
||||
cashupAudit: "Cashup Audit Trail",
|
||||
discounts: "Discounts Report",
|
||||
};
|
||||
|
||||
const doPrintPdf = async () => {
|
||||
@@ -1558,6 +1618,54 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{report === "discounts" && (
|
||||
<div>
|
||||
{discountSummary.rows.length === 0 ? (
|
||||
<div className="text-sm text-gray-500">No discount codes used for the selected events and dates.</div>
|
||||
) : (
|
||||
<>
|
||||
<StatTileRow>
|
||||
<StatTile icon={TicketPercent} label="Value given away" value={`R ${discountSummary.totalValue.toFixed(2)}`} tone="rose" />
|
||||
<StatTile icon={ShoppingCart} label="Uses" value={String(discountSummary.totalUses)} tone="violet" />
|
||||
<StatTile icon={Gift} label="Codes used" value={String(discountSummary.codes)} tone="blue" />
|
||||
</StatTileRow>
|
||||
<div className="mt-4 border border-gray-100 rounded-xl p-4">
|
||||
<div className="text-xs text-gray-500 mb-3">Value given away, by code</div>
|
||||
<HorizontalBarChart data={discountSummary.chart} valueFormatter={v => `R ${v.toFixed(2)}`} />
|
||||
</div>
|
||||
<div className="mt-4 overflow-auto border border-gray-100 rounded-xl">
|
||||
<table className="min-w-[640px] w-full">
|
||||
<thead>
|
||||
<tr className="text-left text-gray-500 text-xs uppercase tracking-wide bg-gray-50">
|
||||
<th className="py-2 px-3">Code</th>
|
||||
<th className="py-2 px-3">Discount</th>
|
||||
<th className="py-2 px-3">Event</th>
|
||||
<th className="py-2 px-3 text-right">Uses</th>
|
||||
<th className="py-2 px-3 text-right">Value (R)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{discountSummary.rows.map(row => (
|
||||
<tr key={`${row.code}-${row.event}`} className="border-t border-gray-100">
|
||||
<td className="py-2 px-3 font-mono">{row.code}</td>
|
||||
<td className="py-2 px-3">{row.summary}</td>
|
||||
<td className="py-2 px-3">{row.event}</td>
|
||||
<td className="py-2 px-3 text-right">{row.uses}</td>
|
||||
<td className="py-2 px-3 text-right">R {row.total.toFixed(2)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr className="font-semibold bg-gray-50 border-t border-gray-200">
|
||||
<td className="py-2 px-3" colSpan={3}>Total</td>
|
||||
<td className="py-2 px-3 text-right">{discountSummary.totalUses}</td>
|
||||
<td className="py-2 px-3 text-right">R {discountSummary.totalValue.toFixed(2)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{report === "donations" && (
|
||||
<div>
|
||||
{Object.keys(paymentsByEvent).length === 0 ? (
|
||||
@@ -1878,7 +1986,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
<div className="font-medium text-gray-900">{ev?.title || evId}</div>
|
||||
|
||||
<StatTileRow>
|
||||
<StatTile icon={ShoppingCart} label="What was sold" value={`R ${(f.salesByOption || []).reduce((s: number, o: any) => s + (o.revenue || 0), 0).toFixed(2)}`} tone="green" />
|
||||
<StatTile icon={ShoppingCart} label={f.discountsTotal > 0 ? "What was sold (after discounts)" : "What was sold"} value={`R ${((f.salesByOption || []).reduce((s: number, o: any) => s + (o.revenue || 0), 0) - (f.discountsTotal || 0)).toFixed(2)}`} tone="green" />
|
||||
<StatTile icon={CreditCard} label="Paid by (all methods)" value={`R ${METHOD_KEYS.reduce((s, m) => s + (f.paymentsByMethod?.[m] || 0), 0).toFixed(2)}`} tone="blue" />
|
||||
<StatTile icon={HandHeart} label="Donations counted as profit" value={`R ${(f.unallocatedDonationsTotal || 0).toFixed(2)}`} tone="rose" />
|
||||
<StatTile icon={FileSpreadsheet} label="Total costs" value={`R ${(f.totalCosts || 0).toFixed(2)}`} tone="amber" />
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { TicketPercent, X } from "lucide-react";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
|
||||
export type BasketItem = { eventOptionId: string; variantId?: string | null; quantity: number };
|
||||
|
||||
export type AppliedCoupon = {
|
||||
code: string;
|
||||
summary: string;
|
||||
discount: number;
|
||||
subtotal: number;
|
||||
total: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* "Have a code?" field. Checks the code against the current basket with
|
||||
* POST /api/coupons/validate and reports the result through `onChange` — the parent
|
||||
* sends `applied.code` as `couponCode` when it registers. Re-checks automatically when
|
||||
* the basket changes, since the discount (or whether the code applies at all) can change.
|
||||
*
|
||||
* Staff checking on someone's behalf pass `forUserId` (the attendee), or `null` for a
|
||||
* walk-in with no account yet.
|
||||
*/
|
||||
export function CouponCodeField({
|
||||
eventId,
|
||||
basket,
|
||||
token,
|
||||
forUserId,
|
||||
applied,
|
||||
onChange,
|
||||
compact = false,
|
||||
}: {
|
||||
eventId: string;
|
||||
basket: BasketItem[];
|
||||
token?: string | null;
|
||||
forUserId?: string | null;
|
||||
applied: AppliedCoupon | null;
|
||||
onChange: (applied: AppliedCoupon | null) => void;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(!!applied);
|
||||
const [code, setCode] = useState(applied?.code || "");
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const items = basket.filter(b => b.quantity > 0);
|
||||
const basketKey = JSON.stringify(items);
|
||||
const lastKey = useRef(basketKey);
|
||||
|
||||
const check = async (value: string) => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return;
|
||||
if (items.length === 0) { setError("Choose your tickets first."); return; }
|
||||
setChecking(true);
|
||||
setError(null);
|
||||
try {
|
||||
const body: Record<string, unknown> = { code: trimmed, eventId, options: items };
|
||||
if (forUserId !== undefined) body.forUserId = forUserId;
|
||||
const res = await apiFetch<AppliedCoupon & { valid: boolean }>("/api/coupons/validate", { method: "POST", authToken: token || undefined, body });
|
||||
onChange({ code: res.code, summary: res.summary, discount: res.discount, subtotal: res.subtotal, total: res.total });
|
||||
} catch (e) {
|
||||
onChange(null);
|
||||
setError(e instanceof ApiError ? e.message : "Couldn't check that code. Please try again.");
|
||||
} finally {
|
||||
setChecking(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Basket changed after a code was applied: check it again for the new items.
|
||||
useEffect(() => {
|
||||
if (lastKey.current === basketKey) return;
|
||||
lastKey.current = basketKey;
|
||||
if (applied) check(applied.code);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [basketKey]);
|
||||
|
||||
// Staff switched attendee: restricted codes depend on who it's for.
|
||||
useEffect(() => {
|
||||
if (applied) check(applied.code);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [forUserId]);
|
||||
|
||||
const remove = () => {
|
||||
onChange(null);
|
||||
setCode("");
|
||||
setError(null);
|
||||
};
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<button type="button" onClick={() => setOpen(true)} className="inline-flex items-center gap-1.5 text-sm text-brand-600 hover:underline">
|
||||
<TicketPercent className="w-4 h-4" /> Have a code?
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
if (applied) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border border-green-200 bg-green-50 px-3 py-2 text-sm">
|
||||
<div className="flex items-center gap-2 text-green-800">
|
||||
<TicketPercent className="w-4 h-4 shrink-0" />
|
||||
<span>
|
||||
<span className="font-mono font-semibold">{applied.code}</span> — {applied.summary}
|
||||
{applied.discount > 0 && <span className="font-medium"> (−R {applied.discount.toFixed(2)})</span>}
|
||||
</span>
|
||||
</div>
|
||||
<button type="button" onClick={remove} className="text-green-800 hover:text-green-950" aria-label="Remove code">
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{!compact && <label className="block text-sm font-medium text-gray-700 mb-1">Discount code</label>}
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={code}
|
||||
onChange={e => { setCode(e.target.value.toUpperCase()); setError(null); }}
|
||||
onKeyDown={e => { if (e.key === "Enter") { e.preventDefault(); check(code); } }}
|
||||
placeholder="Enter code"
|
||||
className="flex-1 min-w-0 border rounded-lg px-3 py-2 text-sm font-mono uppercase focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||||
aria-label="Discount code"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => check(code)}
|
||||
disabled={checking || !code.trim()}
|
||||
className="px-4 py-2 rounded-lg border border-brand-600 text-brand-700 text-sm font-medium hover:bg-brand-50 disabled:opacity-50"
|
||||
>
|
||||
{checking ? "Checking…" : "Apply"}
|
||||
</button>
|
||||
</div>
|
||||
{error && <p className="text-xs text-red-600 mt-1">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user