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
@@ -0,0 +1,53 @@
-- CreateEnum
CREATE TYPE "CashupWriteOffCategory" AS ENUM ('card_fees', 'bank_charges', 'cash_shortfall', 'other');
-- AlterTable
ALTER TABLE "EventCashupLine" ADD COLUMN "bankAmount" DOUBLE PRECISION,
ADD COLUMN "onHandAmount" DOUBLE PRECISION,
ADD COLUMN "pendingAmount" DOUBLE PRECISION,
ADD COLUMN "pendingReference" TEXT,
ADD COLUMN "writeOffTotal" DOUBLE PRECISION NOT NULL DEFAULT 0;
-- CreateTable
CREATE TABLE "EventCashupWriteOff" (
"id" TEXT NOT NULL,
"lineId" TEXT NOT NULL,
"category" "CashupWriteOffCategory" NOT NULL,
"amount" DOUBLE PRECISION NOT NULL,
"reason" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "EventCashupWriteOff_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventCashupPendingResolution" (
"id" TEXT NOT NULL,
"lineId" TEXT NOT NULL,
"outcome" TEXT NOT NULL,
"amount" DOUBLE PRECISION NOT NULL,
"category" "CashupWriteOffCategory",
"notes" TEXT,
"performedById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "EventCashupPendingResolution_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "EventCashupWriteOff_lineId_idx" ON "EventCashupWriteOff"("lineId");
-- CreateIndex
CREATE INDEX "EventCashupPendingResolution_lineId_idx" ON "EventCashupPendingResolution"("lineId");
-- CreateIndex
CREATE INDEX "EventCashupPendingResolution_performedById_idx" ON "EventCashupPendingResolution"("performedById");
-- AddForeignKey
ALTER TABLE "EventCashupWriteOff" ADD CONSTRAINT "EventCashupWriteOff_lineId_fkey" FOREIGN KEY ("lineId") REFERENCES "EventCashupLine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashupPendingResolution" ADD CONSTRAINT "EventCashupPendingResolution_lineId_fkey" FOREIGN KEY ("lineId") REFERENCES "EventCashupLine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashupPendingResolution" ADD CONSTRAINT "EventCashupPendingResolution_performedById_fkey" FOREIGN KEY ("performedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+58 -9
View File
@@ -88,6 +88,7 @@ model User {
eventsClosed Event[] @relation("EventClosedBy")
eventsReopened Event[] @relation("EventReopenedBy")
cashupsPerformed EventCashup[]
pendingResolved EventCashupPendingResolution[] @relation("PendingResolutionBy")
notifyForEvents Event[] @relation("EventNotifyRecipients")
personCashCountsFor EventCashupPersonCount[] @relation("EventCashupPersonCountFor")
@@ -708,20 +709,68 @@ model EventCashup {
@@index([eventId, createdAt])
}
// Where one method's expected takings ended up. actualAmount = bank + on hand + pending
// (money held or on its way); write-offs explain money that's gone (fees, charges,
// shortfalls). expected - actual - writeOffTotal is what's still unaccounted for.
model EventCashupLine {
id String @id @default(uuid())
cashupId String
cashup EventCashup @relation(fields: [cashupId], references: [id], onDelete: Cascade)
method String
expectedAmount Float @default(0)
actualAmount Float?
variance Float?
notes String?
denominations EventCashupDenomination[]
id String @id @default(uuid())
cashupId String
cashup EventCashup @relation(fields: [cashupId], references: [id], onDelete: Cascade)
method String
expectedAmount Float @default(0)
actualAmount Float?
variance Float?
notes String?
bankAmount Float?
onHandAmount Float?
pendingAmount Float?
// Card/Yoco report or POP reference for the pending amount.
pendingReference String?
writeOffTotal Float @default(0)
denominations EventCashupDenomination[]
writeOffs EventCashupWriteOff[]
pendingResolutions EventCashupPendingResolution[]
@@index([cashupId])
}
enum CashupWriteOffCategory {
card_fees
bank_charges
cash_shortfall
other
}
model EventCashupWriteOff {
id String @id @default(uuid())
lineId String
line EventCashupLine @relation(fields: [lineId], references: [id], onDelete: Cascade)
category CashupWriteOffCategory
amount Float
reason String?
createdAt DateTime @default(now())
@@index([lineId])
}
// Pending money settled after the event was closed: it reached the bank ('received') or
// never will ('written_off'). Append-only, like EventCashup — the line itself is never edited.
model EventCashupPendingResolution {
id String @id @default(uuid())
lineId String
line EventCashupLine @relation(fields: [lineId], references: [id], onDelete: Cascade)
outcome String // 'received' | 'written_off'
amount Float
category CashupWriteOffCategory?
notes String?
performedById String?
performedBy User? @relation("PendingResolutionBy", fields: [performedById], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
@@index([lineId])
@@index([performedById])
}
model EventCashupDenomination {
id String @id @default(uuid())
lineId String
@@ -1,7 +1,20 @@
const prisma = require('../config/db');
const { v4: uuidv4 } = require('uuid');
const { safeErrorMessage } = require('../utils/errorUtils');
const { ALL_METHODS, assertEventOpen, computeEventFinancials, computeAccountabilityByUser, computeEventCashActualFromPersonCounts, savePersonCashCount } = require('../utils/cashupUtils');
const { ALL_METHODS, WRITE_OFF_CATEGORIES, PENDING_OUTCOMES, settleLine, applyPendingResolutions, assertEventOpen, computeEventFinancials, computeAccountabilityByUser, computeEventCashActualFromPersonCounts, savePersonCashCount } = require('../utils/cashupUtils');
// What the cashup screen sends per method: where the money ended up and what was written off.
function cleanDraftLine(l) {
return {
method: l.method,
bankAmount: l.bankAmount ?? null,
onHandAmount: l.onHandAmount ?? null,
pendingAmount: l.pendingAmount ?? null,
pendingReference: l.pendingReference || null,
writeOffs: (Array.isArray(l.writeOffs) ? l.writeOffs : []).map(w => ({ category: w.category, amount: w.amount ?? null, reason: w.reason || null })),
notes: l.notes || null
};
}
// @desc Cashup preview for an event: live expected/actual numbers, costs, donations-to-profit, and history
// @route GET /api/cashups/event/:eventId
@@ -66,7 +79,7 @@ const saveEventCashupDraft = async (req, res) => {
await prisma.event.update({
where: { id: eventId },
data: { cashupDraft: { lines: Array.isArray(lines) ? lines : [], notes: notes || null, savedAt: new Date().toISOString() } }
data: { cashupDraft: { lines: (Array.isArray(lines) ? lines : []).filter(l => l && ALL_METHODS.includes(l.method)).map(cleanDraftLine), notes: notes || null, savedAt: new Date().toISOString() } }
});
res.json({ message: 'Draft saved' });
@@ -88,40 +101,32 @@ const closeEvent = async (req, res) => {
const financials = await computeEventFinancials(eventId);
const isFullCashup = Array.isArray(lines) && lines.length > 0;
// Each method says where its expected money ended up (see settleLine). Cash is never a
// single event-wide figure: when staff counted it, the count is the cash there is, sourced
// here from the per-person counts rather than from whatever the frontend sent.
let cashupLines = [];
if (isFullCashup) {
const nonCashLines = lines
.filter(l => l && ALL_METHODS.includes(l.method) && l.method !== 'cash')
.map(l => {
const expected = financials.expectedCashByMethod[l.method] || 0;
const actual = l.actualAmount !== undefined && l.actualAmount !== null && l.actualAmount !== '' ? parseFloat(l.actualAmount) : null;
return {
id: uuidv4(),
method: l.method,
expectedAmount: expected,
actualAmount: actual,
variance: actual !== null ? actual - expected : null,
notes: l.notes || null
};
});
// Cash is never entered as a single event-wide figure — it's always the live sum of every
// staff member's per-person count (see computeEventCashActualFromPersonCounts), so it's
// always sourced here rather than from whatever (if anything) the frontend sent for it.
const cashLineInput = lines.find(l => l && l.method === 'cash');
const { actual: cashActual, denominations: cashDenominations } = await computeEventCashActualFromPersonCounts(eventId);
const cashExpected = financials.expectedCashByMethod.cash || 0;
const cashLine = {
id: uuidv4(),
method: 'cash',
expectedAmount: cashExpected,
actualAmount: cashActual,
variance: cashActual !== null ? cashActual - cashExpected : null,
notes: cashLineInput?.notes || null,
denominations: cashDenominations.length > 0 ? { create: cashDenominations } : undefined
};
cashupLines = [cashLine, ...nonCashLines];
const { actual: cashCounted, denominations: cashDenominations } = await computeEventCashActualFromPersonCounts(eventId);
cashupLines = ALL_METHODS.map(method => {
const input = lines.find(l => l && l.method === method) || {};
const expected = financials.expectedCashByMethod[method] || 0;
const settled = settleLine({ method, expected, counted: method === 'cash' ? cashCounted : null, input });
return {
id: uuidv4(),
method,
expectedAmount: expected,
actualAmount: settled.actual,
variance: settled.variance,
notes: input.notes || null,
bankAmount: settled.bankAmount,
onHandAmount: settled.onHandAmount,
pendingAmount: settled.pendingAmount,
pendingReference: settled.pendingReference,
writeOffTotal: settled.writeOffTotal,
writeOffs: settled.writeOffs.length > 0 ? { create: settled.writeOffs } : undefined,
denominations: method === 'cash' && cashDenominations.length > 0 ? { create: cashDenominations } : undefined
};
});
}
const totalActualRevenue = isFullCashup
@@ -142,7 +147,7 @@ const closeEvent = async (req, res) => {
performedById: req.user.id,
lines: { create: cashupLines }
},
include: { lines: { include: { denominations: true } }, performedBy: { select: { id: true, name: true, email: true } } }
include: { lines: { include: { denominations: true, writeOffs: true } }, performedBy: { select: { id: true, name: true, email: true } } }
});
await prisma.event.update({
@@ -185,9 +190,33 @@ const reopenEvent = async (req, res) => {
include: { performedBy: { select: { id: true, name: true, email: true } } }
});
// Start the next cashup from the last one, with pending money that has since been
// received or written off folded in, so nothing has to be typed in again.
const lastClose = await prisma.eventCashup.findFirst({
where: { eventId, action: { in: ['closed', 'quick_closed'] } },
orderBy: { createdAt: 'desc' },
include: { lines: { include: { writeOffs: true, pendingResolutions: true } } }
});
const cashupDraft = lastClose && lastClose.lines.length > 0 ? {
lines: lastClose.lines.map(l => {
const settled = applyPendingResolutions(l);
return cleanDraftLine({
method: l.method,
bankAmount: settled.bank,
onHandAmount: settled.onHand,
pendingAmount: settled.pendingOutstanding || null,
pendingReference: settled.pendingOutstanding ? settled.pendingReference : null,
writeOffs: settled.writeOffs,
notes: l.notes
});
}),
notes: null,
savedAt: new Date().toISOString()
} : undefined;
await prisma.event.update({
where: { id: eventId },
data: { cashupStatus: 'open', reopenedAt: new Date(), reopenedById: req.user.id }
data: { cashupStatus: 'open', reopenedAt: new Date(), reopenedById: req.user.id, ...(cashupDraft ? { cashupDraft } : {}) }
});
res.status(201).json(auditRow);
@@ -196,6 +225,66 @@ const reopenEvent = async (req, res) => {
}
};
// @desc Settle money that was pending when the event was closed (on the card report, or a
// POP we hadn't seen in the bank yet): it has now reached the bank, or it never will and
// is written off. Allowed while the event is closed — no reopen needed.
// @route POST /api/cashups/lines/:lineId/pending
// @access Private/Admin
const resolvePending = async (req, res) => {
try {
const { lineId } = req.params;
const { outcome, amount, category, notes } = req.body;
if (!PENDING_OUTCOMES.includes(outcome)) {
res.status(400);
throw new Error('Say whether the money was received or written off');
}
const value = Math.round(Number(amount) * 100) / 100;
if (!Number.isFinite(value) || value <= 0) {
res.status(400);
throw new Error('Enter an amount more than R0');
}
const resolution = await prisma.$transaction(async (tx) => {
// Lock the line so two people settling at once can't settle more than is pending.
await tx.$executeRaw`SELECT 1 FROM "EventCashupLine" WHERE id = ${lineId} FOR UPDATE`;
const line = await tx.eventCashupLine.findUnique({
where: { id: lineId },
include: { cashup: { select: { id: true, eventId: true } }, pendingResolutions: true }
});
if (!line) {
res.status(404);
throw new Error('Cashup line not found');
}
const latest = await tx.eventCashup.findFirst({ where: { eventId: line.cashup.eventId }, orderBy: { createdAt: 'desc' }, select: { id: true } });
if (!latest || latest.id !== line.cashupId) {
res.status(400);
throw new Error('Only the current cashup of a closed event can be updated');
}
const { pendingOutstanding } = applyPendingResolutions(line);
if (value > pendingOutstanding + 0.005) {
res.status(400);
throw new Error(`Only R${pendingOutstanding.toFixed(2)} is still pending`);
}
return tx.eventCashupPendingResolution.create({
data: {
lineId,
outcome,
amount: value,
category: outcome === 'written_off' ? (WRITE_OFF_CATEGORIES.includes(category) ? category : 'other') : null,
notes: notes ? String(notes).trim().slice(0, 200) : null,
performedById: req.user.id
},
include: { performedBy: { select: { id: true, name: true } } }
});
});
res.status(201).json(resolution);
} catch (error) {
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) });
}
};
// @desc Flat audit log of every close/quick-close/reopen, optionally filtered
// @route GET /api/cashups/audit
// @access Private/Supervisor
@@ -234,5 +323,6 @@ module.exports = {
saveEventCashupDraft,
closeEvent,
reopenEvent,
resolvePending,
getCashupAudit
};
@@ -1,6 +1,6 @@
const express = require('express');
const router = express.Router();
const { getEventCashup, getCashByRecordedUser, savePersonCash, saveEventCashupDraft, closeEvent, reopenEvent, getCashupAudit } = require('../controllers/cashupController');
const { getEventCashup, getCashByRecordedUser, savePersonCash, saveEventCashupDraft, closeEvent, reopenEvent, resolvePending, getCashupAudit } = require('../controllers/cashupController');
const { protect, supervisor, admin } = require('../middleware/authMiddleware');
router.get('/audit', protect, supervisor, getCashupAudit);
@@ -10,5 +10,6 @@ router.put('/event/:eventId/person-cash/:userId', protect, supervisor, savePerso
router.put('/event/:eventId/draft', protect, admin, saveEventCashupDraft);
router.post('/event/:eventId/close', protect, admin, closeEvent);
router.post('/event/:eventId/reopen', protect, admin, reopenEvent);
router.post('/lines/:lineId/pending', protect, admin, resolvePending);
module.exports = router;
+149 -8
View File
@@ -6,10 +6,111 @@ const ALL_METHODS = ['cash', 'card', 'eft', 'other'];
// Standard South African Rand note/coin denominations used for the cash count grid.
const ZAR_DENOMINATIONS = [200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1];
const WRITE_OFF_CATEGORIES = ['card_fees', 'bank_charges', 'cash_shortfall', 'other'];
const PENDING_OUTCOMES = ['received', 'written_off'];
function emptyByMethod(fill = 0) {
return { cash: fill, card: fill, eft: fill, other: fill };
}
const cents = (n) => Math.round(n * 100) / 100;
const sum = (rows) => rows.reduce((s, r) => s + r.amount, 0);
// A non-negative amount rounded to cents, or null when left blank.
function amountOrNull(value, label) {
if (value === undefined || value === null || value === '') return null;
const n = Number(value);
if (!Number.isFinite(n) || n < 0) throw new Error(`${label} must be zero or more`);
return cents(n);
}
/**
* Where one method's expected takings ended up, as entered on the cashup screen. Pure.
*
* actual = in bank + on hand + pending (money held or on its way); write-offs explain money
* that's gone (card fees, bank charges, a cash shortfall). Whatever is left —
* expected − actual − write-offs — is unaccounted for. Cash has no pending; when staff
* counted it (per-person counts), the count is all the cash there is, so whatever wasn't
* deposited is on hand.
*
* @param {object} p
* @param {string} p.method - 'cash' | 'card' | 'eft' | 'other'
* @param {number} p.expected - expected amount for the method (payments − costs paid from it)
* @param {number|null} [p.counted] - cash counted by staff, or null when nobody counted
* @param {object} [p.input] - { bankAmount, onHandAmount, pendingAmount, pendingReference, writeOffs: [{ category, amount, reason }] }
*/
function settleLine({ method, expected, counted = null, input = {} }) {
const bankAmount = amountOrNull(input.bankAmount, 'In bank');
let onHandAmount = method === 'cash' ? amountOrNull(input.onHandAmount, 'Cash on hand') : null;
const pendingAmount = method === 'cash' ? null : amountOrNull(input.pendingAmount, 'Pending');
if (method === 'cash' && counted !== null && counted !== undefined) {
if ((bankAmount || 0) > counted + 0.005) throw new Error('More cash was deposited than was counted');
onHandAmount = cents(counted - (bankAmount || 0));
}
const writeOffs = (Array.isArray(input.writeOffs) ? input.writeOffs : [])
.filter(w => w && w.amount !== undefined && w.amount !== null && w.amount !== '')
.map(w => {
if (!WRITE_OFF_CATEGORIES.includes(w.category)) throw new Error('Choose what each write-off is for');
const amount = amountOrNull(w.amount, 'Write-off');
if (!(amount > 0)) throw new Error('A write-off must be more than R0');
return { category: w.category, amount, reason: String(w.reason || '').trim().slice(0, 200) || null };
});
const writeOffTotal = cents(sum(writeOffs));
const parts = [bankAmount, onHandAmount, pendingAmount];
const entered = parts.some(v => v !== null) || writeOffs.length > 0;
const actual = entered ? cents(parts.reduce((s, v) => s + (v || 0), 0)) : null;
return {
bankAmount,
onHandAmount,
pendingAmount,
pendingReference: pendingAmount ? (String(input.pendingReference || '').trim().slice(0, 200) || null) : null,
writeOffs,
writeOffTotal,
actual,
variance: actual === null ? null : cents(actual - expected),
unaccounted: entered ? cents(expected - actual - writeOffTotal) : null,
};
}
/**
* A closed cashup line with any later pending resolutions folded in. Pure.
* 'received' moves pending money into the bank (actual unchanged); 'written_off' turns it
* into a write-off (actual goes down). Lines from before settlement existed have only
* actualAmount, so their unaccounted is the old variance.
*/
function applyPendingResolutions(line) {
const resolutions = line.pendingResolutions || [];
const received = cents(sum(resolutions.filter(r => r.outcome === 'received')));
const lateWriteOffs = resolutions.filter(r => r.outcome === 'written_off');
const writtenOff = cents(sum(lateWriteOffs));
const pending = line.pendingAmount || 0;
const actual = line.actualAmount === null || line.actualAmount === undefined ? null : cents(line.actualAmount - writtenOff);
const writeOffTotal = cents((line.writeOffTotal || 0) + writtenOff);
const expected = line.expectedAmount || 0;
return {
bank: line.bankAmount == null && received === 0 ? null : cents((line.bankAmount || 0) + received),
onHand: line.onHandAmount ?? null,
pending: line.pendingAmount ?? null,
pendingReference: line.pendingReference || null,
pendingReceived: received,
pendingOutstanding: cents(Math.max(pending - received - writtenOff, 0)),
writeOffs: [
...(line.writeOffs || []).map(w => ({ id: w.id, category: w.category, amount: w.amount, reason: w.reason, createdAt: w.createdAt, afterClose: false })),
...lateWriteOffs.map(r => ({ id: r.id, category: r.category || 'other', amount: r.amount, reason: r.notes, createdAt: r.createdAt, afterClose: true })),
],
writeOffTotal,
actual,
variance: actual === null ? null : cents(actual - expected),
unaccounted: actual === null && writeOffTotal === 0 ? null : cents(expected - (actual || 0) - writeOffTotal),
};
}
// Normalizes a free-text Payment.method into one of the fixed cashup buckets.
// Card-network wallets (Apple Pay, Google Pay, etc.) settle exactly like a card payment —
// no separate float to reconcile — so they belong in the 'card' bucket, not 'other'.
@@ -88,7 +189,13 @@ async function computeEventFinancials(eventId) {
prisma.eventCashup.findMany({
where: { eventId },
include: {
lines: { include: { denominations: true } },
lines: {
include: {
denominations: true,
writeOffs: { orderBy: { createdAt: 'asc' } },
pendingResolutions: { include: { performedBy: { select: { id: true, name: true } } }, orderBy: { createdAt: 'asc' } }
}
},
performedBy: { select: { id: true, name: true, email: true } }
},
orderBy: { createdAt: 'desc' }
@@ -169,29 +276,55 @@ async function computeEventFinancials(eventId) {
const out = {};
for (const m of ALL_METHODS) {
const line = latestReconciled.lines.find(l => l.method === m);
const settled = line ? applyPendingResolutions(line) : null;
out[m] = {
lineId: line ? line.id : null,
expected: line ? line.expectedAmount : expectedCashByMethod[m],
actual: line && line.actualAmount != null ? line.actualAmount : null,
variance: line && line.variance != null ? line.variance : null,
actual: settled ? settled.actual : null,
variance: settled ? settled.variance : null,
notes: line ? line.notes : null,
denominations: line ? line.denominations : []
denominations: line ? line.denominations : [],
bank: settled ? settled.bank : null,
onHand: settled ? settled.onHand : null,
pending: settled ? settled.pending : null,
pendingReference: settled ? settled.pendingReference : null,
pendingReceived: settled ? settled.pendingReceived : 0,
pendingOutstanding: settled ? settled.pendingOutstanding : 0,
pendingResolutions: line ? line.pendingResolutions : [],
writeOffs: settled ? settled.writeOffs : [],
writeOffTotal: settled ? settled.writeOffTotal : 0,
unaccounted: settled ? settled.unaccounted : null
};
}
return out;
})()
} : null;
// Money written off at (or after) the cashup: card fees, bank charges, shortfalls.
const writeOffsByMethod = emptyByMethod();
const writeOffsByCategory = Object.fromEntries(WRITE_OFF_CATEGORIES.map(c => [c, 0]));
let pendingOutstandingTotal = 0;
for (const m of ALL_METHODS) {
const r = reconciled?.byMethod?.[m];
if (!r) continue;
writeOffsByMethod[m] = r.writeOffTotal;
pendingOutstandingTotal += r.pendingOutstanding;
for (const w of r.writeOffs) writeOffsByCategory[w.category] = cents((writeOffsByCategory[w.category] || 0) + w.amount);
}
const totalWriteOffs = cents(ALL_METHODS.reduce((s, m) => s + writeOffsByMethod[m], 0));
// Reconciled value is truth; system (expected) value is the fallback when nothing was counted.
// Tagged costs are added back so a reconciled cash count still yields a correct *gross* income figure —
// costs get subtracted from profit exactly once, via totalCosts, never twice.
// Tagged costs and write-offs are added back so income stays a *gross* figure — costs and
// write-offs each come off profit exactly once, below, never twice. (Unaccounted money
// isn't added back: it lowers income, like any variance.)
const effectiveGrossIncomeByMethod = emptyByMethod();
for (const m of ALL_METHODS) {
const actual = reconciled?.byMethod?.[m]?.actual;
const base = actual != null ? actual : expectedCashByMethod[m];
const base = actual != null ? actual + writeOffsByMethod[m] : expectedCashByMethod[m];
effectiveGrossIncomeByMethod[m] = base + costsByMethod[m];
}
const effectiveTotalRevenue = ALL_METHODS.reduce((s, m) => s + effectiveGrossIncomeByMethod[m], 0);
const netProfit = effectiveTotalRevenue - totalCosts;
const netProfit = effectiveTotalRevenue - totalCosts - totalWriteOffs;
// What was actually sold, by ticket type — for the Finance report's income-stream breakdown.
// Revenue is tranche-aware: a line spanning two early-bird prices contributes each tranche
@@ -221,6 +354,10 @@ async function computeEventFinancials(eventId) {
reconciled,
effectiveGrossIncomeByMethod,
effectiveTotalRevenue,
writeOffsByMethod,
writeOffsByCategory,
totalWriteOffs,
pendingOutstandingTotal: cents(pendingOutstandingTotal),
netProfit,
unallocatedDonations,
unallocatedDonationsTotal,
@@ -362,6 +499,10 @@ module.exports = {
METHOD_BUCKETS,
ALL_METHODS,
ZAR_DENOMINATIONS,
WRITE_OFF_CATEGORIES,
PENDING_OUTCOMES,
settleLine,
applyPendingResolutions,
bucketForMethod,
isDonationLeg,
assertEventOpen,
@@ -0,0 +1,136 @@
const { settleLine, applyPendingResolutions } = require('../src/utils/cashupUtils');
describe('settleLine', () => {
test('card settled net of fees, with the fees written off, leaves nothing unaccounted', () => {
const s = settleLine({
method: 'card',
expected: 12450,
input: { bankAmount: '12080.40', writeOffs: [{ category: 'card_fees', amount: '369.60', reason: 'Yoco 2.95%' }] },
});
expect(s.actual).toBe(12080.4);
expect(s.writeOffTotal).toBe(369.6);
expect(s.unaccounted).toBe(0);
expect(s.variance).toBe(-369.6);
expect(s.writeOffs).toEqual([{ category: 'card_fees', amount: 369.6, reason: 'Yoco 2.95%' }]);
});
test('EFT with a POP not yet in the bank counts the pending money as accounted for', () => {
const s = settleLine({ method: 'eft', expected: 8200, input: { bankAmount: 7200, pendingAmount: 1000, pendingReference: 'POP #417' } });
expect(s.actual).toBe(8200);
expect(s.pendingAmount).toBe(1000);
expect(s.pendingReference).toBe('POP #417');
expect(s.unaccounted).toBe(0);
});
test('a pending reference is dropped when nothing is pending', () => {
const s = settleLine({ method: 'eft', expected: 100, input: { bankAmount: 100, pendingReference: 'POP' } });
expect(s.pendingReference).toBeNull();
});
test('counted cash that was not deposited is on hand, and a shortfall shows as unaccounted', () => {
const s = settleLine({ method: 'cash', expected: 3000, counted: 2950, input: { bankAmount: 2000, onHandAmount: 999 } });
expect(s.onHandAmount).toBe(950); // derived from the count, not the typed 999
expect(s.actual).toBe(2950);
expect(s.unaccounted).toBe(50);
});
test('a cash shortfall written off leaves nothing unaccounted', () => {
const s = settleLine({ method: 'cash', expected: 3000, counted: 2950, input: { bankAmount: 2950, writeOffs: [{ category: 'cash_shortfall', amount: 50 }] } });
expect(s.onHandAmount).toBe(0);
expect(s.unaccounted).toBe(0);
});
test('cash never has a pending amount', () => {
const s = settleLine({ method: 'cash', expected: 500, input: { onHandAmount: 500, pendingAmount: 200 } });
expect(s.pendingAmount).toBeNull();
expect(s.actual).toBe(500);
});
test('without a count, cash on hand can be typed in', () => {
const s = settleLine({ method: 'cash', expected: 500, counted: null, input: { bankAmount: 300, onHandAmount: 200 } });
expect(s.actual).toBe(500);
expect(s.unaccounted).toBe(0);
});
test('depositing more cash than was counted is rejected', () => {
expect(() => settleLine({ method: 'cash', expected: 500, counted: 400, input: { bankAmount: 450 } })).toThrow('More cash was deposited');
});
test('negative or non-numeric amounts are rejected', () => {
expect(() => settleLine({ method: 'card', expected: 100, input: { bankAmount: -5 } })).toThrow('In bank');
expect(() => settleLine({ method: 'card', expected: 100, input: { pendingAmount: 'abc' } })).toThrow('Pending');
});
test('a write-off needs a known category and an amount over zero', () => {
expect(() => settleLine({ method: 'card', expected: 100, input: { writeOffs: [{ category: 'lunch', amount: 5 }] } })).toThrow('what each write-off is for');
expect(() => settleLine({ method: 'card', expected: 100, input: { writeOffs: [{ category: 'other', amount: 0 }] } })).toThrow('more than R0');
});
test('blank write-off rows are ignored', () => {
const s = settleLine({ method: 'card', expected: 100, input: { bankAmount: 100, writeOffs: [{ category: 'other', amount: '' }] } });
expect(s.writeOffs).toEqual([]);
});
test('nothing entered leaves the method unreconciled', () => {
const s = settleLine({ method: 'eft', expected: 100, input: {} });
expect(s.actual).toBeNull();
expect(s.variance).toBeNull();
expect(s.unaccounted).toBeNull();
});
test('amounts are rounded to cents', () => {
const s = settleLine({ method: 'card', expected: 0.3, input: { bankAmount: 0.1, pendingAmount: 0.2 } });
expect(s.actual).toBe(0.3);
expect(s.unaccounted).toBe(0);
});
});
describe('applyPendingResolutions', () => {
const line = {
expectedAmount: 8200,
actualAmount: 8200,
bankAmount: 7200,
onHandAmount: null,
pendingAmount: 1000,
pendingReference: 'POP #417',
writeOffTotal: 0,
writeOffs: [],
};
test('with nothing settled yet, all the pending money is outstanding', () => {
const s = applyPendingResolutions({ ...line, pendingResolutions: [] });
expect(s.pendingOutstanding).toBe(1000);
expect(s.bank).toBe(7200);
expect(s.unaccounted).toBe(0);
});
test('money received later moves into the bank without changing actual', () => {
const s = applyPendingResolutions({ ...line, pendingResolutions: [{ id: 'r1', outcome: 'received', amount: 600 }] });
expect(s.bank).toBe(7800);
expect(s.actual).toBe(8200);
expect(s.pendingOutstanding).toBe(400);
expect(s.writeOffTotal).toBe(0);
});
test('money written off later lowers actual and becomes a write-off', () => {
const s = applyPendingResolutions({
...line,
pendingResolutions: [
{ id: 'r1', outcome: 'received', amount: 600 },
{ id: 'r2', outcome: 'written_off', amount: 400, category: 'other', notes: 'Never paid' },
],
});
expect(s.actual).toBe(7800);
expect(s.writeOffTotal).toBe(400);
expect(s.pendingOutstanding).toBe(0);
expect(s.unaccounted).toBe(0);
expect(s.writeOffs).toEqual([expect.objectContaining({ id: 'r2', category: 'other', amount: 400, reason: 'Never paid', afterClose: true })]);
});
test('a line from before settlement existed reports its old variance as unaccounted', () => {
const s = applyPendingResolutions({ expectedAmount: 1000, actualAmount: 980, variance: -20 });
expect(s.bank).toBeNull();
expect(s.pendingOutstanding).toBe(0);
expect(s.unaccounted).toBe(20);
});
});
@@ -1,13 +1,14 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useParams, useRouter } from "next/navigation";
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, Event } from "@/types";
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<CashupMethod, string> = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" };
const METHODS: CashupMethod[] = ["cash", "card", "eft", "other"];
@@ -20,12 +21,9 @@ function denomLabel(v: number): string {
return v >= 1 ? `R${v}` : `${Math.round(v * 100)}c`;
}
type LineInput = { actualAmount: string; notes: string };
export default function EventCashupPage() {
const params = useParams<{ id: string }>();
const eventId = params.id;
const router = useRouter();
const { token } = useAuth();
const [tab, setTab] = useState<"costs" | "reconciliation" | "report">("costs");
@@ -65,7 +63,7 @@ export default function EventCashupPage() {
<Wallet className="w-5 h-5 text-brand-600" />
</div>
<div>
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard/admin/cashup")}>← Back to cashup</button>
<BackLink href="/dashboard/admin/cashup" label="Back to cashup" />
<h1 className="text-xl font-semibold text-gray-900 mt-0.5">{data?.event?.title || "Event"} — Cashup</h1>
</div>
</div>
@@ -537,34 +535,73 @@ function ReportTab({ eventId, token, data, isClosed }: {
</div>
<div className="bg-white border rounded-lg p-4 space-y-2 overflow-auto">
<div className="text-sm font-medium">Revenue by method</div>
<table className="w-full text-sm min-w-[560px]">
<div className="text-sm font-medium">Where the money ended up</div>
<table className="w-full text-sm min-w-[720px]">
<thead>
<tr className="text-left text-gray-500 border-b">
<th className="py-1">Method</th>
<th className="py-1 text-right">Income</th>
<th className="py-1 text-right">Expected cash</th>
<th className="py-1 text-right">Actual</th>
<th className="py-1 text-right">Variance</th>
<th className="py-1 text-right">Expected</th>
<th className="py-1 text-right">In bank</th>
<th className="py-1 text-right">On hand</th>
<th className="py-1 text-right">Pending</th>
<th className="py-1 text-right">Written off</th>
<th className="py-1 text-right">Unaccounted</th>
</tr>
</thead>
<tbody>
{METHODS.map(m => {
const r = reconciled?.byMethod?.[m];
const cell = (v: number | null | undefined) => (v != null && Math.abs(v) >= 0.005 ? money(v) : "—");
return (
<tr key={m} className="border-b last:border-0">
<td className="py-1.5">{METHOD_LABELS[m]}</td>
<td className="py-1.5 text-right">{money(data.paymentsByMethod[m])}</td>
<td className="py-1.5 text-right">{money(data.expectedCashByMethod[m])}</td>
<td className="py-1.5 text-right">{r?.actual != null ? money(r.actual) : "—"}</td>
<td className="py-1.5 text-right">{r?.variance != null ? money(r.variance) : "—"}</td>
<td className="py-1.5 text-right">{cell(r?.bank)}</td>
<td className="py-1.5 text-right">{cell(r?.onHand)}</td>
<td className="py-1.5 text-right">{cell(r?.pendingOutstanding)}</td>
<td className="py-1.5 text-right">{cell(r?.writeOffTotal)}</td>
<td className={"py-1.5 text-right " + (r?.unaccounted != null && Math.abs(r.unaccounted) >= 0.005 ? "text-rose-700 font-medium" : "")}>
{r?.unaccounted != null ? (Math.abs(r.unaccounted) >= 0.005 ? money(r.unaccounted) : "R0.00") : "—"}
</td>
</tr>
);
})}
</tbody>
</table>
{!reconciled && <div className="text-xs text-gray-400">Not settled yet. Columns fill in once the event is closed with a cashup.</div>}
</div>
{(() => {
const writeOffs = METHODS.flatMap(m => (reconciled?.byMethod?.[m]?.writeOffs || []).map(w => ({ ...w, method: m })));
return writeOffs.length > 0 ? (
<div className="bg-white border rounded-lg p-4 space-y-2 overflow-auto">
<div className="text-sm font-medium">Write-offs</div>
<table className="w-full text-sm min-w-[480px]">
<thead>
<tr className="text-left text-gray-500 border-b">
<th className="py-1">Method</th>
<th className="py-1">Type</th>
<th className="py-1">Reason</th>
<th className="py-1 text-right">Amount</th>
</tr>
</thead>
<tbody>
{writeOffs.map((w, i) => (
<tr key={w.id || i} className="border-b last:border-0">
<td className="py-1.5">{METHOD_LABELS[w.method]}</td>
<td className="py-1.5">{WRITE_OFF_LABELS[w.category]}{w.afterClose ? " (after closing)" : ""}</td>
<td className="py-1.5 text-gray-600">{w.reason || "—"}</td>
<td className="py-1.5 text-right">{money(w.amount)}</td>
</tr>
))}
</tbody>
</table>
</div>
) : null;
})()}
{reconciled?.byMethod?.cash?.denominations?.length ? (
<div className="bg-white border rounded-lg p-4 space-y-2">
<div className="text-sm font-medium">Cash denomination count</div>
@@ -604,19 +641,271 @@ function ReportTab({ eventId, token, data, isClosed }: {
</div>
)}
<div className="bg-white border rounded-lg p-4 grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm">
<ProfitSummary data={data} />
</div>
);
}
// ─── 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<CashupWriteOffCategory, string> = {
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<CashupMethod, CashupWriteOffCategory> = { cash: "cash_shortfall", card: "card_fees", eft: "bank_charges", other: "other" };
const BANK_HELP: Record<CashupMethod, string> = {
cash: "Deposited into the bank",
card: "Settled into the bank account",
eft: "Showing on the bank statement",
other: "Received in the bank",
};
const PENDING_HELP: Record<CashupMethod, string> = {
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<CashupMethod, string> = { 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 onHand = method === "cash" ? (counted !== null ? round2(counted - (bank || 0)) : num(input.onHandAmount)) : null;
const pending = method === "cash" ? null : num(input.pendingAmount);
const writeOffTotal = round2(input.writeOffs.reduce((s, w) => s + (num(w.amount) || 0), 0));
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 <span className="text-xs text-gray-400">Not settled yet</span>;
if (Math.abs(unaccounted) < 0.005) return <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-emerald-50 text-emerald-700">All accounted for</span>;
return (
<span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-rose-50 text-rose-700">
{unaccounted > 0 ? `${money(unaccounted)} unaccounted` : `${money(-unaccounted)} more than expected`}
</span>
);
}
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<WriteOffInput>) =>
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 (
<div className="border rounded-lg p-3 space-y-3">
<div className="flex items-start justify-between gap-3 flex-wrap">
<div>
<div className="text-gray-500 text-xs">Donations counted as profit</div>
<div className="font-semibold">{money(data.unallocatedDonationsTotal)}</div>
<div className="text-sm font-medium">{METHOD_LABELS[method]}</div>
<div className="text-xs text-gray-500">
Expected {money(expected)}
{data.costsByMethod[method] > 0 && <> ({money(data.paymentsByMethod[method])} taken, less {money(data.costsByMethod[method])} paid out)</>}
</div>
</div>
<UnaccountedBadge unaccounted={s.unaccounted} />
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<div className="text-gray-500 text-xs">Total costs</div>
<div className="font-semibold">{money(data.totalCosts)}</div>
<label className="block text-xs text-gray-600 mb-1">In bank</label>
<input type="number" step="0.01" min={0} className="w-full border rounded px-2 py-1.5 text-sm" value={input.bankAmount} onChange={e => set("bankAmount", e.target.value)} />
<p className="text-[10px] text-gray-400 mt-0.5">{BANK_HELP[method]}</p>
</div>
{method === "cash" ? (
<div>
<label className="block text-xs text-gray-600 mb-1">Cash on hand</label>
{counted !== null ? (
<div className="text-sm py-1.5">{money(s.onHand)}</div>
) : (
<input type="number" step="0.01" min={0} className="w-full border rounded px-2 py-1.5 text-sm" value={input.onHandAmount} onChange={e => set("onHandAmount", e.target.value)} />
)}
<p className="text-[10px] text-gray-400 mt-0.5">
{counted !== null ? `Counted ${money(counted)}, less what was deposited` : "Not deposited yet. Enter staff cash counts below to work this out."}
</p>
</div>
) : (
<div>
<label className="block text-xs text-gray-600 mb-1">Pending</label>
<div className="flex gap-2">
<input type="number" step="0.01" min={0} className="w-28 border rounded px-2 py-1.5 text-sm" value={input.pendingAmount} onChange={e => set("pendingAmount", e.target.value)} />
<input className="flex-1 min-w-0 border rounded px-2 py-1.5 text-sm" placeholder={PENDING_REFERENCE_PLACEHOLDER[method]} value={input.pendingReference} onChange={e => set("pendingReference", e.target.value)} />
</div>
<p className="text-[10px] text-gray-400 mt-0.5">{PENDING_HELP[method]}</p>
</div>
)}
</div>
<div className="space-y-2">
<div className="text-xs text-gray-600">Write-offs</div>
{input.writeOffs.map((w, i) => (
<div key={i} className="flex flex-wrap gap-2 items-center">
<select className="border rounded px-2 py-1.5 text-sm" value={w.category} onChange={e => setWriteOff(i, { category: e.target.value as CashupWriteOffCategory })}>
{WRITE_OFF_CATEGORIES.map(c => <option key={c} value={c}>{WRITE_OFF_LABELS[c]}</option>)}
</select>
<input type="number" step="0.01" min={0} className="w-28 border rounded px-2 py-1.5 text-sm" placeholder="Amount" value={w.amount} onChange={e => setWriteOff(i, { amount: e.target.value })} />
<input className="flex-1 min-w-[140px] border rounded px-2 py-1.5 text-sm" placeholder="Reason (optional)" value={w.reason} onChange={e => setWriteOff(i, { reason: e.target.value })} />
<button className="text-xs text-red-600 hover:underline" onClick={() => removeWriteOff(i)}>Remove</button>
</div>
))}
<button className="text-xs text-brand-600 hover:underline" onClick={addWriteOff}>+ Add write-off</button>
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">Notes (optional)</label>
<input className="w-full border rounded px-2 py-1.5 text-sm" value={input.notes} onChange={e => set("notes", e.target.value)} />
</div>
</div>
);
}
// 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 (
<div className="border rounded-lg p-3 space-y-2">
<div className="flex items-start justify-between gap-3 flex-wrap">
<div>
<div className="text-gray-500 text-xs">Net profit</div>
<div className="font-semibold">{money(data.netProfit)}</div>
<div className="text-sm font-medium">{METHOD_LABELS[method]}</div>
<div className="text-xs text-gray-500">Expected {money(r.expected)}</div>
</div>
<UnaccountedBadge unaccounted={r.unaccounted} />
</div>
<dl className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-sm">
<div><dt className="text-xs text-gray-500">In bank</dt><dd>{r.bank !== null ? money(r.bank) : "—"}</dd></div>
{method === "cash"
? <div><dt className="text-xs text-gray-500">On hand</dt><dd>{r.onHand !== null ? money(r.onHand) : "—"}</dd></div>
: <div><dt className="text-xs text-gray-500">Pending</dt><dd>{r.pendingOutstanding > 0 ? money(r.pendingOutstanding) : "—"}</dd></div>}
<div><dt className="text-xs text-gray-500">Written off</dt><dd>{r.writeOffTotal > 0 ? money(r.writeOffTotal) : "—"}</dd></div>
<div><dt className="text-xs text-gray-500">Actual</dt><dd>{r.actual !== null ? money(r.actual) : "—"}</dd></div>
</dl>
{r.writeOffs.length > 0 && (
<ul className="text-xs text-gray-600 space-y-0.5">
{r.writeOffs.map((w, i) => (
<li key={w.id || i}>
{WRITE_OFF_LABELS[w.category]} {money(w.amount)}{w.reason ? ` — ${w.reason}` : ""}{w.afterClose ? " (after closing)" : ""}
</li>
))}
</ul>
)}
{(r.pending || 0) > 0 && (
<PendingSettler method={method} r={r} token={token} onChanged={onChanged} />
)}
{r.notes && <div className="text-xs text-gray-500">Notes: {r.notes}</div>}
</div>
);
}
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<CashupWriteOffCategory>(DEFAULT_WRITE_OFF[method]);
const [notes, setNotes] = useState("");
const [saving, setSaving] = useState(false);
const [err, setErr] = useState<string | null>(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 (
<div className="bg-amber-50 border border-amber-100 rounded p-2 space-y-2 text-xs">
<div className="flex items-center justify-between gap-2 flex-wrap">
<span>
Pending {money(r.pending)}{r.pendingReference ? ` (${r.pendingReference})` : ""}
{r.pendingOutstanding > 0 ? <> — <strong>{money(r.pendingOutstanding)} still outstanding</strong></> : " — all settled"}
</span>
{r.pendingOutstanding > 0 && mode === null && (
<span className="flex gap-3">
<button className="text-brand-600 hover:underline" onClick={() => start("received")}>Mark received</button>
<button className="text-red-600 hover:underline" onClick={() => start("written_off")}>Write off</button>
</span>
)}
</div>
{r.pendingResolutions.length > 0 && (
<ul className="text-gray-600 space-y-0.5">
{r.pendingResolutions.map(p => (
<li key={p.id}>
{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}` : ""}
</li>
))}
</ul>
)}
{mode !== null && (
<div className="flex flex-wrap gap-2 items-center">
<input type="number" step="0.01" min={0} className="w-28 border rounded px-2 py-1 text-sm bg-white" value={amount} onChange={e => setAmount(e.target.value)} />
{mode === "written_off" && (
<select className="border rounded px-2 py-1 text-sm bg-white" value={category} onChange={e => setCategory(e.target.value as CashupWriteOffCategory)}>
{WRITE_OFF_CATEGORIES.map(c => <option key={c} value={c}>{WRITE_OFF_LABELS[c]}</option>)}
</select>
)}
<input className="flex-1 min-w-[140px] border rounded px-2 py-1 text-sm bg-white" placeholder={mode === "received" ? "Bank reference (optional)" : "Reason (optional)"} value={notes} onChange={e => setNotes(e.target.value)} />
<button className="px-2 py-1 rounded border bg-white" onClick={() => setMode(null)} disabled={saving}>Cancel</button>
<button className="px-2 py-1 rounded bg-brand-600 text-white hover:bg-brand-700" onClick={save} disabled={saving}>
{saving ? "Saving…" : mode === "received" ? "Mark received" : "Write off"}
</button>
{err && <span className="text-red-600 w-full">{err}</span>}
</div>
)}
</div>
);
}
function ProfitSummary({ data }: { data: EventFinancials }) {
return (
<div className="bg-white border rounded-lg p-4 grid grid-cols-2 sm:grid-cols-5 gap-3 text-sm">
<div>
<div className="text-gray-500 text-xs">Donations counted as profit</div>
<div className="font-semibold">{money(data.unallocatedDonationsTotal)}</div>
</div>
<div>
<div className="text-gray-500 text-xs">Total costs</div>
<div className="font-semibold">{money(data.totalCosts)}</div>
</div>
<div>
<div className="text-gray-500 text-xs">Bank &amp; card charges</div>
<div className="font-semibold">{money(data.totalWriteOffs)}</div>
</div>
<div>
<div className="text-gray-500 text-xs">Pending (outstanding)</div>
<div className="font-semibold">{money(data.pendingOutstandingTotal)}</div>
</div>
<div>
<div className="text-gray-500 text-xs">Net profit</div>
<div className="font-semibold">{money(data.netProfit)}</div>
</div>
</div>
);
@@ -629,32 +918,53 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
const isClosed = data.event.cashupStatus === "closed";
const draftLines = data.event.cashupDraft?.lines;
const initialLines: Record<CashupMethod, LineInput> = useMemo(() => {
const base: Record<CashupMethod, LineInput> = { cash: { actualAmount: "", notes: "" }, card: { actualAmount: "", notes: "" }, eft: { actualAmount: "", notes: "" }, other: { actualAmount: "", notes: "" } };
const initialLines: Record<CashupMethod, SettlementInput> = useMemo(() => {
const base: Record<CashupMethod, SettlementInput> = { cash: emptySettlement(), card: emptySettlement(), eft: emptySettlement(), other: emptySettlement() };
for (const l of draftLines || []) {
if (l.method in base) base[l.method as CashupMethod] = { actualAmount: l.actualAmount != null ? String(l.actualAmount) : "", notes: l.notes || "" };
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<Record<CashupMethod, LineInput>>(initialLines);
const [lines, setLines] = useState<Record<CashupMethod, SettlementInput>>(initialLines);
const [closeNotes, setCloseNotes] = useState("");
const [reopenNotes, setReopenNotes] = useState("");
// Cash no longer has its own manual entry — it's the live sum of every staff member's
// per-person count, reported up from CashByUserSection below.
// 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, field: keyof LineInput, value: string) => {
setLines(prev => ({ ...prev, [method]: { ...prev[method], [field]: value } }));
};
const setLine = (method: CashupMethod, next: SettlementInput) => setLines(prev => ({ ...prev, [method]: next }));
// Cash is included with notes only — its actual/denominations are always sourced server-side
// from per-person counts (see cashupController.closeEvent), never from this payload.
const buildLinesPayload = () => METHODS.map(m => m === "cash"
? { method: "cash", notes: lines.cash.notes || null }
: { method: m, actualAmount: lines[m].actualAmount === "" ? null : parseFloat(lines[m].actualAmount), notes: lines[m].notes || null });
// 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);
@@ -669,7 +979,14 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
};
const closeWithCashup = async () => {
if (!confirm("Close this event with the entered reconciliation? This will count unallocated donations as profit and fully lock the event until it's reopened.")) return;
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 } });
@@ -683,7 +1000,7 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
};
const quickClose = async () => {
if (!confirm("Quick close this event without a per-method 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;
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 } });
@@ -710,60 +1027,41 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
};
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 (
<div className="space-y-4">
<div className="bg-white border rounded-lg p-4 space-y-3 overflow-auto">
<div className="text-sm font-medium">Cash-up reconciliation</div>
<table className="w-full text-sm min-w-[640px]">
<thead>
<tr className="text-left text-gray-500 border-b">
<th className="py-1">Method</th>
<th className="py-1 text-right">Income</th>
<th className="py-1 text-right">Costs from method</th>
<th className="py-1 text-right">Expected cash</th>
<th className="py-1 text-right">Actual</th>
<th className="py-1 text-right">Variance</th>
<th className="py-1">Notes</th>
</tr>
</thead>
<tbody>
{METHODS.map(m => {
const r = reconciled?.byMethod?.[m];
return (
<tr key={m} className="border-b last:border-0 align-top">
<td className="py-1.5">{METHOD_LABELS[m]}</td>
<td className="py-1.5 text-right">{money(data.paymentsByMethod[m])}</td>
<td className="py-1.5 text-right">{money(data.costsByMethod[m])}</td>
<td className="py-1.5 text-right">{money(data.expectedCashByMethod[m])}</td>
<td className="py-1.5 text-right">
{isClosed ? (
money(r?.actual ?? null)
) : m === "cash" ? (
cashSummary.actualTotal != null ? money(cashSummary.actualTotal) : <span className="text-gray-400">not counted</span>
) : (
<input type="number" step="0.01" className="w-28 border rounded px-2 py-1 text-sm text-right" value={lines[m].actualAmount} onChange={e => setLine(m, "actualAmount", e.target.value)} />
)}
</td>
<td className="py-1.5 text-right">
{isClosed
? (r?.variance != null ? money(r.variance) : <span className="text-gray-400">not reconciled</span>)
: (m === "cash"
? (cashSummary.actualTotal != null ? money(cashSummary.actualTotal - data.expectedCashByMethod[m]) : "—")
: (lines[m].actualAmount !== "" ? money(parseFloat(lines[m].actualAmount) - data.expectedCashByMethod[m]) : "—"))}
</td>
<td className="py-1.5">
{isClosed ? (r?.notes || "—") : (
<input className="w-full border rounded px-2 py-1 text-sm" value={lines[m].notes} onChange={e => setLine(m, "notes", e.target.value)} />
)}
</td>
</tr>
);
})}
</tbody>
</table>
{!isClosed && (
<div className="text-xs text-gray-500">Cash actual is the live sum of per-staff-member counts entered below — there&apos;s no separate event-wide entry.</div>
<div className="bg-white border rounded-lg p-4 space-y-3">
<div>
<div className="text-sm font-medium">Where did the money end up?</div>
<div className="text-xs text-gray-500">
{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."}
</div>
</div>
{isClosed ? (
reconciled?.action === "closed" && settledMethods.length > 0 ? (
settledMethods.map(m => <SettledCard key={m} method={m} r={reconciled.byMethod[m]} token={token} onChanged={onChanged} />)
) : (
<div className="text-xs text-gray-400">This event was quick closed, so no settlement was recorded.</div>
)
) : shownMethods.length === 0 ? (
<div className="text-xs text-gray-400">No payments to settle for this event.</div>
) : (
shownMethods.map(m => (
<SettlementCard
key={m}
method={m}
data={data}
counted={m === "cash" ? cashSummary.actualTotal : null}
input={lines[m]}
onChange={next => setLine(m, next)}
/>
))
)}
</div>
@@ -789,20 +1087,7 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
})()}
</div>
<div className="bg-white border rounded-lg p-4 grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm">
<div>
<div className="text-gray-500 text-xs">Donations counted as profit</div>
<div className="font-semibold">{money(data.unallocatedDonationsTotal)}</div>
</div>
<div>
<div className="text-gray-500 text-xs">Total costs</div>
<div className="font-semibold">{money(data.totalCosts)}</div>
</div>
<div>
<div className="text-gray-500 text-xs">Net profit</div>
<div className="font-semibold">{money(data.netProfit)}</div>
</div>
</div>
<ProfitSummary data={data} />
{!isClosed && (
<div className="bg-white border rounded-lg p-4 space-y-2">
@@ -1,15 +1,13 @@
"use client";
import React, { Suspense } from "react";
import { useRouter } from "next/navigation";
import ReportsV2 from "@/components/reports/ReportsV2";
export default function SupervisorReportsPage() {
const router = useRouter();
return (
<div className="w-full p-6">
<Suspense fallback={<div className="text-sm text-gray-400">Loading…</div>}>
<ReportsV2 onBack={() => router.push('/dashboard')} />
<ReportsV2 backHref="/dashboard" />
</Suspense>
</div>
);
@@ -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 && (
@@ -43,13 +43,23 @@ export const dashboardAdminCashupDetailHelpContent: HelpContent = {
icon: ClipboardCheck,
content: (
<div className="space-y-4">
<p>A per-method table (cash, card, EFT, other) compares income, costs charged to that method, and expected vs actual amounts.</p>
<p>For each payment method (cash, card, EFT, other) you say where the expected money ended up. Expected is what was taken, less any costs paid out of that method.</p>
<ul className="list-disc pl-5 space-y-1">
<li><strong>In bank</strong>: card settlements, EFTs on the statement, cash that was deposited.</li>
<li><strong>Cash on hand</strong>: cash not deposited yet.</li>
<li><strong>Pending</strong>: on the card machine or Yoco report, or you have a proof of payment, but it isn&apos;t in the bank yet. Add the report or POP reference.</li>
<li><strong>Write-offs</strong>: money that&apos;s gone, such as card fees, bank charges or a cash shortfall. Write-offs come off net profit and show as &quot;Bank &amp; card charges&quot; in the reports.</li>
</ul>
<p>Each method shows what&apos;s still <strong>unaccounted</strong>. You can close with an unaccounted amount, but you&apos;ll be warned and it comes off profit.</p>
<div className="space-y-4">
<GuideItem icon={ClipboardCheck} title="Cash accountability" tone="amber">
Cash&apos;s &quot;actual&quot; figure isn&apos;t typed directly — it&apos;s the live total of the staff cash-count panel below, where each staff member enters their physical cash by denomination.
Counted cash comes from the staff cash-count panel below, where each staff member enters their physical cash by denomination. When counts are entered, cash on hand is the count less what was deposited.
</GuideItem>
<GuideItem icon={Wallet} title="Pending money after closing" tone="blue">
Once the event is closed, pending money shows as outstanding. When it reaches the bank, use Mark received; if it never will, use Write off. You don&apos;t need to reopen the event.
</GuideItem>
<GuideItem icon={Lock} title="Closing the event" tone="rose">
Save draft keeps working on it later; Quick close skips detailed reconciliation; Close event with cashup locks everything in. A closed event can be Reopened if something needs fixing — both actions are logged in the History panel.
Save draft keeps working on it later; Quick close skips the settlement; Close event with cashup locks everything in. A closed event can be Reopened if something needs fixing, and the next cashup starts from the last one. Both actions are logged in the History panel.
</GuideItem>
</div>
</div>
@@ -61,7 +71,7 @@ export const dashboardAdminCashupDetailHelpContent: HelpContent = {
icon: FileBarChart,
content: (
<div className="space-y-4">
<p>A read-only summary of revenue by method, denomination breakdown, staff cash accountability, costs, donations, and net profit. This becomes the default view automatically once the event is closed.</p>
<p>A read-only summary of where the money ended up by method (in bank, on hand, pending, written off, unaccounted), write-offs, denomination breakdown, staff cash accountability, costs, donations, and net profit. This becomes the default view automatically once the event is closed.</p>
</div>
),
},
+53 -3
View File
@@ -183,7 +183,36 @@ export type EventCashupLine = {
actualAmount?: number | null;
variance?: number | null;
notes?: string | null;
bankAmount?: number | null;
onHandAmount?: number | null;
pendingAmount?: number | null;
pendingReference?: string | null;
writeOffTotal?: number;
denominations?: EventCashupDenomination[];
writeOffs?: CashupWriteOff[];
};
export type CashupWriteOffCategory = "card_fees" | "bank_charges" | "cash_shortfall" | "other";
export type CashupWriteOff = {
id?: string;
category: CashupWriteOffCategory;
amount: number;
reason?: string | null;
createdAt?: string;
// Written off after the event was closed (from pending money that never arrived).
afterClose?: boolean;
};
export type PendingResolution = {
id: string;
lineId: string;
outcome: "received" | "written_off";
amount: number;
category?: CashupWriteOffCategory | null;
notes?: string | null;
performedBy?: { id: string; name: string } | null;
createdAt: string;
};
export type CashupAction = "closed" | "quick_closed" | "reopened";
@@ -204,12 +233,25 @@ export type EventCashup = {
event?: Pick<Event, "id" | "title">;
};
// One method of the latest close, with pending money settled since then folded in.
export type ReconciledByMethod = {
lineId: string | null;
expected: number;
actual: number | null;
variance: number | null;
notes?: string | null;
denominations: EventCashupDenomination[];
bank: number | null;
onHand: number | null;
pending: number | null;
pendingReference: string | null;
pendingReceived: number;
pendingOutstanding: number;
pendingResolutions: PendingResolution[];
writeOffs: CashupWriteOff[];
writeOffTotal: number;
// expected − actual − write-offs; null when nothing was entered for the method.
unaccounted: number | null;
};
export type ReconciledSnapshot = {
@@ -225,9 +267,12 @@ export type ReconciledSnapshot = {
export type CashupDraft = {
lines?: {
method: string;
actualAmount?: string | number;
notes?: string;
denominations?: { value: number; count: number }[];
bankAmount?: string | number | null;
onHandAmount?: string | number | null;
pendingAmount?: string | number | null;
pendingReference?: string | null;
writeOffs?: { category: CashupWriteOffCategory; amount: string | number | null; reason?: string | null }[];
notes?: string | null;
}[];
};
@@ -250,6 +295,11 @@ export type EventFinancials = {
reconciled: ReconciledSnapshot | null;
effectiveGrossIncomeByMethod: Record<CashupMethod, number>;
effectiveTotalRevenue: number;
writeOffsByMethod: Record<CashupMethod, number>;
writeOffsByCategory: Record<CashupWriteOffCategory, number>;
// Card fees, bank charges and shortfalls written off; comes off net profit.
totalWriteOffs: number;
pendingOutstandingTotal: number;
netProfit: number;
// Coupon discounts given on the event's registrations.
discountsTotal?: number;