diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md
index 03d4225..94d6308 100644
--- a/apps/events/CHANGELOG.md
+++ b/apps/events/CHANGELOG.md
@@ -7,6 +7,23 @@ and this project follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+## [1.27.0] - 2026-10-21
+
+Run `npm run prisma:deploy` in the backend when deploying. This release adds a migration.
+
+### Added
+
+- Cashups now record where each payment method's money ended up. For cash, card, EFT and other, the expected takings are split into what's **in the bank**, **cash on hand**, and **pending** (on the card machine or Yoco report, or with a proof of payment), with a reference for the pending amount. Card fees, bank charges, cash shortfalls and other losses are **written off** with a reason. Each method shows what's still **unaccounted**. Closing with an unaccounted amount is allowed after a warning, and the amount comes off profit, as variance did before.
+- When staff have counted the cash, cash on hand is worked out for you: the count, less what reached the bank and any deposit fee written off as a bank charge.
+- Pending money on a closed event can be marked **received** or **written off** later from the cashup screen, without reopening the event. Each one is logged with who did it and when.
+- Reopening an event starts the next cashup from the last one, with any pending money settled since folded in.
+- Write-offs show as **Bank & card charges** on the cashup screen and in the Cashup, Finance and Profit reports. The Cashup report has new In bank, On hand, Pending, Written off and Unaccounted columns.
+
+### Changed
+
+- Net profit now subtracts write-offs as their own line instead of showing card fees and bank charges as missing income. The net figure is the same.
+- Every dashboard page uses the same back link: the small "← Back to dashboard" link above the page title, as on the Waitlist page. The grey Back buttons are gone. Site settings, profile, donate and manual registration, which had no way back, now have one too.
+
## [1.26.1] - 2026-10-21
### Added
diff --git a/apps/events/backend/prisma/migrations/20261021110951_add_cashup_settlement/migration.sql b/apps/events/backend/prisma/migrations/20261021110951_add_cashup_settlement/migration.sql
new file mode 100644
index 0000000..ee6866d
--- /dev/null
+++ b/apps/events/backend/prisma/migrations/20261021110951_add_cashup_settlement/migration.sql
@@ -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;
diff --git a/apps/events/backend/prisma/schema.prisma b/apps/events/backend/prisma/schema.prisma
index d581291..763a89a 100644
--- a/apps/events/backend/prisma/schema.prisma
+++ b/apps/events/backend/prisma/schema.prisma
@@ -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
diff --git a/apps/events/backend/src/controllers/cashupController.js b/apps/events/backend/src/controllers/cashupController.js
index 8080b41..8573c24 100644
--- a/apps/events/backend/src/controllers/cashupController.js
+++ b/apps/events/backend/src/controllers/cashupController.js
@@ -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
};
diff --git a/apps/events/backend/src/routes/cashupRoutes.js b/apps/events/backend/src/routes/cashupRoutes.js
index 51dbd87..653f9ba 100644
--- a/apps/events/backend/src/routes/cashupRoutes.js
+++ b/apps/events/backend/src/routes/cashupRoutes.js
@@ -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;
diff --git a/apps/events/backend/src/utils/cashupUtils.js b/apps/events/backend/src/utils/cashupUtils.js
index a9e7274..d9313db 100644
--- a/apps/events/backend/src/utils/cashupUtils.js
+++ b/apps/events/backend/src/utils/cashupUtils.js
@@ -6,10 +6,114 @@ 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 (or taken by the bank as a deposit fee) 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');
+
+ 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));
+
+ if (method === 'cash' && counted !== null && counted !== undefined) {
+ // A deposit fee comes out of cash that was counted and banked, so the count is what
+ // reached the bank + the fee + what's still on hand.
+ const depositFees = cents(sum(writeOffs.filter(w => w.category === 'bank_charges')));
+ if ((bankAmount || 0) + depositFees > counted + 0.005) throw new Error('More cash was deposited than was counted');
+ onHandAmount = cents(counted - (bankAmount || 0) - depositFees);
+ }
+
+ 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 +192,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 +279,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 +357,10 @@ async function computeEventFinancials(eventId) {
reconciled,
effectiveGrossIncomeByMethod,
effectiveTotalRevenue,
+ writeOffsByMethod,
+ writeOffsByCategory,
+ totalWriteOffs,
+ pendingOutstandingTotal: cents(pendingOutstandingTotal),
netProfit,
unallocatedDonations,
unallocatedDonationsTotal,
@@ -362,6 +502,10 @@ module.exports = {
METHOD_BUCKETS,
ALL_METHODS,
ZAR_DENOMINATIONS,
+ WRITE_OFF_CATEGORIES,
+ PENDING_OUTCOMES,
+ settleLine,
+ applyPendingResolutions,
bucketForMethod,
isDonationLeg,
assertEventOpen,
diff --git a/apps/events/backend/tests/cashupSettlement.test.js b/apps/events/backend/tests/cashupSettlement.test.js
new file mode 100644
index 0000000..6d6dd24
--- /dev/null
+++ b/apps/events/backend/tests/cashupSettlement.test.js
@@ -0,0 +1,154 @@
+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('a deposit fee comes out of the counted cash, not on top of it', () => {
+ // Counted R1000; the bank credited R941.50 after a R58.50 deposit fee; nothing left on hand.
+ const s = settleLine({ method: 'cash', expected: 1000, counted: 1000, input: { bankAmount: 941.5, writeOffs: [{ category: 'bank_charges', amount: 58.5 }] } });
+ expect(s.onHandAmount).toBe(0);
+ expect(s.actual).toBe(941.5);
+ expect(s.unaccounted).toBe(0);
+ });
+
+ test('a cash shortfall write-off does not change what is on hand', () => {
+ const s = settleLine({ method: 'cash', expected: 1000, counted: 980, input: { bankAmount: 480, writeOffs: [{ category: 'cash_shortfall', amount: 20 }] } });
+ expect(s.onHandAmount).toBe(500);
+ expect(s.unaccounted).toBe(0);
+ });
+
+ test('banking more than was counted, counting the deposit fee, is rejected', () => {
+ expect(() => settleLine({ method: 'cash', expected: 1000, counted: 1000, input: { bankAmount: 1000, writeOffs: [{ category: 'bank_charges', amount: 58.5 }] } })).toThrow('More cash was deposited');
+ });
+
+ 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);
+ });
+});
diff --git a/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx b/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx
index 3dc6d09..9a3c331 100644
--- a/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx
+++ b/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx
@@ -8,6 +8,7 @@ import { useDismissingState } from "@/hooks/useDismissingState";
import { History } from "lucide-react";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { errorMessage } from "@/lib/utils";
+import { BackLink } from "@/components/shared/BackLink";
const ACTIONS = [
"refund_created",
@@ -192,7 +193,7 @@ export default function AdminAuditLogPage() {
{total} action{total !== 1 ? "s" : ""} recorded
| Method | Income | -Expected cash | -Actual | -Variance | +Expected | +In bank | +On hand | +Pending | +Written off | +Unaccounted |
|---|---|---|---|---|---|---|---|---|---|---|
| {METHOD_LABELS[m]} | {money(data.paymentsByMethod[m])} | {money(data.expectedCashByMethod[m])} | -{r?.actual != null ? money(r.actual) : "—"} | -{r?.variance != null ? money(r.variance) : "—"} | +{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") : "—"} + |
| Method | +Type | +Reason | +Amount | +
|---|---|---|---|
| {METHOD_LABELS[w.method]} | +{WRITE_OFF_LABELS[w.category]}{w.afterClose ? " (after closing)" : ""} | +{w.reason || "—"} | +{money(w.amount)} | +
{BANK_HELP[method]}
+ {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."} +
+{PENDING_HELP[method]}
+| Method | -Income | -Costs from method | -Expected cash | -Actual | -Variance | -Notes | -
|---|---|---|---|---|---|---|
| {METHOD_LABELS[m]} | -{money(data.paymentsByMethod[m])} | -{money(data.costsByMethod[m])} | -{money(data.expectedCashByMethod[m])} | -- {isClosed ? ( - money(r?.actual ?? null) - ) : m === "cash" ? ( - cashSummary.actualTotal != null ? money(cashSummary.actualTotal) : not counted - ) : ( - setLine(m, "actualAmount", e.target.value)} /> - )} - | -- {isClosed - ? (r?.variance != null ? money(r.variance) : not reconciled) - : (m === "cash" - ? (cashSummary.actualTotal != null ? money(cashSummary.actualTotal - data.expectedCashByMethod[m]) : "—") - : (lines[m].actualAmount !== "" ? money(parseFloat(lines[m].actualAmount) - data.expectedCashByMethod[m]) : "—"))} - | -- {isClosed ? (r?.notes || "—") : ( - setLine(m, "notes", e.target.value)} /> - )} - | -
Set costs, reconcile takings, and close out an event. Admin only.
{registrations.length} registration{registrations.length !== 1 ? "s" : ""} total
Configure your organisation, branding, email, and legal pages.
{total} user{total !== 1 ? "s" : ""} total
View and print tickets for an event.
diff --git a/apps/events/frontend/src/app/dashboard/staff/my-groups/page.tsx b/apps/events/frontend/src/app/dashboard/staff/my-groups/page.tsx
index 14b04bd..6b08c6f 100644
--- a/apps/events/frontend/src/app/dashboard/staff/my-groups/page.tsx
+++ b/apps/events/frontend/src/app/dashboard/staff/my-groups/page.tsx
@@ -2,10 +2,10 @@
import React, { useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
-import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
import { formatDate } from "@/lib/date";
import { Users } from "lucide-react";
+import { BackLink } from "@/components/shared/BackLink";
type Member = {
id: string; name: string; gender: string | null; dateOfBirth: string | null; phone: string | null;
@@ -25,7 +25,6 @@ const ageOn = (dob: string | null, on: string) => {
/** Groups the signed-in staff member leads (rooms, small groups, buses) and who's in them. */
export default function MyGroupsPage() {
const { token } = useAuth();
- const router = useRouter();
const [data, setData] = useState<{ medicalShown: boolean; groups: MyGroup[] } | null>(null);
const [error, setError] = useState Rooms, small groups and buses you lead
Use the button to start/stop scanning. The back camera will be used when available.
diff --git a/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx
index ec85282..aff84c2 100644
--- a/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx
+++ b/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx
@@ -10,6 +10,7 @@ import { useDismissingState } from "@/hooks/useDismissingState";
import { BedDouble, Plus, Wand2, Printer, Trash2, Pencil, Eraser } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import type { Event } from "@/types";
+import { BackLink } from "@/components/shared/BackLink";
type Group = { id: string; name: string; capacity: number | null; gender: "male" | "female" | null; leaderUserId: string | null; leader?: { id: string; name: string } | null };
type AllocSet = { id: string; name: string; showOnTicket: boolean; groups: Group[]; assignments: { attendeeId: string; groupId: string }[] };
@@ -207,7 +208,7 @@ export default function AllocationsPage() {
Put attendees into rooms, small groups, teams or buses Youth events: who still needs a parent's consent before check-in Discounts for staff, leaders, volunteers and promotions Manage and create eventsMy groups
Ticket Scanning
+ Ticket Scanning
+ Rooms & groups
Parental consent
Coupon codes
Email Attendees
-
- Email Attendees
+ Event options
+ Event options
+ Events
+ Events
Forms
+ Forms
+