From e1b66504545bde15f7ae7e6a08ed9b6399d3d3f3 Mon Sep 17 00:00:00 2001 From: Agent Date: Sat, 13 Jun 2026 16:48:05 -0400 Subject: [PATCH] feat: notification dropdown panel and /notifications page --- .opencode/plans/server-thresholds.md | 256 ++++++++++++++++++++++++ public/assets/css/style.css | 40 ++++ routes/web.php | 1 + src/Controllers/DashboardController.php | 19 ++ views/layouts/main.php | 83 ++++---- views/notifications/index.php | 91 +++++++++ 6 files changed, 450 insertions(+), 40 deletions(-) create mode 100644 .opencode/plans/server-thresholds.md create mode 100644 views/notifications/index.php diff --git a/.opencode/plans/server-thresholds.md b/.opencode/plans/server-thresholds.md new file mode 100644 index 0000000..3c439f5 --- /dev/null +++ b/.opencode/plans/server-thresholds.md @@ -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 + + + +``` + +**b) Modal** (después del `#agentConfirmModal`, antes de `
`): + +```php +
+``` + +**c) JavaScript** (al final del bloque ``): + +```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//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()`. diff --git a/public/assets/css/style.css b/public/assets/css/style.css index 7f033d2..6c04cc0 100755 --- a/public/assets/css/style.css +++ b/public/assets/css/style.css @@ -3306,3 +3306,43 @@ input[type="range"]::-moz-range-track { 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); +} diff --git a/routes/web.php b/routes/web.php index 2113309..9af7e95 100755 --- a/routes/web.php +++ b/routes/web.php @@ -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]); diff --git a/src/Controllers/DashboardController.php b/src/Controllers/DashboardController.php index ac2d50b..1942e58 100755 --- a/src/Controllers/DashboardController.php +++ b/src/Controllers/DashboardController.php @@ -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, + ]); + } } diff --git a/views/layouts/main.php b/views/layouts/main.php index 2a98ec8..598df63 100755 --- a/views/layouts/main.php +++ b/views/layouts/main.php @@ -40,6 +40,12 @@ Dashboard +