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>
+81 -16
View File
@@ -1,40 +1,105 @@
import Link from "next/link";
import { StatusCard } from "@/components/admin/dashboard";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
function fromDate(d: Date | null | undefined): string {
return d ? d.toISOString().slice(0, 16).replace("T", " ") : "—";
}
export default async function AdminDashboard() {
let users = 0;
let users = -1;
let online = 0;
let articles = 0;
let bans = 0;
try {
[users, online, articles] = await Promise.all([
[users, online, articles, bans] = await Promise.all([
prisma.user.count(),
prisma.user.count({ where: { online: "1" } }),
prisma.websiteArticles.count(),
prisma.ban.count({ where: { banExpire: { gt: Math.floor(Date.now() / 1000) } } }),
]);
} catch {
// DB unavailable — show zeroed stats instead of a 500.
}
const dbOk = users >= 0;
const stats = [
{ label: "Users", value: users },
{ label: "Online now", value: online },
{ label: "Articles", value: articles },
];
const activity = await prisma.staffActivities
.findMany({ orderBy: { createdAt: "desc" }, take: 8 })
.catch(() => [] as Awaited<ReturnType<typeof prisma.staffActivities.findMany>>);
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 u = await prisma.user
.findMany({ where: { id: { in: staffIds } }, select: { id: true, username: true } })
.catch(() => []);
nameById = new Map(u.map((x) => [x.id, x.username]));
}
return (
<main>
<h1>Dashboard</h1>
<div className="grid cols-2">
{stats.map((s) => (
<div key={s.label} className="card">
<h2 style={{ margin: 0 }}>{s.value}</h2>
<p className="muted" style={{ margin: 0 }}>
{s.label}
</p>
</div>
))}
<div className="admin-stats">
<StatusCard
label="Players online"
value={online}
hint={dbOk ? `${users} accounts` : "DB unavailable"}
state={dbOk ? "neutral" : "danger"}
icon="👤"
/>
<StatusCard label="Articles" value={dbOk ? articles : "—"} icon="📰" />
<StatusCard
label="Active bans"
value={dbOk ? bans : "—"}
state={bans > 0 ? "warn" : "neutral"}
icon="🔨"
/>
<StatusCard
label="Database"
value={dbOk ? "Connected" : "Down"}
state={dbOk ? "ok" : "danger"}
icon="🗄️"
/>
</div>
<section className="admin-section">
<div style={{ display: "flex", alignItems: "baseline", gap: "0.75rem" }}>
<h2 style={{ margin: 0 }}>Recent staff activity</h2>
<Link href="/admin/commandocentrum" className="muted" style={{ fontSize: "0.82rem" }}>
View all →
</Link>
</div>
{activity.length === 0 ? (
<p className="muted">No staff activity logged yet.</p>
) : (
<table style={{ marginTop: "0.7rem" }}>
<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>
</main>
);
}
+115
View File
@@ -564,3 +564,118 @@ td {
.admin-badge.danger {
background: color-mix(in srgb, #ef4444 22%, transparent);
}
/* Dashboard: live-status tiles, server info, diagnostics */
.admin-stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 0.9rem;
margin-bottom: 1.4rem;
}
.admin-stat-card {
background: var(--color-surface);
border: 1px solid var(--border);
border-left: 4px solid var(--color-text-muted);
border-radius: 12px;
padding: 0.85rem 1rem;
box-shadow: var(--shadow-card);
}
.admin-stat-card.ok {
border-left-color: #16a34a;
}
.admin-stat-card.warn {
border-left-color: var(--color-primary, #eeb425);
}
.admin-stat-card.danger {
border-left-color: #ef4444;
}
.admin-stat-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.admin-stat-label {
font-size: 0.72rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--color-text-muted);
}
.admin-stat-icon {
font-size: 1.1rem;
line-height: 1;
}
.admin-stat-value {
font-size: 1.7rem;
font-weight: 800;
line-height: 1.1;
margin-top: 0.3rem;
}
.admin-stat-hint {
font-size: 0.78rem;
color: var(--color-text-muted);
margin-top: 0.15rem;
}
.admin-info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 0.6rem 1.2rem;
}
.admin-info-item {
display: flex;
flex-direction: column;
gap: 0.1rem;
font-size: 0.88rem;
}
.admin-diag {
display: flex;
flex-direction: column;
}
.admin-diag-row {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.5rem 0.1rem;
border-top: 1px solid color-mix(in srgb, var(--color-text-muted) 12%, transparent);
}
.admin-diag-row:first-child {
border-top: none;
}
.admin-diag-label {
font-weight: 700;
font-size: 0.88rem;
}
.admin-diag-detail {
flex: 1;
font-size: 0.82rem;
}
.admin-dot {
flex: none;
width: 9px;
height: 9px;
border-radius: 999px;
background: var(--color-text-muted);
}
.admin-dot.ok {
background: #16a34a;
box-shadow: 0 0 0 3px color-mix(in srgb, #16a34a 22%, transparent);
}
.admin-dot.warn {
background: var(--color-primary, #eeb425);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary) 22%, transparent);
}
.admin-dot.danger {
background: #ef4444;
box-shadow: 0 0 0 3px color-mix(in srgb, #ef4444 22%, transparent);
}
.admin-section {
margin-top: 1.6rem;
}
.admin-section > h2 {
margin: 0 0 0.7rem;
font-size: 1.15rem;
}
+66
View File
@@ -0,0 +1,66 @@
import type { ReactNode } from "react";
type State = "ok" | "warn" | "danger" | "neutral";
/** A single live-status tile (online users, emulator, DB, …). */
export function StatusCard({
label,
value,
hint,
state = "neutral",
icon,
}: {
label: string;
value: ReactNode;
hint?: string;
state?: State;
icon?: string;
}) {
return (
<div className={`admin-stat-card ${state}`}>
<div className="admin-stat-top">
<span className="admin-stat-label">{label}</span>
{icon ? (
<span className="admin-stat-icon" aria-hidden>
{icon}
</span>
) : null}
</div>
<div className="admin-stat-value">{value}</div>
{hint ? <div className="admin-stat-hint">{hint}</div> : null}
</div>
);
}
/** A row in the system-diagnostics list with an ok/warn/error pill. */
export function DiagnosticRow({
label,
detail,
state,
}: {
label: string;
detail: string;
state: Exclude<State, "neutral">;
}) {
const text = state === "ok" ? "OK" : state === "warn" ? "WARN" : "ERROR";
return (
<div className="admin-diag-row">
<span className={`admin-dot ${state}`} aria-hidden />
<span className="admin-diag-label">{label}</span>
<span className="admin-diag-detail muted">{detail}</span>
<span className={`admin-badge ${state === "ok" ? "ok" : state === "danger" ? "danger" : ""}`}>
{text}
</span>
</div>
);
}
/** Small labelled key/value used in the server-info card. */
export function InfoItem({ label, value }: { label: string; value: ReactNode }) {
return (
<div className="admin-info-item">
<span className="muted">{label}</span>
<strong>{value}</strong>
</div>
);
}