Refactor dashboard notification handling and improve admin broadcast functionality. Ensure only admins can access global notifications, implement draft management for broadcast messages, and add event listeners for real-time updates across dashboard components.
Some checks failed
CI / Bot (Python) (push) Successful in 12s
CI / Dashboard (Next.js) (push) Failing after 9s

This commit is contained in:
TheOnlyMace
2026-07-21 22:30:08 +02:00
parent 18ef29f777
commit 60390009d1
2 changed files with 114 additions and 30 deletions

View File

@@ -70,8 +70,14 @@ export default function DashboardLayout({
signIn("discord");
}
// Fetch global notification
if (status !== "authenticated") return;
const fetchNotification = async () => {
// Only admins can read admin config — skip for everyone else
if (!isAdmin(session?.user?.id)) {
setGlobalNotification(null);
return;
}
try {
const config = await api.getAdminConfig();
setGlobalNotification(config.global_notification);
@@ -79,8 +85,15 @@ export default function DashboardLayout({
console.error("Failed to fetch notifications:", err);
}
};
fetchNotification();
}, [status]);
const onBroadcastUpdated = () => {
fetchNotification();
};
window.addEventListener("axiom:broadcast-updated", onBroadcastUpdated);
return () => window.removeEventListener("axiom:broadcast-updated", onBroadcastUpdated);
}, [status, session?.user?.id]);
if (status === "loading" || status === "unauthenticated") {
return (
@@ -367,7 +380,17 @@ export default function DashboardLayout({
<div className="flex items-center justify-between mb-4 border-b border-white/5 pb-2">
<p className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">Broadcast Metrics</p>
<button
onClick={() => setGlobalNotification(null)}
type="button"
onClick={async () => {
setGlobalNotification(null);
if (isAdmin(session?.user?.id)) {
try {
await api.updateAdminConfig({ global_notification: "" });
} catch (err) {
console.error("Failed to clear broadcast:", err);
}
}
}}
className="text-[10px] font-bold text-primary/60 hover:text-primary transition-colors uppercase"
>
Clear

View File

@@ -14,7 +14,7 @@
*/
"use client";
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useRef } from "react";
import {
Shield, Users, Server, Activity, Database, Cpu, Globe, Lock, Settings, RefreshCw
} from "lucide-react";
@@ -29,7 +29,9 @@ export function AdminContent() {
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [saving, setSaving] = useState(false);
const [notification, setNotification] = useState("");
/** Draft text — never auto-saved / never sent on page load */
const [draft, setDraft] = useState("");
const draftTouched = useRef(false);
const fetchData = async (isRefresh = false) => {
if (isRefresh) setRefreshing(true);
@@ -40,7 +42,10 @@ export function AdminContent() {
]);
setStats(statsData);
setConfig(configData);
setNotification(configData.global_notification || "");
// Only hydrate draft from server once / when user hasn't edited yet
if (!draftTouched.current) {
setDraft(configData.global_notification || "");
}
} catch (err) {
console.error("Failed to fetch admin data:", err);
toast.error("Failed to load real-time data");
@@ -52,7 +57,7 @@ export function AdminContent() {
useEffect(() => {
fetchData();
const interval = setInterval(() => fetchData(true), 30000); // Auto refresh every 30s
const interval = setInterval(() => fetchData(true), 30000);
return () => clearInterval(interval);
}, []);
@@ -61,9 +66,10 @@ export function AdminContent() {
setSaving(true);
try {
const newStatus = !config.maintenance_mode;
// Only patch maintenance — never touch global_notification here
await api.updateAdminConfig({ maintenance_mode: newStatus });
setConfig({ ...config, maintenance_mode: newStatus });
toast.success(`Maintenance mode ${newStatus ? 'enabled' : 'disabled'}`);
toast.success(`Maintenance mode ${newStatus ? "enabled" : "disabled"}`);
} catch (err) {
toast.error("Failed to update maintenance mode");
} finally {
@@ -71,12 +77,18 @@ export function AdminContent() {
}
};
const handleBroadcast = async () => {
const handleBroadcast = async (e?: React.MouseEvent | React.FormEvent) => {
e?.preventDefault();
e?.stopPropagation();
setSaving(true);
try {
await api.updateAdminConfig({ global_notification: notification });
if (config) setConfig({ ...config, global_notification: notification });
toast.success("Broadcast message updated");
const message = draft.trim();
await api.updateAdminConfig({ global_notification: message });
if (config) setConfig({ ...config, global_notification: message || null });
draftTouched.current = false;
toast.success(message ? "Broadcast published" : "Broadcast cleared");
// Notify other dashboard tabs/layout to refresh the bell
window.dispatchEvent(new CustomEvent("axiom:broadcast-updated"));
} catch (err) {
toast.error("Failed to update broadcast message");
} finally {
@@ -84,6 +96,22 @@ export function AdminContent() {
}
};
const handleClearBroadcast = async () => {
setSaving(true);
try {
await api.updateAdminConfig({ global_notification: "" });
setDraft("");
draftTouched.current = false;
if (config) setConfig({ ...config, global_notification: null });
toast.success("Broadcast cleared");
window.dispatchEvent(new CustomEvent("axiom:broadcast-updated"));
} catch (err) {
toast.error("Failed to clear broadcast");
} finally {
setSaving(false);
}
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-[400px]">
@@ -99,9 +127,11 @@ export function AdminContent() {
{ name: "Database Size", value: stats?.db_size || "0 MB", icon: Database, color: "text-purple-500" },
];
const activeBroadcast = (config?.global_notification || "").trim();
const draftDirty = draft.trim() !== activeBroadcast;
return (
<div className="space-y-10 animate-in fade-in duration-500">
{/* Header */}
<div className="relative group">
<div className="absolute -inset-1 bg-gradient-to-r from-red-500 to-indigo-500 rounded-3xl blur opacity-10 group-hover:opacity-20 transition duration-1000"></div>
<div className="relative bg-[#0f172a] border border-white/10 rounded-3xl p-8 lg:p-12 flex flex-col lg:flex-row lg:items-center justify-between gap-8">
@@ -115,6 +145,7 @@ export function AdminContent() {
</div>
</div>
<button
type="button"
onClick={() => fetchData(true)}
className="flex items-center gap-3 bg-red-500/5 px-6 py-3 rounded-2xl border border-red-500/10 hover:bg-red-500/10 transition-all active:scale-95 group/refresh"
>
@@ -126,7 +157,6 @@ export function AdminContent() {
</div>
</div>
{/* Stats Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{statItems.map((stat) => (
<div key={stat.name} className="glass border border-white/5 rounded-3xl p-6 hover:border-white/10 transition-all group">
@@ -144,9 +174,7 @@ export function AdminContent() {
))}
</div>
{/* System Status Section */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* API Health */}
<div className="lg:col-span-2 glass border border-white/5 rounded-[2.5rem] overflow-hidden">
<div className="p-8 border-b border-white/5 flex items-center justify-between bg-white/[0.01]">
<div className="flex items-center gap-4">
@@ -185,7 +213,6 @@ export function AdminContent() {
</div>
</div>
{/* Global Config */}
<div className="glass border border-white/5 rounded-[2.5rem] overflow-hidden flex flex-col">
<div className="p-8 border-b border-white/5 flex items-center gap-4 bg-white/[0.01]">
<Settings className="h-5 w-5 text-indigo-500" />
@@ -195,6 +222,7 @@ export function AdminContent() {
<div className="space-y-2">
<label className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-500 pl-1">Maintenance Mode</label>
<button
type="button"
onClick={handleToggleMaintenance}
disabled={saving}
className={cn(
@@ -220,22 +248,55 @@ export function AdminContent() {
</div>
<div className="space-y-2">
<label className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-500 pl-1">Global Notification</label>
<div className="flex items-center justify-between pl-1">
<label className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-500">
Broadcast draft
</label>
{activeBroadcast ? (
<span className="text-[10px] font-bold uppercase tracking-widest text-emerald-500">
Live
</span>
) : (
<span className="text-[10px] font-bold uppercase tracking-widest text-slate-600">
Not published
</span>
)}
</div>
<textarea
value={notification}
onChange={(e) => setNotification(e.target.value)}
className="w-full h-32 bg-white/[0.03] border border-white/5 rounded-2xl p-4 text-xs font-medium text-slate-300 focus:outline-none focus:ring-1 focus:ring-red-500/30 transition-all placeholder:text-slate-600"
placeholder="Message to display across all dashboards..."
value={draft}
onChange={(e) => {
draftTouched.current = true;
setDraft(e.target.value);
}}
className="w-full h-32 bg-white/[0.03] border border-white/5 rounded-2xl p-4 text-xs font-medium text-slate-300 focus:outline-none focus:ring-1 focus:ring-primary/30 transition-all placeholder:text-slate-600"
placeholder="Write a message… nothing is published until you click Broadcast."
/>
<p className="text-[10px] text-slate-500 pl-1">
Reloading this page does not publish. Only the Broadcast button updates the dashboard bell.
{draftDirty ? " • Unsaved draft" : ""}
</p>
</div>
<div className="flex flex-col gap-3">
<button
type="button"
onClick={handleBroadcast}
disabled={saving}
disabled={saving || !draftDirty}
className="w-full py-4 bg-primary rounded-2xl font-black uppercase tracking-widest text-xs shadow-xl shadow-primary/20 hover:brightness-110 active:scale-[0.98] transition-all disabled:opacity-50"
>
{saving ? "Processing..." : "Broadcast Message"}
</button>
{activeBroadcast && (
<button
type="button"
onClick={handleClearBroadcast}
disabled={saving}
className="w-full py-3 rounded-2xl font-black uppercase tracking-widest text-[10px] border border-white/10 text-slate-400 hover:text-white hover:bg-white/5 transition-all disabled:opacity-50"
>
Clear active broadcast
</button>
)}
</div>
</div>
</div>
</div>