Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc02f6b9ff | ||
|
|
103c328a6a | ||
|
|
7446388bfa | ||
|
|
8a4c144f6d | ||
|
|
3a68b24a0f | ||
|
|
9be78c3c34 |
@@ -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
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "event-management-backend",
|
||||
"version": "1.26.1",
|
||||
"version": "1.27.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "event-management-backend",
|
||||
"version": "1.26.1",
|
||||
"version": "1.27.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "event-management-backend",
|
||||
"version": "1.26.1",
|
||||
"version": "1.27.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -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;
|
||||
@@ -88,6 +88,7 @@ model User {
|
||||
eventsClosed Event[] @relation("EventClosedBy")
|
||||
eventsReopened Event[] @relation("EventReopenedBy")
|
||||
cashupsPerformed EventCashup[]
|
||||
pendingResolved EventCashupPendingResolution[] @relation("PendingResolutionBy")
|
||||
notifyForEvents Event[] @relation("EventNotifyRecipients")
|
||||
|
||||
personCashCountsFor EventCashupPersonCount[] @relation("EventCashupPersonCountFor")
|
||||
@@ -708,20 +709,68 @@ model EventCashup {
|
||||
@@index([eventId, createdAt])
|
||||
}
|
||||
|
||||
// Where one method's expected takings ended up. actualAmount = bank + on hand + pending
|
||||
// (money held or on its way); write-offs explain money that's gone (fees, charges,
|
||||
// shortfalls). expected - actual - writeOffTotal is what's still unaccounted for.
|
||||
model EventCashupLine {
|
||||
id String @id @default(uuid())
|
||||
cashupId String
|
||||
cashup EventCashup @relation(fields: [cashupId], references: [id], onDelete: Cascade)
|
||||
method String
|
||||
expectedAmount Float @default(0)
|
||||
actualAmount Float?
|
||||
variance Float?
|
||||
notes String?
|
||||
denominations EventCashupDenomination[]
|
||||
id String @id @default(uuid())
|
||||
cashupId String
|
||||
cashup EventCashup @relation(fields: [cashupId], references: [id], onDelete: Cascade)
|
||||
method String
|
||||
expectedAmount Float @default(0)
|
||||
actualAmount Float?
|
||||
variance Float?
|
||||
notes String?
|
||||
bankAmount Float?
|
||||
onHandAmount Float?
|
||||
pendingAmount Float?
|
||||
// Card/Yoco report or POP reference for the pending amount.
|
||||
pendingReference String?
|
||||
writeOffTotal Float @default(0)
|
||||
denominations EventCashupDenomination[]
|
||||
writeOffs EventCashupWriteOff[]
|
||||
pendingResolutions EventCashupPendingResolution[]
|
||||
|
||||
@@index([cashupId])
|
||||
}
|
||||
|
||||
enum CashupWriteOffCategory {
|
||||
card_fees
|
||||
bank_charges
|
||||
cash_shortfall
|
||||
other
|
||||
}
|
||||
|
||||
model EventCashupWriteOff {
|
||||
id String @id @default(uuid())
|
||||
lineId String
|
||||
line EventCashupLine @relation(fields: [lineId], references: [id], onDelete: Cascade)
|
||||
category CashupWriteOffCategory
|
||||
amount Float
|
||||
reason String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([lineId])
|
||||
}
|
||||
|
||||
// Pending money settled after the event was closed: it reached the bank ('received') or
|
||||
// never will ('written_off'). Append-only, like EventCashup — the line itself is never edited.
|
||||
model EventCashupPendingResolution {
|
||||
id String @id @default(uuid())
|
||||
lineId String
|
||||
line EventCashupLine @relation(fields: [lineId], references: [id], onDelete: Cascade)
|
||||
outcome String // 'received' | 'written_off'
|
||||
amount Float
|
||||
category CashupWriteOffCategory?
|
||||
notes String?
|
||||
performedById String?
|
||||
performedBy User? @relation("PendingResolutionBy", fields: [performedById], references: [id], onDelete: SetNull)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([lineId])
|
||||
@@index([performedById])
|
||||
}
|
||||
|
||||
model EventCashupDenomination {
|
||||
id String @id @default(uuid())
|
||||
lineId String
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
const prisma = require('../config/db');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const { safeErrorMessage } = require('../utils/errorUtils');
|
||||
const { ALL_METHODS, assertEventOpen, computeEventFinancials, computeAccountabilityByUser, computeEventCashActualFromPersonCounts, savePersonCashCount } = require('../utils/cashupUtils');
|
||||
const { ALL_METHODS, WRITE_OFF_CATEGORIES, PENDING_OUTCOMES, settleLine, applyPendingResolutions, assertEventOpen, computeEventFinancials, computeAccountabilityByUser, computeEventCashActualFromPersonCounts, savePersonCashCount } = require('../utils/cashupUtils');
|
||||
|
||||
// What the cashup screen sends per method: where the money ended up and what was written off.
|
||||
function cleanDraftLine(l) {
|
||||
return {
|
||||
method: l.method,
|
||||
bankAmount: l.bankAmount ?? null,
|
||||
onHandAmount: l.onHandAmount ?? null,
|
||||
pendingAmount: l.pendingAmount ?? null,
|
||||
pendingReference: l.pendingReference || null,
|
||||
writeOffs: (Array.isArray(l.writeOffs) ? l.writeOffs : []).map(w => ({ category: w.category, amount: w.amount ?? null, reason: w.reason || null })),
|
||||
notes: l.notes || null
|
||||
};
|
||||
}
|
||||
|
||||
// @desc Cashup preview for an event: live expected/actual numbers, costs, donations-to-profit, and history
|
||||
// @route GET /api/cashups/event/:eventId
|
||||
@@ -66,7 +79,7 @@ const saveEventCashupDraft = async (req, res) => {
|
||||
|
||||
await prisma.event.update({
|
||||
where: { id: eventId },
|
||||
data: { cashupDraft: { lines: Array.isArray(lines) ? lines : [], notes: notes || null, savedAt: new Date().toISOString() } }
|
||||
data: { cashupDraft: { lines: (Array.isArray(lines) ? lines : []).filter(l => l && ALL_METHODS.includes(l.method)).map(cleanDraftLine), notes: notes || null, savedAt: new Date().toISOString() } }
|
||||
});
|
||||
|
||||
res.json({ message: 'Draft saved' });
|
||||
@@ -88,40 +101,32 @@ const closeEvent = async (req, res) => {
|
||||
const financials = await computeEventFinancials(eventId);
|
||||
const isFullCashup = Array.isArray(lines) && lines.length > 0;
|
||||
|
||||
// Each method says where its expected money ended up (see settleLine). Cash is never a
|
||||
// single event-wide figure: when staff counted it, the count is the cash there is, sourced
|
||||
// here from the per-person counts rather than from whatever the frontend sent.
|
||||
let cashupLines = [];
|
||||
if (isFullCashup) {
|
||||
const nonCashLines = lines
|
||||
.filter(l => l && ALL_METHODS.includes(l.method) && l.method !== 'cash')
|
||||
.map(l => {
|
||||
const expected = financials.expectedCashByMethod[l.method] || 0;
|
||||
const actual = l.actualAmount !== undefined && l.actualAmount !== null && l.actualAmount !== '' ? parseFloat(l.actualAmount) : null;
|
||||
return {
|
||||
id: uuidv4(),
|
||||
method: l.method,
|
||||
expectedAmount: expected,
|
||||
actualAmount: actual,
|
||||
variance: actual !== null ? actual - expected : null,
|
||||
notes: l.notes || null
|
||||
};
|
||||
});
|
||||
|
||||
// Cash is never entered as a single event-wide figure — it's always the live sum of every
|
||||
// staff member's per-person count (see computeEventCashActualFromPersonCounts), so it's
|
||||
// always sourced here rather than from whatever (if anything) the frontend sent for it.
|
||||
const cashLineInput = lines.find(l => l && l.method === 'cash');
|
||||
const { actual: cashActual, denominations: cashDenominations } = await computeEventCashActualFromPersonCounts(eventId);
|
||||
const cashExpected = financials.expectedCashByMethod.cash || 0;
|
||||
const cashLine = {
|
||||
id: uuidv4(),
|
||||
method: 'cash',
|
||||
expectedAmount: cashExpected,
|
||||
actualAmount: cashActual,
|
||||
variance: cashActual !== null ? cashActual - cashExpected : null,
|
||||
notes: cashLineInput?.notes || null,
|
||||
denominations: cashDenominations.length > 0 ? { create: cashDenominations } : undefined
|
||||
};
|
||||
|
||||
cashupLines = [cashLine, ...nonCashLines];
|
||||
const { actual: cashCounted, denominations: cashDenominations } = await computeEventCashActualFromPersonCounts(eventId);
|
||||
cashupLines = ALL_METHODS.map(method => {
|
||||
const input = lines.find(l => l && l.method === method) || {};
|
||||
const expected = financials.expectedCashByMethod[method] || 0;
|
||||
const settled = settleLine({ method, expected, counted: method === 'cash' ? cashCounted : null, input });
|
||||
return {
|
||||
id: uuidv4(),
|
||||
method,
|
||||
expectedAmount: expected,
|
||||
actualAmount: settled.actual,
|
||||
variance: settled.variance,
|
||||
notes: input.notes || null,
|
||||
bankAmount: settled.bankAmount,
|
||||
onHandAmount: settled.onHandAmount,
|
||||
pendingAmount: settled.pendingAmount,
|
||||
pendingReference: settled.pendingReference,
|
||||
writeOffTotal: settled.writeOffTotal,
|
||||
writeOffs: settled.writeOffs.length > 0 ? { create: settled.writeOffs } : undefined,
|
||||
denominations: method === 'cash' && cashDenominations.length > 0 ? { create: cashDenominations } : undefined
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const totalActualRevenue = isFullCashup
|
||||
@@ -142,7 +147,7 @@ const closeEvent = async (req, res) => {
|
||||
performedById: req.user.id,
|
||||
lines: { create: cashupLines }
|
||||
},
|
||||
include: { lines: { include: { denominations: true } }, performedBy: { select: { id: true, name: true, email: true } } }
|
||||
include: { lines: { include: { denominations: true, writeOffs: true } }, performedBy: { select: { id: true, name: true, email: true } } }
|
||||
});
|
||||
|
||||
await prisma.event.update({
|
||||
@@ -185,9 +190,33 @@ const reopenEvent = async (req, res) => {
|
||||
include: { performedBy: { select: { id: true, name: true, email: true } } }
|
||||
});
|
||||
|
||||
// Start the next cashup from the last one, with pending money that has since been
|
||||
// received or written off folded in, so nothing has to be typed in again.
|
||||
const lastClose = await prisma.eventCashup.findFirst({
|
||||
where: { eventId, action: { in: ['closed', 'quick_closed'] } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { lines: { include: { writeOffs: true, pendingResolutions: true } } }
|
||||
});
|
||||
const cashupDraft = lastClose && lastClose.lines.length > 0 ? {
|
||||
lines: lastClose.lines.map(l => {
|
||||
const settled = applyPendingResolutions(l);
|
||||
return cleanDraftLine({
|
||||
method: l.method,
|
||||
bankAmount: settled.bank,
|
||||
onHandAmount: settled.onHand,
|
||||
pendingAmount: settled.pendingOutstanding || null,
|
||||
pendingReference: settled.pendingOutstanding ? settled.pendingReference : null,
|
||||
writeOffs: settled.writeOffs,
|
||||
notes: l.notes
|
||||
});
|
||||
}),
|
||||
notes: null,
|
||||
savedAt: new Date().toISOString()
|
||||
} : undefined;
|
||||
|
||||
await prisma.event.update({
|
||||
where: { id: eventId },
|
||||
data: { cashupStatus: 'open', reopenedAt: new Date(), reopenedById: req.user.id }
|
||||
data: { cashupStatus: 'open', reopenedAt: new Date(), reopenedById: req.user.id, ...(cashupDraft ? { cashupDraft } : {}) }
|
||||
});
|
||||
|
||||
res.status(201).json(auditRow);
|
||||
@@ -196,6 +225,66 @@ const reopenEvent = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Settle money that was pending when the event was closed (on the card report, or a
|
||||
// POP we hadn't seen in the bank yet): it has now reached the bank, or it never will and
|
||||
// is written off. Allowed while the event is closed — no reopen needed.
|
||||
// @route POST /api/cashups/lines/:lineId/pending
|
||||
// @access Private/Admin
|
||||
const resolvePending = async (req, res) => {
|
||||
try {
|
||||
const { lineId } = req.params;
|
||||
const { outcome, amount, category, notes } = req.body;
|
||||
|
||||
if (!PENDING_OUTCOMES.includes(outcome)) {
|
||||
res.status(400);
|
||||
throw new Error('Say whether the money was received or written off');
|
||||
}
|
||||
const value = Math.round(Number(amount) * 100) / 100;
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
res.status(400);
|
||||
throw new Error('Enter an amount more than R0');
|
||||
}
|
||||
|
||||
const resolution = await prisma.$transaction(async (tx) => {
|
||||
// Lock the line so two people settling at once can't settle more than is pending.
|
||||
await tx.$executeRaw`SELECT 1 FROM "EventCashupLine" WHERE id = ${lineId} FOR UPDATE`;
|
||||
const line = await tx.eventCashupLine.findUnique({
|
||||
where: { id: lineId },
|
||||
include: { cashup: { select: { id: true, eventId: true } }, pendingResolutions: true }
|
||||
});
|
||||
if (!line) {
|
||||
res.status(404);
|
||||
throw new Error('Cashup line not found');
|
||||
}
|
||||
const latest = await tx.eventCashup.findFirst({ where: { eventId: line.cashup.eventId }, orderBy: { createdAt: 'desc' }, select: { id: true } });
|
||||
if (!latest || latest.id !== line.cashupId) {
|
||||
res.status(400);
|
||||
throw new Error('Only the current cashup of a closed event can be updated');
|
||||
}
|
||||
const { pendingOutstanding } = applyPendingResolutions(line);
|
||||
if (value > pendingOutstanding + 0.005) {
|
||||
res.status(400);
|
||||
throw new Error(`Only R${pendingOutstanding.toFixed(2)} is still pending`);
|
||||
}
|
||||
return tx.eventCashupPendingResolution.create({
|
||||
data: {
|
||||
lineId,
|
||||
outcome,
|
||||
amount: value,
|
||||
category: outcome === 'written_off' ? (WRITE_OFF_CATEGORIES.includes(category) ? category : 'other') : null,
|
||||
notes: notes ? String(notes).trim().slice(0, 200) : null,
|
||||
performedById: req.user.id
|
||||
},
|
||||
include: { performedBy: { select: { id: true, name: true } } }
|
||||
});
|
||||
});
|
||||
|
||||
res.status(201).json(resolution);
|
||||
} catch (error) {
|
||||
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Flat audit log of every close/quick-close/reopen, optionally filtered
|
||||
// @route GET /api/cashups/audit
|
||||
// @access Private/Supervisor
|
||||
@@ -234,5 +323,6 @@ module.exports = {
|
||||
saveEventCashupDraft,
|
||||
closeEvent,
|
||||
reopenEvent,
|
||||
resolvePending,
|
||||
getCashupAudit
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { getEventCashup, getCashByRecordedUser, savePersonCash, saveEventCashupDraft, closeEvent, reopenEvent, getCashupAudit } = require('../controllers/cashupController');
|
||||
const { getEventCashup, getCashByRecordedUser, savePersonCash, saveEventCashupDraft, closeEvent, reopenEvent, resolvePending, getCashupAudit } = require('../controllers/cashupController');
|
||||
const { protect, supervisor, admin } = require('../middleware/authMiddleware');
|
||||
|
||||
router.get('/audit', protect, supervisor, getCashupAudit);
|
||||
@@ -10,5 +10,6 @@ router.put('/event/:eventId/person-cash/:userId', protect, supervisor, savePerso
|
||||
router.put('/event/:eventId/draft', protect, admin, saveEventCashupDraft);
|
||||
router.post('/event/:eventId/close', protect, admin, closeEvent);
|
||||
router.post('/event/:eventId/reopen', protect, admin, reopenEvent);
|
||||
router.post('/lines/:lineId/pending', protect, admin, resolvePending);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "hope-events-frontend",
|
||||
"version": "1.26.1",
|
||||
"version": "1.27.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "hope-events-frontend",
|
||||
"version": "1.26.1",
|
||||
"version": "1.27.0",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@hookform/resolvers": "^5.2.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hope-events-frontend",
|
||||
"version": "1.26.1",
|
||||
"version": "1.27.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack",
|
||||
|
||||
@@ -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() {
|
||||
<History className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard/admin")}>← Back to dashboard</button>
|
||||
<BackLink href="/dashboard/admin" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Admin Audit Log</h1>
|
||||
<p className="text-sm text-gray-500">{total} action{total !== 1 ? "s" : ""} recorded</p>
|
||||
</div>
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import type { EventCost, EventCostType, EventFinancials, CashupMethod, Event } from "@/types";
|
||||
import type { EventCost, EventCostType, EventFinancials, CashupMethod, CashupWriteOffCategory, ReconciledByMethod, Event } from "@/types";
|
||||
import { Wallet, DollarSign, ClipboardCheck, FileBarChart } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { BackLink } from "@/components/shared/BackLink";
|
||||
|
||||
const METHOD_LABELS: Record<CashupMethod, string> = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" };
|
||||
const METHODS: CashupMethod[] = ["cash", "card", "eft", "other"];
|
||||
@@ -20,12 +21,9 @@ function denomLabel(v: number): string {
|
||||
return v >= 1 ? `R${v}` : `${Math.round(v * 100)}c`;
|
||||
}
|
||||
|
||||
type LineInput = { actualAmount: string; notes: string };
|
||||
|
||||
export default function EventCashupPage() {
|
||||
const params = useParams<{ id: string }>();
|
||||
const eventId = params.id;
|
||||
const router = useRouter();
|
||||
const { token } = useAuth();
|
||||
|
||||
const [tab, setTab] = useState<"costs" | "reconciliation" | "report">("costs");
|
||||
@@ -65,7 +63,7 @@ export default function EventCashupPage() {
|
||||
<Wallet className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard/admin/cashup")}>← Back to cashup</button>
|
||||
<BackLink href="/dashboard/admin/cashup" label="Back to cashup" />
|
||||
<h1 className="text-xl font-semibold text-gray-900 mt-0.5">{data?.event?.title || "Event"} — Cashup</h1>
|
||||
</div>
|
||||
</div>
|
||||
@@ -537,34 +535,73 @@ function ReportTab({ eventId, token, data, isClosed }: {
|
||||
</div>
|
||||
|
||||
<div className="bg-white border rounded-lg p-4 space-y-2 overflow-auto">
|
||||
<div className="text-sm font-medium">Revenue by method</div>
|
||||
<table className="w-full text-sm min-w-[560px]">
|
||||
<div className="text-sm font-medium">Where the money ended up</div>
|
||||
<table className="w-full text-sm min-w-[720px]">
|
||||
<thead>
|
||||
<tr className="text-left text-gray-500 border-b">
|
||||
<th className="py-1">Method</th>
|
||||
<th className="py-1 text-right">Income</th>
|
||||
<th className="py-1 text-right">Expected cash</th>
|
||||
<th className="py-1 text-right">Actual</th>
|
||||
<th className="py-1 text-right">Variance</th>
|
||||
<th className="py-1 text-right">Expected</th>
|
||||
<th className="py-1 text-right">In bank</th>
|
||||
<th className="py-1 text-right">On hand</th>
|
||||
<th className="py-1 text-right">Pending</th>
|
||||
<th className="py-1 text-right">Written off</th>
|
||||
<th className="py-1 text-right">Unaccounted</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{METHODS.map(m => {
|
||||
const r = reconciled?.byMethod?.[m];
|
||||
const cell = (v: number | null | undefined) => (v != null && Math.abs(v) >= 0.005 ? money(v) : "—");
|
||||
return (
|
||||
<tr key={m} className="border-b last:border-0">
|
||||
<td className="py-1.5">{METHOD_LABELS[m]}</td>
|
||||
<td className="py-1.5 text-right">{money(data.paymentsByMethod[m])}</td>
|
||||
<td className="py-1.5 text-right">{money(data.expectedCashByMethod[m])}</td>
|
||||
<td className="py-1.5 text-right">{r?.actual != null ? money(r.actual) : "—"}</td>
|
||||
<td className="py-1.5 text-right">{r?.variance != null ? money(r.variance) : "—"}</td>
|
||||
<td className="py-1.5 text-right">{cell(r?.bank)}</td>
|
||||
<td className="py-1.5 text-right">{cell(r?.onHand)}</td>
|
||||
<td className="py-1.5 text-right">{cell(r?.pendingOutstanding)}</td>
|
||||
<td className="py-1.5 text-right">{cell(r?.writeOffTotal)}</td>
|
||||
<td className={"py-1.5 text-right " + (r?.unaccounted != null && Math.abs(r.unaccounted) >= 0.005 ? "text-rose-700 font-medium" : "")}>
|
||||
{r?.unaccounted != null ? (Math.abs(r.unaccounted) >= 0.005 ? money(r.unaccounted) : "R0.00") : "—"}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
{!reconciled && <div className="text-xs text-gray-400">Not settled yet. Columns fill in once the event is closed with a cashup.</div>}
|
||||
</div>
|
||||
|
||||
{(() => {
|
||||
const writeOffs = METHODS.flatMap(m => (reconciled?.byMethod?.[m]?.writeOffs || []).map(w => ({ ...w, method: m })));
|
||||
return writeOffs.length > 0 ? (
|
||||
<div className="bg-white border rounded-lg p-4 space-y-2 overflow-auto">
|
||||
<div className="text-sm font-medium">Write-offs</div>
|
||||
<table className="w-full text-sm min-w-[480px]">
|
||||
<thead>
|
||||
<tr className="text-left text-gray-500 border-b">
|
||||
<th className="py-1">Method</th>
|
||||
<th className="py-1">Type</th>
|
||||
<th className="py-1">Reason</th>
|
||||
<th className="py-1 text-right">Amount</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{writeOffs.map((w, i) => (
|
||||
<tr key={w.id || i} className="border-b last:border-0">
|
||||
<td className="py-1.5">{METHOD_LABELS[w.method]}</td>
|
||||
<td className="py-1.5">{WRITE_OFF_LABELS[w.category]}{w.afterClose ? " (after closing)" : ""}</td>
|
||||
<td className="py-1.5 text-gray-600">{w.reason || "—"}</td>
|
||||
<td className="py-1.5 text-right">{money(w.amount)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : null;
|
||||
})()}
|
||||
|
||||
{reconciled?.byMethod?.cash?.denominations?.length ? (
|
||||
<div className="bg-white border rounded-lg p-4 space-y-2">
|
||||
<div className="text-sm font-medium">Cash denomination count</div>
|
||||
@@ -604,19 +641,273 @@ function ReportTab({ eventId, token, data, isClosed }: {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-white border rounded-lg p-4 grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm">
|
||||
<ProfitSummary data={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Settlement ────────────────────────────────────────────────────────────
|
||||
// For each method, where did the expected money end up: in the bank, still on hand (cash),
|
||||
// or pending (on the card report / a POP we haven't seen in the bank yet) — and what was
|
||||
// written off (card fees, bank charges, a shortfall). Mirrors settleLine in
|
||||
// backend/src/utils/cashupUtils.js, which has the final say when the event is closed.
|
||||
|
||||
type WriteOffInput = { category: CashupWriteOffCategory; amount: string; reason: string };
|
||||
type SettlementInput = { bankAmount: string; onHandAmount: string; pendingAmount: string; pendingReference: string; writeOffs: WriteOffInput[]; notes: string };
|
||||
|
||||
const WRITE_OFF_LABELS: Record<CashupWriteOffCategory, string> = {
|
||||
card_fees: "Card / online fees",
|
||||
bank_charges: "Bank charges",
|
||||
cash_shortfall: "Cash shortfall",
|
||||
other: "Other",
|
||||
};
|
||||
const WRITE_OFF_CATEGORIES = Object.keys(WRITE_OFF_LABELS) as CashupWriteOffCategory[];
|
||||
const DEFAULT_WRITE_OFF: Record<CashupMethod, CashupWriteOffCategory> = { cash: "cash_shortfall", card: "card_fees", eft: "bank_charges", other: "other" };
|
||||
const BANK_HELP: Record<CashupMethod, string> = {
|
||||
cash: "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<CashupMethod, string> = {
|
||||
cash: "",
|
||||
card: "On the card machine / Yoco report, not in the bank yet",
|
||||
eft: "Proof of payment received, not in the bank yet",
|
||||
other: "Expected but not in the bank yet",
|
||||
};
|
||||
const PENDING_REFERENCE_PLACEHOLDER: Record<CashupMethod, string> = { cash: "", card: "Report or batch reference", eft: "POP reference", other: "Reference" };
|
||||
|
||||
const round2 = (n: number) => Math.round(n * 100) / 100;
|
||||
const emptySettlement = (): SettlementInput => ({ bankAmount: "", onHandAmount: "", pendingAmount: "", pendingReference: "", writeOffs: [], notes: "" });
|
||||
const amountText = (v: string | number | null | undefined) => (v === null || v === undefined ? "" : String(v));
|
||||
|
||||
function settle(method: CashupMethod, expected: number, counted: number | null, input: SettlementInput) {
|
||||
const num = (v: string) => (v.trim() === "" || isNaN(Number(v)) ? null : Number(v));
|
||||
const bank = num(input.bankAmount);
|
||||
const 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 <span className="text-xs text-gray-400">Not settled yet</span>;
|
||||
if (Math.abs(unaccounted) < 0.005) return <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-emerald-50 text-emerald-700">All accounted for</span>;
|
||||
return (
|
||||
<span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-rose-50 text-rose-700">
|
||||
{unaccounted > 0 ? `${money(unaccounted)} unaccounted` : `${money(-unaccounted)} more than expected`}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SettlementCard({ method, data, counted, input, onChange }: {
|
||||
method: CashupMethod; data: EventFinancials; counted: number | null; input: SettlementInput; onChange: (next: SettlementInput) => void;
|
||||
}) {
|
||||
const expected = data.expectedCashByMethod[method];
|
||||
const s = settle(method, expected, counted, input);
|
||||
const set = (field: keyof SettlementInput, value: string) => onChange({ ...input, [field]: value });
|
||||
const setWriteOff = (i: number, patch: Partial<WriteOffInput>) =>
|
||||
onChange({ ...input, writeOffs: input.writeOffs.map((w, j) => (j === i ? { ...w, ...patch } : w)) });
|
||||
const addWriteOff = () => onChange({ ...input, writeOffs: [...input.writeOffs, { category: DEFAULT_WRITE_OFF[method], amount: "", reason: "" }] });
|
||||
const removeWriteOff = (i: number) => onChange({ ...input, writeOffs: input.writeOffs.filter((_, j) => j !== i) });
|
||||
|
||||
return (
|
||||
<div className="border rounded-lg p-3 space-y-3">
|
||||
<div className="flex items-start justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Donations counted as profit</div>
|
||||
<div className="font-semibold">{money(data.unallocatedDonationsTotal)}</div>
|
||||
<div className="text-sm font-medium">{METHOD_LABELS[method]}</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
Expected {money(expected)}
|
||||
{data.costsByMethod[method] > 0 && <> ({money(data.paymentsByMethod[method])} taken, less {money(data.costsByMethod[method])} paid out)</>}
|
||||
</div>
|
||||
</div>
|
||||
<UnaccountedBadge unaccounted={s.unaccounted} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Total costs</div>
|
||||
<div className="font-semibold">{money(data.totalCosts)}</div>
|
||||
<label className="block text-xs text-gray-600 mb-1">In bank</label>
|
||||
<input type="number" step="0.01" min={0} className="w-full border rounded px-2 py-1.5 text-sm" value={input.bankAmount} onChange={e => set("bankAmount", e.target.value)} />
|
||||
<p className="text-[10px] text-gray-400 mt-0.5">{BANK_HELP[method]}</p>
|
||||
</div>
|
||||
{method === "cash" ? (
|
||||
<div>
|
||||
<label className="block text-xs text-gray-600 mb-1">Cash on hand</label>
|
||||
{counted !== null ? (
|
||||
<div className="text-sm py-1.5">{money(s.onHand)}</div>
|
||||
) : (
|
||||
<input type="number" step="0.01" min={0} className="w-full border rounded px-2 py-1.5 text-sm" value={input.onHandAmount} onChange={e => set("onHandAmount", e.target.value)} />
|
||||
)}
|
||||
<p className="text-[10px] text-gray-400 mt-0.5">
|
||||
{counted !== null ? `Counted ${money(counted)}, less what was deposited and any deposit fee` : "Not deposited yet. Enter staff cash counts below to work this out."}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<label className="block text-xs text-gray-600 mb-1">Pending</label>
|
||||
<div className="flex gap-2">
|
||||
<input type="number" step="0.01" min={0} className="w-28 border rounded px-2 py-1.5 text-sm" value={input.pendingAmount} onChange={e => set("pendingAmount", e.target.value)} />
|
||||
<input className="flex-1 min-w-0 border rounded px-2 py-1.5 text-sm" placeholder={PENDING_REFERENCE_PLACEHOLDER[method]} value={input.pendingReference} onChange={e => set("pendingReference", e.target.value)} />
|
||||
</div>
|
||||
<p className="text-[10px] text-gray-400 mt-0.5">{PENDING_HELP[method]}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs text-gray-600">Write-offs</div>
|
||||
{input.writeOffs.map((w, i) => (
|
||||
<div key={i} className="flex flex-wrap gap-2 items-center">
|
||||
<select className="border rounded px-2 py-1.5 text-sm" value={w.category} onChange={e => setWriteOff(i, { category: e.target.value as CashupWriteOffCategory })}>
|
||||
{WRITE_OFF_CATEGORIES.map(c => <option key={c} value={c}>{WRITE_OFF_LABELS[c]}</option>)}
|
||||
</select>
|
||||
<input type="number" step="0.01" min={0} className="w-28 border rounded px-2 py-1.5 text-sm" placeholder="Amount" value={w.amount} onChange={e => setWriteOff(i, { amount: e.target.value })} />
|
||||
<input className="flex-1 min-w-[140px] border rounded px-2 py-1.5 text-sm" placeholder="Reason (optional)" value={w.reason} onChange={e => setWriteOff(i, { reason: e.target.value })} />
|
||||
<button className="text-xs text-red-600 hover:underline" onClick={() => removeWriteOff(i)}>Remove</button>
|
||||
</div>
|
||||
))}
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={addWriteOff}>+ Add write-off</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs text-gray-600 mb-1">Notes (optional)</label>
|
||||
<input className="w-full border rounded px-2 py-1.5 text-sm" value={input.notes} onChange={e => set("notes", e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// A closed method's settlement, read-only, with a way to settle pending money that has
|
||||
// since arrived (or never will) without reopening the event.
|
||||
function SettledCard({ method, r, token, onChanged }: { method: CashupMethod; r: ReconciledByMethod; token: string; onChanged: () => void }) {
|
||||
return (
|
||||
<div className="border rounded-lg p-3 space-y-2">
|
||||
<div className="flex items-start justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Net profit</div>
|
||||
<div className="font-semibold">{money(data.netProfit)}</div>
|
||||
<div className="text-sm font-medium">{METHOD_LABELS[method]}</div>
|
||||
<div className="text-xs text-gray-500">Expected {money(r.expected)}</div>
|
||||
</div>
|
||||
<UnaccountedBadge unaccounted={r.unaccounted} />
|
||||
</div>
|
||||
<dl className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-sm">
|
||||
<div><dt className="text-xs text-gray-500">In bank</dt><dd>{r.bank !== null ? money(r.bank) : "—"}</dd></div>
|
||||
{method === "cash"
|
||||
? <div><dt className="text-xs text-gray-500">On hand</dt><dd>{r.onHand !== null ? money(r.onHand) : "—"}</dd></div>
|
||||
: <div><dt className="text-xs text-gray-500">Pending</dt><dd>{r.pendingOutstanding > 0 ? money(r.pendingOutstanding) : "—"}</dd></div>}
|
||||
<div><dt className="text-xs text-gray-500">Written off</dt><dd>{r.writeOffTotal > 0 ? money(r.writeOffTotal) : "—"}</dd></div>
|
||||
<div><dt className="text-xs text-gray-500">Actual</dt><dd>{r.actual !== null ? money(r.actual) : "—"}</dd></div>
|
||||
</dl>
|
||||
{r.writeOffs.length > 0 && (
|
||||
<ul className="text-xs text-gray-600 space-y-0.5">
|
||||
{r.writeOffs.map((w, i) => (
|
||||
<li key={w.id || i}>
|
||||
{WRITE_OFF_LABELS[w.category]} {money(w.amount)}{w.reason ? ` — ${w.reason}` : ""}{w.afterClose ? " (after closing)" : ""}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{(r.pending || 0) > 0 && (
|
||||
<PendingSettler method={method} r={r} token={token} onChanged={onChanged} />
|
||||
)}
|
||||
{r.notes && <div className="text-xs text-gray-500">Notes: {r.notes}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PendingSettler({ method, r, token, onChanged }: { method: CashupMethod; r: ReconciledByMethod; token: string; onChanged: () => void }) {
|
||||
const [mode, setMode] = useState<"received" | "written_off" | null>(null);
|
||||
const [amount, setAmount] = useState("");
|
||||
const [category, setCategory] = useState<CashupWriteOffCategory>(DEFAULT_WRITE_OFF[method]);
|
||||
const [notes, setNotes] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
|
||||
const start = (m: "received" | "written_off") => { setMode(m); setAmount(String(r.pendingOutstanding)); setNotes(""); setErr(null); };
|
||||
|
||||
const save = async () => {
|
||||
if (!r.lineId || !mode) return;
|
||||
setSaving(true); setErr(null);
|
||||
try {
|
||||
await apiFetch(`/api/cashups/lines/${r.lineId}/pending`, { method: "POST", authToken: token, body: { outcome: mode, amount: parseFloat(amount), category, notes: notes || null } });
|
||||
setMode(null);
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
setErr(errorMessage(e) || "Failed to save");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-amber-50 border border-amber-100 rounded p-2 space-y-2 text-xs">
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<span>
|
||||
Pending {money(r.pending)}{r.pendingReference ? ` (${r.pendingReference})` : ""}
|
||||
{r.pendingOutstanding > 0 ? <> — <strong>{money(r.pendingOutstanding)} still outstanding</strong></> : " — all settled"}
|
||||
</span>
|
||||
{r.pendingOutstanding > 0 && mode === null && (
|
||||
<span className="flex gap-3">
|
||||
<button className="text-brand-600 hover:underline" onClick={() => start("received")}>Mark received</button>
|
||||
<button className="text-red-600 hover:underline" onClick={() => start("written_off")}>Write off</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{r.pendingResolutions.length > 0 && (
|
||||
<ul className="text-gray-600 space-y-0.5">
|
||||
{r.pendingResolutions.map(p => (
|
||||
<li key={p.id}>
|
||||
{p.outcome === "received" ? "Received in bank" : `Written off (${WRITE_OFF_LABELS[p.category || "other"]})`} {money(p.amount)}
|
||||
{" — "}{p.performedBy?.name || "Unknown"}, {new Date(p.createdAt).toLocaleDateString()}{p.notes ? ` — ${p.notes}` : ""}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{mode !== null && (
|
||||
<div className="flex flex-wrap gap-2 items-center">
|
||||
<input type="number" step="0.01" min={0} className="w-28 border rounded px-2 py-1 text-sm bg-white" value={amount} onChange={e => setAmount(e.target.value)} />
|
||||
{mode === "written_off" && (
|
||||
<select className="border rounded px-2 py-1 text-sm bg-white" value={category} onChange={e => setCategory(e.target.value as CashupWriteOffCategory)}>
|
||||
{WRITE_OFF_CATEGORIES.map(c => <option key={c} value={c}>{WRITE_OFF_LABELS[c]}</option>)}
|
||||
</select>
|
||||
)}
|
||||
<input className="flex-1 min-w-[140px] border rounded px-2 py-1 text-sm bg-white" placeholder={mode === "received" ? "Bank reference (optional)" : "Reason (optional)"} value={notes} onChange={e => setNotes(e.target.value)} />
|
||||
<button className="px-2 py-1 rounded border bg-white" onClick={() => setMode(null)} disabled={saving}>Cancel</button>
|
||||
<button className="px-2 py-1 rounded bg-brand-600 text-white hover:bg-brand-700" onClick={save} disabled={saving}>
|
||||
{saving ? "Saving…" : mode === "received" ? "Mark received" : "Write off"}
|
||||
</button>
|
||||
{err && <span className="text-red-600 w-full">{err}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProfitSummary({ data }: { data: EventFinancials }) {
|
||||
return (
|
||||
<div className="bg-white border rounded-lg p-4 grid grid-cols-2 sm:grid-cols-5 gap-3 text-sm">
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Donations counted as profit</div>
|
||||
<div className="font-semibold">{money(data.unallocatedDonationsTotal)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Total costs</div>
|
||||
<div className="font-semibold">{money(data.totalCosts)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Bank & card charges</div>
|
||||
<div className="font-semibold">{money(data.totalWriteOffs)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Pending (outstanding)</div>
|
||||
<div className="font-semibold">{money(data.pendingOutstandingTotal)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Net profit</div>
|
||||
<div className="font-semibold">{money(data.netProfit)}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -629,32 +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<CashupMethod, LineInput> = useMemo(() => {
|
||||
const base: Record<CashupMethod, LineInput> = { cash: { actualAmount: "", notes: "" }, card: { actualAmount: "", notes: "" }, eft: { actualAmount: "", notes: "" }, other: { actualAmount: "", notes: "" } };
|
||||
const initialLines: Record<CashupMethod, SettlementInput> = useMemo(() => {
|
||||
const base: Record<CashupMethod, SettlementInput> = { cash: emptySettlement(), card: emptySettlement(), eft: emptySettlement(), other: emptySettlement() };
|
||||
for (const l of draftLines || []) {
|
||||
if (l.method in base) base[l.method as CashupMethod] = { actualAmount: l.actualAmount != null ? String(l.actualAmount) : "", notes: l.notes || "" };
|
||||
if (!(l.method in base)) continue;
|
||||
base[l.method as CashupMethod] = {
|
||||
bankAmount: amountText(l.bankAmount),
|
||||
onHandAmount: amountText(l.onHandAmount),
|
||||
pendingAmount: amountText(l.pendingAmount),
|
||||
pendingReference: l.pendingReference || "",
|
||||
writeOffs: (l.writeOffs || []).map(w => ({ category: w.category, amount: amountText(w.amount), reason: w.reason || "" })),
|
||||
notes: l.notes || "",
|
||||
};
|
||||
}
|
||||
return base;
|
||||
}, [draftLines]);
|
||||
|
||||
const [lines, setLines] = useState<Record<CashupMethod, LineInput>>(initialLines);
|
||||
const [lines, setLines] = useState<Record<CashupMethod, SettlementInput>>(initialLines);
|
||||
const [closeNotes, setCloseNotes] = useState("");
|
||||
const [reopenNotes, setReopenNotes] = useState("");
|
||||
// Cash no longer has its own manual entry — it's the live sum of every staff member's
|
||||
// per-person count, reported up from CashByUserSection below.
|
||||
// Counted cash is the live sum of every staff member's per-person count, reported up from
|
||||
// CashByUserSection below; when there is one, cash on hand is whatever wasn't deposited.
|
||||
const [cashSummary, setCashSummary] = useState<{ actualTotal: number | null; denominations: PersonDenom[] }>({ actualTotal: null, denominations: [] });
|
||||
|
||||
useEffect(() => { setLines(initialLines); }, [initialLines]);
|
||||
|
||||
const setLine = (method: CashupMethod, field: keyof LineInput, value: string) => {
|
||||
setLines(prev => ({ ...prev, [method]: { ...prev[method], [field]: value } }));
|
||||
};
|
||||
const setLine = (method: CashupMethod, next: SettlementInput) => setLines(prev => ({ ...prev, [method]: next }));
|
||||
|
||||
// Cash is included with notes only — its actual/denominations are always sourced server-side
|
||||
// from per-person counts (see cashupController.closeEvent), never from this payload.
|
||||
const buildLinesPayload = () => METHODS.map(m => m === "cash"
|
||||
? { method: "cash", notes: lines.cash.notes || null }
|
||||
: { method: m, actualAmount: lines[m].actualAmount === "" ? null : parseFloat(lines[m].actualAmount), notes: lines[m].notes || null });
|
||||
// Methods with nothing expected and nothing entered are hidden to keep the screen short.
|
||||
const hasInput = (m: CashupMethod) => {
|
||||
const l = lines[m];
|
||||
return l.bankAmount !== "" || l.onHandAmount !== "" || l.pendingAmount !== "" || l.writeOffs.length > 0;
|
||||
};
|
||||
const shownMethods = METHODS.filter(m => Math.abs(data.expectedCashByMethod[m]) > 0.005 || hasInput(m) || (m === "cash" && cashSummary.actualTotal !== null));
|
||||
|
||||
const buildLinesPayload = () => METHODS.map(m => {
|
||||
const l = lines[m];
|
||||
const amount = (v: string) => (v.trim() === "" ? null : parseFloat(v));
|
||||
return {
|
||||
method: m,
|
||||
bankAmount: amount(l.bankAmount),
|
||||
onHandAmount: m === "cash" ? amount(l.onHandAmount) : null,
|
||||
pendingAmount: m === "cash" ? null : amount(l.pendingAmount),
|
||||
pendingReference: l.pendingReference || null,
|
||||
writeOffs: l.writeOffs.map(w => ({ category: w.category, amount: amount(w.amount), reason: w.reason || null })),
|
||||
notes: l.notes || null,
|
||||
};
|
||||
});
|
||||
|
||||
const saveDraft = async () => {
|
||||
setBusy(true); setError(null);
|
||||
@@ -669,7 +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 (
|
||||
<div className="space-y-4">
|
||||
<div className="bg-white border rounded-lg p-4 space-y-3 overflow-auto">
|
||||
<div className="text-sm font-medium">Cash-up reconciliation</div>
|
||||
<table className="w-full text-sm min-w-[640px]">
|
||||
<thead>
|
||||
<tr className="text-left text-gray-500 border-b">
|
||||
<th className="py-1">Method</th>
|
||||
<th className="py-1 text-right">Income</th>
|
||||
<th className="py-1 text-right">Costs from method</th>
|
||||
<th className="py-1 text-right">Expected cash</th>
|
||||
<th className="py-1 text-right">Actual</th>
|
||||
<th className="py-1 text-right">Variance</th>
|
||||
<th className="py-1">Notes</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{METHODS.map(m => {
|
||||
const r = reconciled?.byMethod?.[m];
|
||||
return (
|
||||
<tr key={m} className="border-b last:border-0 align-top">
|
||||
<td className="py-1.5">{METHOD_LABELS[m]}</td>
|
||||
<td className="py-1.5 text-right">{money(data.paymentsByMethod[m])}</td>
|
||||
<td className="py-1.5 text-right">{money(data.costsByMethod[m])}</td>
|
||||
<td className="py-1.5 text-right">{money(data.expectedCashByMethod[m])}</td>
|
||||
<td className="py-1.5 text-right">
|
||||
{isClosed ? (
|
||||
money(r?.actual ?? null)
|
||||
) : m === "cash" ? (
|
||||
cashSummary.actualTotal != null ? money(cashSummary.actualTotal) : <span className="text-gray-400">not counted</span>
|
||||
) : (
|
||||
<input type="number" step="0.01" className="w-28 border rounded px-2 py-1 text-sm text-right" value={lines[m].actualAmount} onChange={e => setLine(m, "actualAmount", e.target.value)} />
|
||||
)}
|
||||
</td>
|
||||
<td className="py-1.5 text-right">
|
||||
{isClosed
|
||||
? (r?.variance != null ? money(r.variance) : <span className="text-gray-400">not reconciled</span>)
|
||||
: (m === "cash"
|
||||
? (cashSummary.actualTotal != null ? money(cashSummary.actualTotal - data.expectedCashByMethod[m]) : "—")
|
||||
: (lines[m].actualAmount !== "" ? money(parseFloat(lines[m].actualAmount) - data.expectedCashByMethod[m]) : "—"))}
|
||||
</td>
|
||||
<td className="py-1.5">
|
||||
{isClosed ? (r?.notes || "—") : (
|
||||
<input className="w-full border rounded px-2 py-1 text-sm" value={lines[m].notes} onChange={e => setLine(m, "notes", e.target.value)} />
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
{!isClosed && (
|
||||
<div className="text-xs text-gray-500">Cash actual is the live sum of per-staff-member counts entered below — there's no separate event-wide entry.</div>
|
||||
<div className="bg-white border rounded-lg p-4 space-y-3">
|
||||
<div>
|
||||
<div className="text-sm font-medium">Where did the money end up?</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{isClosed
|
||||
? "As recorded when the event was closed. Pending money can be marked received or written off without reopening."
|
||||
: "For each payment method, say how much is in the bank, still on hand or pending, and write off anything lost to fees, charges or shortfalls."}
|
||||
</div>
|
||||
</div>
|
||||
{isClosed ? (
|
||||
reconciled?.action === "closed" && settledMethods.length > 0 ? (
|
||||
settledMethods.map(m => <SettledCard key={m} method={m} r={reconciled.byMethod[m]} token={token} onChanged={onChanged} />)
|
||||
) : (
|
||||
<div className="text-xs text-gray-400">This event was quick closed, so no settlement was recorded.</div>
|
||||
)
|
||||
) : shownMethods.length === 0 ? (
|
||||
<div className="text-xs text-gray-400">No payments to settle for this event.</div>
|
||||
) : (
|
||||
shownMethods.map(m => (
|
||||
<SettlementCard
|
||||
key={m}
|
||||
method={m}
|
||||
data={data}
|
||||
counted={m === "cash" ? cashSummary.actualTotal : null}
|
||||
input={lines[m]}
|
||||
onChange={next => setLine(m, next)}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -789,20 +1089,7 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
|
||||
})()}
|
||||
</div>
|
||||
|
||||
<div className="bg-white border rounded-lg p-4 grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm">
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Donations counted as profit</div>
|
||||
<div className="font-semibold">{money(data.unallocatedDonationsTotal)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Total costs</div>
|
||||
<div className="font-semibold">{money(data.totalCosts)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500 text-xs">Net profit</div>
|
||||
<div className="font-semibold">{money(data.netProfit)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<ProfitSummary data={data} />
|
||||
|
||||
{!isClosed && (
|
||||
<div className="bg-white border rounded-lg p-4 space-y-2">
|
||||
|
||||
@@ -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() {
|
||||
<Wallet className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-gray-900">Post-event Cashup</h1>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-xl font-semibold text-gray-900 mt-0.5">Post-event Cashup</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">Set costs, reconcile takings, and close out an event. Admin only.</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shrink-0"
|
||||
onClick={() => router.push("/dashboard")}
|
||||
>Back</button>
|
||||
</div>
|
||||
|
||||
{error && <div className="text-sm text-red-600 bg-red-50 border border-red-100 rounded p-2">{error}</div>}
|
||||
|
||||
@@ -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() {
|
||||
<ClipboardList className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Manage Registrations</h1>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Manage Registrations</h1>
|
||||
<p className="text-sm text-gray-500">{registrations.length} registration{registrations.length !== 1 ? "s" : ""} total</p>
|
||||
</div>
|
||||
</div>
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200" onClick={() => router.push('/dashboard')}>Back</button>
|
||||
</div>
|
||||
|
||||
{!isAdmin && (
|
||||
|
||||
@@ -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 */}
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Site Settings</h1>
|
||||
<BackLink href="/dashboard/admin" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Site Settings</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">Configure your organisation, branding, email, and legal pages.</p>
|
||||
</div>
|
||||
<button
|
||||
className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200"
|
||||
onClick={() => router.push("/dashboard/admin")}
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Tab bar */}
|
||||
|
||||
@@ -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() {
|
||||
<UsersIcon className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">User Management</h1>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">User Management</h1>
|
||||
<p className="text-sm text-gray-500">{total} user{total !== 1 ? "s" : ""} total</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200" onClick={() => router.push("/dashboard")}>Back</button>
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-brand-600 text-white hover:bg-brand-700" onClick={() => setCreateOpen(v => !v)}>
|
||||
{createOpen ? "Close" : "Create user"}
|
||||
</button>
|
||||
|
||||
@@ -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() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<Ticket className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Event Tickets</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Event Tickets</h1>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm"
|
||||
onClick={() => router.push("/dashboard")}
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 mb-4">
|
||||
View and print tickets for an event.
|
||||
|
||||
@@ -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<string | null>(null);
|
||||
|
||||
@@ -42,7 +41,7 @@ export default function MyGroupsPage() {
|
||||
<Users className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard")}>← Back to dashboard</button>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">My groups</h1>
|
||||
<p className="text-sm text-gray-500">Rooms, small groups and buses you lead</p>
|
||||
</div>
|
||||
|
||||
@@ -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<QRScannerHandle>(null);
|
||||
const [scanInfo, setScanInfo] = useDismissingState<string | null>(null);
|
||||
const [error, setError] = useDismissingState<string | null>(null);
|
||||
@@ -330,9 +329,11 @@ export default function TicketScanningPage() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<QrCode className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Ticket Scanning</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Ticket Scanning</h1>
|
||||
</div>
|
||||
</div>
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm" onClick={() => router.push('/dashboard')}>Back</button>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 mb-4">
|
||||
Use the button to start/stop scanning. The back camera will be used when available.
|
||||
|
||||
@@ -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() {
|
||||
<BedDouble className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard")}>← Back to dashboard</button>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Rooms & groups</h1>
|
||||
<p className="text-sm text-gray-500">Put attendees into rooms, small groups, teams or buses</p>
|
||||
</div>
|
||||
|
||||
@@ -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<ConsentRow["status"], { label: string; cls: string }> = {
|
||||
@@ -134,7 +135,7 @@ export default function ConsentTrackerPage() {
|
||||
<ShieldCheck className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard")}>← Back to dashboard</button>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Parental consent</h1>
|
||||
<p className="text-sm text-gray-500">Youth events: who still needs a parent's consent before check-in</p>
|
||||
</div>
|
||||
|
||||
@@ -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() {
|
||||
<TicketPercent className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard")}>← Back to dashboard</button>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Coupon codes</h1>
|
||||
<p className="text-sm text-gray-500">Discounts for staff, leaders, volunteers and promotions</p>
|
||||
</div>
|
||||
|
||||
@@ -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() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<Mail className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Email Attendees</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm" onClick={() => router.push('/dashboard')}>Back</button>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Email Attendees</h1>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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 <input type="datetime-local">
|
||||
// This returns local time (browser timezone) as YYYY-MM-DDTHH:mm
|
||||
@@ -209,9 +210,11 @@ function EventOptionsContent() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<Ticket className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Event options</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard/supervisor/events" label="Back to events" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Event options</h1>
|
||||
</div>
|
||||
</div>
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm" onClick={() => router.push('/dashboard/supervisor/events')}>Back</button>
|
||||
</div>
|
||||
|
||||
{!canView && (
|
||||
|
||||
@@ -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() {
|
||||
<Calendar className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Events</h1>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Events</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">Manage and create events</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button type="button" className="px-4 py-2 text-sm rounded-lg bg-brand-600 text-white hover:bg-brand-700 shadow-sm font-medium" onClick={openCreate}>+ Add Event</button>
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800" onClick={() => router.push("/dashboard")}>Back</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<FileText className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Forms</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Forms</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200" onClick={() => router.push("/dashboard")}>Back</button>
|
||||
{mode === 'view' && (
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-brand-600 text-white hover:bg-brand-700" onClick={onPrint} disabled={items.length === 0}>
|
||||
Print forms
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { UserPlus } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import type { Registration } from "@/types";
|
||||
import { BackLink } from "@/components/shared/BackLink";
|
||||
|
||||
type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown };
|
||||
|
||||
@@ -67,7 +68,10 @@ export default function ManualRegistrationPage() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<UserPlus className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-xl font-semibold text-gray-900">Manual Registration</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-xl font-semibold text-gray-900 mt-0.5">Manual Registration</h1>
|
||||
</div>
|
||||
</div>
|
||||
<form onSubmit={submit} className="space-y-3">
|
||||
<div>
|
||||
|
||||
@@ -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() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<UserPlus className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Manual registration</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Manual registration</h1>
|
||||
</div>
|
||||
</div>
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm" onClick={() => router.push('/dashboard')}>Back</button>
|
||||
</div>
|
||||
|
||||
{!canView && (
|
||||
|
||||
@@ -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() {
|
||||
<WifiOff className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard")}>← Back to dashboard</button>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Offline scanning</h1>
|
||||
<p className="text-sm text-gray-500">Devices scanning without a connection, and their synced scans</p>
|
||||
</div>
|
||||
|
||||
@@ -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() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<Wallet className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Payments</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Payments</h1>
|
||||
</div>
|
||||
</div>
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm" onClick={() => router.push('/dashboard')}>Back</button>
|
||||
</div>
|
||||
|
||||
{!canView && (
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import React, { Suspense } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import ReportsV2 from "@/components/reports/ReportsV2";
|
||||
|
||||
export default function SupervisorReportsPage() {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<div className="w-full p-6">
|
||||
<Suspense fallback={<div className="text-sm text-gray-400">Loading…</div>}>
|
||||
<ReportsV2 onBack={() => router.push('/dashboard')} />
|
||||
<ReportsV2 backHref="/dashboard" />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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() {
|
||||
<ListChecks className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard")}>← Back to dashboard</button>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Waitlist</h1>
|
||||
<p className="text-sm text-gray-500">People waiting for sold-out tickets</p>
|
||||
</div>
|
||||
|
||||
@@ -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() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<MessageCircle className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">WhatsApp Attendees</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">WhatsApp Attendees</h1>
|
||||
</div>
|
||||
</div>
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm" onClick={() => router.push("/dashboard")}>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!canView && (
|
||||
|
||||
@@ -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() {
|
||||
<HandHeart className="w-5 h-5 text-rose-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Make a donation</h1>
|
||||
<BackLink href="/dashboard/user" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Make a donation</h1>
|
||||
<p className="text-sm text-gray-500">Support an event or the ministry directly.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<FileText className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Attendee forms</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard/user" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Attendee forms</h1>
|
||||
</div>
|
||||
</div>
|
||||
<button className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200" onClick={() => router.push('/dashboard/user')}>Back</button>
|
||||
</div>
|
||||
|
||||
{loading && <div className="text-sm text-gray-600 mb-2">Loading…</div>}
|
||||
|
||||
@@ -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() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<Receipt className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">My Payments</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard/user" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">My Payments</h1>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="px-2.5 py-1 text-xs rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-1"
|
||||
onClick={() => router.push("/dashboard/user")}
|
||||
>Back to dashboard</button>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-red-600 text-sm mb-3">{error}</p>}
|
||||
|
||||
@@ -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 (
|
||||
<div className="max-w-4xl mx-auto w-full">
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Profile & Security</h1>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Profile & Security</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">Manage your personal information and keep your account secure.</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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() {
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<KeyRound className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Reset password</h1>
|
||||
<div>
|
||||
<BackLink href="/dashboard/user" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Reset password</h1>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="px-2.5 py-1 text-xs rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-1"
|
||||
onClick={() => router.push("/dashboard/user")}
|
||||
>Back to dashboard</button>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-red-600 text-sm mb-3">{error}</p>}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { ArrowLeft, Search } from "lucide-react";
|
||||
import { Search } from "lucide-react";
|
||||
import { BackLink } from "@/components/shared/BackLink";
|
||||
import { REPORTS, REPORT_CATEGORIES, type ReportKey, type ReportCategory } from "./ReportCatalog";
|
||||
import EventsDropdown from "./EventsDropdown";
|
||||
|
||||
@@ -17,7 +18,7 @@ export default function ReportsShell({
|
||||
dateFrom, setDateFrom, dateTo, setDateTo,
|
||||
report, setReport,
|
||||
onViewReport, busy,
|
||||
onBack,
|
||||
backHref,
|
||||
}: {
|
||||
events: EventLite[]; isAdmin: boolean;
|
||||
showPastEvents: boolean; setShowPastEvents: (v: boolean) => void;
|
||||
@@ -27,7 +28,7 @@ export default function ReportsShell({
|
||||
dateFrom: string; setDateFrom: (v: string) => void; dateTo: string; setDateTo: (v: string) => void;
|
||||
report: ReportKey; setReport: (r: ReportKey) => void;
|
||||
onViewReport: () => void; busy: boolean;
|
||||
onBack?: () => void;
|
||||
backHref?: string;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [category, setCategory] = useState<"All" | ReportCategory>("All");
|
||||
@@ -67,7 +68,8 @@ export default function ReportsShell({
|
||||
<div>
|
||||
<div className="flex flex-wrap items-start justify-between gap-3 sm:gap-4 mb-6">
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Reports</h1>
|
||||
{backHref && <BackLink href={backHref} />}
|
||||
<h1 className={"text-2xl font-semibold text-gray-900" + (backHref ? " mt-0.5" : "")}>Reports</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">View, export, or email operational reports for events.</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 w-full sm:w-auto">
|
||||
@@ -80,11 +82,6 @@ export default function ReportsShell({
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{onBack && (
|
||||
<button type="button" className="shrink-0 flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800" onClick={onBack}>
|
||||
<ArrowLeft className="w-4 h-4" /> Back
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import type { ConsentRow, Event, EventCashup, EventFinancials, MedicalRow, Payme
|
||||
|
||||
const METHOD_KEYS = ["cash", "card", "eft", "other"] as const;
|
||||
const METHOD_LABEL: Record<string, string> = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" };
|
||||
const WRITE_OFF_LABEL: Record<string, string> = { card_fees: "Card / online fees", bank_charges: "Bank charges", cash_shortfall: "Cash shortfall", other: "Other" };
|
||||
function denomLabel(v: number): string {
|
||||
return v >= 1 ? `R${v}` : `${Math.round(v * 100)}c`;
|
||||
}
|
||||
@@ -143,7 +144,7 @@ type FunnelReport = {
|
||||
};
|
||||
|
||||
// Simple MultiSelect control used in filters
|
||||
export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
|
||||
const { token, user } = useAuth();
|
||||
const role = user?.role || "user";
|
||||
const canView = role === "admin" || role === "supervisor";
|
||||
@@ -1178,23 +1179,25 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
METHOD_KEYS.forEach(m => {
|
||||
const r = f.reconciled?.byMethod?.[m];
|
||||
incomeByMethod[m] = (incomeByMethod[m] || 0) + (f.paymentsByMethod?.[m] || 0);
|
||||
rows.push([title, METHOD_LABEL[m], Number((f.paymentsByMethod?.[m] || 0).toFixed(2)), Number((f.costsByMethod?.[m] || 0).toFixed(2)), Number((f.expectedCashByMethod?.[m] || 0).toFixed(2)), r?.actual != null ? Number(r.actual.toFixed(2)) : "not reconciled", r?.variance != null ? Number(r.variance.toFixed(2)) : ""]);
|
||||
const amount = (v: number | null | undefined) => (v != null && Math.abs(v) >= 0.005 ? Number(v.toFixed(2)) : "");
|
||||
rows.push([title, METHOD_LABEL[m], Number((f.paymentsByMethod?.[m] || 0).toFixed(2)), Number((f.costsByMethod?.[m] || 0).toFixed(2)), Number((f.expectedCashByMethod?.[m] || 0).toFixed(2)), amount(r?.bank), amount(r?.onHand), amount(r?.pendingOutstanding), amount(r?.writeOffTotal), r?.unaccounted != null ? Number(r.unaccounted.toFixed(2)) : "not reconciled"]);
|
||||
if (m === "cash") {
|
||||
(r?.denominations || []).forEach((d) => rows.push([title, ` ${denomLabel(d.value)} × ${d.count}`, "", "", "", Number((d.value * d.count).toFixed(2)), ""]));
|
||||
(r?.denominations || []).forEach((d) => rows.push([title, ` ${denomLabel(d.value)} × ${d.count}`, "", "", "", "", Number((d.value * d.count).toFixed(2)), "", "", ""]));
|
||||
}
|
||||
(r?.writeOffs || []).forEach((w) => rows.push([title, ` Write-off: ${WRITE_OFF_LABEL[w.category] || w.category}${w.reason ? ` (${w.reason})` : ""}`, "", "", "", "", "", "", Number(w.amount.toFixed(2)), ""]));
|
||||
});
|
||||
if ((f.untaggedCostsTotal || 0) > 0) rows.push([title, "Untagged costs", "", Number(f.untaggedCostsTotal.toFixed(2)), "", "", ""]);
|
||||
rows.push([title, "Donations counted as profit", "", "", "", Number((f.unallocatedDonationsTotal || 0).toFixed(2)), ""]);
|
||||
if ((f.untaggedCostsTotal || 0) > 0) rows.push([title, "Untagged costs", "", Number(f.untaggedCostsTotal.toFixed(2)), "", "", "", "", "", ""]);
|
||||
rows.push([title, "Donations counted as profit", "", "", "", "", "", "", "", Number((f.unallocatedDonationsTotal || 0).toFixed(2))]);
|
||||
});
|
||||
return {
|
||||
title: 'Cashup Report', subtitle, kind: 'table', orientation: 'landscape',
|
||||
chart: { title: 'Income by method, across all selected events', data: METHOD_KEYS.map(m => ({ label: METHOD_LABEL[m], value: incomeByMethod[m] || 0, displayValue: `R ${(incomeByMethod[m] || 0).toFixed(2)}` })) },
|
||||
table: { columns: ["Event", "Method", "Income", "Costs from method", "Expected cash", "Actual", "Variance"], rows }
|
||||
table: { columns: ["Event", "Method", "Income", "Costs from method", "Expected", "In bank", "On hand", "Pending", "Written off", "Unaccounted"], rows }
|
||||
};
|
||||
}
|
||||
if (report === "financeReport") {
|
||||
const rows: (string | number)[][] = [];
|
||||
let sold = 0, paidByAll = 0, donationsProfit = 0, costsTotal = 0, netProfitTotal = 0;
|
||||
let sold = 0, paidByAll = 0, donationsProfit = 0, costsTotal = 0, writeOffsTotal = 0, netProfitTotal = 0;
|
||||
const paidByMethod: Record<string, number> = {};
|
||||
Object.keys(financialsByEvent).forEach(evId => {
|
||||
const f = financialsByEvent[evId];
|
||||
@@ -1206,6 +1209,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
METHOD_KEYS.forEach(m => { paidByMethod[m] = (paidByMethod[m] || 0) + (f.paymentsByMethod?.[m] || 0); });
|
||||
donationsProfit += f.unallocatedDonationsTotal || 0;
|
||||
costsTotal += f.totalCosts || 0;
|
||||
writeOffsTotal += f.totalWriteOffs || 0;
|
||||
netProfitTotal += f.netProfit || 0;
|
||||
// "Sales" is ticket-price revenue for orders that reached 'paid' status — whether that
|
||||
// order was funded directly or via an assigned donation, its full price is already
|
||||
@@ -1221,10 +1225,11 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
rows.push([title, "Cashup comparison", "", ""]);
|
||||
METHOD_KEYS.forEach(m => {
|
||||
const r = f.reconciled?.byMethod?.[m];
|
||||
rows.push([title, "", `${METHOD_LABEL[m]} — expected / actual / variance`, `${money2(f.expectedCashByMethod?.[m])} / ${r?.actual != null ? money2(r.actual) : "—"} / ${r?.variance != null ? money2(r.variance) : "—"}`]);
|
||||
rows.push([title, "", `${METHOD_LABEL[m]} — expected / actual / unaccounted`, `${money2(f.expectedCashByMethod?.[m])} / ${r?.actual != null ? money2(r.actual) : "—"} / ${r?.unaccounted != null ? money2(r.unaccounted) : "—"}`]);
|
||||
});
|
||||
rows.push([title, "Costs", "", ""]);
|
||||
(f.costs || []).forEach((c) => rows.push([title, "", `${c.label}${c.paidFromMethod ? ` (via ${METHOD_LABEL[c.paidFromMethod]})` : ""}`, Number((-(c.total ?? c.amount)).toFixed(2))]));
|
||||
METHOD_KEYS.forEach(m => (f.reconciled?.byMethod?.[m]?.writeOffs || []).forEach((w) => rows.push([title, "", `${WRITE_OFF_LABEL[w.category] || w.category} (${METHOD_LABEL[m]})${w.reason ? ` — ${w.reason}` : ""}`, -Number(w.amount.toFixed(2))])));
|
||||
rows.push([title, "", "Donations counted as profit", Number((f.unallocatedDonationsTotal || 0).toFixed(2))]);
|
||||
rows.push([title, "", "Net profit", Number((f.netProfit || 0).toFixed(2))]);
|
||||
});
|
||||
@@ -1235,6 +1240,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
{ label: 'Paid by (all methods)', value: `R ${paidByAll.toFixed(2)}`, tone: 'blue' },
|
||||
{ label: 'Donations counted as profit', value: `R ${donationsProfit.toFixed(2)}`, tone: 'rose' },
|
||||
{ label: 'Total costs', value: `R ${costsTotal.toFixed(2)}`, tone: 'amber' },
|
||||
{ label: 'Bank & card charges', value: `R ${writeOffsTotal.toFixed(2)}`, tone: 'amber' },
|
||||
{ label: 'Net profit', value: `R ${netProfitTotal.toFixed(2)}`, tone: 'violet' },
|
||||
],
|
||||
chart: { title: 'Paid by, across all selected events', data: METHOD_KEYS.map(m => ({ label: METHOD_LABEL[m], value: paidByMethod[m] || 0, displayValue: `R ${(paidByMethod[m] || 0).toFixed(2)}` })) },
|
||||
@@ -1247,23 +1253,25 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
const f = financialsByEvent[evId];
|
||||
acc.revenue += f?.effectiveTotalRevenue || 0;
|
||||
acc.costs += f?.totalCosts || 0;
|
||||
acc.charges += f?.totalWriteOffs || 0;
|
||||
acc.profit += f?.netProfit || 0;
|
||||
return acc;
|
||||
}, { revenue: 0, costs: 0, profit: 0 });
|
||||
}, { revenue: 0, costs: 0, charges: 0, profit: 0 });
|
||||
const rows: (string | number)[][] = evIds.map(evId => {
|
||||
const f = financialsByEvent[evId];
|
||||
const ev = filteredEvents.find(e => e.id === evId);
|
||||
return [ev?.title || evId, Number((f?.effectiveTotalRevenue || 0).toFixed(2)), Number((f?.totalCosts || 0).toFixed(2)), Number((f?.netProfit || 0).toFixed(2))];
|
||||
return [ev?.title || evId, Number((f?.effectiveTotalRevenue || 0).toFixed(2)), Number((f?.totalCosts || 0).toFixed(2)), Number((f?.totalWriteOffs || 0).toFixed(2)), Number((f?.netProfit || 0).toFixed(2))];
|
||||
});
|
||||
return {
|
||||
title: 'Profit Report', subtitle, kind: 'table', orientation: 'portrait',
|
||||
stats: [
|
||||
{ label: 'Revenue', value: `R ${totals.revenue.toFixed(2)}`, tone: 'green' },
|
||||
{ label: 'Costs', value: `R ${totals.costs.toFixed(2)}`, tone: 'amber' },
|
||||
{ label: 'Bank & card charges', value: `R ${totals.charges.toFixed(2)}`, tone: 'amber' },
|
||||
{ label: 'Net profit', value: `R ${totals.profit.toFixed(2)}`, tone: 'violet' },
|
||||
],
|
||||
chart: evIds.length > 1 ? { title: 'Net profit by event', data: evIds.map(evId => ({ label: filteredEvents.find(e => e.id === evId)?.title || evId, value: financialsByEvent[evId]?.netProfit || 0, displayValue: `R ${(financialsByEvent[evId]?.netProfit || 0).toFixed(2)}` })) } : undefined,
|
||||
table: { columns: ["Event", "Revenue", "Costs", "Net profit"], rows }
|
||||
table: { columns: ["Event", "Revenue", "Costs", "Bank & card charges", "Net profit"], rows }
|
||||
};
|
||||
}
|
||||
if (report === "cashupAudit") {
|
||||
@@ -1455,7 +1463,7 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
report={report} setReport={(r: ReportKey) => { setReport(r); setReady(false); }}
|
||||
onViewReport={() => { setPopupOpen(true); onView(); }}
|
||||
busy={busy}
|
||||
onBack={onBack}
|
||||
backHref={backHref}
|
||||
/>
|
||||
|
||||
{popupOpen && (
|
||||
|
||||
@@ -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 (
|
||||
<Link href={href} className="inline-block text-xs text-brand-600 hover:underline">
|
||||
← {label}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -43,13 +43,23 @@ export const dashboardAdminCashupDetailHelpContent: HelpContent = {
|
||||
icon: ClipboardCheck,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>A per-method table (cash, card, EFT, other) compares income, costs charged to that method, and expected vs actual amounts.</p>
|
||||
<p>For each payment method (cash, card, EFT, other) you say where the expected money ended up. Expected is what was taken, less any costs paid out of that method.</p>
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li><strong>In bank</strong>: card settlements, EFTs on the statement, cash that was deposited.</li>
|
||||
<li><strong>Cash on hand</strong>: cash not deposited yet.</li>
|
||||
<li><strong>Pending</strong>: on the card machine or Yoco report, or you have a proof of payment, but it isn't in the bank yet. Add the report or POP reference.</li>
|
||||
<li><strong>Write-offs</strong>: 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.</li>
|
||||
</ul>
|
||||
<p>Each method shows what's still <strong>unaccounted</strong>. You can close with an unaccounted amount, but you'll be warned and it comes off profit.</p>
|
||||
<div className="space-y-4">
|
||||
<GuideItem icon={ClipboardCheck} title="Cash accountability" tone="amber">
|
||||
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).
|
||||
</GuideItem>
|
||||
<GuideItem icon={Wallet} title="Pending money after closing" tone="blue">
|
||||
Once the event is closed, pending money shows as outstanding. When it reaches the bank, use Mark received; if it never will, use Write off. You don't need to reopen the event.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Lock} title="Closing the event" tone="rose">
|
||||
Save draft keeps working on it later; Quick close skips detailed reconciliation; Close event with cashup locks everything in. A closed event can be Reopened if something needs fixing — both actions are logged in the History panel.
|
||||
Save draft keeps working on it later; Quick close skips the settlement; Close event with cashup locks everything in. A closed event can be Reopened if something needs fixing, and the next cashup starts from the last one. Both actions are logged in the History panel.
|
||||
</GuideItem>
|
||||
</div>
|
||||
</div>
|
||||
@@ -61,7 +71,7 @@ export const dashboardAdminCashupDetailHelpContent: HelpContent = {
|
||||
icon: FileBarChart,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>A read-only summary of revenue by method, denomination breakdown, staff cash accountability, costs, donations, and net profit. This becomes the default view automatically once the event is closed.</p>
|
||||
<p>A read-only summary of where the money ended up by method (in bank, on hand, pending, written off, unaccounted), write-offs, denomination breakdown, staff cash accountability, costs, donations, and net profit. This becomes the default view automatically once the event is closed.</p>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -183,7 +183,36 @@ export type EventCashupLine = {
|
||||
actualAmount?: number | null;
|
||||
variance?: number | null;
|
||||
notes?: string | null;
|
||||
bankAmount?: number | null;
|
||||
onHandAmount?: number | null;
|
||||
pendingAmount?: number | null;
|
||||
pendingReference?: string | null;
|
||||
writeOffTotal?: number;
|
||||
denominations?: EventCashupDenomination[];
|
||||
writeOffs?: CashupWriteOff[];
|
||||
};
|
||||
|
||||
export type CashupWriteOffCategory = "card_fees" | "bank_charges" | "cash_shortfall" | "other";
|
||||
|
||||
export type CashupWriteOff = {
|
||||
id?: string;
|
||||
category: CashupWriteOffCategory;
|
||||
amount: number;
|
||||
reason?: string | null;
|
||||
createdAt?: string;
|
||||
// Written off after the event was closed (from pending money that never arrived).
|
||||
afterClose?: boolean;
|
||||
};
|
||||
|
||||
export type PendingResolution = {
|
||||
id: string;
|
||||
lineId: string;
|
||||
outcome: "received" | "written_off";
|
||||
amount: number;
|
||||
category?: CashupWriteOffCategory | null;
|
||||
notes?: string | null;
|
||||
performedBy?: { id: string; name: string } | null;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
export type CashupAction = "closed" | "quick_closed" | "reopened";
|
||||
@@ -204,12 +233,25 @@ export type EventCashup = {
|
||||
event?: Pick<Event, "id" | "title">;
|
||||
};
|
||||
|
||||
// One method of the latest close, with pending money settled since then folded in.
|
||||
export type ReconciledByMethod = {
|
||||
lineId: string | null;
|
||||
expected: number;
|
||||
actual: number | null;
|
||||
variance: number | null;
|
||||
notes?: string | null;
|
||||
denominations: EventCashupDenomination[];
|
||||
bank: number | null;
|
||||
onHand: number | null;
|
||||
pending: number | null;
|
||||
pendingReference: string | null;
|
||||
pendingReceived: number;
|
||||
pendingOutstanding: number;
|
||||
pendingResolutions: PendingResolution[];
|
||||
writeOffs: CashupWriteOff[];
|
||||
writeOffTotal: number;
|
||||
// expected − actual − write-offs; null when nothing was entered for the method.
|
||||
unaccounted: number | null;
|
||||
};
|
||||
|
||||
export type ReconciledSnapshot = {
|
||||
@@ -225,9 +267,12 @@ export type ReconciledSnapshot = {
|
||||
export type CashupDraft = {
|
||||
lines?: {
|
||||
method: string;
|
||||
actualAmount?: string | number;
|
||||
notes?: string;
|
||||
denominations?: { value: number; count: number }[];
|
||||
bankAmount?: string | number | null;
|
||||
onHandAmount?: string | number | null;
|
||||
pendingAmount?: string | number | null;
|
||||
pendingReference?: string | null;
|
||||
writeOffs?: { category: CashupWriteOffCategory; amount: string | number | null; reason?: string | null }[];
|
||||
notes?: string | null;
|
||||
}[];
|
||||
};
|
||||
|
||||
@@ -250,6 +295,11 @@ export type EventFinancials = {
|
||||
reconciled: ReconciledSnapshot | null;
|
||||
effectiveGrossIncomeByMethod: Record<CashupMethod, number>;
|
||||
effectiveTotalRevenue: number;
|
||||
writeOffsByMethod: Record<CashupMethod, number>;
|
||||
writeOffsByCategory: Record<CashupWriteOffCategory, number>;
|
||||
// Card fees, bank charges and shortfalls written off; comes off net profit.
|
||||
totalWriteOffs: number;
|
||||
pendingOutstandingTotal: number;
|
||||
netProfit: number;
|
||||
// Coupon discounts given on the event's registrations.
|
||||
discountsTotal?: number;
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "hope-events",
|
||||
"version": "1.26.1",
|
||||
"version": "1.27.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "hope-events",
|
||||
"version": "1.26.1",
|
||||
"version": "1.27.0",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.2.1"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hope-events",
|
||||
"version": "1.26.1",
|
||||
"version": "1.27.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
|
||||
Reference in New Issue
Block a user