feat: notification bell with modal in top bar #76

Merged
rafaga21 merged 4 commits from feat/server-thresholds into master 2026-06-13 16:52:44 -04:00
6 changed files with 515 additions and 5 deletions

View File

@@ -3170,3 +3170,179 @@ input[type="range"]::-moz-range-track {
height: 6px;
border-radius: 3px;
}
/* ==========================================================================
Notification Bell & Modal
========================================================================== */
.notification-btn-wrapper {
position: relative;
display: inline-flex;
}
.notification-btn {
position: relative;
}
.notification-badge {
position: absolute;
top: 2px;
right: 2px;
min-width: 16px;
height: 16px;
padding: 0 4px;
border-radius: 100px;
background: var(--danger);
color: #fff;
font-size: 0.6rem;
font-weight: 700;
display: inline-flex;
align-items: center;
justify-content: center;
line-height: 1;
box-shadow: 0 0 0 2px var(--bg-secondary);
pointer-events: none;
}
.notif-item {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 14px 18px;
border-bottom: 1px solid var(--border-color);
cursor: pointer;
transition: background 0.15s;
}
.notif-item:hover {
background: var(--bg-hover);
}
.notif-item:last-child {
border-bottom: none;
}
.notif-unread {
background: rgba(99, 102, 241, 0.04);
}
.notif-unread:hover {
background: rgba(99, 102, 241, 0.08);
}
.notif-icon {
width: 32px;
height: 32px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
font-size: 0.85em;
}
.notif-icon.notif-danger { background: var(--danger-bg); color: var(--danger); }
.notif-icon.notif-warning { background: var(--warning-bg); color: var(--warning); }
.notif-icon.notif-info { background: var(--info-bg); color: var(--info); }
.notif-content {
flex: 1;
min-width: 0;
}
.notif-title {
font-size: 0.88em;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 2px;
}
.notif-message {
font-size: 0.82em;
color: var(--text-muted);
line-height: 1.4;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.notif-time {
font-size: 0.72em;
color: var(--text-muted);
margin-top: 3px;
opacity: 0.7;
}
.notif-read .notif-title {
font-weight: 400;
opacity: 0.65;
}
.notif-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--info);
flex-shrink: 0;
margin-top: 6px;
}
.btn-sm {
padding: 0.3rem 0.6rem;
font-size: 0.82rem;
border-radius: var(--radius-sm, 6px);
}
.btn-text {
background: none;
border: none;
color: var(--text-secondary);
cursor: pointer;
transition: color 0.15s;
}
.btn-text:hover {
color: var(--text-primary);
background: var(--bg-hover);
}
/* ==========================================================================
Notification Dropdown Panel
========================================================================== */
.notification-dropdown {
display: none;
position: absolute;
top: calc(100% + 6px);
right: 0;
width: 380px;
max-height: 520px;
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
box-shadow: 0 8px 32px rgba(0,0,0,0.4);
z-index: 300;
overflow: hidden;
}
.notification-dropdown.open {
display: block;
}
.notif-dropdown-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
border-bottom: 1px solid var(--border-color);
}
.notif-dropdown-body {
max-height: 360px;
overflow-y: auto;
}
.notif-dropdown-footer {
border-top: 1px solid var(--border-color);
}

View File

@@ -22,6 +22,7 @@ $router->get('/dashboard', [DashboardController::class, 'index'], [AuthMiddlewar
$router->get('/dashboard/stats', [DashboardController::class, 'stats'], [AuthMiddleware::class]);
$router->get('/dashboard/refresh-metrics', [DashboardController::class, 'refreshMetrics'], [AuthMiddleware::class]);
$router->get('/dashboard/chart-data', [DashboardController::class, 'chartData'], [AuthMiddleware::class]);
$router->get('/notifications', [DashboardController::class, 'notifications'], [AuthMiddleware::class]);
$router->get('/login', [AuthController::class, 'loginForm']);
$router->post('/login', [AuthController::class, 'login'], [CSRFMiddleware::class, RateLimitMiddleware::class]);

View File

@@ -7,6 +7,7 @@ namespace ServerManager\Controllers;
use ServerManager\Core\App;
use ServerManager\Core\Session;
use ServerManager\Models\Server;
use ServerManager\Models\Notification;
use ServerManager\Services\MonitoringService;
use ServerManager\Services\AuditService;
@@ -80,4 +81,22 @@ class DashboardController
'data' => $data,
]);
}
public function notifications(): void
{
$userId = (int) Session::get('user_id');
$page = (int) ($_GET['page'] ?? 1);
$perPage = 20;
$notificationModel = new Notification();
$result = $notificationModel->getForUser($userId, $page, $perPage);
$unreadCount = $notificationModel->getUnreadCount($userId);
$this->view->display('notifications.index', [
'title' => 'Notifications - ServerManager',
'notifications' => $result['data'],
'pagination' => $result,
'unreadCount' => $unreadCount,
]);
}
}

