From 1d8f5616c8cc8238c52a6d84d56a2a94b11ad46f Mon Sep 17 00:00:00 2001 From: joshua Date: Wed, 21 Oct 2026 13:25:04 +0200 Subject: [PATCH] Settle cashups: where the money ended up A full cashup now records, per payment method, how much of the expected takings is in the bank, still on hand (cash) or pending (on the card report or with a POP), and writes off what was lost to card fees, bank charges or a shortfall. Whatever is left is shown as unaccounted; closing with an unaccounted amount is allowed after a warning. Pending money can be marked received or written off after the event is closed, without reopening it. Reopening starts the next cashup from the last one. Write-offs come off net profit and show as "Bank & card charges" in the cashup, finance and profit reports. The reports page also moves to the shared back link. Co-Authored-By: Claude Opus 5.5 --- .../migration.sql | 53 ++ apps/events/backend/prisma/schema.prisma | 67 ++- .../src/controllers/cashupController.js | 162 ++++-- .../events/backend/src/routes/cashupRoutes.js | 3 +- apps/events/backend/src/utils/cashupUtils.js | 157 +++++- .../backend/tests/cashupSettlement.test.js | 136 +++++ .../app/dashboard/admin/cashup/[id]/page.tsx | 487 ++++++++++++++---- .../app/dashboard/supervisor/reports/page.tsx | 4 +- .../src/components/reports/ReportsShell.tsx | 15 +- .../src/components/reports/ReportsV2.tsx | 32 +- .../content/help/dashboard-admin-cashup.tsx | 18 +- apps/events/frontend/src/types/index.ts | 56 +- 12 files changed, 1004 insertions(+), 186 deletions(-) create mode 100644 apps/events/backend/prisma/migrations/20261021110951_add_cashup_settlement/migration.sql create mode 100644 apps/events/backend/tests/cashupSettlement.test.js 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..b50b087 100644 --- a/apps/events/backend/src/utils/cashupUtils.js +++ b/apps/events/backend/src/utils/cashupUtils.js @@ -6,10 +6,111 @@ const ALL_METHODS = ['cash', 'card', 'eft', 'other']; // Standard South African Rand note/coin denominations used for the cash count grid. const ZAR_DENOMINATIONS = [200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1]; +const WRITE_OFF_CATEGORIES = ['card_fees', 'bank_charges', 'cash_shortfall', 'other']; +const PENDING_OUTCOMES = ['received', 'written_off']; + function emptyByMethod(fill = 0) { return { cash: fill, card: fill, eft: fill, other: fill }; } +const cents = (n) => Math.round(n * 100) / 100; +const sum = (rows) => rows.reduce((s, r) => s + r.amount, 0); + +// A non-negative amount rounded to cents, or null when left blank. +function amountOrNull(value, label) { + if (value === undefined || value === null || value === '') return null; + const n = Number(value); + if (!Number.isFinite(n) || n < 0) throw new Error(`${label} must be zero or more`); + return cents(n); +} + +/** + * Where one method's expected takings ended up, as entered on the cashup screen. Pure. + * + * actual = in bank + on hand + pending (money held or on its way); write-offs explain money + * that's gone (card fees, bank charges, a cash shortfall). Whatever is left — + * expected − actual − write-offs — is unaccounted for. Cash has no pending; when staff + * counted it (per-person counts), the count is all the cash there is, so whatever wasn't + * deposited is on hand. + * + * @param {object} p + * @param {string} p.method - 'cash' | 'card' | 'eft' | 'other' + * @param {number} p.expected - expected amount for the method (payments − costs paid from it) + * @param {number|null} [p.counted] - cash counted by staff, or null when nobody counted + * @param {object} [p.input] - { bankAmount, onHandAmount, pendingAmount, pendingReference, writeOffs: [{ category, amount, reason }] } + */ +function settleLine({ method, expected, counted = null, input = {} }) { + const bankAmount = amountOrNull(input.bankAmount, 'In bank'); + let onHandAmount = method === 'cash' ? amountOrNull(input.onHandAmount, 'Cash on hand') : null; + const pendingAmount = method === 'cash' ? null : amountOrNull(input.pendingAmount, 'Pending'); + + if (method === 'cash' && counted !== null && counted !== undefined) { + if ((bankAmount || 0) > counted + 0.005) throw new Error('More cash was deposited than was counted'); + onHandAmount = cents(counted - (bankAmount || 0)); + } + + const writeOffs = (Array.isArray(input.writeOffs) ? input.writeOffs : []) + .filter(w => w && w.amount !== undefined && w.amount !== null && w.amount !== '') + .map(w => { + if (!WRITE_OFF_CATEGORIES.includes(w.category)) throw new Error('Choose what each write-off is for'); + const amount = amountOrNull(w.amount, 'Write-off'); + if (!(amount > 0)) throw new Error('A write-off must be more than R0'); + return { category: w.category, amount, reason: String(w.reason || '').trim().slice(0, 200) || null }; + }); + const writeOffTotal = cents(sum(writeOffs)); + + const parts = [bankAmount, onHandAmount, pendingAmount]; + const entered = parts.some(v => v !== null) || writeOffs.length > 0; + const actual = entered ? cents(parts.reduce((s, v) => s + (v || 0), 0)) : null; + + return { + bankAmount, + onHandAmount, + pendingAmount, + pendingReference: pendingAmount ? (String(input.pendingReference || '').trim().slice(0, 200) || null) : null, + writeOffs, + writeOffTotal, + actual, + variance: actual === null ? null : cents(actual - expected), + unaccounted: entered ? cents(expected - actual - writeOffTotal) : null, + }; +} + +/** + * A closed cashup line with any later pending resolutions folded in. Pure. + * 'received' moves pending money into the bank (actual unchanged); 'written_off' turns it + * into a write-off (actual goes down). Lines from before settlement existed have only + * actualAmount, so their unaccounted is the old variance. + */ +function applyPendingResolutions(line) { + const resolutions = line.pendingResolutions || []; + const received = cents(sum(resolutions.filter(r => r.outcome === 'received'))); + const lateWriteOffs = resolutions.filter(r => r.outcome === 'written_off'); + const writtenOff = cents(sum(lateWriteOffs)); + + const pending = line.pendingAmount || 0; + const actual = line.actualAmount === null || line.actualAmount === undefined ? null : cents(line.actualAmount - writtenOff); + const writeOffTotal = cents((line.writeOffTotal || 0) + writtenOff); + const expected = line.expectedAmount || 0; + + return { + bank: line.bankAmount == null && received === 0 ? null : cents((line.bankAmount || 0) + received), + onHand: line.onHandAmount ?? null, + pending: line.pendingAmount ?? null, + pendingReference: line.pendingReference || null, + pendingReceived: received, + pendingOutstanding: cents(Math.max(pending - received - writtenOff, 0)), + writeOffs: [ + ...(line.writeOffs || []).map(w => ({ id: w.id, category: w.category, amount: w.amount, reason: w.reason, createdAt: w.createdAt, afterClose: false })), + ...lateWriteOffs.map(r => ({ id: r.id, category: r.category || 'other', amount: r.amount, reason: r.notes, createdAt: r.createdAt, afterClose: true })), + ], + writeOffTotal, + actual, + variance: actual === null ? null : cents(actual - expected), + unaccounted: actual === null && writeOffTotal === 0 ? null : cents(expected - (actual || 0) - writeOffTotal), + }; +} + // Normalizes a free-text Payment.method into one of the fixed cashup buckets. // Card-network wallets (Apple Pay, Google Pay, etc.) settle exactly like a card payment — // no separate float to reconcile — so they belong in the 'card' bucket, not 'other'. @@ -88,7 +189,13 @@ async function computeEventFinancials(eventId) { prisma.eventCashup.findMany({ where: { eventId }, include: { - lines: { include: { denominations: true } }, + lines: { + include: { + denominations: true, + writeOffs: { orderBy: { createdAt: 'asc' } }, + pendingResolutions: { include: { performedBy: { select: { id: true, name: true } } }, orderBy: { createdAt: 'asc' } } + } + }, performedBy: { select: { id: true, name: true, email: true } } }, orderBy: { createdAt: 'desc' } @@ -169,29 +276,55 @@ async function computeEventFinancials(eventId) { const out = {}; for (const m of ALL_METHODS) { const line = latestReconciled.lines.find(l => l.method === m); + const settled = line ? applyPendingResolutions(line) : null; out[m] = { + lineId: line ? line.id : null, expected: line ? line.expectedAmount : expectedCashByMethod[m], - actual: line && line.actualAmount != null ? line.actualAmount : null, - variance: line && line.variance != null ? line.variance : null, + actual: settled ? settled.actual : null, + variance: settled ? settled.variance : null, notes: line ? line.notes : null, - denominations: line ? line.denominations : [] + denominations: line ? line.denominations : [], + bank: settled ? settled.bank : null, + onHand: settled ? settled.onHand : null, + pending: settled ? settled.pending : null, + pendingReference: settled ? settled.pendingReference : null, + pendingReceived: settled ? settled.pendingReceived : 0, + pendingOutstanding: settled ? settled.pendingOutstanding : 0, + pendingResolutions: line ? line.pendingResolutions : [], + writeOffs: settled ? settled.writeOffs : [], + writeOffTotal: settled ? settled.writeOffTotal : 0, + unaccounted: settled ? settled.unaccounted : null }; } return out; })() } : null; + // Money written off at (or after) the cashup: card fees, bank charges, shortfalls. + const writeOffsByMethod = emptyByMethod(); + const writeOffsByCategory = Object.fromEntries(WRITE_OFF_CATEGORIES.map(c => [c, 0])); + let pendingOutstandingTotal = 0; + for (const m of ALL_METHODS) { + const r = reconciled?.byMethod?.[m]; + if (!r) continue; + writeOffsByMethod[m] = r.writeOffTotal; + pendingOutstandingTotal += r.pendingOutstanding; + for (const w of r.writeOffs) writeOffsByCategory[w.category] = cents((writeOffsByCategory[w.category] || 0) + w.amount); + } + const totalWriteOffs = cents(ALL_METHODS.reduce((s, m) => s + writeOffsByMethod[m], 0)); + // Reconciled value is truth; system (expected) value is the fallback when nothing was counted. - // Tagged costs are added back so a reconciled cash count still yields a correct *gross* income figure — - // costs get subtracted from profit exactly once, via totalCosts, never twice. + // Tagged costs and write-offs are added back so income stays a *gross* figure — costs and + // write-offs each come off profit exactly once, below, never twice. (Unaccounted money + // isn't added back: it lowers income, like any variance.) const effectiveGrossIncomeByMethod = emptyByMethod(); for (const m of ALL_METHODS) { const actual = reconciled?.byMethod?.[m]?.actual; - const base = actual != null ? actual : expectedCashByMethod[m]; + const base = actual != null ? actual + writeOffsByMethod[m] : expectedCashByMethod[m]; effectiveGrossIncomeByMethod[m] = base + costsByMethod[m]; } const effectiveTotalRevenue = ALL_METHODS.reduce((s, m) => s + effectiveGrossIncomeByMethod[m], 0); - const netProfit = effectiveTotalRevenue - totalCosts; + const netProfit = effectiveTotalRevenue - totalCosts - totalWriteOffs; // What was actually sold, by ticket type — for the Finance report's income-stream breakdown. // Revenue is tranche-aware: a line spanning two early-bird prices contributes each tranche @@ -221,6 +354,10 @@ async function computeEventFinancials(eventId) { reconciled, effectiveGrossIncomeByMethod, effectiveTotalRevenue, + writeOffsByMethod, + writeOffsByCategory, + totalWriteOffs, + pendingOutstandingTotal: cents(pendingOutstandingTotal), netProfit, unallocatedDonations, unallocatedDonationsTotal, @@ -362,6 +499,10 @@ module.exports = { METHOD_BUCKETS, ALL_METHODS, ZAR_DENOMINATIONS, + WRITE_OFF_CATEGORIES, + PENDING_OUTCOMES, + settleLine, + applyPendingResolutions, bucketForMethod, isDonationLeg, assertEventOpen, diff --git a/apps/events/backend/tests/cashupSettlement.test.js b/apps/events/backend/tests/cashupSettlement.test.js new file mode 100644 index 0000000..59e26d6 --- /dev/null +++ b/apps/events/backend/tests/cashupSettlement.test.js @@ -0,0 +1,136 @@ +const { settleLine, applyPendingResolutions } = require('../src/utils/cashupUtils'); + +describe('settleLine', () => { + test('card settled net of fees, with the fees written off, leaves nothing unaccounted', () => { + const s = settleLine({ + method: 'card', + expected: 12450, + input: { bankAmount: '12080.40', writeOffs: [{ category: 'card_fees', amount: '369.60', reason: 'Yoco 2.95%' }] }, + }); + expect(s.actual).toBe(12080.4); + expect(s.writeOffTotal).toBe(369.6); + expect(s.unaccounted).toBe(0); + expect(s.variance).toBe(-369.6); + expect(s.writeOffs).toEqual([{ category: 'card_fees', amount: 369.6, reason: 'Yoco 2.95%' }]); + }); + + test('EFT with a POP not yet in the bank counts the pending money as accounted for', () => { + const s = settleLine({ method: 'eft', expected: 8200, input: { bankAmount: 7200, pendingAmount: 1000, pendingReference: 'POP #417' } }); + expect(s.actual).toBe(8200); + expect(s.pendingAmount).toBe(1000); + expect(s.pendingReference).toBe('POP #417'); + expect(s.unaccounted).toBe(0); + }); + + test('a pending reference is dropped when nothing is pending', () => { + const s = settleLine({ method: 'eft', expected: 100, input: { bankAmount: 100, pendingReference: 'POP' } }); + expect(s.pendingReference).toBeNull(); + }); + + test('counted cash that was not deposited is on hand, and a shortfall shows as unaccounted', () => { + const s = settleLine({ method: 'cash', expected: 3000, counted: 2950, input: { bankAmount: 2000, onHandAmount: 999 } }); + expect(s.onHandAmount).toBe(950); // derived from the count, not the typed 999 + expect(s.actual).toBe(2950); + expect(s.unaccounted).toBe(50); + }); + + test('a cash shortfall written off leaves nothing unaccounted', () => { + const s = settleLine({ method: 'cash', expected: 3000, counted: 2950, input: { bankAmount: 2950, writeOffs: [{ category: 'cash_shortfall', amount: 50 }] } }); + expect(s.onHandAmount).toBe(0); + expect(s.unaccounted).toBe(0); + }); + + test('cash never has a pending amount', () => { + const s = settleLine({ method: 'cash', expected: 500, input: { onHandAmount: 500, pendingAmount: 200 } }); + expect(s.pendingAmount).toBeNull(); + expect(s.actual).toBe(500); + }); + + test('without a count, cash on hand can be typed in', () => { + const s = settleLine({ method: 'cash', expected: 500, counted: null, input: { bankAmount: 300, onHandAmount: 200 } }); + expect(s.actual).toBe(500); + expect(s.unaccounted).toBe(0); + }); + + test('depositing more cash than was counted is rejected', () => { + expect(() => settleLine({ method: 'cash', expected: 500, counted: 400, input: { bankAmount: 450 } })).toThrow('More cash was deposited'); + }); + + test('negative or non-numeric amounts are rejected', () => { + expect(() => settleLine({ method: 'card', expected: 100, input: { bankAmount: -5 } })).toThrow('In bank'); + expect(() => settleLine({ method: 'card', expected: 100, input: { pendingAmount: 'abc' } })).toThrow('Pending'); + }); + + test('a write-off needs a known category and an amount over zero', () => { + expect(() => settleLine({ method: 'card', expected: 100, input: { writeOffs: [{ category: 'lunch', amount: 5 }] } })).toThrow('what each write-off is for'); + expect(() => settleLine({ method: 'card', expected: 100, input: { writeOffs: [{ category: 'other', amount: 0 }] } })).toThrow('more than R0'); + }); + + test('blank write-off rows are ignored', () => { + const s = settleLine({ method: 'card', expected: 100, input: { bankAmount: 100, writeOffs: [{ category: 'other', amount: '' }] } }); + expect(s.writeOffs).toEqual([]); + }); + + test('nothing entered leaves the method unreconciled', () => { + const s = settleLine({ method: 'eft', expected: 100, input: {} }); + expect(s.actual).toBeNull(); + expect(s.variance).toBeNull(); + expect(s.unaccounted).toBeNull(); + }); + + test('amounts are rounded to cents', () => { + const s = settleLine({ method: 'card', expected: 0.3, input: { bankAmount: 0.1, pendingAmount: 0.2 } }); + expect(s.actual).toBe(0.3); + expect(s.unaccounted).toBe(0); + }); +}); + +describe('applyPendingResolutions', () => { + const line = { + expectedAmount: 8200, + actualAmount: 8200, + bankAmount: 7200, + onHandAmount: null, + pendingAmount: 1000, + pendingReference: 'POP #417', + writeOffTotal: 0, + writeOffs: [], + }; + + test('with nothing settled yet, all the pending money is outstanding', () => { + const s = applyPendingResolutions({ ...line, pendingResolutions: [] }); + expect(s.pendingOutstanding).toBe(1000); + expect(s.bank).toBe(7200); + expect(s.unaccounted).toBe(0); + }); + + test('money received later moves into the bank without changing actual', () => { + const s = applyPendingResolutions({ ...line, pendingResolutions: [{ id: 'r1', outcome: 'received', amount: 600 }] }); + expect(s.bank).toBe(7800); + expect(s.actual).toBe(8200); + expect(s.pendingOutstanding).toBe(400); + expect(s.writeOffTotal).toBe(0); + }); + + test('money written off later lowers actual and becomes a write-off', () => { + const s = applyPendingResolutions({ + ...line, + pendingResolutions: [ + { id: 'r1', outcome: 'received', amount: 600 }, + { id: 'r2', outcome: 'written_off', amount: 400, category: 'other', notes: 'Never paid' }, + ], + }); + expect(s.actual).toBe(7800); + expect(s.writeOffTotal).toBe(400); + expect(s.pendingOutstanding).toBe(0); + expect(s.unaccounted).toBe(0); + expect(s.writeOffs).toEqual([expect.objectContaining({ id: 'r2', category: 'other', amount: 400, reason: 'Never paid', afterClose: true })]); + }); + + test('a line from before settlement existed reports its old variance as unaccounted', () => { + const s = applyPendingResolutions({ expectedAmount: 1000, actualAmount: 980, variance: -20 }); + expect(s.bank).toBeNull(); + expect(s.pendingOutstanding).toBe(0); + expect(s.unaccounted).toBe(20); + }); +}); 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..6d584b3 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,271 @@ 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: "Deposited into the bank", + card: "Settled into the bank account", + eft: "Showing on the bank statement", + other: "Received in the bank", +}; +const PENDING_HELP: Record = { + 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 onHand = method === "cash" ? (counted !== null ? round2(counted - (bank || 0)) : num(input.onHandAmount)) : null; + const pending = method === "cash" ? null : num(input.pendingAmount); + const writeOffTotal = round2(input.writeOffs.reduce((s, w) => s + (num(w.amount) || 0), 0)); + const entered = [bank, onHand, pending].some(v => v !== null) || input.writeOffs.some(w => num(w.amount) !== null); + const actual = entered ? round2((bank || 0) + (onHand || 0) + (pending || 0)) : null; + return { bank, onHand, pending, writeOffTotal, actual, unaccounted: actual === null ? null : round2(expected - actual - writeOffTotal) }; +} + +function UnaccountedBadge({ unaccounted }: { unaccounted: number | null }) { + if (unaccounted === null) return 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` : "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 +918,53 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh const isClosed = data.event.cashupStatus === "closed"; const draftLines = data.event.cashupDraft?.lines; - const initialLines: Record = 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 +979,14 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh }; const closeWithCashup = async () => { - if (!confirm("Close this event with the entered reconciliation? This will count unallocated donations as profit and fully lock the event until it's reopened.")) return; + const open = shownMethods + .map(m => ({ m, s: settle(m, data.expectedCashByMethod[m], m === "cash" ? cashSummary.actualTotal : null, lines[m]) })) + .filter(({ s }) => s.unaccounted === null || Math.abs(s.unaccounted) >= 0.005) + .map(({ m, s }) => `${METHOD_LABELS[m]}: ${s.unaccounted === null ? "not settled" : money(s.unaccounted)}`); + const warning = open.length > 0 + ? `\n\nNot everything is accounted for:\n${open.join("\n")}\n\nThis will be recorded as a variance and comes off profit.` + : ""; + if (!confirm(`Close this event with this cashup? Unallocated donations will be counted as profit and the event will be locked until it's reopened.${warning}`)) return; setBusy(true); setError(null); try { await apiFetch(`/api/cashups/event/${eventId}/close`, { method: "POST", authToken: token, body: { lines: buildLinesPayload(), notes: closeNotes || null } }); @@ -683,7 +1000,7 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh }; const quickClose = async () => { - if (!confirm("Quick close this event without a per-method cashup? System totals will be accepted as-is, unallocated donations will be counted as profit, and the event will be fully locked until it's reopened.")) return; + if (!confirm("Quick close this event without a cashup? System totals will be accepted as-is, unallocated donations will be counted as profit, and the event will be fully locked until it's reopened.")) return; setBusy(true); setError(null); try { await apiFetch(`/api/cashups/event/${eventId}/close`, { method: "POST", authToken: token, body: { notes: closeNotes || null } }); @@ -710,60 +1027,41 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh }; const reconciled = data.reconciled; + const settledMethods = METHODS.filter(m => { + const r = reconciled?.byMethod?.[m]; + return r && (Math.abs(r.expected) > 0.005 || r.actual !== null || r.writeOffTotal > 0); + }); return (
-
-
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 +1087,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/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/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/content/help/dashboard-admin-cashup.tsx b/apps/events/frontend/src/content/help/dashboard-admin-cashup.tsx index f0c63dc..1cad907 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 was deposited. + + + 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;