Build a live status dashboard for Commandocentrum + admin home

The Commandocentrum (AtomCMS's verification/diagnostics hub) was just RCON
buttons + an error table. Rebuilt it as a real status dashboard, and gave
the admin home the same treatment, with reusable StatusCard / DiagnosticRow
/ InfoItem components and a scoped CSS layer:

Commandocentrum now shows:
- Live status tiles: players online, emulator (RCON ping), database,
  emulator error count — colour-accented by state.
- Server info: Node version, platform, app/host uptime, heap/RSS, load,
  CPUs (from node:os / process).
- System diagnostics: DB, emulator RCON, RCON config, APP_KEY (2FA),
  SMTP, maintenance mode — each with an ok/warn/error dot + pill.
- Existing RCON controls + hotel alert, a recent staff-activity feed
  (staff_activities, now a real table), and the emulator error log.

Admin home: four status tiles (online/articles/active bans/database) +
recent staff activity, replacing the three plain count cards.

Verified in a real authed admin session (prod, amx_test): both pages
render the tiles/diagnostics with live data (Node v22, real memory/uptime,
APP_KEY/SMTP correctly flagged WARN). tsc 0, vitest 49/49, next build 0.
This commit is contained in:
Simo committed 2026-06-28 18:45:48 +02:00
1 parent f4e0924e71
commit d419731566
4 files changed
+433 -25

No files matched your search

+171 -9
View File
@@ -1,10 +1,14 @@
import os from "node:os";
import {
hotelAlert,
updateCatalog,
updateNavigator,
updateWordFilter,
} from "@/actions/commandocentrum";
import { DiagnosticRow, InfoItem, StatusCard } from "@/components/admin/dashboard";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
import { siteSettings } from "@/lib/services/site-settings";
export const dynamic = "force-dynamic";
@@ -13,6 +17,10 @@ function formatTimestamp(ts: number | null | undefined): string {
return new Date(ts * 1000).toISOString().slice(0, 19).replace("T", " ");
}
function fromDate(d: Date | null | undefined): string {
return d ? d.toISOString().slice(0, 19).replace("T", " ") : "—";
}
// stacktrace is a MySQL BLOB (Prisma `Bytes`), so it arrives as a Buffer/
// Uint8Array. Decode to UTF-8 and trim to a single readable preview line.
function decodeStacktrace(raw: unknown): string {
@@ -25,23 +33,144 @@ function decodeStacktrace(raw: unknown): string {
}
}
function mb(bytes: number): string {
return `${Math.round(bytes / 1024 / 1024)} MB`;
}
function uptime(seconds: number): string {
const d = Math.floor(seconds / 86400);
const h = Math.floor((seconds % 86400) / 3600);
const m = Math.floor((seconds % 3600) / 60);
return d > 0 ? `${d}d ${h}h ${m}m` : h > 0 ? `${h}h ${m}m` : `${m}m`;
}
export default async function CommandoCentrum() {
const errors = await prisma.emulatorErrors
.findMany({
orderBy: { timestamp: "desc" },
take: 50,
})
.catch(() => []);
// Gather everything in parallel; any failure degrades to a safe default so the
// panel still renders (and the DB-down state is itself a diagnostic).
const [onlineCount, totalUsers, errors, dbOk, emulatorOnline, maintenance, activity] =
await Promise.all([
prisma.user.count({ where: { online: "1" } }).catch(() => 0),
prisma.user.count().catch(() => -1),
prisma.emulatorErrors.findMany({ orderBy: { timestamp: "desc" }, take: 50 }).catch(() => []),
prisma.websiteSetting
.count()
.then(() => true)
.catch(() => false),
rcon.send("ping", null).catch(() => false),
siteSettings.getBool("maintenance_enabled", false),
prisma.staffActivities
.findMany({ orderBy: { createdAt: "desc" }, take: 12 })
.catch(() => [] as Awaited<ReturnType<typeof prisma.staffActivities.findMany>>),
]);
// Resolve staff usernames for the activity feed.
const staffIds = Array.from(new Set(activity.map((a) => Number(a.userId)))).filter((n) => n > 0);
let nameById = new Map<number, string>();
if (staffIds.length) {
const users = await prisma.user
.findMany({ where: { id: { in: staffIds } }, select: { id: true, username: true } })
.catch(() => []);
nameById = new Map(users.map((u) => [u.id, u.username]));
}
const appKeySet = !!process.env.APP_KEY;
const smtpSet = !!process.env.SMTP_HOST;
const rconSet = !!process.env.RCON_HOST;
return (
<main>
<h1>Commandocentrum</h1>
<p className="muted" style={{ marginTop: "-0.25rem" }}>
Emulator control center — push live reloads and broadcast alerts over RCON.
Live hotel status, diagnostics and emulator control over RCON.
</p>
{/* ── Live status ────────────────────────────────────────── */}
<div className="admin-stats" style={{ marginTop: "1.1rem" }}>
<StatusCard
label="Players online"
value={onlineCount}
hint={totalUsers >= 0 ? `${totalUsers} accounts total` : "DB unavailable"}
state="neutral"
icon="👤"
/>
<StatusCard
label="Emulator"
value={emulatorOnline ? "Online" : "Offline"}
hint={emulatorOnline ? "RCON reachable" : "RCON not responding"}
state={emulatorOnline ? "ok" : "danger"}
icon="🎮"
/>
<StatusCard
label="Database"
value={dbOk ? "Connected" : "Down"}
hint={dbOk ? "Queries responding" : "Cannot reach DB"}
state={dbOk ? "ok" : "danger"}
icon="🗄️"
/>
<StatusCard
label="Emulator errors"
value={errors.length}
hint="last 50 logged"
state={errors.length === 0 ? "ok" : "warn"}
icon="⚠️"
/>
</div>
{/* ── Server info + diagnostics ──────────────────────────── */}
<div className="grid cols-2">
<section className="card">
<h2 style={{ marginTop: 0 }}>Server info</h2>
<div className="admin-info-grid">
<InfoItem label="Node" value={process.version} />
<InfoItem label="Platform" value={`${process.platform} ${process.arch}`} />
<InfoItem label="App uptime" value={uptime(process.uptime())} />
<InfoItem label="Heap used" value={mb(process.memoryUsage().heapUsed)} />
<InfoItem label="RSS" value={mb(process.memoryUsage().rss)} />
<InfoItem label="Host uptime" value={uptime(os.uptime())} />
<InfoItem label="Load (1m)" value={os.loadavg()[0]?.toFixed(2) ?? "—"} />
<InfoItem label="CPUs" value={os.cpus().length} />
</div>
</section>
<section className="card">
<h2 style={{ marginTop: 0 }}>System diagnostics</h2>
<div className="admin-diag">
<DiagnosticRow
label="Database"
detail={dbOk ? "Connection healthy" : "Unreachable"}
state={dbOk ? "ok" : "danger"}
/>
<DiagnosticRow
label="Emulator (RCON)"
detail={emulatorOnline ? "Responding to ping" : "No response — is it running?"}
state={emulatorOnline ? "ok" : "warn"}
/>
<DiagnosticRow
label="RCON config"
detail={rconSet ? "RCON_HOST set" : "RCON_HOST not configured"}
state={rconSet ? "ok" : "warn"}
/>
<DiagnosticRow
label="2FA encryption key"
detail={appKeySet ? "APP_KEY configured" : "APP_KEY missing — 2FA secrets can't decrypt"}
state={appKeySet ? "ok" : "warn"}
/>
<DiagnosticRow
label="Email (SMTP)"
detail={smtpSet ? "SMTP_HOST set" : "Not configured — emails disabled"}
state={smtpSet ? "ok" : "warn"}
/>
<DiagnosticRow
label="Maintenance mode"
detail={maintenance ? "Site is in maintenance" : "Site is live"}
state={maintenance ? "warn" : "ok"}
/>
</div>
</section>
</div>
{/* ── RCON controls ──────────────────────────────────────── */}
<section style={{ marginTop: "1.5rem" }}>
<section className="admin-section">
<h2>Emulator controls</h2>
<div className="grid cols-3">
<form action={updateCatalog} className="card">
@@ -95,8 +224,41 @@ export default async function CommandoCentrum() {
</form>
</section>
{/* ── Staff activity ─────────────────────────────────────── */}
<section className="admin-section">
<h2>Recent staff activity</h2>
{activity.length === 0 ? (
<p className="muted">No staff activity logged yet.</p>
) : (
<table>
<thead>
<tr>
<th>When</th>
<th>Staff</th>
<th>Action</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{activity.map((a) => (
<tr key={String(a.id)}>
<td className="muted" style={{ whiteSpace: "nowrap" }}>
{fromDate(a.createdAt)}
</td>
<td>{nameById.get(Number(a.userId)) ?? `#${a.userId}`}</td>
<td>
<span className="admin-badge">{a.action}</span>
</td>
<td>{a.description}</td>
</tr>
))}
</tbody>
</table>
)}
</section>
{/* ── Emulator errors ────────────────────────────────────── */}
<section style={{ marginTop: "1.5rem" }}>
<section className="admin-section">
<h2>Recent emulator errors</h2>
{errors.length === 0 ? (
<p className="muted">No emulator errors logged.</p>