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/AGENTS.md b/AGENTS.md index 78aacfe..3e14ee3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +49,7 @@ Repo-specific guidance for OpenCode sessions. Verified against code. ## Database - Migrations run manually: `mysql servermanager < database/migrations/NNN_name.sql` -- 12 migrations: `001_initial_schema`, `002_server_access`, `003_teams`, `004_soft_deletes`, `005_app_config_and_notifications`, `006_agent_tokens`, `007_server_permission_checks`, `008_notification_reads`, `009_remove_notification_obsolete_columns`, `010_user_fcm_tokens`, `011_cleanup_unused_tables`, `012_server_thresholds` +- 13 migrations: `001_initial_schema`, `002_server_access`, `003_teams`, `004_soft_deletes`, `005_app_config_and_notifications`, `006_agent_tokens`, `007_server_permission_checks`, `008_notification_reads`, `009_remove_notification_obsolete_columns`, `010_user_fcm_tokens`, `011_cleanup_unused_tables`, `012_server_thresholds`, `013_user_notification_prefs` - Users table has `role` ENUM: `super_admin`, `admin`, `operator` - `api_token` column on users for Bearer token auth - `server_permissions` table stores required SSH permissions per server (FK to `servers.id` CASCADE) diff --git a/android/app/src/main/java/com/devlab/app/data/model/LoginModels.kt b/android/app/src/main/java/com/devlab/app/data/model/LoginModels.kt index d588fec..f2dd3ec 100644 --- a/android/app/src/main/java/com/devlab/app/data/model/LoginModels.kt +++ b/android/app/src/main/java/com/devlab/app/data/model/LoginModels.kt @@ -21,7 +21,8 @@ data class ProfileUpdateRequest( val email: String, val current_password: String? = null, val new_password: String? = null, - val confirm_password: String? = null + val confirm_password: String? = null, + val notifications_enabled: Boolean? = null ) @Serializable @@ -51,5 +52,6 @@ data class UserProfile( val username: String = "", val email: String = "", val role: String = "", - val created_at: String? = null + val created_at: String? = null, + val notifications_enabled: Boolean = true ) diff --git a/android/app/src/main/java/com/devlab/app/data/repository/ProfileRepository.kt b/android/app/src/main/java/com/devlab/app/data/repository/ProfileRepository.kt index d4173d8..037d777 100644 --- a/android/app/src/main/java/com/devlab/app/data/repository/ProfileRepository.kt +++ b/android/app/src/main/java/com/devlab/app/data/repository/ProfileRepository.kt @@ -24,14 +24,16 @@ class ProfileRepository { email: String, currentPassword: String?, newPassword: String?, - confirmPassword: String? + confirmPassword: String?, + notificationsEnabled: Boolean = true ): Result { return try { val request = ProfileUpdateRequest( email = email, current_password = currentPassword?.takeIf { it.isNotBlank() }, new_password = newPassword?.takeIf { it.isNotBlank() }, - confirm_password = confirmPassword?.takeIf { it.isNotBlank() } + confirm_password = confirmPassword?.takeIf { it.isNotBlank() }, + notifications_enabled = notificationsEnabled ) val response = api.updateProfile(request) if (response.success) { diff --git a/android/app/src/main/java/com/devlab/app/ui/profile/ProfileScreen.kt b/android/app/src/main/java/com/devlab/app/ui/profile/ProfileScreen.kt index 6689ac8..6ae537b 100644 --- a/android/app/src/main/java/com/devlab/app/ui/profile/ProfileScreen.kt +++ b/android/app/src/main/java/com/devlab/app/ui/profile/ProfileScreen.kt @@ -249,6 +249,49 @@ fun ProfileScreen( } } + Spacer(modifier = Modifier.height(16.dp)) + + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface + ), + elevation = CardDefaults.cardElevation(defaultElevation = 2.dp) + ) { + Column(modifier = Modifier.padding(16.dp)) { + Text( + text = "Notifications", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold + ) + + Spacer(modifier = Modifier.height(12.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = "Push Notifications", + style = MaterialTheme.typography.bodyLarge + ) + Text( + text = "Receive alerts for threshold breaches and app updates", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch( + checked = state.notificationsEnabled, + onCheckedChange = viewModel::updateNotificationsEnabled, + enabled = !state.isSaving + ) + } + } + } + if (state.error != null) { Spacer(modifier = Modifier.height(16.dp)) Card( diff --git a/android/app/src/main/java/com/devlab/app/ui/profile/ProfileViewModel.kt b/android/app/src/main/java/com/devlab/app/ui/profile/ProfileViewModel.kt index af6aac7..77879b8 100644 --- a/android/app/src/main/java/com/devlab/app/ui/profile/ProfileViewModel.kt +++ b/android/app/src/main/java/com/devlab/app/ui/profile/ProfileViewModel.kt @@ -23,7 +23,8 @@ data class ProfileUiState( val successMessage: String? = null, val emailError: String? = null, val newPasswordError: String? = null, - val confirmPasswordError: String? = null + val confirmPasswordError: String? = null, + val notificationsEnabled: Boolean = true ) class ProfileViewModel : ViewModel() { @@ -44,7 +45,8 @@ class ProfileViewModel : ViewModel() { isLoading = false, username = profile.username, email = profile.email, - role = profile.role + role = profile.role, + notificationsEnabled = profile.notifications_enabled ) }, onFailure = { e -> @@ -61,6 +63,10 @@ class ProfileViewModel : ViewModel() { _uiState.value = _uiState.value.copy(email = value, error = null, successMessage = null, emailError = null) } + fun updateNotificationsEnabled(value: Boolean) { + _uiState.value = _uiState.value.copy(notificationsEnabled = value) + } + fun updateCurrentPassword(value: String) { _uiState.value = _uiState.value.copy(currentPassword = value, error = null, successMessage = null) } @@ -103,7 +109,8 @@ class ProfileViewModel : ViewModel() { state.email, state.currentPassword.takeIf { it.isNotBlank() }, state.newPassword.takeIf { it.isNotBlank() }, - state.confirmPassword.takeIf { it.isNotBlank() } + state.confirmPassword.takeIf { it.isNotBlank() }, + state.notificationsEnabled ) result.fold( onSuccess = { message -> diff --git a/database/migrations/013_user_notification_prefs.sql b/database/migrations/013_user_notification_prefs.sql new file mode 100644 index 0000000..c474225 --- /dev/null +++ b/database/migrations/013_user_notification_prefs.sql @@ -0,0 +1,2 @@ +ALTER TABLE `users` + ADD COLUMN `notifications_enabled` TINYINT(1) NOT NULL DEFAULT 1 AFTER `status`; diff --git a/public/sysadmin.apk b/public/sysadmin.apk index 490a157..264867a 100644 Binary files a/public/sysadmin.apk and b/public/sysadmin.apk differ diff --git a/src/Controllers/ApiController.php b/src/Controllers/ApiController.php index 0121573..b4b48fd 100755 --- a/src/Controllers/ApiController.php +++ b/src/Controllers/ApiController.php @@ -452,6 +452,15 @@ class ApiController if (!empty($breaches)) { $userIds = $serverModel->getAccessibleUserIds((int) $server['id']); + + $db = \ServerManager\Core\Database::getInstance(); + $placeholders = implode(',', array_fill(0, count($userIds), '?')); + $enabled = $db->fetchCol( + "SELECT id FROM users WHERE id IN ({$placeholders}) AND notifications_enabled = 1", + $userIds + ); + $userIds = $enabled; + $notificationModel = new Notification(); $fcm = new FCMService(); foreach ($breaches as $b) { @@ -572,6 +581,7 @@ class ApiController 'email' => $user['email'], 'role' => $user['role'], 'created_at' => $user['created_at'], + 'notifications_enabled' => (bool) ($user['notifications_enabled'] ?? true), ], ]); } @@ -597,6 +607,10 @@ class ApiController $updateData = ['email' => $input['email']]; + if (isset($input['notifications_enabled'])) { + $updateData['notifications_enabled'] = $input['notifications_enabled'] ? 1 : 0; + } + if (!empty($input['new_password'])) { if (strlen($input['new_password']) < 8) { $this->view->json([ diff --git a/src/Controllers/AuthController.php b/src/Controllers/AuthController.php index 9239e2b..21f90e9 100755 --- a/src/Controllers/AuthController.php +++ b/src/Controllers/AuthController.php @@ -194,6 +194,12 @@ class AuthController $updateData = ['email' => $_POST['email']]; + if (isset($_POST['notifications_enabled'])) { + $updateData['notifications_enabled'] = 1; + } else { + $updateData['notifications_enabled'] = 0; + } + if (!empty($_POST['new_password'])) { $updateData['password'] = $_POST['new_password']; } diff --git a/views/auth/profile.php b/views/auth/profile.php index 081201d..988721d 100755 --- a/views/auth/profile.php +++ b/views/auth/profile.php @@ -54,6 +54,18 @@ +
+

Notification Preferences

+ +

+ Receive alerts for threshold breaches and app updates. +

+
+