- Events: loading demo data emptied ProductLink but kept auth_mode, so a site in Accounts mode had no link and nobody could sign in (ACCOUNTS_UNAVAILABLE on events-demo). set-demo.js keeps ProductLink and LinkNonce; a site in Accounts mode without a link reconnects at its next heartbeat; sign-in failures are kept and sent in the heartbeat (stats.signIn). - Contracts 1.13.0: stats.signIn in the Cross Events heartbeat. - Agent 1.3.1: 1.3.0 reported itself as 1.2.0 (AGENT_VERSION not bumped). - What's New notes for Events 3.4.0 / 3.5.0 and Accounts 1.4.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
193 lines
9.0 KiB
JavaScript
193 lines
9.0 KiB
JavaScript
/**
|
||
* 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();
|
||
|
||
// The tops of the income bands, in rand (docs/hub-protocol.md §3). Cross Code's licence tiers
|
||
// are billed on the 12-month event-income band, so every tier edge (R50 000, R150 000, R400 000,
|
||
// R1m, R2.5m, R5m, R10m) is also a band edge: change them together.
|
||
const BAND_TOPS = [1000, 5000, 20000, 50000, 100000, 150000, 250000, 400000, 700000, 1000000, 2500000, 5000000, 10000000];
|
||
|
||
const randText = n => `R${String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ' ')}`;
|
||
const INCOME_BANDS = BAND_TOPS.map((top, i) => [top, `${randText(i ? BAND_TOPS[i - 1] + 1 : 0)}–${randText(top)}`]);
|
||
const TOP_BAND = `over ${randText(BAND_TOPS[BAND_TOPS.length - 1])}`;
|
||
|
||
/** The range an amount falls in: "R5 001–R20 000", or "over R10 000 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 TOP_BAND;
|
||
}
|
||
|
||
// Applying an earlier donation to a registration adds a "leg" payment that isn't new money
|
||
// (cashupUtils.isDonationLeg), so every money total leaves it out.
|
||
const NOT_DONATION_LEG = { NOT: { AND: [{ isDonation: false }, { originalPaymentId: { not: null } }, { amount: { gt: 0 } }] } };
|
||
// Event income, what the licence tier is billed on: payments less refunds, without donations or
|
||
// sponsorships (both isDonation) and without the legs that apply a donation to a registration.
|
||
const EVENT_INCOME = { isDonation: false, ...NOT_DONATION_LEG };
|
||
|
||
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;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 3.2.0: what's happening at the church now (heartbeat `stats.live`), so the Hub warns before an
|
||
* emergency update takes the site down: events with a session on now, or a one-day event (no
|
||
* sessions, at most 36 hours long) on now, each give or take 30 minutes; and tickets checked in
|
||
* during the last hour. A multi-week course without a session today doesn't count.
|
||
*/
|
||
async function liveNow(now = new Date()) {
|
||
const soon = new Date(now.getTime() + 30 * 60e3);
|
||
const recent = new Date(now.getTime() - 30 * 60e3);
|
||
const [sessions, plain, checkInsLastHour] = await Promise.all([
|
||
prisma.eventSession.findMany({ where: { cancelledAt: null, startsAt: { lte: soon }, endsAt: { gte: recent }, event: { isActive: true } }, select: { eventId: true } }),
|
||
prisma.event.findMany({ where: { isActive: true, startDate: { lte: soon }, endDate: { gte: recent }, sessions: { none: {} } }, select: { id: true, startDate: true, endDate: true } }),
|
||
prisma.ticketUsage.count({ where: { scannedAt: { gte: new Date(now.getTime() - 60 * 60e3) } } }),
|
||
]);
|
||
const ids = new Set(sessions.map(x => x.eventId));
|
||
for (const e of plain) if (new Date(e.endDate) - new Date(e.startDate) <= 36 * 60 * 60e3) ids.add(e.id);
|
||
return { eventsNow: ids.size, checkInsLastHour };
|
||
}
|
||
|
||
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 yearAgo = new Date(now.getTime() - 365 * 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, eventIncome12m, 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 }, ...NOT_DONATION_LEG }, _sum: { amount: true } }),
|
||
prisma.payment.aggregate({ where: NOT_DONATION_LEG, _sum: { amount: true } }),
|
||
prisma.payment.aggregate({ where: { createdAt: { gte: yearAgo }, ...EVENT_INCOME }, _sum: { amount: true } }),
|
||
require('../payments').availableProviders().then(list => list.map(p => p.id)).catch(() => []),
|
||
]);
|
||
const live = await liveNow(now).catch(() => undefined);
|
||
const campusesOn = await campusesEnabled().catch(() => false);
|
||
const campusCount = campusesOn ? await prisma.campus.count({ where: { archivedAt: null } }) : 0;
|
||
// 3.5.0: how people sign in (the Hub flags a site in Accounts mode without a link, or failing).
|
||
const signIn = await require('../accounts/status').signInStatus().catch(() => undefined);
|
||
return {
|
||
users,
|
||
events: { active: activeEvents, upcoming: upcomingEvents, total: totalEvents },
|
||
...(live ? { live } : {}),
|
||
...(signIn ? { signIn } : {}),
|
||
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),
|
||
// 2.0.2+: event income over the last 12 months, what the licence tier is billed on.
|
||
eventIncome12m: incomeBand(eventIncome12m._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, liveNow };
|