View File

@@ -154,6 +154,12 @@ $aggregatedMetrics = $aggregatedMetrics ?? [];
<?= htmlspecialchars($activity['actor_name'] ?? $activity['username'] ?? 'System') ?>
&middot; <?= date('H:i', strtotime($activity['created_at'] ?? '')) ?>
</span>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
@@ -298,9 +304,4 @@ if (aggregatedData.length > 0) {
setInterval(refreshAggregatedChart, 30000);
</script>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</div>
</div>

View File

@@ -4,6 +4,17 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="<?= $_SESSION['csrf_token'] ?? '' ?>">
<meta name="api-token" content="<?php
$uid = $_SESSION['user_id'] ?? 0;
$token = '';
if ($uid) {
$u = \ServerManager\Core\Database::getInstance()->fetch(
'SELECT api_token FROM users WHERE id = ? AND status = \'active\'', [(int) $uid]
);
$token = $u['api_token'] ?? '';
}
echo htmlspecialchars($token);
?>">
<title><?= htmlspecialchars($title ?? 'ServerManager') ?></title>
<link rel="icon" type="image/svg+xml" href="/assets/img/server.svg">
<link rel="stylesheet" href="/assets/css/style.css">
@@ -29,6 +40,12 @@
<span>Dashboard</span>
</a>
</li>
<li class="nav-item">
<a href="/notifications" class="nav-link <?= str_starts_with($_SERVER['REQUEST_URI'] ?? '', '/notifications') ? 'active' : '' ?>">
<i class="fas fa-bell"></i>
<span>Notifications</span>
</a>
</li>
<li class="nav-item nav-item-accordion <?= str_starts_with($_SERVER['REQUEST_URI'] ?? '', '/servers') ? 'active' : '' ?>">
<a href="#" class="nav-link" onclick="toggleServerList(event)">
<i class="fas fa-hdd"></i>
@@ -135,6 +152,34 @@
<button class="btn-icon" id="themeToggle" title="Toggle theme">
<i class="fas fa-moon"></i>
</button>
<div class="notification-btn-wrapper">
<button class="btn-icon notification-btn" id="notificationBell" title="Notifications" onclick="toggleNotifications()">
<i class="fas fa-bell"></i>
<span class="notification-badge" id="notificationBadge" style="display:none">0</span>
</button>
<div class="notification-dropdown" id="notifDropdown">
<div class="notif-dropdown-header">
<span style="font-weight:600;font-size:0.9em">Notifications</span>
<div style="display:flex;align-items:center;gap:6px">
<button class="btn-text" id="markAllReadBtn" onclick="markAllRead()" style="display:none;font-size:0.78em;padding:2px 6px;border-radius:4px">
<i class="fas fa-check-double"></i> Mark all read
</button>
<button class="btn-text" onclick="closeNotifications()" style="font-size:0.78em;padding:2px 6px;border-radius:4px">&times;</button>
</div>
</div>
<div class="notif-dropdown-body" id="notifList">
<div style="padding:40px 20px;text-align:center;color:var(--text-muted)">
<i class="fas fa-spinner fa-spin" style="font-size:1.5em;margin-bottom:10px;display:block"></i>
<span>Loading notifications...</span>
</div>
</div>
<div class="notif-dropdown-footer">
<a href="/notifications" class="btn-text" style="font-size:0.82em;color:var(--info);width:100%;text-align:center;padding:8px;display:block">
<i class="fas fa-external-link-alt"></i> View all notifications
</a>
</div>
</div>
</div>
</div>
</div>
</header>
@@ -169,6 +214,183 @@
<?php endif; ?>
<script>
let serverListLoaded = false;
function getApiToken() {
return document.querySelector('meta[name="api-token"]')?.getAttribute('content') || '';
}
function toggleNotifications() {
const dd = document.getElementById('notifDropdown');
if (dd.classList.contains('open')) {
closeNotifications();
} else {
openNotifications();
}
}
function openNotifications() {
const dd = document.getElementById('notifDropdown');
dd.classList.add('open');
fetchNotifications();
document.addEventListener('click', notifOutsideClick);
}
function closeNotifications() {
const dd = document.getElementById('notifDropdown');
dd.classList.remove('open');
document.removeEventListener('click', notifOutsideClick);
}
function notifOutsideClick(e) {
const wrapper = document.querySelector('.notification-btn-wrapper');
if (!wrapper.contains(e.target)) {
closeNotifications();
}
}
function fetchNotifications() {
const list = document.getElementById('notifList');
list.innerHTML = '<div style="padding:40px 20px;text-align:center;color:var(--text-muted)"><i class="fas fa-spinner fa-spin" style="font-size:1.5em;margin-bottom:10px;display:block"></i><span>Loading notifications...</span></div>';
const token = getApiToken();
const headers = { 'Accept': 'application/json' };
if (token) headers['Authorization'] = 'Bearer ' + token;
fetch('/api/notifications?per_page=10', { headers })
.then(r => r.json())
.then(d => {
if (!d.success) {
list.innerHTML = '<div style="padding:40px 20px;text-align:center;color:var(--text-muted)">Could not load notifications.</div>';
return;
}
renderNotifications(d.data || [], d.unread_count || 0);
})
.catch(() => {
list.innerHTML = '<div style="padding:40px 20px;text-align:center;color:var(--danger)">Failed to load notifications.</div>';
});
}
function renderNotifications(items, unreadCount) {
const list = document.getElementById('notifList');
if (!items.length) {
list.innerHTML = '<div style="padding:40px 20px;text-align:center;color:var(--text-muted)">'
+ '<i class="fas fa-check-circle" style="font-size:1.8em;margin-bottom:10px;display:block;color:var(--success)"></i>'
+ '<span>No notifications</span></div>';
document.getElementById('markAllReadBtn').style.display = 'none';
return;
}
let html = '';
items.forEach(function(n) {
const typeColors = { error: 'danger', warning: 'warning', info: 'info' };
const typeColor = typeColors[n.type] || 'info';
const icons = { error: 'fa-times-circle', warning: 'fa-exclamation-triangle', info: 'fa-info-circle' };
const icon = icons[n.type] || 'fa-info-circle';
html += '<div class="notif-item ' + (n.is_read ? 'notif-read' : 'notif-unread') + '"'
+ ' onclick="markRead(' + n.id + ', this)"'
+ ' data-id="' + n.id + '">'
+ '<div class="notif-icon notif-' + typeColor + '"><i class="fas ' + icon + '"></i></div>'
+ '<div class="notif-content">'
+ '<div class="notif-title">' + escapeHtml(n.title) + '</div>'
+ '<div class="notif-message">' + escapeHtml(n.message) + '</div>'
+ '<div class="notif-time">' + timeAgo(n.created_at) + '</div>'
+ '</div>'
+ (n.is_read ? '' : '<div class="notif-dot"></div>')
+ '</div>';
});
list.innerHTML = html;
document.getElementById('markAllReadBtn').style.display = unreadCount > 0 ? 'inline-flex' : 'none';
}
function markRead(id, el) {
if (el.classList.contains('notif-read')) return;
const token = getApiToken();
const headers = { 'Accept': 'application/json' };
if (token) headers['Authorization'] = 'Bearer ' + token;
fetch('/api/notifications/' + id + '/read', { method: 'POST', headers })
.then(r => r.json())
.then(d => {
if (d.success) {
el.classList.remove('notif-unread');
el.classList.add('notif-read');
const dot = el.querySelector('.notif-dot');
if (dot) dot.remove();
updateUnreadCount();
}
})
.catch(function(){});
}
function markAllRead() {
const token = getApiToken();
const headers = { 'Accept': 'application/json' };
if (token) headers['Authorization'] = 'Bearer ' + token;
fetch('/api/notifications/read-all', { method: 'POST', headers })
.then(r => r.json())
.then(d => {
if (d.success) {
document.querySelectorAll('.notif-item').forEach(function(el) {
el.classList.remove('notif-unread');
el.classList.add('notif-read');
const dot = el.querySelector('.notif-dot');
if (dot) dot.remove();
});
document.getElementById('markAllReadBtn').style.display = 'none';
updateUnreadCount();
}
})
.catch(function(){});
}
function updateUnreadCount() {
const token = getApiToken();
const headers = { 'Accept': 'application/json' };
if (token) headers['Authorization'] = 'Bearer ' + token;
fetch('/api/notifications/unread-count', { headers })
.then(r => r.json())
.then(d => {
const count = d.unread_count || 0;
const badge = document.getElementById('notificationBadge');
if (count > 0) {
badge.textContent = count > 99 ? '99+' : count;
badge.style.display = 'inline-flex';
} else {
badge.style.display = 'none';
}
})
.catch(function(){});
}
function escapeHtml(str) {
const d = document.createElement('div');
d.textContent = str;
return d.innerHTML;
}
function timeAgo(dateStr) {
const now = new Date();
const d = new Date(dateStr.replace(' ', 'T') + (dateStr.includes('Z') ? '' : 'Z'));
const diff = Math.floor((now - d) / 1000);
if (diff < 60) return 'just now';
if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
const days = Math.floor(diff / 86400);
if (days < 7) return days + 'd ago';
return d.toLocaleDateString();
}
// Poll unread count every 60s
setInterval(updateUnreadCount, 60000);
// Initial fetch
updateUnreadCount();
function toggleServerList(e) {
e.preventDefault();
const item = e.currentTarget.closest('.nav-item-accordion');

View File

@@ -0,0 +1,91 @@
<?php
$notifications = $notifications ?? [];
$pagination = $pagination ?? [];
$unreadCount = $unreadCount ?? 0;
$data = $notifications ?? [];
?>
<div class="page-header">
<div class="page-header-left">
<div class="back-link">
<a href="/dashboard"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
</div>
<h1 class="page-title">Notifications</h1>
<p class="page-subtitle">
<?= $unreadCount ?> unread &middot; <?= $pagination['total'] ?? 0 ?> total
</p>
</div>
<div class="page-header-right">
<?php if ($unreadCount > 0): ?>
<button class="btn btn-sm btn-text" onclick="markAllRead()" style="font-size:0.85em">
<i class="fas fa-check-double"></i> Mark all read
</button>
<?php endif; ?>
</div>
</div>
<div class="card">
<div class="card-body" style="padding:0">
<?php if (empty($data)): ?>
<div style="padding:60px 20px;text-align:center;color:var(--text-muted)">
<i class="fas fa-check-circle" style="font-size:2.5em;margin-bottom:12px;display:block;color:var(--success)"></i>
<p style="font-size:1.05em">All caught up!</p>
<p style="font-size:0.9em">No notifications to show.</p>
</div>
<?php else: ?>
<?php foreach ($data as $n): ?>
<?php
$typeColors = ['error' => 'danger', 'warning' => 'warning', 'info' => 'info'];
$icons = ['error' => 'fa-times-circle', 'warning' => 'fa-exclamation-triangle', 'info' => 'fa-info-circle'];
$tc = $typeColors[$n['type']] ?? 'info';
$icon = $icons[$n['type']] ?? 'fa-info-circle';
$isRead = !empty($n['is_read']);
?>
<div class="notif-item <?= $isRead ? 'notif-read' : 'notif-unread' ?>" data-id="<?= $n['id'] ?>">
<div class="notif-icon notif-<?= $tc ?>"><i class="fas <?= $icon ?>"></i></div>
<div class="notif-content">
<div class="notif-title"><?= htmlspecialchars($n['title'] ?? '') ?></div>
<div class="notif-message"><?= htmlspecialchars($n['message'] ?? '') ?></div>
<div class="notif-time"><?= time_ago($n['created_at'] ?? '') ?></div>
</div>
<?php if (!$isRead): ?>
<div class="notif-dot"></div>
<?php endif; ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
<?php if (($pagination['total_pages'] ?? 1) > 1): ?>
<div class="pagination">
<?php for ($i = 1; $i <= $pagination['total_pages']; $i++): ?>
<a href="/notifications?page=<?= $i ?>" class="btn btn-sm <?= ($pagination['page'] ?? 1) === $i ? 'btn-primary' : 'btn-secondary' ?>">
<?= $i ?>
</a>
<?php endfor; ?>
</div>
<?php endif; ?>
<script>
function markAllRead() {
const token = document.querySelector('meta[name="api-token"]')?.getAttribute('content') || '';
const headers = { 'Accept': 'application/json' };
if (token) headers['Authorization'] = 'Bearer ' + token;
fetch('/api/notifications/read-all', { method: 'POST', headers })
.then(r => r.json())
.then(d => {
if (d.success) {
document.querySelectorAll('.notif-item').forEach(function(el) {
el.classList.remove('notif-unread');
el.classList.add('notif-read');
const dot = el.querySelector('.notif-dot');
if (dot) dot.remove();
});
location.reload();
}
})
.catch(function(){});
}
</script>