"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useParams } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; import { apiFetch } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import type { EventCost, EventCostType, EventFinancials, CashupMethod, CashupWriteOffCategory, ReconciledByMethod, Event } from "@/types"; import { Wallet, DollarSign, ClipboardCheck, FileBarChart } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; const METHOD_LABELS: Record = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" }; const METHODS: CashupMethod[] = ["cash", "card", "eft", "other"]; const ZAR_DENOMINATIONS = [200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1]; function money(n: number | null | undefined): string { return `R${Number(n || 0).toFixed(2)}`; } function denomLabel(v: number): string { return v >= 1 ? `R${v}` : `${Math.round(v * 100)}c`; } export default function EventCashupPage() { const params = useParams<{ id: string }>(); const eventId = params.id; const { token } = useAuth(); const [tab, setTab] = useState<"costs" | "reconciliation" | "report">("costs"); const [data, setData] = useState(null); const [eventOptions, setEventOptions] = useState<{ id: string; name: string }[]>([]); const [loading, setLoading] = useState(false); const [error, setError] = useDismissingState(null); const [busy, setBusy] = useState(false); const isClosed = data?.event?.cashupStatus === "closed"; const load = useCallback(async () => { if (!token || !eventId) return; setLoading(true); setError(null); try { const [financials, event] = await Promise.all([ apiFetch(`/api/cashups/event/${eventId}`, { authToken: token }), apiFetch(`/api/events/${eventId}`, { authToken: token }) ]); setData(financials); setEventOptions((event.eventOptions || []).map((o) => ({ id: o.id, name: o.name }))); } catch (e) { setError(errorMessage(e) || "Failed to load cashup data"); } finally { setLoading(false); } }, [token, eventId, setError]); useEffect(() => { load(); }, [load]); return (

{data?.event?.title || "Event"} — Cashup

{isClosed ? "Closed" : "Open"}
{error &&
{error}
}
{loading &&
Loading…
} {!loading && data && tab === "costs" && ( )} {!loading && data && tab === "reconciliation" && ( setTab("report")} /> )} {!loading && data && tab === "report" && ( )}
); } // ─── Costs tab ───────────────────────────────────────────────────────────── function CostsTab({ eventId, token, costs, eventOptions, isClosed, onChanged }: { eventId: string; token: string; costs: EventCost[]; eventOptions: { id: string; name: string }[]; isClosed: boolean; onChanged: () => void; }) { const [editingId, setEditingId] = useState(null); const [label, setLabel] = useState(""); const [costType, setCostType] = useState("once_off"); const [amount, setAmount] = useState(""); const [eventOptionId, setEventOptionId] = useState(""); const [paidFromMethod, setPaidFromMethod] = useState<"" | CashupMethod>(""); const [notes, setNotes] = useState(""); const [saving, setSaving] = useState(false); const [err, setErr] = useState(null); const startNew = () => { setEditingId("new"); setLabel(""); setCostType("once_off"); setAmount(""); setEventOptionId(""); setPaidFromMethod(""); setNotes(""); setErr(null); }; const startEdit = (c: EventCost) => { setEditingId(c.id); setLabel(c.label); setCostType(c.costType); setAmount(String(c.amount)); setEventOptionId(c.eventOptionId || ""); setPaidFromMethod(c.paidFromMethod || ""); setNotes(c.notes || ""); setErr(null); }; const cancel = () => setEditingId(null); const save = async () => { if (!label.trim()) { setErr("Label is required"); return; } if (!amount || isNaN(parseFloat(amount))) { setErr("Amount is required"); return; } if (costType === "per_item" && !eventOptionId) { setErr("Select a ticket type for per-item costs"); return; } setSaving(true); setErr(null); try { const body = { label: label.trim(), costType, amount: parseFloat(amount), eventOptionId: costType === "per_item" ? eventOptionId : null, paidFromMethod: paidFromMethod || null, notes: notes || null }; if (editingId === "new") { await apiFetch(`/api/events/${eventId}/costs`, { method: "POST", authToken: token, body }); } else { await apiFetch(`/api/costs/${editingId}`, { method: "PUT", authToken: token, body }); } setEditingId(null); onChanged(); } catch (e) { setErr(errorMessage(e) || "Failed to save cost"); } finally { setSaving(false); } }; const remove = async (id: string) => { if (!confirm("Delete this cost?")) return; try { await apiFetch(`/api/costs/${id}`, { method: "DELETE", authToken: token }); onChanged(); } catch (e) { alert(errorMessage(e) || "Failed to delete cost"); } }; const totalCosts = costs.reduce((sum, c) => sum + (c.total ?? c.amount), 0); return (
Event costs
{!isClosed && editingId === null && ( )}
{isClosed &&
This event is closed — costs can't be changed until it's reopened.
}
{!isClosed && } {costs.map(c => ( {!isClosed && ( )} ))} {costs.length === 0 && ( )} {costs.length > 0 && ( {!isClosed && )}
Label Type Ticket type Paid from Amount Total
{c.label} {c.costType === "once_off" ? "Once-off" : "Per item"} {c.eventOption?.name || "—"} {c.paidFromMethod || "—"} {money(c.amount)} {money(c.total ?? c.amount)}
No costs added yet.
Total costs {money(totalCosts)}}
{editingId !== null && (
{err &&
{err}
}
setLabel(e.target.value)} placeholder="e.g. Venue hire" />
{costType === "per_item" && (
)}
setAmount(e.target.value)} />

