feat: notification dropdown panel and /notifications page

This commit is contained in:
2026-06-13 16:48:05 -04:00
parent 25dfb517ee
commit e1b6650454
6 changed files with 450 additions and 40 deletions

View File

@@ -0,0 +1,256 @@
# Plan: Umbrales de notificación por servidor
## Archivos a modificar/crear
### 1. `database/migrations/012_server_thresholds.sql` — CREAR
```sql
ALTER TABLE `servers`
ADD COLUMN `threshold_cpu_warning` DECIMAL(5,2) DEFAULT 80.00 AFTER `agent_last_seen_at`,
ADD COLUMN `threshold_cpu_critical` DECIMAL(5,2) DEFAULT 95.00 AFTER `threshold_cpu_warning`,
ADD COLUMN `threshold_ram_warning` DECIMAL(5,2) DEFAULT 80.00 AFTER `threshold_cpu_critical`,
ADD COLUMN `threshold_ram_critical` DECIMAL(5,2) DEFAULT 95.00 AFTER `threshold_ram_warning`,
ADD COLUMN `threshold_disk_warning` DECIMAL(5,2) DEFAULT 85.00 AFTER `threshold_disk_warning`,
ADD COLUMN `threshold_disk_critical` DECIMAL(5,2) DEFAULT 95.00 AFTER `threshold_disk_critical`;
```
### 2. `src/Core/Database.php` — MODIFICAR
Agregar método `fetchCol()` después de `fetchAll()`:
```php
public function fetchCol(string $sql, array $params = []): array
{
return $this->query($sql, $params)->fetchAll(\PDO::FETCH_COLUMN);
}
```
### 3. `src/Models/Server.php` — MODIFICAR
Agregar método `getAccessibleUserIds()` antes de `findByAgentKey()`:
```php
public function getAccessibleUserIds(int $serverId): array
{
$direct = $this->db->fetchCol(
'SELECT user_id FROM server_user WHERE server_id = ? AND status = \'active\'',
[$serverId]
);
$team = $this->db->fetchCol(
'SELECT DISTINCT tu.user_id FROM team_user tu
JOIN team_server ts ON tu.team_id = ts.team_id
WHERE ts.server_id = ? AND tu.status = \'active\' AND ts.status = \'active\'',
[$serverId]
);
$owner = $this->db->fetchCol(
'SELECT created_by FROM servers WHERE id = ? AND status = \'active\'',
[$serverId]
);
return array_unique(array_merge($direct, $team, $owner));
}
```
### 4. `routes/web.php` — MODIFICAR
Agregar después de línea 67 (`/servers/:id/metrics`):
```php
$router->post('/servers/:id/thresholds', [ServerController::class, 'saveThresholds'], [AuthMiddleware::class, CSRFMiddleware::class]);
```
### 5. `src/Controllers/ServerController.php` — MODIFICAR
Agregar en `use` imports (si no está ya) + nuevo método después de `metrics()`:
```php
public function saveThresholds(int $id): void
{
$server = $this->requireServerAccess($id, 'manager');
$role = $this->serverModel->getUserRole($id, (int) Session::get('user_id'));
if ($role !== 'owner') {
$this->view->json(['success' => false, 'error' => 'Only the server owner can modify notification thresholds.'], 403);
}
$fields = ['cpu_warning', 'cpu_critical', 'ram_warning', 'ram_critical', 'disk_warning', 'disk_critical'];
$data = [];
foreach ($fields as $f) {
$key = 'threshold_' . $f;
$data[$key] = isset($_POST[$f]) ? max(0, min(100, (float) $_POST[$f])) : null;
}
$this->serverModel->update($id, $data);
$this->auditService->log('thresholds_updated', 'server', $id, $data);
$this->view->json(['success' => true, 'message' => 'Notification thresholds updated.']);
}
```
### 6. `src/Controllers/ApiController.php` — MODIFICAR
En `pushMetrics()`, después de `updateAgentLastSeen()` (línea 435) y antes de `$this->view->json(['success' => true])` (línea 437):
```php
// --- Verificar umbrales de notificación ---
$checks = [
'cpu' => ['val' => $cpu, 'warn' => $server['threshold_cpu_warning'], 'crit' => $server['threshold_cpu_critical']],
'ram' => ['val' => $ram, 'warn' => $server['threshold_ram_warning'], 'crit' => $server['threshold_ram_critical']],
'disk' => ['val' => $disk, 'warn' => $server['threshold_disk_warning'], 'crit' => $server['threshold_disk_critical']],
];
$breaches = [];
foreach ($checks as $metric => $c) {
if ($c['crit'] !== null && $c['val'] >= (float) $c['crit']) {
$breaches[] = ['metric' => $metric, 'level' => 'critical', 'current' => $c['val'], 'threshold' => $c['crit']];
} elseif ($c['warn'] !== null && $c['val'] >= (float) $c['warn']) {
$breaches[] = ['metric' => $metric, 'level' => 'warning', 'current' => $c['val'], 'threshold' => $c['warn']];
}
}
if (!empty($breaches)) {
$userIds = $serverModel->getAccessibleUserIds((int) $server['id']);
$notificationModel = new \ServerManager\Models\Notification();
foreach ($breaches as $b) {
$title = strtoupper($b['metric']) . " {$b['level']} on {$server['name']}";
$message = "{$server['name']}: {$b['metric']} at {$b['current']}% ({$b['level']} threshold: {$b['threshold']}%)";
foreach ($userIds as $uid) {
$notificationModel->create([
'user_id' => (int) $uid,
'title' => $title,
'message' => $message,
'type' => $b['level'],
]);
}
}
}
```
Agregar import de Notification en los `use` del ApiController (si no está):
```php
use ServerManager\Models\Notification;
```
### 7. `views/servers/show.php` — MODIFICAR
**a) Botón en Management Actions** (después de línea 272, antes de `<?php endif; ?>`):
```php
<?php if ($server_role === 'owner'): ?>
<button class="action-card" onclick="showThresholdModal()">
<i class="fas fa-bell"></i>
<span>Notification Thresholds</span>
</button>
<?php endif; ?>
```
**b) Modal** (después del `#agentConfirmModal`, antes de `<form id="csrfForm">`):
```php
<div id="thresholdModal" class="modal">
<div class="modal-dialog">
<div class="modal-header">
<h3><i class="fas fa-bell"></i> Notification Thresholds</h3>
<button type="button" class="modal-close" onclick="closeThresholdModal()">&times;</button>
</div>
<div class="modal-body">
<p class="text-muted" style="margin-bottom:20px">
Notifications are sent to all users with access to this server when the agent reports values
exceeding these thresholds. Only the server owner can modify them.
</p>
<form id="thresholdForm" onsubmit="return false">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Resource</th>
<th>Warning (%)</th>
<th>Critical (%)</th>
</tr>
</thead>
<tbody>
<?php foreach (['cpu' => 'CPU', 'ram' => 'RAM', 'disk' => 'Disk'] as $key => $label): ?>
<tr>
<td><strong><?= $label ?></strong></td>
<td>
<input type="number" name="<?= $key ?>_warning"
value="<?= htmlspecialchars((string)($server["threshold_{$key}_warning"] ?? 80)) ?>"
min="0" max="100" step="0.01" class="form-control" style="width:120px">
</td>
<td>
<input type="number" name="<?= $key ?>_critical"
value="<?= htmlspecialchars((string)($server["threshold_{$key}_critical"] ?? 95)) ?>"
min="0" max="100" step="0.01" class="form-control" style="width:120px">
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" onclick="saveThresholds()"><i class="fas fa-save"></i> Save</button>
<button class="btn btn-secondary" onclick="closeThresholdModal()">Cancel</button>
</div>
</div>
</div>
```
**c) JavaScript** (al final del bloque `<script>`, antes de `</script>`):
```javascript
function showThresholdModal() {
document.getElementById('thresholdModal').style.display = 'flex';
document.getElementById('thresholdModal').onclick = function(e) {
if (e.target === this) closeThresholdModal();
};
}
function closeThresholdModal() {
document.getElementById('thresholdModal').style.display = 'none';
}
function saveThresholds() {
const form = document.getElementById('thresholdForm');
const data = new URLSearchParams(new FormData(form));
data.append('_csrf_token', getCsrfToken());
document.querySelector('#thresholdModal .btn-primary').disabled = true;
fetch('/servers/<?= $server['id'] ?>/thresholds', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-Token': getCsrfToken(),
},
body: data.toString(),
})
.then(r => r.json())
.then(d => {
showToast(d.success ? 'success' : 'error', d.message ?? d.error);
if (d.success) closeThresholdModal();
})
.catch(e => showToast('error', 'Request failed: ' + e.message))
.finally(() => {
document.querySelector('#thresholdModal .btn-primary').disabled = false;
});
}
```
### 8. Ejecutar migración
```bash
mysql -u root -p"servermanager2024" servermanager < /var/www/servermanager/database/migrations/012_server_thresholds.sql
```
### 9. Commit y push
```bash
git add -A && git commit -m "feat: per-server notification thresholds with alert on agent metrics push" && git push origin feat/fcm-apk-v1.8.2
```
## Variables de umbral en la vista
Las columnas nuevas (`threshold_cpu_warning`, etc.) viajan automáticamente en `$server` porque `findById()` hace `SELECT *`. No requiere cambios en `ServerController::show()`.

