/** * What this install tells the Hub (docs/hub-protocol.md §3): health, and aggregate counts — * no personal information. Income goes as a range, never an amount. */ const fs = require('fs'); const os = require('os'); const path = require('path'); const prisma = require('../config/db'); const errorCounter = require('../utils/errorCounter'); const DAY = 24 * 60 * 60 * 1000; const APP_VERSION = require('../../package.json').version; const STARTED_AT = Date.now(); const INCOME_BANDS = [ [1000, 'R0–R1 000'], [5000, 'R1 001–R5 000'], [20000, 'R5 001–R20 000'], [50000, 'R20 001–R50 000'], [100000, 'R50 001–R100 000'], ]; /** The range an amount falls in: "R5 001–R20 000", or "over R100 000". */ function incomeBand(amount) { const rand = Math.max(0, Math.round(Number(amount) || 0)); for (const [max, label] of INCOME_BANDS) if (rand <= max) return label; return 'over R100 000'; } async function postgresVersion() { try { const rows = await prisma.$queryRawUnsafe('SHOW server_version'); return String(rows[0]?.server_version || '').split(' ')[0] || null; } catch { return null; } } /** Migrations in the repo that the database hasn't applied. */ async function pendingMigrations() { try { const dir = path.join(__dirname, '..', '..', 'prisma', 'migrations'); const folders = fs.readdirSync(dir, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name); const rows = await prisma.$queryRawUnsafe('SELECT migration_name FROM "_prisma_migrations" WHERE finished_at IS NOT NULL AND rolled_back_at IS NULL'); const applied = new Set(rows.map(r => r.migration_name)); return folders.filter(f => !applied.has(f)).length; } catch { return null; } } async function disk() { try { const s = await fs.promises.statfs(path.join(__dirname, '..', '..')); return { freeBytes: s.bavail * s.bsize, totalBytes: s.blocks * s.bsize }; } catch { return null; } } async function jobsHealth() { try { const { jobStatus } = require('../jobs'); const status = await jobStatus(prisma); const since = Date.now() - DAY; const failed = status.jobs.flatMap(j => j.recent).filter(r => r.state === 'failed' && new Date(r.completedOn || r.startedOn || 0).getTime() > since).length; return { mode: status.mode, failedLast24h: failed }; } catch { return null; } } async function lastBackupAt() { try { const backups = await require('../utils/backupUtils').listBackups(); return backups[0]?.createdAt ? new Date(backups[0].createdAt).toISOString() : null; } catch { return null; } } async function health() { let db = true; try { await prisma.$queryRawUnsafe('SELECT 1'); } catch { db = false; } const [jobs, backupAt, diskInfo, pending] = await Promise.all([jobsHealth(), lastBackupAt(), disk(), pendingMigrations()]); return { uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000), db, jobs, lastBackupAt: backupAt, disk: diskInfo, errorsLast24h: errorCounter.countLast24h(), pendingMigrations: pending, }; } async function stats(now = new Date()) { const { campusesEnabled } = require('../utils/campuses'); const since = new Date(now.getTime() - 30 * DAY); const realUser = { isActive: true, NOT: [{ email: { endsWith: '@deleted.invalid' } }, { email: { endsWith: '@guest.local' } }] }; const [users, activeEvents, upcomingEvents, totalEvents, regs30, regsTotal, tickets30, ticketsTotal, checkIns30, income30, incomeAll, providers] = await Promise.all([ prisma.user.count({ where: realUser }), prisma.event.count({ where: { isActive: true, startDate: { lte: now }, endDate: { gte: now } } }), prisma.event.count({ where: { isActive: true, startDate: { gt: now } } }), prisma.event.count(), prisma.registration.count({ where: { createdAt: { gte: since } } }), prisma.registration.count(), prisma.ticket.count({ where: { createdAt: { gte: since } } }), prisma.ticket.count(), prisma.ticketUsage.count({ where: { scannedAt: { gte: since } } }), prisma.payment.aggregate({ where: { createdAt: { gte: since } }, _sum: { amount: true } }), prisma.payment.aggregate({ _sum: { amount: true } }), require('../payments').availableProviders().then(list => list.map(p => p.id)).catch(() => []), ]); const campusesOn = await campusesEnabled().catch(() => false); const campusCount = campusesOn ? await prisma.campus.count({ where: { archivedAt: null } }) : 0; return { users, events: { active: activeEvents, upcoming: upcomingEvents, total: totalEvents }, registrations: { last30d: regs30, total: regsTotal }, tickets: { last30d: tickets30, total: ticketsTotal }, checkIns: { last30d: checkIns30 }, // Messages aren't logged one by one, so there's nothing to count yet. messages: null, paymentProviders: providers, campuses: campusesOn, campusCount, income: { last30d: incomeBand(income30._sum.amount), allTime: incomeBand(incomeAll._sum.amount) }, }; } /** What the install says about itself when registering. */ async function installInfo() { const { getSetting } = require('../utils/settingsCache'); const [name, url, waConfigured, providers, campusesOn] = await Promise.all([ getSetting('org_name', ''), getSetting('app_base_url', process.env.FRONTEND_URL || ''), require('../utils/whatsapp').isConfigured().catch(() => false), require('../payments').availableProviders().then(list => list.map(p => p.id)).catch(() => []), require('../utils/campuses').campusesEnabled().catch(() => false), ]); return { name: name || 'Cross Events', url: String(url || process.env.FRONTEND_URL || '').split(',')[0].trim().replace(/\/$/, ''), version: APP_VERSION, timezone: process.env.APP_TIMEZONE || 'Africa/Johannesburg', server: { node: process.versions.node, postgres: await postgresVersion(), os: `${os.platform()} ${os.release()}` }, features: { whatsapp: !!waConfigured, paymentProviders: providers, campuses: campusesOn }, }; } module.exports = { APP_VERSION, incomeBand, health, stats, installInfo };