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() {
- +

Admin Audit Log

{total} action{total !== 1 ? "s" : ""} recorded

diff --git a/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx b/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx index d6fdd07..840406c 100644 --- a/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx @@ -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 = { 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() {
- +

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

@@ -537,34 +535,73 @@ function ReportTab({ eventId, token, data, isClosed }: {
-
Revenue by method
- +
Where the money ended up
+
- - - + + + + + + {METHODS.map(m => { const r = reconciled?.byMethod?.[m]; + const cell = (v: number | null | undefined) => (v != null && Math.abs(v) >= 0.005 ? money(v) : "—"); return ( - - + + + + + ); })}
Method IncomeExpected cashActualVarianceExpectedIn bankOn handPendingWritten offUnaccounted
{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") : "—"} +
+ {!reconciled &&
Not settled yet. Columns fill in once the event is closed with a cashup.
}
+ {(() => { + const writeOffs = METHODS.flatMap(m => (reconciled?.byMethod?.[m]?.writeOffs || []).map(w => ({ ...w, method: m }))); + return writeOffs.length > 0 ? ( +
+
Write-offs
+ + + + + + + + + + + {writeOffs.map((w, i) => ( + + + + + + + ))} + +
MethodTypeReasonAmount
{METHOD_LABELS[w.method]}{WRITE_OFF_LABELS[w.category]}{w.afterClose ? " (after closing)" : ""}{w.reason || "—"}{money(w.amount)}
+
+ ) : null; + })()} + {reconciled?.byMethod?.cash?.denominations?.length ? (
Cash denomination count
@@ -604,19 +641,273 @@ function ReportTab({ eventId, token, data, isClosed }: {
)} -
+ +
+ ); +} + +// ─── Settlement ──────────────────────────────────────────────────────────── +// For each method, where did the expected money end up: in the bank, still on hand (cash), +// or pending (on the card report / a POP we haven't seen in the bank yet) — and what was +// written off (card fees, bank charges, a shortfall). Mirrors settleLine in +// backend/src/utils/cashupUtils.js, which has the final say when the event is closed. + +type WriteOffInput = { category: CashupWriteOffCategory; amount: string; reason: string }; +type SettlementInput = { bankAmount: string; onHandAmount: string; pendingAmount: string; pendingReference: string; writeOffs: WriteOffInput[]; notes: string }; + +const WRITE_OFF_LABELS: Record = { + card_fees: "Card / online fees", + bank_charges: "Bank charges", + cash_shortfall: "Cash shortfall", + other: "Other", +}; +const WRITE_OFF_CATEGORIES = Object.keys(WRITE_OFF_LABELS) as CashupWriteOffCategory[]; +const DEFAULT_WRITE_OFF: Record = { cash: "cash_shortfall", card: "card_fees", eft: "bank_charges", other: "other" }; +const BANK_HELP: Record = { + cash: "What reached the bank, after any deposit fee", + card: "Settled into the bank account", + eft: "Showing on the bank statement", + other: "Received in the bank", +}; +const PENDING_HELP: Record = { + cash: "", + card: "On the card machine / Yoco report, not in the bank yet", + eft: "Proof of payment received, not in the bank yet", + other: "Expected but not in the bank yet", +}; +const PENDING_REFERENCE_PLACEHOLDER: Record = { cash: "", card: "Report or batch reference", eft: "POP reference", other: "Reference" }; + +const round2 = (n: number) => Math.round(n * 100) / 100; +const emptySettlement = (): SettlementInput => ({ bankAmount: "", onHandAmount: "", pendingAmount: "", pendingReference: "", writeOffs: [], notes: "" }); +const amountText = (v: string | number | null | undefined) => (v === null || v === undefined ? "" : String(v)); + +function settle(method: CashupMethod, expected: number, counted: number | null, input: SettlementInput) { + const num = (v: string) => (v.trim() === "" || isNaN(Number(v)) ? null : Number(v)); + const bank = num(input.bankAmount); + const writeOffTotal = round2(input.writeOffs.reduce((s, w) => s + (num(w.amount) || 0), 0)); + // A deposit fee comes out of the counted cash that was banked. + const depositFees = round2(input.writeOffs.filter(w => w.category === "bank_charges").reduce((s, w) => s + (num(w.amount) || 0), 0)); + const onHand = method === "cash" ? (counted !== null ? round2(counted - (bank || 0) - depositFees) : num(input.onHandAmount)) : null; + const pending = method === "cash" ? null : num(input.pendingAmount); + const entered = [bank, onHand, pending].some(v => v !== null) || input.writeOffs.some(w => num(w.amount) !== null); + const actual = entered ? round2((bank || 0) + (onHand || 0) + (pending || 0)) : null; + return { bank, onHand, pending, writeOffTotal, actual, unaccounted: actual === null ? null : round2(expected - actual - writeOffTotal) }; +} + +function UnaccountedBadge({ unaccounted }: { unaccounted: number | null }) { + if (unaccounted === null) return Not settled yet; + if (Math.abs(unaccounted) < 0.005) return All accounted for; + return ( + + {unaccounted > 0 ? `${money(unaccounted)} unaccounted` : `${money(-unaccounted)} more than expected`} + + ); +} + +function SettlementCard({ method, data, counted, input, onChange }: { + method: CashupMethod; data: EventFinancials; counted: number | null; input: SettlementInput; onChange: (next: SettlementInput) => void; +}) { + const expected = data.expectedCashByMethod[method]; + const s = settle(method, expected, counted, input); + const set = (field: keyof SettlementInput, value: string) => onChange({ ...input, [field]: value }); + const setWriteOff = (i: number, patch: Partial) => + onChange({ ...input, writeOffs: input.writeOffs.map((w, j) => (j === i ? { ...w, ...patch } : w)) }); + const addWriteOff = () => onChange({ ...input, writeOffs: [...input.writeOffs, { category: DEFAULT_WRITE_OFF[method], amount: "", reason: "" }] }); + const removeWriteOff = (i: number) => onChange({ ...input, writeOffs: input.writeOffs.filter((_, j) => j !== i) }); + + return ( +
+
-
Donations counted as profit
-
{money(data.unallocatedDonationsTotal)}
+
{METHOD_LABELS[method]}
+
+ Expected {money(expected)} + {data.costsByMethod[method] > 0 && <> ({money(data.paymentsByMethod[method])} taken, less {money(data.costsByMethod[method])} paid out)} +
+ +
+ +
-
Total costs
-
{money(data.totalCosts)}
+ + set("bankAmount", e.target.value)} /> +

{BANK_HELP[method]}

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

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

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

{PENDING_HELP[method]}

+
+ )} +
+ +
+
Write-offs
+ {input.writeOffs.map((w, i) => ( +
+ + setWriteOff(i, { amount: e.target.value })} /> + setWriteOff(i, { reason: e.target.value })} /> + +
+ ))} + +
+ +
+ + set("notes", e.target.value)} /> +
+
+ ); +} + +// A closed method's settlement, read-only, with a way to settle pending money that has +// since arrived (or never will) without reopening the event. +function SettledCard({ method, r, token, onChanged }: { method: CashupMethod; r: ReconciledByMethod; token: string; onChanged: () => void }) { + return ( +
+
-
Net profit
-
{money(data.netProfit)}
+
{METHOD_LABELS[method]}
+
Expected {money(r.expected)}
+ +
+
+
In bank
{r.bank !== null ? money(r.bank) : "—"}
+ {method === "cash" + ?
On hand
{r.onHand !== null ? money(r.onHand) : "—"}
+ :
Pending
{r.pendingOutstanding > 0 ? money(r.pendingOutstanding) : "—"}
} +
Written off
{r.writeOffTotal > 0 ? money(r.writeOffTotal) : "—"}
+
Actual
{r.actual !== null ? money(r.actual) : "—"}
+
+ {r.writeOffs.length > 0 && ( +
    + {r.writeOffs.map((w, i) => ( +
  • + {WRITE_OFF_LABELS[w.category]} {money(w.amount)}{w.reason ? ` — ${w.reason}` : ""}{w.afterClose ? " (after closing)" : ""} +
  • + ))} +
+ )} + {(r.pending || 0) > 0 && ( + + )} + {r.notes &&
Notes: {r.notes}
} +
+ ); +} + +function PendingSettler({ method, r, token, onChanged }: { method: CashupMethod; r: ReconciledByMethod; token: string; onChanged: () => void }) { + const [mode, setMode] = useState<"received" | "written_off" | null>(null); + const [amount, setAmount] = useState(""); + const [category, setCategory] = useState(DEFAULT_WRITE_OFF[method]); + const [notes, setNotes] = useState(""); + const [saving, setSaving] = useState(false); + const [err, setErr] = useState(null); + + const start = (m: "received" | "written_off") => { setMode(m); setAmount(String(r.pendingOutstanding)); setNotes(""); setErr(null); }; + + const save = async () => { + if (!r.lineId || !mode) return; + setSaving(true); setErr(null); + try { + await apiFetch(`/api/cashups/lines/${r.lineId}/pending`, { method: "POST", authToken: token, body: { outcome: mode, amount: parseFloat(amount), category, notes: notes || null } }); + setMode(null); + onChanged(); + } catch (e) { + setErr(errorMessage(e) || "Failed to save"); + } finally { + setSaving(false); + } + }; + + return ( +
+
+ + Pending {money(r.pending)}{r.pendingReference ? ` (${r.pendingReference})` : ""} + {r.pendingOutstanding > 0 ? <> — {money(r.pendingOutstanding)} still outstanding : " — all settled"} + + {r.pendingOutstanding > 0 && mode === null && ( + + + + + )} +
+ {r.pendingResolutions.length > 0 && ( +
    + {r.pendingResolutions.map(p => ( +
  • + {p.outcome === "received" ? "Received in bank" : `Written off (${WRITE_OFF_LABELS[p.category || "other"]})`} {money(p.amount)} + {" — "}{p.performedBy?.name || "Unknown"}, {new Date(p.createdAt).toLocaleDateString()}{p.notes ? ` — ${p.notes}` : ""} +
  • + ))} +
+ )} + {mode !== null && ( +
+ setAmount(e.target.value)} /> + {mode === "written_off" && ( + + )} + setNotes(e.target.value)} /> + + + {err && {err}} +
+ )} +
+ ); +} + +function ProfitSummary({ data }: { data: EventFinancials }) { + return ( +
+
+
Donations counted as profit
+
{money(data.unallocatedDonationsTotal)}
+
+
+
Total costs
+
{money(data.totalCosts)}
+
+
+
Bank & card charges
+
{money(data.totalWriteOffs)}
+
+
+
Pending (outstanding)
+
{money(data.pendingOutstandingTotal)}
+
+
+
Net profit
+
{money(data.netProfit)}
); @@ -629,32 +920,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 = useMemo(() => { - const base: Record = { cash: { actualAmount: "", notes: "" }, card: { actualAmount: "", notes: "" }, eft: { actualAmount: "", notes: "" }, other: { actualAmount: "", notes: "" } }; + const initialLines: Record = useMemo(() => { + const base: Record = { cash: emptySettlement(), card: emptySettlement(), eft: emptySettlement(), other: emptySettlement() }; for (const l of draftLines || []) { - if (l.method in base) 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>(initialLines); + const [lines, setLines] = useState>(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 +981,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 +1002,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 +1029,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 (
-
-
Cash-up reconciliation
- - - - - - - - - - - - - - {METHODS.map(m => { - const r = reconciled?.byMethod?.[m]; - return ( - - - - - - - - - - ); - })} - -
MethodIncomeCosts from methodExpected cashActualVarianceNotes
{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)} /> - )} -
- {!isClosed && ( -
Cash actual is the live sum of per-staff-member counts entered below — there's no separate event-wide entry.
+
+
+
Where did the money end up?
+
+ {isClosed + ? "As recorded when the event was closed. Pending money can be marked received or written off without reopening." + : "For each payment method, say how much is in the bank, still on hand or pending, and write off anything lost to fees, charges or shortfalls."} +
+
+ {isClosed ? ( + reconciled?.action === "closed" && settledMethods.length > 0 ? ( + settledMethods.map(m => ) + ) : ( +
This event was quick closed, so no settlement was recorded.
+ ) + ) : shownMethods.length === 0 ? ( +
No payments to settle for this event.
+ ) : ( + shownMethods.map(m => ( + setLine(m, next)} + /> + )) )}
@@ -789,20 +1089,7 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh })()}
-
-
-
Donations counted as profit
-
{money(data.unallocatedDonationsTotal)}
-
-
-
Total costs
-
{money(data.totalCosts)}
-
-
-
Net profit
-
{money(data.netProfit)}
-
-
+ {!isClosed && (
diff --git a/apps/events/frontend/src/app/dashboard/admin/cashup/page.tsx b/apps/events/frontend/src/app/dashboard/admin/cashup/page.tsx index 036f769..8b932e1 100644 --- a/apps/events/frontend/src/app/dashboard/admin/cashup/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/cashup/page.tsx @@ -8,6 +8,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { Wallet } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Event } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; export default function CashupLandingPage() { const { token } = useAuth(); @@ -55,15 +56,11 @@ export default function CashupLandingPage() {
-

Post-event Cashup

+ +

Post-event Cashup

Set costs, reconcile takings, and close out an event. Admin only.

- {error &&
{error}
} diff --git a/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx b/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx index 9bd901f..39eade3 100644 --- a/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx @@ -8,6 +8,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { ClipboardList } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Event, FormResponse, Registration } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; const STATUS_OPTIONS = ["pending", "confirmed", "partial_paid", "paid", "cancelled"] as const; @@ -197,11 +198,11 @@ export default function AdminRegistrationsPage() {
-

Manage Registrations

+ +

Manage Registrations

{registrations.length} registration{registrations.length !== 1 ? "s" : ""} total

- {!isAdmin && ( diff --git a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx index b738983..a2369c9 100644 --- a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx @@ -2,7 +2,7 @@ import React, { Suspense, useCallback, useEffect, useRef, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; -import { useRouter, useSearchParams } from "next/navigation"; +import { useSearchParams } from "next/navigation"; import { apiFetch, ApiError, API_BASE, resolveToApiOrigin } from "@/lib/api"; import { useSiteSettings } from "@/contexts/SiteSettingsContext"; import { useDismissingState } from "@/hooks/useDismissingState"; @@ -14,6 +14,7 @@ import { YocoTab } from "@/components/admin/YocoTab"; import { extractDominantColors } from "@/lib/extractColors"; import { mapsSearchUrl } from "@/lib/maps"; import { errorMessage } from "@/lib/utils"; +import { BackLink } from "@/components/shared/BackLink"; type TabId = "organisation" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "yoco" | "backups"; @@ -85,7 +86,6 @@ export default function SiteSettingsPage() { function SiteSettingsPageInner() { const { token } = useAuth(); - const router = useRouter(); const searchParams = useSearchParams(); const { reload: reloadSettings } = useSiteSettings(); @@ -366,15 +366,10 @@ function SiteSettingsPageInner() { {/* Header */}
-

Site Settings

+ +

Site Settings

Configure your organisation, branding, email, and legal pages.

-
{/* Tab bar */} diff --git a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx index 24322a9..6e08dfd 100644 --- a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx @@ -10,6 +10,7 @@ import { Users as UsersIcon } from "lucide-react"; import { RoleBadge, type Role as RoleBadgeRole } from "@/components/shared/RoleBadge"; import { errorMessage } from "@/lib/utils"; import type { Paginated } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; interface UserItem { id: string; @@ -259,12 +260,12 @@ export default function AdminUsersPage() {
-

User Management

+ +

User Management

{total} user{total !== 1 ? "s" : ""} total

- diff --git a/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx b/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx index 1050d19..c57d2fc 100644 --- a/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx @@ -10,6 +10,7 @@ import { QrImage } from "@/components/shared/QrImage"; import { Ticket } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Event, Ticket as TicketRecord } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; function EventTicketsContent() { const { token, user } = useAuth(); @@ -239,14 +240,11 @@ function EventTicketsContent() {
-

Event Tickets

+
+ +

Event Tickets

+
-

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(null); @@ -42,7 +41,7 @@ export default function MyGroupsPage() {

- +

My groups

Rooms, small groups and buses you lead

diff --git a/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx b/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx index 6c0162b..2700d55 100644 --- a/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx @@ -5,13 +5,13 @@ import { QRScanner, QRScannerHandle } from "@/components/qr/QRScanner"; import { useAuth } from "@/hooks/useAuth"; import { apiFetch } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; -import { useRouter } from "next/navigation"; import { QrCode } from "lucide-react"; import { useOfflineScanning } from "@/components/scanner/useOfflineScanning"; import { OfflineScanPanel } from "@/components/scanner/OfflineScanPanel"; import type { SnapshotTicket } from "@/lib/offlineScan"; import { errorMessage } from "@/lib/utils"; import type { Event, RecentScan, ScanStats, Section } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; // GET /api/tickets/scan-preview/:qr — just the fields the confirm step needs. Offline // scans build the same shape from the downloaded ticket list. @@ -33,7 +33,6 @@ type ScanTicket = { }; export default function TicketScanningPage() { - const router = useRouter(); const scannerRef = useRef(null); const [scanInfo, setScanInfo] = useDismissingState(null); const [error, setError] = useDismissingState(null); @@ -330,9 +329,11 @@ export default function TicketScanningPage() {
-

Ticket Scanning

+
+ +

Ticket Scanning

+
-

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() {

- +

Rooms & groups

Put attendees into rooms, small groups, teams or buses

diff --git a/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx index a774ac0..90ac0b1 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx @@ -10,6 +10,7 @@ import { ShieldCheck, Send, RefreshCw, HeartPulse, Printer } from "lucide-react" import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table"; import { errorMessage } from "@/lib/utils"; import type { Event, ConsentRow, MedicalRow } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; const STATUS_STYLE: Record = { @@ -134,7 +135,7 @@ export default function ConsentTrackerPage() {
- +

Parental consent

Youth events: who still needs a parent's consent before check-in

diff --git a/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx index ad8533e..5cbfa8a 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx @@ -8,6 +8,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { TicketPercent, Plus, X, Search } 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"; type CouponType = "percent" | "fixed" | "comp"; type Role = "user" | "staff" | "supervisor" | "admin"; @@ -206,7 +207,7 @@ export default function CouponsPage() {
- +

Coupon codes

Discounts for staff, leaders, volunteers and promotions

diff --git a/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx index 25549e1..ca08500 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx @@ -9,6 +9,7 @@ import { Mail, Users, Zap, Clock } from "lucide-react"; import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter"; import { errorMessage } from "@/lib/utils"; import type { Event, MessageSendResult, Registration, User } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; type Attendee = { id: string; name: string; email: string; pref: string }; type TemplateKey = 'custom'|'payment_reminder'|'event_reminder'|'tickets'; @@ -489,10 +490,10 @@ function EmailAttendeesPageInner() {
-

Email Attendees

- -
- +
+ +

Email Attendees

+
diff --git a/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx index 8b5aaa2..7956187 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx @@ -8,6 +8,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { Ticket } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Event, EventOption } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; // Format a Date (or date-like input) to the value expected by // This returns local time (browser timezone) as YYYY-MM-DDTHH:mm @@ -209,9 +210,11 @@ function EventOptionsContent() {
-

Event options

+
+ +

Event options

+
- {!canView && ( diff --git a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx index a2b88ec..ba3296f 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx @@ -12,6 +12,7 @@ import { Calendar } from "lucide-react"; import { ChoicesEditor } from "@/components/shared/FormFieldExtras"; import { errorMessage } from "@/lib/utils"; import type { Event, EventAttachment, EventFormField, EventOption, Paginated, Section } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; // ─── helpers ──────────────────────────────────────────────────────────────── @@ -1792,13 +1793,13 @@ export default function ManageEventsPage() {
-

Events

+ +

Events

Manage and create events

-
diff --git a/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx index f5e067e..07609c9 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx @@ -9,6 +9,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { FileText } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Event, EventForm, FormResponse, Registration, User } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; type FormFieldType = 'yes_no' | 'text' | 'date' | 'numeric' | 'statement' | 'paragraph' | 'rating' | 'multiple_choice'; @@ -452,10 +453,12 @@ export default function FormsBrowserPage() {
-

Forms

+
+ +

Forms

+
- {mode === 'view' && (
diff --git a/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx index a949fad..1981d30 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx @@ -12,6 +12,7 @@ import { UserPlus, CreditCard } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { optionUnitNow, variantUnitNow } from "@/lib/pricing"; import type { Event, EventOption, Registration, RegistrationOption, User } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; // ─── Pricing helpers ───────────────────────────────────────────────────────── @@ -348,9 +349,11 @@ export default function ManualRegistrationPage() {
-

Manual registration

+
+ +

Manual registration

+
- {!canView && ( diff --git a/apps/events/frontend/src/app/dashboard/supervisor/offline-scans/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/offline-scans/page.tsx index 17d4abc..c4474f5 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/offline-scans/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/offline-scans/page.tsx @@ -9,6 +9,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { WifiOff, Unlock, CheckCircle2 } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Event } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; type Lock = { id: string; sectionName: string | null; deviceName: string | null; user: { name: string }; lockedAt: string; snapshotAt: string | null; lastSyncAt: string | null }; type Report = { @@ -86,7 +87,7 @@ export default function OfflineScansPage() {
- +

Offline scanning

Devices scanning without a connection, and their synced scans

diff --git a/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx index be2c908..eab36a9 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx @@ -10,6 +10,7 @@ import { Wallet, RotateCcw, HandHeart, ScanLine, Link2 } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { registrationOptionUnitPrice } from "@/lib/pricing"; import type { Event, Payment, Registration, User } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; // A donation is never mutated once created — assigning it to a registration creates a separate // "leg" Payment row (isDonation:false, originalPaymentId -> the donation, amount > 0) instead. @@ -499,9 +500,11 @@ function PaymentsContent() {
-

Payments

+
+ +

Payments

+
- {!canView && ( diff --git a/apps/events/frontend/src/app/dashboard/supervisor/reports/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/reports/page.tsx index 2841ed2..2d8fdc5 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/reports/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/reports/page.tsx @@ -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 (
Loading…
}> - router.push('/dashboard')} /> + ); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/waitlist/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/waitlist/page.tsx index 8bfce8c..fdc95a4 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/waitlist/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/waitlist/page.tsx @@ -10,6 +10,7 @@ import { ListChecks, ArrowUp, ArrowDown } from "lucide-react"; import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table"; import { errorMessage } from "@/lib/utils"; import type { Event } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; type Entry = { id: string; @@ -100,7 +101,7 @@ export default function WaitlistPage() {
- +

Waitlist

People waiting for sold-out tickets

diff --git a/apps/events/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx index 8d98cc0..bdf68da 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx @@ -9,6 +9,7 @@ import { MessageCircle, Users, Zap, Send, Clock, type LucideIcon } from "lucide- import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter"; import { errorMessage } from "@/lib/utils"; import type { Event, MessageSendResult, Registration, User } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; // Attendee with preference info type Attendee = { id: string; name: string; phone: string; pref: string }; @@ -608,11 +609,11 @@ function WhatsAppAttendeesPageInner() {
-

WhatsApp Attendees

+
+ +

WhatsApp Attendees

+
- {!canView && ( diff --git a/apps/events/frontend/src/app/dashboard/user/donate/page.tsx b/apps/events/frontend/src/app/dashboard/user/donate/page.tsx index 3ee06c8..9ceaf2b 100644 --- a/apps/events/frontend/src/app/dashboard/user/donate/page.tsx +++ b/apps/events/frontend/src/app/dashboard/user/donate/page.tsx @@ -6,6 +6,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { HandHeart } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Event } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; export default function DonatePage() { const { token } = useAuth(); @@ -65,7 +66,8 @@ export default function DonatePage() {
-

Make a donation

+ +

Make a donation

Support an event or the ministry directly.

diff --git a/apps/events/frontend/src/app/dashboard/user/forms/page.tsx b/apps/events/frontend/src/app/dashboard/user/forms/page.tsx index 5f8dad8..8df2046 100644 --- a/apps/events/frontend/src/app/dashboard/user/forms/page.tsx +++ b/apps/events/frontend/src/app/dashboard/user/forms/page.tsx @@ -8,6 +8,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { FileText } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Registration } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; // Types for form fields type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown }; @@ -139,9 +140,11 @@ function FormsContent() {
-

Attendee forms

+
+ +

Attendee forms

+
- {loading &&
Loading…
} diff --git a/apps/events/frontend/src/app/dashboard/user/payments/page.tsx b/apps/events/frontend/src/app/dashboard/user/payments/page.tsx index 0acd7cb..3b0c6c1 100644 --- a/apps/events/frontend/src/app/dashboard/user/payments/page.tsx +++ b/apps/events/frontend/src/app/dashboard/user/payments/page.tsx @@ -9,6 +9,7 @@ import { formatPaymentMethod } from "@/lib/paymentMethod"; import { Receipt } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Paginated } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; interface PaymentItem { id: string; @@ -108,12 +109,11 @@ export default function UserPaymentsPage() {
-

My Payments

+
+ +

My Payments

+
- {error &&

{error}

} diff --git a/apps/events/frontend/src/app/dashboard/user/profile/page.tsx b/apps/events/frontend/src/app/dashboard/user/profile/page.tsx index 35a1054..1677fb5 100644 --- a/apps/events/frontend/src/app/dashboard/user/profile/page.tsx +++ b/apps/events/frontend/src/app/dashboard/user/profile/page.tsx @@ -9,6 +9,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { TwoFactorChallenge, TwoFactorMethod } from "@/lib/auth"; import { User, Lock, ShieldAlert, ShieldCheck, ShieldOff, Trash2, Clock, LogIn, KeyRound, RotateCcw } from "lucide-react"; import { errorMessage } from "@/lib/utils"; +import { BackLink } from "@/components/shared/BackLink"; type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string }; @@ -309,7 +310,8 @@ export default function UserProfilePage() { return (
-

Profile & Security

+ +

Profile & Security

Manage your personal information and keep your account secure.

diff --git a/apps/events/frontend/src/app/dashboard/user/reset-password/page.tsx b/apps/events/frontend/src/app/dashboard/user/reset-password/page.tsx index 81236ed..1348fe0 100644 --- a/apps/events/frontend/src/app/dashboard/user/reset-password/page.tsx +++ b/apps/events/frontend/src/app/dashboard/user/reset-password/page.tsx @@ -6,6 +6,7 @@ import { useDismissingState } from "@/hooks/useDismissingState"; import { useRouter } from "next/navigation"; import { KeyRound } from "lucide-react"; import { errorMessage } from "@/lib/utils"; +import { BackLink } from "@/components/shared/BackLink"; export default function ResetPasswordPage() { const { token } = useAuth(); @@ -50,12 +51,11 @@ export default function ResetPasswordPage() {
-

Reset password

+
+ +

Reset password

+
- {error &&

{error}

} diff --git a/apps/events/frontend/src/components/reports/ReportsShell.tsx b/apps/events/frontend/src/components/reports/ReportsShell.tsx index 3efdc6a..9c15dee 100644 --- a/apps/events/frontend/src/components/reports/ReportsShell.tsx +++ b/apps/events/frontend/src/components/reports/ReportsShell.tsx @@ -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({
-

Reports

+ {backHref && } +

Reports

View, export, or email operational reports for events.

@@ -80,11 +82,6 @@ export default function ReportsShell({ onChange={e => setSearch(e.target.value)} />
- {onBack && ( - - )}
diff --git a/apps/events/frontend/src/components/reports/ReportsV2.tsx b/apps/events/frontend/src/components/reports/ReportsV2.tsx index 863c23b..8ae483e 100644 --- a/apps/events/frontend/src/components/reports/ReportsV2.tsx +++ b/apps/events/frontend/src/components/reports/ReportsV2.tsx @@ -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 = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" }; +const WRITE_OFF_LABEL: Record = { 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 = {}; 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 && ( diff --git a/apps/events/frontend/src/components/shared/BackLink.tsx b/apps/events/frontend/src/components/shared/BackLink.tsx new file mode 100644 index 0000000..27b5671 --- /dev/null +++ b/apps/events/frontend/src/components/shared/BackLink.tsx @@ -0,0 +1,14 @@ +import React from "react"; +import Link from "next/link"; + +/** + * The site-wide "← Back to …" link, shown above a page's title (next to its icon tile). + * Every dashboard page uses this one so back navigation looks and sits the same everywhere. + */ +export function BackLink({ href, label = "Back to dashboard" }: { href: string; label?: string }) { + return ( + + ← {label} + + ); +} diff --git a/apps/events/frontend/src/content/help/dashboard-admin-cashup.tsx b/apps/events/frontend/src/content/help/dashboard-admin-cashup.tsx index f0c63dc..44f6457 100644 --- a/apps/events/frontend/src/content/help/dashboard-admin-cashup.tsx +++ b/apps/events/frontend/src/content/help/dashboard-admin-cashup.tsx @@ -43,13 +43,23 @@ export const dashboardAdminCashupDetailHelpContent: HelpContent = { icon: ClipboardCheck, content: (
-

A per-method table (cash, card, EFT, other) compares income, costs charged to that method, and expected vs actual amounts.

+

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.

+
    +
  • In bank: card settlements, EFTs on the statement, cash that was deposited.
  • +
  • Cash on hand: cash not deposited yet.
  • +
  • Pending: on the card machine or Yoco report, or you have a proof of payment, but it isn't in the bank yet. Add the report or POP reference.
  • +
  • Write-offs: money that's gone, such as card fees, bank charges or a cash shortfall. Write-offs come off net profit and show as "Bank & card charges" in the reports.
  • +
+

Each method shows what's still unaccounted. You can close with an unaccounted amount, but you'll be warned and it comes off profit.

- Cash's "actual" figure isn't typed directly — it'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 reached the bank and any deposit fee (written off as a bank charge). + + + 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't need to reopen the event. - 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.
@@ -61,7 +71,7 @@ export const dashboardAdminCashupDetailHelpContent: HelpContent = { icon: FileBarChart, content: (
-

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.

+

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.

), }, diff --git a/apps/events/frontend/src/types/index.ts b/apps/events/frontend/src/types/index.ts index 2f5b8e2..01ac112 100644 --- a/apps/events/frontend/src/types/index.ts +++ b/apps/events/frontend/src/types/index.ts @@ -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; }; +// 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; effectiveTotalRevenue: number; + writeOffsByMethod: Record; + writeOffsByCategory: Record; + // 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;