If this was paid out of the door takings (e.g. cash to a vendor), tag it so the Cashup report deducts it from that method's expected amount.

setNotes(e.target.value)} />
)}
); } // ─── Reconciliation tab ───────────────────────────────────────────────────── type PersonDenom = { value: number; count: number }; type MethodTotals = { total: number; count: number }; type CashMethodTotals = MethodTotals & { actual: number | null; variance: number | null; denominations: PersonDenom[]; enteredBy: { id: string; name: string } | null; countUpdatedAt: string | null; notes: string | null; }; type AccountabilityRow = { userId: string | null; name: string; email: string | null; cash: CashMethodTotals; card: MethodTotals; eft: MethodTotals; other: MethodTotals; }; type AccountabilityResponse = { rows: AccountabilityRow[]; cashActualTotal: number | null; cashDenominations: PersonDenom[] }; // Payment accountability, per staff member who recorded the payment, broken down by method — // separate from the overall cash reconciliation above, which only totals the float without // saying who's responsible for it. For cash, staff can optionally enter what was physically // counted for each person, any time (not required to close the event); the event's cash actual // is the live sum of these per-person counts, shown here and used by the reconciliation table. function CashByUserSection({ eventId, token, onCashSummaryChange }: { eventId: string; token: string; onCashSummaryChange?: (summary: { actualTotal: number | null; denominations: PersonDenom[] }) => void; }) { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [open, setOpen] = useState(true); const [editingUserId, setEditingUserId] = useState(null); const load = useCallback(() => { if (!token || !eventId) return; setLoading(true); apiFetch(`/api/cashups/event/${eventId}/cash-by-user`, { authToken: token }) .then(r => { setData(r); onCashSummaryChange?.({ actualTotal: r?.cashActualTotal ?? null, denominations: r?.cashDenominations || [] }); }) .catch(() => setData({ rows: [], cashActualTotal: null, cashDenominations: [] })) .finally(() => setLoading(false)); }, [eventId, token, onCashSummaryChange]); // onCashSummaryChange is a state setter in the parent, so this only reruns when the event/token change. useEffect(load, [load]); const rows = data?.rows || []; const sumOf = (m: "cash" | "card" | "eft" | "other", key: "total" | "count") => rows.reduce((s, r) => s + (r[m][key] || 0), 0); const totalCash = sumOf("cash", "total"); const totalCashActual = rows.reduce((s, r) => s + (r.cash.actual || 0), 0); const grandTotal = rows.reduce((s, r) => s + r.cash.total + r.card.total + r.eft.total + r.other.total, 0); return (
{open && ( loading ? (
Loading…
) : rows.length === 0 ? (
No payments recorded for this event.
) : (
{rows.map(r => ( {r.userId && editingUserId === r.userId && ( )} ))}
Staff member Cash Card EFT Other Total
Expected Actual Variance
{r.name}
{r.email &&
{r.email}
}
{money(r.cash.total)} {r.cash.actual != null ? money(r.cash.actual) : —} {r.cash.variance != null ? ( Math.abs(r.cash.variance) > 0.01 ? ( {money(r.cash.variance)} ) : Matches ) : —} {r.card.total > 0 ? money(r.card.total) : —} {r.eft.total > 0 ? money(r.eft.total) : —} {r.other.total > 0 ? money(r.other.total) : —} {money(r.cash.total + r.card.total + r.eft.total + r.other.total)} {r.userId && ( )}
{ setEditingUserId(null); load(); }} onCancel={() => setEditingUserId(null)} />
Total {money(totalCash)} {money(totalCashActual)} {money(totalCashActual - totalCash)} {money(sumOf("card", "total"))} {money(sumOf("eft", "total"))} {money(sumOf("other", "total"))} {money(grandTotal)}
) )}
); } // Denomination entry for one person's actual cash count — pick a denomination from the dropdown, // enter how many, add it to the list. Repeatable, editable, removable before saving. function PersonCashCountEditor({ eventId, token, userId, initialDenominations, initialNotes, enteredBy, countUpdatedAt, onSaved, onCancel }: { eventId: string; token: string; userId: string; initialDenominations: PersonDenom[]; initialNotes: string | null; enteredBy: { id: string; name: string } | null; countUpdatedAt: string | null; onSaved: () => void; onCancel: () => void; }) { const initialCounts: Record = {}; for (const d of initialDenominations) initialCounts[d.value] = String(d.count); const [counts, setCounts] = useState>(initialCounts); const [notes, setNotes] = useState(initialNotes || ""); const [saving, setSaving] = useState(false); const [err, setErr] = useState(null); const setCount = (value: number, v: string) => setCounts(prev => ({ ...prev, [value]: v })); const lines: PersonDenom[] = ZAR_DENOMINATIONS .map(value => ({ value, count: parseInt(counts[value] || "0", 10) || 0 })) .filter(d => d.count > 0); const runningTotal = lines.reduce((s, l) => s + l.value * l.count, 0); const save = async () => { setSaving(true); setErr(null); try { await apiFetch(`/api/cashups/event/${eventId}/person-cash/${userId}`, { method: "PUT", authToken: token, body: { denominations: lines, notes: notes || null } }); onSaved(); } catch (e) { setErr(errorMessage(e) || "Failed to save count"); } finally { setSaving(false); } }; return (
{err &&
{err}
} {enteredBy && countUpdatedAt && (
Last entered by {enteredBy.name} on {new Date(countUpdatedAt).toLocaleString()}
)}
{ZAR_DENOMINATIONS.map(v => (
{denomLabel(v)} × setCount(v, e.target.value)} />
))}
Total: {money(runningTotal)}
setNotes(e.target.value)} />
); } // ─── Report tab ────────────────────────────────────────────────────────── // A clean, read-only summary of the cashup — opened automatically once the event is closed, so // staff land straight on "here's what happened" instead of the editable Reconciliation tab. function ReportTab({ eventId, token, data, isClosed }: { eventId: string; token: string; data: EventFinancials; isClosed: boolean; }) { const reconciled = data.reconciled; const latestClose = data.history.find(h => h.action === "closed" || h.action === "quick_closed"); return (
Cashup report
{isClosed ? "Closed" : "Open (live preview)"}
{latestClose ? (
{latestClose.action === "closed" ? "Closed (full cashup)" : "Quick closed"} by {latestClose.performedBy?.name || "Unknown"} on {new Date(latestClose.createdAt).toLocaleString()}
) : (
This event hasn't been closed yet — figures below are a live preview and will change as more payments come in.
)}
Where the money ended up
{METHODS.map(m => { const r = reconciled?.byMethod?.[m]; const cell = (v: number | null | undefined) => (v != null && Math.abs(v) >= 0.005 ? money(v) : "—"); return ( ); })}
Method Income Expected In bank On hand Pending Written off Unaccounted
{METHOD_LABELS[m]} {money(data.paymentsByMethod[m])} {money(data.expectedCashByMethod[m])} {cell(r?.bank)} {cell(r?.onHand)} {cell(r?.pendingOutstanding)} {cell(r?.writeOffTotal)} = 0.005 ? "text-rose-700 font-medium" : "")}> {r?.unaccounted != null ? (Math.abs(r.unaccounted) >= 0.005 ? money(r.unaccounted) : "R0.00") : "—"}
{!reconciled &&
Not settled yet. Columns fill in once the event is closed with a cashup.
}
{(() => { const writeOffs = METHODS.flatMap(m => (reconciled?.byMethod?.[m]?.writeOffs || []).map(w => ({ ...w, method: m }))); return writeOffs.length > 0 ? (
Write-offs
{writeOffs.map((w, i) => ( ))}
Method Type Reason Amount
{METHOD_LABELS[w.method]} {WRITE_OFF_LABELS[w.category]}{w.afterClose ? " (after closing)" : ""} {w.reason || "—"} {money(w.amount)}
) : null; })()} {reconciled?.byMethod?.cash?.denominations?.length ? (
Cash denomination count
{reconciled.byMethod.cash.denominations.map((d) => ( ))}
{denomLabel(d.value)}× {d.count}{money(d.value * d.count)}
) : null} {data.costs.length > 0 && (
Costs
{data.costs.map((c) => ( ))}
Label Paid from Total
{c.label} {c.paidFromMethod || "—"} {money(c.total ?? c.amount)}
)}
); } // ─── Settlement ──────────────────────────────────────────────────────────── // For each method, where did the expected money end up: in the bank, still on hand (cash), // or pending (on the card report / a POP we haven't seen in the bank yet) — and what was // written off (card fees, bank charges, a shortfall). Mirrors settleLine in // backend/src/utils/cashupUtils.js, which has the final say when the event is closed. type WriteOffInput = { category: CashupWriteOffCategory; amount: string; reason: string }; type SettlementInput = { bankAmount: string; onHandAmount: string; pendingAmount: string; pendingReference: string; writeOffs: WriteOffInput[]; notes: string }; const WRITE_OFF_LABELS: Record = { card_fees: "Card / online fees", bank_charges: "Bank charges", cash_shortfall: "Cash shortfall", other: "Other", }; const WRITE_OFF_CATEGORIES = Object.keys(WRITE_OFF_LABELS) as CashupWriteOffCategory[]; const DEFAULT_WRITE_OFF: Record = { cash: "cash_shortfall", card: "card_fees", eft: "bank_charges", other: "other" }; const BANK_HELP: Record = { cash: "What reached the bank, after any deposit fee", card: "Settled into the bank account", eft: "Showing on the bank statement", other: "Received in the bank", }; const PENDING_HELP: Record = { cash: "", card: "On the card machine / Yoco report, not in the bank yet", eft: "Proof of payment received, not in the bank yet", other: "Expected but not in the bank yet", }; const PENDING_REFERENCE_PLACEHOLDER: Record = { cash: "", card: "Report or batch reference", eft: "POP reference", other: "Reference" }; const round2 = (n: number) => Math.round(n * 100) / 100; const emptySettlement = (): SettlementInput => ({ bankAmount: "", onHandAmount: "", pendingAmount: "", pendingReference: "", writeOffs: [], notes: "" }); const amountText = (v: string | number | null | undefined) => (v === null || v === undefined ? "" : String(v)); function settle(method: CashupMethod, expected: number, counted: number | null, input: SettlementInput) { const num = (v: string) => (v.trim() === "" || isNaN(Number(v)) ? null : Number(v)); const bank = num(input.bankAmount); const writeOffTotal = round2(input.writeOffs.reduce((s, w) => s + (num(w.amount) || 0), 0)); // A deposit fee comes out of the counted cash that was banked. const depositFees = round2(input.writeOffs.filter(w => w.category === "bank_charges").reduce((s, w) => s + (num(w.amount) || 0), 0)); const onHand = method === "cash" ? (counted !== null ? round2(counted - (bank || 0) - depositFees) : num(input.onHandAmount)) : null; const pending = method === "cash" ? null : num(input.pendingAmount); const entered = [bank, onHand, pending].some(v => v !== null) || input.writeOffs.some(w => num(w.amount) !== null); const actual = entered ? round2((bank || 0) + (onHand || 0) + (pending || 0)) : null; return { bank, onHand, pending, writeOffTotal, actual, unaccounted: actual === null ? null : round2(expected - actual - writeOffTotal) }; } function UnaccountedBadge({ unaccounted }: { unaccounted: number | null }) { if (unaccounted === null) return Not settled yet; if (Math.abs(unaccounted) < 0.005) return All accounted for; return ( {unaccounted > 0 ? `${money(unaccounted)} unaccounted` : `${money(-unaccounted)} more than expected`} ); } function SettlementCard({ method, data, counted, input, onChange }: { method: CashupMethod; data: EventFinancials; counted: number | null; input: SettlementInput; onChange: (next: SettlementInput) => void; }) { const expected = data.expectedCashByMethod[method]; const s = settle(method, expected, counted, input); const set = (field: keyof SettlementInput, value: string) => onChange({ ...input, [field]: value }); const setWriteOff = (i: number, patch: Partial) => onChange({ ...input, writeOffs: input.writeOffs.map((w, j) => (j === i ? { ...w, ...patch } : w)) }); const addWriteOff = () => onChange({ ...input, writeOffs: [...input.writeOffs, { category: DEFAULT_WRITE_OFF[method], amount: "", reason: "" }] }); const removeWriteOff = (i: number) => onChange({ ...input, writeOffs: input.writeOffs.filter((_, j) => j !== i) }); return (
{METHOD_LABELS[method]}
Expected {money(expected)} {data.costsByMethod[method] > 0 && <> ({money(data.paymentsByMethod[method])} taken, less {money(data.costsByMethod[method])} paid out)}
set("bankAmount", e.target.value)} />

