Staff, supervisor and admin dashboards start with what's on today (checked in vs places, children in now, volunteers here; money in today and this week for supervisors) and, for supervisors and admins, what's waiting for someone (unpaid registrations, consent, waitlists, cover requests, roster gaps; for admins cashups, reconciling, privacy requests, failed webhooks), each linking to where it's dealt with. Ctrl+K opens a palette of pages, settings, reports and actions for the role, with search: events, payments by amount, people and registrations (admins). All campus-scoped. Bulk actions and saved filters follow as 1.49.1 and 1.49.2. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
250 lines
13 KiB
JavaScript
250 lines
13 KiB
JavaScript
/**
|
|
* The home dashboard for staff, supervisors and admins (1.49.0): what's on today, money in, and
|
|
* what's waiting for someone — plus the search behind the Ctrl+K command palette.
|
|
*
|
|
* Everything follows the person's campus scope (utils/campusScope.js): a campus-limited
|
|
* supervisor sees their campuses' events and church-wide ones. Items only some roles can act on
|
|
* (cashups, provider payments, privacy requests, webhooks) are shown to those roles only.
|
|
*/
|
|
|
|
const prisma = require('../config/db');
|
|
const { scopeFor, eventWhere } = require('./campusScope');
|
|
|
|
const DAY = 864e5;
|
|
// The same "real money" as the dashboards: everything except legs that apply an earlier donation.
|
|
const EXCLUDE_DONATION_LEGS = { NOT: { AND: [{ isDonation: false }, { originalPaymentId: { not: null } }, { amount: { gt: 0 } }] } };
|
|
|
|
function dayBounds(now = new Date()) {
|
|
const start = new Date(now); start.setHours(0, 0, 0, 0);
|
|
return { start, end: new Date(start.getTime() + DAY - 1) };
|
|
}
|
|
|
|
const isAdmin = req => req.user?.role === 'admin';
|
|
const isSupervisor = req => ['admin', 'supervisor'].includes(req.user?.role);
|
|
|
|
/** Events on today (single-date events running today, or a session today), with how it's going. */
|
|
async function todaysEvents(scopeWhere, now = new Date()) {
|
|
const { start, end } = dayBounds(now);
|
|
const events = await prisma.event.findMany({
|
|
where: {
|
|
AND: [scopeWhere, { isActive: true }, {
|
|
OR: [
|
|
{ scheduleType: 'single', startDate: { lte: end }, endDate: { gte: start } },
|
|
{ scheduleType: 'sessions', sessions: { some: { startsAt: { gte: start, lte: end }, cancelledAt: null } } },
|
|
],
|
|
}],
|
|
},
|
|
orderBy: { startDate: 'asc' },
|
|
select: {
|
|
id: true, title: true, startDate: true, endDate: true, location: true, scheduleType: true, kidsCheckIn: true, isHidden: true,
|
|
campus: { select: { id: true, name: true, slug: true, colour: true } },
|
|
sessions: { where: { startsAt: { gte: start, lte: end }, cancelledAt: null }, orderBy: { startsAt: 'asc' }, select: { id: true, label: true, startsAt: true, endsAt: true } },
|
|
},
|
|
});
|
|
return Promise.all(events.map(async e => {
|
|
const session = e.sessions[0] || null;
|
|
const [places, scans, kidsIn, roles] = await Promise.all([
|
|
prisma.ticket.aggregate({ where: { eventId: e.id, registrationOption: { registration: { status: { not: 'cancelled' } } } }, _sum: { quantity: true } }),
|
|
prisma.ticketUsage.aggregate({ where: { ticket: { eventId: e.id }, scannedAt: { gte: start, lte: end } }, _sum: { quantityRedeemed: true } }),
|
|
e.kidsCheckIn ? prisma.kidsCheckIn.count({ where: { eventId: e.id, checkedOutAt: null, checkedInAt: { gte: start, lte: end } } }) : Promise.resolve(null),
|
|
prisma.servingRole.findMany({
|
|
where: { eventId: e.id, OR: [{ sessionId: null }, ...(session ? [{ sessionId: session.id }] : [])] },
|
|
select: { needed: true, slots: { select: { checkedInAt: true } } },
|
|
}),
|
|
]);
|
|
return {
|
|
id: e.id, title: e.title, location: e.location, campus: e.campus, isHidden: e.isHidden, kidsCheckIn: e.kidsCheckIn,
|
|
startsAt: session ? session.startsAt : e.startDate, endsAt: session ? session.endsAt : e.endDate,
|
|
sessionLabel: session ? session.label : null,
|
|
places: places._sum.quantity || 0,
|
|
checkedIn: scans._sum.quantityRedeemed || 0,
|
|
kidsIn,
|
|
volunteers: roles.length ? {
|
|
needed: roles.reduce((s, r) => s + r.needed, 0),
|
|
rostered: roles.reduce((s, r) => s + r.slots.length, 0),
|
|
checkedIn: roles.reduce((s, r) => s + r.slots.filter(x => x.checkedInAt).length, 0),
|
|
} : null,
|
|
};
|
|
}));
|
|
}
|
|
|
|
/** Money in today and over the last 7 days (the person's events, or everything for the unscoped). */
|
|
async function moneyIn(scope, now = new Date()) {
|
|
const { start } = dayBounds(now);
|
|
const weekStart = new Date(start.getTime() - 6 * DAY);
|
|
const where = from => ({ ...EXCLUDE_DONATION_LEGS, createdAt: { gte: from }, ...(scope ? { event: eventWhere(scope) } : {}) });
|
|
const [today, week] = await Promise.all([
|
|
prisma.payment.aggregate({ where: where(start), _sum: { amount: true }, _count: { _all: true } }),
|
|
prisma.payment.aggregate({ where: where(weekStart), _sum: { amount: true } }),
|
|
]);
|
|
return { today: today._sum.amount || 0, todayCount: today._count._all, week: week._sum.amount || 0 };
|
|
}
|
|
|
|
/**
|
|
* What's waiting for someone: each { key, label, count, href, tone }, only those with a count.
|
|
* `href` takes the person to where it's dealt with.
|
|
*/
|
|
async function pendingItems(req, scope, now = new Date()) {
|
|
const upcoming = { startDate: { gte: now } };
|
|
const scoped = (extra = {}) => ({ AND: [eventWhere(scope), extra] });
|
|
const soon = new Date(now.getTime() + 14 * DAY);
|
|
const week = new Date(now.getTime() + 7 * DAY);
|
|
const items = [];
|
|
const push = async (key, fn) => {
|
|
try {
|
|
const item = await fn();
|
|
if (item && item.count > 0) items.push({ key, ...item });
|
|
} catch (e) {
|
|
console.warn(`[dashboard] ${key}:`, e?.message || e);
|
|
}
|
|
};
|
|
|
|
await Promise.all([
|
|
push('unpaid', async () => ({
|
|
label: 'Unpaid or part-paid registrations for events in the next two weeks',
|
|
count: await prisma.registration.count({ where: { status: { in: ['pending', 'partial_paid'] }, event: scoped({ startDate: { gte: now, lte: soon }, isActive: true }) } }),
|
|
href: isAdmin(req) ? '/dashboard/admin/registrations?status=pending' : '/dashboard/supervisor/reports?report=regStatus',
|
|
tone: 'amber',
|
|
})),
|
|
push('consent', async () => {
|
|
const pending = await prisma.consentRequest.findMany({ where: { status: 'pending', event: scoped(upcoming) }, select: { attendeeId: true }, distinct: ['attendeeId'] });
|
|
const given = new Set((await prisma.consentRequest.findMany({ where: { status: 'given', attendeeId: { in: pending.map(p => p.attendeeId) } }, select: { attendeeId: true } })).map(g => g.attendeeId));
|
|
return { label: 'Young people still waiting for parental consent', count: pending.filter(p => !given.has(p.attendeeId)).length, href: '/dashboard/supervisor/consent', tone: 'rose' };
|
|
}),
|
|
push('waitlist', async () => ({
|
|
label: 'People on a waitlist',
|
|
count: await prisma.waitlistEntry.count({ where: { status: 'waiting', event: scoped(upcoming) } }),
|
|
href: '/dashboard/supervisor/waitlist',
|
|
tone: 'blue',
|
|
})),
|
|
push('cover', async () => ({
|
|
label: 'Volunteers asking for someone to cover their shift',
|
|
count: await prisma.volunteerSwap.count({ where: { status: 'open', role: { event: scoped({ endDate: { gte: now } }) } } }),
|
|
href: '/dashboard/supervisor/volunteers',
|
|
tone: 'violet',
|
|
})),
|
|
push('roster', async () => {
|
|
const roles = await prisma.servingRole.findMany({
|
|
where: {
|
|
event: scoped({ isActive: true }),
|
|
OR: [{ session: { startsAt: { gte: now, lte: week } } }, { sessionId: null, event: { startDate: { gte: now, lte: week } } }],
|
|
},
|
|
select: { needed: true, _count: { select: { slots: true } } },
|
|
});
|
|
return { label: 'Serving roles in the next week that still need people', count: roles.filter(r => r._count.slots < r.needed).length, href: '/dashboard/supervisor/volunteers', tone: 'violet' };
|
|
}),
|
|
isAdmin(req) && push('cashup', async () => ({
|
|
label: 'Past events still to cash up',
|
|
count: await prisma.event.count({ where: { cashupStatus: 'open', endDate: { lt: new Date(now.getTime() - DAY), gte: new Date(now.getTime() - 120 * DAY) }, payments: { some: {} } } }),
|
|
href: '/dashboard/admin/cashup',
|
|
tone: 'green',
|
|
})),
|
|
(isAdmin(req) || (isSupervisor(req) && !scope)) && push('reconcile', async () => ({
|
|
label: 'Online payments that didn\'t match a registration (reconcile them)',
|
|
count: await prisma.providerTransaction.count({ where: { reconciled: false, ignored: false } }),
|
|
href: '/dashboard/supervisor/payments',
|
|
tone: 'amber',
|
|
})),
|
|
isAdmin(req) && push('privacy', async () => ({
|
|
label: 'Privacy requests to answer',
|
|
count: await prisma.dataRequest.count({ where: { status: 'open' } }),
|
|
href: '/dashboard/admin/data-requests',
|
|
tone: 'rose',
|
|
})),
|
|
isAdmin(req) && push('webhooks', async () => ({
|
|
label: 'Webhook deliveries that failed this week',
|
|
count: await prisma.webhookDelivery.count({ where: { status: 'failed', createdAt: { gte: new Date(now.getTime() - 7 * DAY) } } }),
|
|
href: '/dashboard/admin/settings?tab=webhooks',
|
|
tone: 'rose',
|
|
})),
|
|
].filter(Boolean));
|
|
const order = ['privacy', 'consent', 'unpaid', 'cover', 'roster', 'waitlist', 'reconcile', 'cashup', 'webhooks'];
|
|
return items.sort((a, b) => order.indexOf(a.key) - order.indexOf(b.key));
|
|
}
|
|
|
|
async function today(req, now = new Date()) {
|
|
const scope = await scopeFor(req);
|
|
const [events, money, pending] = await Promise.all([
|
|
todaysEvents(eventWhere(scope), now),
|
|
isSupervisor(req) ? moneyIn(scope, now) : Promise.resolve(null),
|
|
isSupervisor(req) ? pendingItems(req, scope, now) : Promise.resolve([]),
|
|
]);
|
|
return { events, money, pending };
|
|
}
|
|
|
|
// ─── Command palette search ──────────────────────────────────────────────────
|
|
|
|
/** "R450", "450", "r 450.50" → 450.5; anything else → null. Pure. */
|
|
function amountOf(q) {
|
|
const m = /^r?\s*(\d{1,7}(?:[.,]\d{1,2})?)$/i.exec(String(q || '').trim());
|
|
return m ? parseFloat(m[1].replace(',', '.')) : null;
|
|
}
|
|
|
|
/**
|
|
* Results for the command palette: events (everyone with dashboard access), and for supervisors
|
|
* payments by amount ("R450"); for admins also people and registrations. Each { type, id, title,
|
|
* subtitle, href }. Up to 5 of each kind.
|
|
*/
|
|
async function search(req, rawQuery, now = new Date()) {
|
|
const q = String(rawQuery || '').trim().slice(0, 80);
|
|
if (q.length < 2) return [];
|
|
const scope = await scopeFor(req);
|
|
const contains = { contains: q, mode: 'insensitive' };
|
|
const out = [];
|
|
const supervisor = isSupervisor(req);
|
|
const fmtDate = d => new Date(d).toLocaleDateString('en-ZA', { day: 'numeric', month: 'short', year: 'numeric' });
|
|
|
|
const events = await prisma.event.findMany({
|
|
where: { AND: [eventWhere(scope), { title: contains }] },
|
|
orderBy: { startDate: 'desc' }, take: 5,
|
|
select: { id: true, title: true, startDate: true, isActive: true, campus: { select: { name: true } } },
|
|
});
|
|
for (const e of events) {
|
|
out.push({
|
|
type: 'event', id: e.id, title: e.title,
|
|
subtitle: [fmtDate(e.startDate), e.campus?.name, e.isActive ? null : 'inactive'].filter(Boolean).join(' · '),
|
|
href: supervisor ? `/dashboard/supervisor/events?edit=${e.id}` : `/events/${e.id}`,
|
|
});
|
|
}
|
|
|
|
const amount = amountOf(q);
|
|
if (supervisor && amount !== null) {
|
|
const payments = await prisma.payment.findMany({
|
|
where: { amount: { in: [amount, -amount] }, createdAt: { gte: new Date(now.getTime() - 365 * DAY) }, ...(scope ? { event: eventWhere(scope) } : {}) },
|
|
orderBy: { createdAt: 'desc' }, take: 5,
|
|
select: { id: true, amount: true, method: true, createdAt: true, registrationId: true, user: { select: { name: true } }, event: { select: { title: true } } },
|
|
});
|
|
for (const p of payments) {
|
|
out.push({
|
|
type: 'payment', id: p.id, title: `R${p.amount.toFixed(2)} — ${p.user?.name || 'Unknown'}`,
|
|
subtitle: [p.method, p.event?.title, fmtDate(p.createdAt)].filter(Boolean).join(' · '),
|
|
href: isAdmin(req) && p.registrationId ? `/dashboard/admin/registrations?q=${p.registrationId}` : '/dashboard/supervisor/payments',
|
|
});
|
|
}
|
|
}
|
|
|
|
if (isAdmin(req)) {
|
|
const people = await prisma.user.findMany({
|
|
where: { isActive: true, OR: [{ name: contains }, { email: contains }, { phoneNumber: { contains: q.replace(/\s+/g, '') } }] },
|
|
orderBy: { name: 'asc' }, take: 5,
|
|
select: { id: true, name: true, email: true, role: true },
|
|
});
|
|
for (const u of people) {
|
|
out.push({ type: 'person', id: u.id, title: u.name, subtitle: [u.email, u.role !== 'user' ? u.role : null].filter(Boolean).join(' · '), href: `/dashboard/admin/users?q=${encodeURIComponent(u.email || u.name)}` });
|
|
}
|
|
// A registration by its reference (the start of its id), as on emails and invoices.
|
|
if (/^[0-9a-f-]{6,36}$/i.test(q)) {
|
|
const regs = await prisma.registration.findMany({
|
|
where: { id: { startsWith: q.toLowerCase() } }, take: 5,
|
|
select: { id: true, status: true, user: { select: { name: true } }, event: { select: { title: true } } },
|
|
});
|
|
for (const r of regs) {
|
|
out.push({ type: 'registration', id: r.id, title: `Registration ${r.id.slice(0, 8)} — ${r.user?.name || ''}`.trim(), subtitle: [r.event?.title, r.status].filter(Boolean).join(' · '), href: `/dashboard/admin/registrations?q=${r.id}` });
|
|
}
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
module.exports = { today, todaysEvents, moneyIn, pendingItems, search, amountOf, dayBounds };
|