View File

@@ -3306,3 +3306,43 @@ input[type="range"]::-moz-range-track {
color: var(--text-primary); color: var(--text-primary);
background: var(--bg-hover); 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/stats', [DashboardController::class, 'stats'], [AuthMiddleware::class]);
$router->get('/dashboard/refresh-metrics', [DashboardController::class, 'refreshMetrics'], [AuthMiddleware::class]); $router->get('/dashboard/refresh-metrics', [DashboardController::class, 'refreshMetrics'], [AuthMiddleware::class]);
$router->get('/dashboard/chart-data', [DashboardController::class, 'chartData'], [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->get('/login', [AuthController::class, 'loginForm']);
$router->post('/login', [AuthController::class, 'login'], [CSRFMiddleware::class, RateLimitMiddleware::class]); $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\App;
use ServerManager\Core\Session; use ServerManager\Core\Session;
use ServerManager\Models\Server; use ServerManager\Models\Server;
use ServerManager\Models\Notification;
use ServerManager\Services\MonitoringService; use ServerManager\Services\MonitoringService;
use ServerManager\Services\AuditService; use ServerManager\Services\AuditService;
@@ -80,4 +81,22 @@ class DashboardController
'data' => $data, '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

@@ -40,6 +40,12 @@
<span>Dashboard</span> <span>Dashboard</span>
</a> </a>
</li> </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' : '' ?>"> <li class="nav-item nav-item-accordion <?= str_starts_with($_SERVER['REQUEST_URI'] ?? '', '/servers') ? 'active' : '' ?>">
<a href="#" class="nav-link" onclick="toggleServerList(event)"> <a href="#" class="nav-link" onclick="toggleServerList(event)">
<i class="fas fa-hdd"></i> <i class="fas fa-hdd"></i>
@@ -151,6 +157,28 @@
<i class="fas fa-bell"></i> <i class="fas fa-bell"></i>
<span class="notification-badge" id="notificationBadge" style="display:none">0</span> <span class="notification-badge" id="notificationBadge" style="display:none">0</span>
</button> </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> </div>
</div> </div>
@@ -178,34 +206,6 @@
<div id="toastContainer" class="toast-container"></div> <div id="toastContainer" class="toast-container"></div>
<div id="notificationModal" class="modal">
<div class="modal-dialog" style="max-width:480px">
<div class="modal-header">
<h3 style="font-size:1em;display:flex;align-items:center;gap:8px">
<i class="fas fa-bell" style="color:var(--info)"></i> Notifications
<span id="notifCountBadge" class="badge" style="display:none;font-size:0.75em">0</span>
</h3>
<div style="display:flex;align-items:center;gap:8px">
<button class="btn btn-sm btn-text" id="markAllReadBtn" onclick="markAllRead()" style="display:none;font-size:0.82em">
<i class="fas fa-check-double"></i> Mark all read
</button>
<button type="button" class="modal-close" onclick="closeNotifications()">&times;</button>
</div>
</div>
<div class="modal-body" style="padding:0;max-height:420px;overflow-y:auto" 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="modal-footer" style="justify-content:center;padding:0.7rem">
<a href="/admin/notifications" class="btn btn-sm btn-text" style="font-size:0.85em;color:var(--info)">
<i class="fas fa-external-link-alt"></i> View all in admin panel
</a>
</div>
</div>
</div>
<script src="/assets/js/app.js"></script> <script src="/assets/js/app.js"></script>
<?php if (isset($scripts)): ?> <?php if (isset($scripts)): ?>
<?php foreach ($scripts as $script): ?> <?php foreach ($scripts as $script): ?>
@@ -220,8 +220,8 @@ function getApiToken() {
} }
function toggleNotifications() { function toggleNotifications() {
const modal = document.getElementById('notificationModal'); const dd = document.getElementById('notifDropdown');
if (modal.style.display === 'flex') { if (dd.classList.contains('open')) {
closeNotifications(); closeNotifications();
} else { } else {
openNotifications(); openNotifications();
@@ -229,16 +229,23 @@ function toggleNotifications() {
} }
function openNotifications() { function openNotifications() {
const modal = document.getElementById('notificationModal'); const dd = document.getElementById('notifDropdown');
modal.style.display = 'flex'; dd.classList.add('open');
modal.onclick = function(e) {
if (e.target === this) closeNotifications();
};
fetchNotifications(); fetchNotifications();
document.addEventListener('click', notifOutsideClick);
} }
function closeNotifications() { function closeNotifications() {
document.getElementById('notificationModal').style.display = 'none'; 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() { function fetchNotifications() {
@@ -351,15 +358,11 @@ function updateUnreadCount() {
.then(d => { .then(d => {
const count = d.unread_count || 0; const count = d.unread_count || 0;
const badge = document.getElementById('notificationBadge'); const badge = document.getElementById('notificationBadge');
const notifCount = document.getElementById('notifCountBadge');
if (count > 0) { if (count > 0) {
badge.textContent = count > 99 ? '99+' : count; badge.textContent = count > 99 ? '99+' : count;
badge.style.display = 'inline-flex'; badge.style.display = 'inline-flex';
notifCount.textContent = count;
notifCount.style.display = 'inline-flex';
} else { } else {
badge.style.display = 'none'; badge.style.display = 'none';
notifCount.style.display = 'none';
} }
}) })
.catch(function(){}); .catch(function(){});

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>