{BANK_HELP[method]}

{method === "cash" ? (
{counted !== null ? (
{money(s.onHand)}
) : ( set("onHandAmount", e.target.value)} /> )}

{counted !== null ? `Counted ${money(counted)}, less what was deposited and any deposit fee` : "Not deposited yet. Enter staff cash counts below to work this out."}

) : (
set("pendingAmount", e.target.value)} /> set("pendingReference", e.target.value)} />

{PENDING_HELP[method]}

)}
Write-offs
{input.writeOffs.map((w, i) => (
setWriteOff(i, { amount: e.target.value })} /> setWriteOff(i, { reason: e.target.value })} />
))}
set("notes", e.target.value)} />
); } // A closed method's settlement, read-only, with a way to settle pending money that has // since arrived (or never will) without reopening the event. function SettledCard({ method, r, token, onChanged }: { method: CashupMethod; r: ReconciledByMethod; token: string; onChanged: () => void }) { return (
{METHOD_LABELS[method]}
Expected {money(r.expected)}
In bank
{r.bank !== null ? money(r.bank) : "—"}
{method === "cash" ?
On hand
{r.onHand !== null ? money(r.onHand) : "—"}
:
Pending
{r.pendingOutstanding > 0 ? money(r.pendingOutstanding) : "—"}
}
Written off
{r.writeOffTotal > 0 ? money(r.writeOffTotal) : "—"}
Actual
{r.actual !== null ? money(r.actual) : "—"}
{r.writeOffs.length > 0 && (
    {r.writeOffs.map((w, i) => (
  • {WRITE_OFF_LABELS[w.category]} {money(w.amount)}{w.reason ? ` — ${w.reason}` : ""}{w.afterClose ? " (after closing)" : ""}
  • ))}
)} {(r.pending || 0) > 0 && ( )} {r.notes &&
Notes: {r.notes}
}
); } function PendingSettler({ method, r, token, onChanged }: { method: CashupMethod; r: ReconciledByMethod; token: string; onChanged: () => void }) { const [mode, setMode] = useState<"received" | "written_off" | null>(null); const [amount, setAmount] = useState(""); const [category, setCategory] = useState(DEFAULT_WRITE_OFF[method]); const [notes, setNotes] = useState(""); const [saving, setSaving] = useState(false); const [err, setErr] = useState(null); const start = (m: "received" | "written_off") => { setMode(m); setAmount(String(r.pendingOutstanding)); setNotes(""); setErr(null); }; const save = async () => { if (!r.lineId || !mode) return; setSaving(true); setErr(null); try { await apiFetch(`/api/cashups/lines/${r.lineId}/pending`, { method: "POST", authToken: token, body: { outcome: mode, amount: parseFloat(amount), category, notes: notes || null } }); setMode(null); onChanged(); } catch (e) { setErr(errorMessage(e) || "Failed to save"); } finally { setSaving(false); } }; return (
Pending {money(r.pending)}{r.pendingReference ? ` (${r.pendingReference})` : ""} {r.pendingOutstanding > 0 ? <> — {money(r.pendingOutstanding)} still outstanding : " — all settled"} {r.pendingOutstanding > 0 && mode === null && ( )}
{r.pendingResolutions.length > 0 && (
    {r.pendingResolutions.map(p => (
  • {p.outcome === "received" ? "Received in bank" : `Written off (${WRITE_OFF_LABELS[p.category || "other"]})`} {money(p.amount)} {" — "}{p.performedBy?.name || "Unknown"}, {new Date(p.createdAt).toLocaleDateString()}{p.notes ? ` — ${p.notes}` : ""}
  • ))}
)} {mode !== null && (
setAmount(e.target.value)} /> {mode === "written_off" && ( )} setNotes(e.target.value)} /> {err && {err}}
)}
); } function ProfitSummary({ data }: { data: EventFinancials }) { return (
Donations counted as profit
{money(data.unallocatedDonationsTotal)}
Total costs
{money(data.totalCosts)}
Bank & card charges
{money(data.totalWriteOffs)}
Pending (outstanding)
{money(data.pendingOutstandingTotal)}
Net profit
{money(data.netProfit)}
); } function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onChanged, onClosed }: { eventId: string; token: string; data: EventFinancials; busy: boolean; setBusy: (b: boolean) => void; setError: (e: string | null) => void; onChanged: () => void; onClosed: () => void; }) { const isClosed = data.event.cashupStatus === "closed"; const draftLines = data.event.cashupDraft?.lines; const initialLines: Record = useMemo(() => { const base: Record = { cash: emptySettlement(), card: emptySettlement(), eft: emptySettlement(), other: emptySettlement() }; for (const l of draftLines || []) { if (!(l.method in base)) continue; base[l.method as CashupMethod] = { bankAmount: amountText(l.bankAmount), onHandAmount: amountText(l.onHandAmount), pendingAmount: amountText(l.pendingAmount), pendingReference: l.pendingReference || "", writeOffs: (l.writeOffs || []).map(w => ({ category: w.category, amount: amountText(w.amount), reason: w.reason || "" })), notes: l.notes || "", }; } return base; }, [draftLines]); const [lines, setLines] = useState>(initialLines); const [closeNotes, setCloseNotes] = useState(""); const [reopenNotes, setReopenNotes] = useState(""); // Counted cash is the live sum of every staff member's per-person count, reported up from // CashByUserSection below; when there is one, cash on hand is whatever wasn't deposited. const [cashSummary, setCashSummary] = useState<{ actualTotal: number | null; denominations: PersonDenom[] }>({ actualTotal: null, denominations: [] }); useEffect(() => { setLines(initialLines); }, [initialLines]); const setLine = (method: CashupMethod, next: SettlementInput) => setLines(prev => ({ ...prev, [method]: next })); // Methods with nothing expected and nothing entered are hidden to keep the screen short. const hasInput = (m: CashupMethod) => { const l = lines[m]; return l.bankAmount !== "" || l.onHandAmount !== "" || l.pendingAmount !== "" || l.writeOffs.length > 0; }; const shownMethods = METHODS.filter(m => Math.abs(data.expectedCashByMethod[m]) > 0.005 || hasInput(m) || (m === "cash" && cashSummary.actualTotal !== null)); const buildLinesPayload = () => METHODS.map(m => { const l = lines[m]; const amount = (v: string) => (v.trim() === "" ? null : parseFloat(v)); return { method: m, bankAmount: amount(l.bankAmount), onHandAmount: m === "cash" ? amount(l.onHandAmount) : null, pendingAmount: m === "cash" ? null : amount(l.pendingAmount), pendingReference: l.pendingReference || null, writeOffs: l.writeOffs.map(w => ({ category: w.category, amount: amount(w.amount), reason: w.reason || null })), notes: l.notes || null, }; }); const saveDraft = async () => { setBusy(true); setError(null); try { await apiFetch(`/api/cashups/event/${eventId}/draft`, { method: "PUT", authToken: token, body: { lines: buildLinesPayload() } }); onChanged(); } catch (e) { setError(errorMessage(e) || "Failed to save draft"); } finally { setBusy(false); } }; const closeWithCashup = async () => { const open = shownMethods .map(m => ({ m, s: settle(m, data.expectedCashByMethod[m], m === "cash" ? cashSummary.actualTotal : null, lines[m]) })) .filter(({ s }) => s.unaccounted === null || Math.abs(s.unaccounted) >= 0.005) .map(({ m, s }) => `${METHOD_LABELS[m]}: ${s.unaccounted === null ? "not settled" : money(s.unaccounted)}`); const warning = open.length > 0 ? `\n\nNot everything is accounted for:\n${open.join("\n")}\n\nThis will be recorded as a variance and comes off profit.` : ""; if (!confirm(`Close this event with this cashup? Unallocated donations will be counted as profit and the event will be locked until it's reopened.${warning}`)) return; setBusy(true); setError(null); try { await apiFetch(`/api/cashups/event/${eventId}/close`, { method: "POST", authToken: token, body: { lines: buildLinesPayload(), notes: closeNotes || null } }); onChanged(); onClosed(); } catch (e) { setError(errorMessage(e) || "Failed to close event"); } finally { setBusy(false); } }; const quickClose = async () => { if (!confirm("Quick close this event without a cashup? System totals will be accepted as-is, unallocated donations will be counted as profit, and the event will be fully locked until it's reopened.")) return; setBusy(true); setError(null); try { await apiFetch(`/api/cashups/event/${eventId}/close`, { method: "POST", authToken: token, body: { notes: closeNotes || null } }); onChanged(); onClosed(); } catch (e) { setError(errorMessage(e) || "Failed to close event"); } finally { setBusy(false); } }; const reopen = async () => { if (!confirm("Reopen this event? Registrations, payments, refunds and donations will be allowed again.")) return; setBusy(true); setError(null); try { await apiFetch(`/api/cashups/event/${eventId}/reopen`, { method: "POST", authToken: token, body: { notes: reopenNotes || null } }); onChanged(); } catch (e) { setError(errorMessage(e) || "Failed to reopen event"); } finally { setBusy(false); } }; const reconciled = data.reconciled; const settledMethods = METHODS.filter(m => { const r = reconciled?.byMethod?.[m]; return r && (Math.abs(r.expected) > 0.005 || r.actual !== null || r.writeOffTotal > 0); }); return (
Where did the money end up?
{isClosed ? "As recorded when the event was closed. Pending money can be marked received or written off without reopening." : "For each payment method, say how much is in the bank, still on hand or pending, and write off anything lost to fees, charges or shortfalls."}
{isClosed ? ( reconciled?.action === "closed" && settledMethods.length > 0 ? ( settledMethods.map(m => ) ) : (
This event was quick closed, so no settlement was recorded.
) ) : shownMethods.length === 0 ? (
No payments to settle for this event.
) : ( shownMethods.map(m => ( setLine(m, next)} /> )) )}
Cash denomination count
{(() => { const denoms = isClosed ? (reconciled?.byMethod?.cash?.denominations || []) : cashSummary.denominations; return denoms.length > 0 ? ( {denoms.map((d: PersonDenom & { id?: string }) => ( ))}
{denomLabel(d.value)}× {d.count}{money(d.value * d.count)}
) : (
{isClosed ? "No denomination breakdown recorded for this cashup." : "No per-staff-member cash counts entered yet — see “Payment accountability by staff member” above."}
); })()}
{!isClosed && (
setCloseNotes(e.target.value)} />
)} {isClosed && (
setReopenNotes(e.target.value)} />
)}
History
{data.history.length === 0 &&
No close/reopen actions yet.
}
    {data.history.map(h => (
  • {h.action === "closed" ? "Closed (full cashup)" : h.action === "quick_closed" ? "Quick closed" : "Reopened"} {" — "}{h.performedBy?.name || "Unknown"} — {new Date(h.createdAt).toLocaleString()} {(h.action === "closed" || h.action === "quick_closed") && ( Donations to profit {money(h.unallocatedDonationsTotal)} · Costs {money(h.totalCosts)} )}
  • ))}
); }