Archived
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:
@@ -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" />
|
||||
|
||||
Reference in New Issue
Block a user