Settle cashups: where the money ended up

A full cashup now records, per payment method, how much of the expected
takings is in the bank, still on hand (cash) or pending (on the card
report or with a POP), and writes off what was lost to card fees, bank
charges or a shortfall. Whatever is left is shown as unaccounted; closing
with an unaccounted amount is allowed after a warning.

Pending money can be marked received or written off after the event is
closed, without reopening it. Reopening starts the next cashup from the
last one. Write-offs come off net profit and show as "Bank & card
charges" in the cashup, finance and profit reports.

The reports page also moves to the shared back link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 13:25:04 +02:00
co-authored by Claude Opus 5.5
parent 724424246c
commit 1d8f5616c8
12 changed files with 1004 additions and 186 deletions
@@ -1,7 +1,8 @@
"use client";
import React, { useMemo, useState } from "react";
import { ArrowLeft, Search } from "lucide-react";
import { Search } from "lucide-react";
import { BackLink } from "@/components/shared/BackLink";
import { REPORTS, REPORT_CATEGORIES, type ReportKey, type ReportCategory } from "./ReportCatalog";
import EventsDropdown from "./EventsDropdown";
@@ -17,7 +18,7 @@ export default function ReportsShell({
dateFrom, setDateFrom, dateTo, setDateTo,
report, setReport,
onViewReport, busy,
onBack,
backHref,
}: {
events: EventLite[]; isAdmin: boolean;
showPastEvents: boolean; setShowPastEvents: (v: boolean) => void;
@@ -27,7 +28,7 @@ export default function ReportsShell({
dateFrom: string; setDateFrom: (v: string) => void; dateTo: string; setDateTo: (v: string) => void;
report: ReportKey; setReport: (r: ReportKey) => void;
onViewReport: () => void; busy: boolean;
onBack?: () => void;
backHref?: string;
}) {
const [search, setSearch] = useState("");
const [category, setCategory] = useState<"All" | ReportCategory>("All");
@@ -67,7 +68,8 @@ export default function ReportsShell({
<div>
<div className="flex flex-wrap items-start justify-between gap-3 sm:gap-4 mb-6">
<div className="min-w-0">
<h1 className="text-2xl font-semibold text-gray-900">Reports</h1>
{backHref && <BackLink href={backHref} />}
<h1 className={"text-2xl font-semibold text-gray-900" + (backHref ? " mt-0.5" : "")}>Reports</h1>
<p className="text-sm text-gray-500 mt-0.5">View, export, or email operational reports for events.</p>
</div>
<div className="flex items-center gap-3 w-full sm:w-auto">
@@ -80,11 +82,6 @@ export default function ReportsShell({
onChange={e => setSearch(e.target.value)}
/>
</div>
{onBack && (
<button type="button" className="shrink-0 flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800" onClick={onBack}>
<ArrowLeft className="w-4 h-4" /> Back
</button>
)}
</div>
</div>
@@ -18,6 +18,7 @@ import type { ConsentRow, Event, EventCashup, EventFinancials, MedicalRow, Payme
const METHOD_KEYS = ["cash", "card", "eft", "other"] as const;
const METHOD_LABEL: Record<string, string> = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" };
const WRITE_OFF_LABEL: Record<string, string> = { card_fees: "Card / online fees", bank_charges: "Bank charges", cash_shortfall: "Cash shortfall", other: "Other" };
function denomLabel(v: number): string {
return v >= 1 ? `R${v}` : `${Math.round(v * 100)}c`;
}
@@ -143,7 +144,7 @@ type FunnelReport = {
};
// Simple MultiSelect control used in filters
export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
const { token, user } = useAuth();
const role = user?.role || "user";
const canView = role === "admin" || role === "supervisor";
@@ -1178,23 +1179,25 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
METHOD_KEYS.forEach(m => {
const r = f.reconciled?.byMethod?.[m];
incomeByMethod[m] = (incomeByMethod[m] || 0) + (f.paymentsByMethod?.[m] || 0);
rows.push([title, METHOD_LABEL[m], Number((f.paymentsByMethod?.[m] || 0).toFixed(2)), Number((f.costsByMethod?.[m] || 0).toFixed(2)), Number((f.expectedCashByMethod?.[m] || 0).toFixed(2)), r?.actual != null ? Number(r.actual.toFixed(2)) : "not reconciled", r?.variance != null ? Number(r.variance.toFixed(2)) : ""]);
const amount = (v: number | null | undefined) => (v != null && Math.abs(v) >= 0.005 ? Number(v.toFixed(2)) : "");
rows.push([title, METHOD_LABEL[m], Number((f.paymentsByMethod?.[m] || 0).toFixed(2)), Number((f.costsByMethod?.[m] || 0).toFixed(2)), Number((f.expectedCashByMethod?.[m] || 0).toFixed(2)), amount(r?.bank), amount(r?.onHand), amount(r?.pendingOutstanding), amount(r?.writeOffTotal), r?.unaccounted != null ? Number(r.unaccounted.toFixed(2)) : "not reconciled"]);
if (m === "cash") {
(r?.denominations || []).forEach((d) => rows.push([title, ` ${denomLabel(d.value)} × ${d.count}`, "", "", "", Number((d.value * d.count).toFixed(2)), ""]));
(r?.denominations || []).forEach((d) => rows.push([title, ` ${denomLabel(d.value)} × ${d.count}`, "", "", "", "", Number((d.value * d.count).toFixed(2)), "", "", ""]));
}
(r?.writeOffs || []).forEach((w) => rows.push([title, ` Write-off: ${WRITE_OFF_LABEL[w.category] || w.category}${w.reason ? ` (${w.reason})` : ""}`, "", "", "", "", "", "", Number(w.amount.toFixed(2)), ""]));
});
if ((f.untaggedCostsTotal || 0) > 0) rows.push([title, "Untagged costs", "", Number(f.untaggedCostsTotal.toFixed(2)), "", "", ""]);
rows.push([title, "Donations counted as profit", "", "", "", Number((f.unallocatedDonationsTotal || 0).toFixed(2)), ""]);
if ((f.untaggedCostsTotal || 0) > 0) rows.push([title, "Untagged costs", "", Number(f.untaggedCostsTotal.toFixed(2)), "", "", "", "", "", ""]);
rows.push([title, "Donations counted as profit", "", "", "", "", "", "", "", Number((f.unallocatedDonationsTotal || 0).toFixed(2))]);
});
return {
title: 'Cashup Report', subtitle, kind: 'table', orientation: 'landscape',
chart: { title: 'Income by method, across all selected events', data: METHOD_KEYS.map(m => ({ label: METHOD_LABEL[m], value: incomeByMethod[m] || 0, displayValue: `R ${(incomeByMethod[m] || 0).toFixed(2)}` })) },
table: { columns: ["Event", "Method", "Income", "Costs from method", "Expected cash", "Actual", "Variance"], rows }
table: { columns: ["Event", "Method", "Income", "Costs from method", "Expected", "In bank", "On hand", "Pending", "Written off", "Unaccounted"], rows }
};
}
if (report === "financeReport") {
const rows: (string | number)[][] = [];
let sold = 0, paidByAll = 0, donationsProfit = 0, costsTotal = 0, netProfitTotal = 0;
let sold = 0, paidByAll = 0, donationsProfit = 0, costsTotal = 0, writeOffsTotal = 0, netProfitTotal = 0;
const paidByMethod: Record<string, number> = {};
Object.keys(financialsByEvent).forEach(evId => {
const f = financialsByEvent[evId];
@@ -1206,6 +1209,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
METHOD_KEYS.forEach(m => { paidByMethod[m] = (paidByMethod[m] || 0) + (f.paymentsByMethod?.[m] || 0); });
donationsProfit += f.unallocatedDonationsTotal || 0;
costsTotal += f.totalCosts || 0;
writeOffsTotal += f.totalWriteOffs || 0;
netProfitTotal += f.netProfit || 0;
// "Sales" is ticket-price revenue for orders that reached 'paid' status — whether that
// order was funded directly or via an assigned donation, its full price is already
@@ -1221,10 +1225,11 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
rows.push([title, "Cashup comparison", "", ""]);
METHOD_KEYS.forEach(m => {
const r = f.reconciled?.byMethod?.[m];
rows.push([title, "", `${METHOD_LABEL[m]} — expected / actual / variance`, `${money2(f.expectedCashByMethod?.[m])} / ${r?.actual != null ? money2(r.actual) : "—"} / ${r?.variance != null ? money2(r.variance) : "—"}`]);
rows.push([title, "", `${METHOD_LABEL[m]} — expected / actual / unaccounted`, `${money2(f.expectedCashByMethod?.[m])} / ${r?.actual != null ? money2(r.actual) : "—"} / ${r?.unaccounted != null ? money2(r.unaccounted) : "—"}`]);
});
rows.push([title, "Costs", "", ""]);
(f.costs || []).forEach((c) => rows.push([title, "", `${c.label}${c.paidFromMethod ? ` (via ${METHOD_LABEL[c.paidFromMethod]})` : ""}`, Number((-(c.total ?? c.amount)).toFixed(2))]));
METHOD_KEYS.forEach(m => (f.reconciled?.byMethod?.[m]?.writeOffs || []).forEach((w) => rows.push([title, "", `${WRITE_OFF_LABEL[w.category] || w.category} (${METHOD_LABEL[m]})${w.reason ? ` — ${w.reason}` : ""}`, -Number(w.amount.toFixed(2))])));
rows.push([title, "", "Donations counted as profit", Number((f.unallocatedDonationsTotal || 0).toFixed(2))]);
rows.push([title, "", "Net profit", Number((f.netProfit || 0).toFixed(2))]);
});
@@ -1235,6 +1240,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
{ label: 'Paid by (all methods)', value: `R ${paidByAll.toFixed(2)}`, tone: 'blue' },
{ label: 'Donations counted as profit', value: `R ${donationsProfit.toFixed(2)}`, tone: 'rose' },
{ label: 'Total costs', value: `R ${costsTotal.toFixed(2)}`, tone: 'amber' },
{ label: 'Bank & card charges', value: `R ${writeOffsTotal.toFixed(2)}`, tone: 'amber' },
{ label: 'Net profit', value: `R ${netProfitTotal.toFixed(2)}`, tone: 'violet' },
],
chart: { title: 'Paid by, across all selected events', data: METHOD_KEYS.map(m => ({ label: METHOD_LABEL[m], value: paidByMethod[m] || 0, displayValue: `R ${(paidByMethod[m] || 0).toFixed(2)}` })) },
@@ -1247,23 +1253,25 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
const f = financialsByEvent[evId];
acc.revenue += f?.effectiveTotalRevenue || 0;
acc.costs += f?.totalCosts || 0;
acc.charges += f?.totalWriteOffs || 0;
acc.profit += f?.netProfit || 0;
return acc;
}, { revenue: 0, costs: 0, profit: 0 });
}, { revenue: 0, costs: 0, charges: 0, profit: 0 });
const rows: (string | number)[][] = evIds.map(evId => {
const f = financialsByEvent[evId];
const ev = filteredEvents.find(e => e.id === evId);
return [ev?.title || evId, Number((f?.effectiveTotalRevenue || 0).toFixed(2)), Number((f?.totalCosts || 0).toFixed(2)), Number((f?.netProfit || 0).toFixed(2))];
return [ev?.title || evId, Number((f?.effectiveTotalRevenue || 0).toFixed(2)), Number((f?.totalCosts || 0).toFixed(2)), Number((f?.totalWriteOffs || 0).toFixed(2)), Number((f?.netProfit || 0).toFixed(2))];
});
return {
title: 'Profit Report', subtitle, kind: 'table', orientation: 'portrait',
stats: [
{ label: 'Revenue', value: `R ${totals.revenue.toFixed(2)}`, tone: 'green' },
{ label: 'Costs', value: `R ${totals.costs.toFixed(2)}`, tone: 'amber' },
{ label: 'Bank & card charges', value: `R ${totals.charges.toFixed(2)}`, tone: 'amber' },
{ label: 'Net profit', value: `R ${totals.profit.toFixed(2)}`, tone: 'violet' },
],
chart: evIds.length > 1 ? { title: 'Net profit by event', data: evIds.map(evId => ({ label: filteredEvents.find(e => e.id === evId)?.title || evId, value: financialsByEvent[evId]?.netProfit || 0, displayValue: `R ${(financialsByEvent[evId]?.netProfit || 0).toFixed(2)}` })) } : undefined,
table: { columns: ["Event", "Revenue", "Costs", "Net profit"], rows }
table: { columns: ["Event", "Revenue", "Costs", "Bank & card charges", "Net profit"], rows }
};
}
if (report === "cashupAudit") {
@@ -1455,7 +1463,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
report={report} setReport={(r: ReportKey) => { setReport(r); setReady(false); }}
onViewReport={() => { setPopupOpen(true); onView(); }}
busy={busy}
onBack={onBack}
backHref={backHref}
/>
{popupOpen && (