From 968e7b3451d5fb17034446545ae5d478b6519479 Mon Sep 17 00:00:00 2001 From: 1sonhador <1sonhador@gmail.com> Date: Wed, 15 Oct 2025 13:48:48 +0100 Subject: [PATCH] feat: Import ErrorMonitoring module from old CRM - Add complete ErrorMonitoring module with controllers, models, services - Include error dashboard, error detail views, and error import functionality - Add error monitoring API endpoints and error collection services - Fix missing error monitoring system for critical error tracking --- .../Controllers/ErrorMonitoringController.php | 849 ++++++++++++++++++ .../ErrorMonitoring/Models/ErrorLog.php | 320 +++++++ crm/Modules/ErrorMonitoring/Module.php | 88 ++ crm/Modules/ErrorMonitoring/Routes/web.php | 36 + .../Services/ErrorCollector.php | 442 +++++++++ .../Services/ErrorImporter.php | 511 +++++++++++ .../ErrorMonitoring/Views/dashboard.php | 245 +++++ .../ErrorMonitoring/Views/error-detail.php | 403 +++++++++ crm/Modules/ErrorMonitoring/Views/errors.php | 86 ++ crm/Modules/ErrorMonitoring/Views/import.php | 187 ++++ .../Widgets/ErrorSummaryWidget.php | 216 +++++ crm/Modules/ErrorMonitoring/assets.php | 24 + .../assets/css/error-monitoring.scss | 151 ++++ crm/Modules/ErrorMonitoring/menu.php | 57 ++ crm/Modules/ErrorMonitoring/widgets.php | 30 + 15 files changed, 3645 insertions(+) create mode 100644 crm/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php create mode 100644 crm/Modules/ErrorMonitoring/Models/ErrorLog.php create mode 100644 crm/Modules/ErrorMonitoring/Module.php create mode 100644 crm/Modules/ErrorMonitoring/Routes/web.php create mode 100644 crm/Modules/ErrorMonitoring/Services/ErrorCollector.php create mode 100644 crm/Modules/ErrorMonitoring/Services/ErrorImporter.php create mode 100644 crm/Modules/ErrorMonitoring/Views/dashboard.php create mode 100644 crm/Modules/ErrorMonitoring/Views/error-detail.php create mode 100644 crm/Modules/ErrorMonitoring/Views/errors.php create mode 100644 crm/Modules/ErrorMonitoring/Views/import.php create mode 100644 crm/Modules/ErrorMonitoring/Widgets/ErrorSummaryWidget.php create mode 100644 crm/Modules/ErrorMonitoring/assets.php create mode 100644 crm/Modules/ErrorMonitoring/assets/css/error-monitoring.scss create mode 100644 crm/Modules/ErrorMonitoring/menu.php create mode 100644 crm/Modules/ErrorMonitoring/widgets.php diff --git a/crm/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php b/crm/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php new file mode 100644 index 0000000..c62eb84 --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php @@ -0,0 +1,849 @@ +requireAuth(); + + try { + View::render('layouts/main.php', [ + 'title' => 'Error Monitoring Dashboard', + 'page_name' => 'error-monitoring-dashboard', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Error Monitoring', + 'title' => 'Dashboard' + ]); + View::render('@errormonitoring/dashboard'); + } + ]); + + } catch (Exception $e) { + $this->errorResponse('Erro ao carregar dashboard: ' . $e->getMessage()); + } + } + + /** + * Lista de erros + */ + public function errors(): void + { + $this->requireAuth(); + + try { + View::render('layouts/main.php', [ + 'title' => 'Error Logs', + 'page_name' => 'error-monitoring-errors', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Error Monitoring', + 'title' => 'Error Logs' + ]); + View::render('@errormonitoring/errors'); + } + ]); + + } catch (Exception $e) { + $this->errorResponse('Erro ao carregar erros: ' . $e->getMessage()); + } + } + + /** + * Detalhes de um erro específico + */ + public function errorDetail($id = null): void + { + $this->requireAuth(); + + $errorId = $id ?? $_GET['id'] ?? null; + if (!$errorId) { + $this->errorResponse('ID do erro não fornecido', 400); + return; + } + + try { + $errorModel = new ErrorLog(); + + // Tentar buscar por ID primeiro + $error = $errorModel->findById((int)$errorId); + + // Se não encontrar por ID, tentar por unique_id + if (!$error) { + $error = $errorModel->findByUniqueId($errorId); + } + + + + // If error not found, return 404 - no dummy data fallbacks + if (!$error) { + http_response_code(404); + echo 'Erro não encontrado'; + exit(); + } + + // Garantir que todos os campos necessários existem + $error = array_merge([ + 'occurrences' => 1, + 'first_seen' => $error['created_at'] ?? date('Y-m-d H:i:s'), + 'last_seen' => $error['created_at'] ?? date('Y-m-d H:i:s'), + 'stack_trace' => '', + 'context_data' => '{}', + 'server_data' => '{}', + 'url' => '', + 'http_method' => '', + 'request_id' => '', + 'ip_address' => '', + 'user_id' => null, + 'session_id' => '', + 'project_name' => 'CRM', + 'environment' => 'production', + 'user_agent' => '' + ], $error); + + View::render('layouts/main.php', [ + 'title' => 'Error Details', + 'page_name' => 'error-monitoring-detail', + 'page_content' => function() use ($error) { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Error Monitoring', + 'title' => 'Error Details' + ]); + View::render('@errormonitoring/error-detail', [ + 'error' => $error + ]); + } + ]); + + } catch (Exception $e) { + $this->errorResponse('Erro ao carregar detalhes: ' . $e->getMessage()); + } + } + + /** + * Importar dados externos + */ + public function import(): void + { + $this->requireAuth(); + + if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $this->handleImport(); + } else { + View::render('layouts/main.php', [ + 'title' => 'Import External Data', + 'page_name' => 'error-monitoring-import', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Error Monitoring', + 'title' => 'Import Data' + ]); + View::render('@errormonitoring/import'); + } + ]); + } + } + + /** + * Processar importação + */ + private function handleImport(): void + { + try { + $validation = $this->validatePostAutoOrFail('file.upload'); + $data = $validation['data']; + + if (!isset($_FILES['import_file']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK) { + $this->errorResponse('Nenhum ficheiro foi enviado ou ocorreu um erro no upload', 400); + return; + } + + $uploadedFile = $_FILES['import_file']; + $projectName = $data['project_name'] ?? 'External'; + $importType = $data['import_type'] ?? 'auto'; + + // Move uploaded file to temp location + $tempPath = sys_get_temp_dir() . '/' . (string) new \Visus\Cuid2\Cuid2() . '_' . $uploadedFile['name']; + if (!move_uploaded_file($uploadedFile['tmp_name'], $tempPath)) { + $this->errorResponse('Erro ao processar ficheiro enviado', 500); + return; + } + + // Import data + $importer = new ErrorImporter($projectName); + $result = $importer->importFromFile($tempPath, $importType); + + // Clean up temp file + unlink($tempPath); + + $this->successResponse($result, 'Importação concluída com sucesso'); + + } catch (Exception $e) { + $this->errorResponse('Erro na importação: ' . $e->getMessage(), 500); + } + } + + /** + * Testar captura de erro + */ + public function testError(): void + { + $this->requireAuth(); + + try { + // Simular um erro para teste + throw new Exception('Este é um erro de teste para validar o sistema de monitorização'); + + } catch (Exception $e) { + // Capturar com o ErrorCollector + $collector = ErrorCollector::getInstance(); + $uniqueId = $collector->addContext('test_context', 'Teste manual do sistema') + ->capture($e); + + $this->successResponse([ + 'unique_id' => $uniqueId, + 'message' => 'O erro foi registado no sistema de monitorização' + ], 'Erro de teste capturado com sucesso'); + } + } + + /** + * API: Dados do dashboard + */ + public function apiDashboard(): void + { + $this->requireAuth(); + + try { + $db = DatabaseManager::getInstance(); + + $totalResult = $db->fetch("SELECT COUNT(*) as count FROM error_logs"); + $criticalResult = $db->fetch("SELECT COUNT(*) as count FROM error_logs WHERE severity = 'critical'"); + $resolvedResult = $db->fetch("SELECT COUNT(*) as count FROM error_logs WHERE status = 'resolved'"); + $projectsResult = $db->fetch("SELECT COUNT(DISTINCT project_name) as count FROM error_logs"); + + $stats = [ + 'total_errors' => $totalResult ? (int)$totalResult['count'] : 0, + 'critical_errors' => $criticalResult ? (int)$criticalResult['count'] : 0, + 'resolved_errors' => $resolvedResult ? (int)$resolvedResult['count'] : 0, + 'monitored_projects' => $projectsResult ? (int)$projectsResult['count'] : 1 + ]; + + $this->successResponse($stats, 'Dashboard data loaded'); + } catch (Exception $e) { + $this->errorResponse('Erro ao carregar dashboard: ' . $e->getMessage()); + } + } + + /** + * API: Erros recentes + */ + public function apiRecentErrors(): void + { + $this->requireAuth(); + + try { + $db = DatabaseManager::getInstance(); + + // Get limit from query parameter, default to 20 + // Use (string)(int) for maximum MariaDB compatibility + $limit = (string)(int)($_GET['limit'] ?? 20); + + $errors = $db->fetchAll(" + SELECT id, unique_id, project_name, environment, error_type, severity, message, + file_path, line_number, stack_trace, context_data, user_id, session_id, + request_id, ip_address, user_agent, url, http_method, request_data, + server_data, occurrences, first_seen, last_seen, status, assigned_to, + resolution_notes, resolved_at, created_at, updated_at + FROM error_logs + WHERE status != 'resolved' + ORDER BY created_at DESC + LIMIT $limit + "); + + // Enriquecer os dados com contexto adicional + $enrichedErrors = []; + foreach ($errors as $error) { + $enrichedError = $error; + + // Parse context_data JSON + $contextData = []; + if (!empty($error['context_data'])) { + $contextData = json_decode($error['context_data'], true) ?: []; + } + + // Parse server_data JSON + $serverData = []; + if (!empty($error['server_data'])) { + $serverData = json_decode($error['server_data'], true) ?: []; + } + + // Parse request_data JSON + $requestData = []; + if (!empty($error['request_data'])) { + $requestData = json_decode($error['request_data'], true) ?: []; + } + + // Adicionar informações enriquecidas + $enrichedError['context_parsed'] = $contextData; + $enrichedError['server_parsed'] = $serverData; + $enrichedError['request_parsed'] = $requestData; + + // Informações de tempo + $enrichedError['age_hours'] = $this->calculateAge($error['created_at']); + $enrichedError['last_seen_hours'] = $this->calculateAge($error['last_seen']); + + // Informações de localização do erro + $enrichedError['file_short'] = $this->getShortFilePath($error['file_path']); + $enrichedError['module'] = $this->extractModuleFromPath($error['file_path']); + + // Informações de browser/device + $enrichedError['browser'] = $this->detectBrowser($error['user_agent']); + $enrichedError['is_mobile'] = $this->isMobileDevice($error['user_agent']); + + // Informações de contexto + $enrichedError['memory_usage_mb'] = $contextData['memory_usage'] ?? null; + $enrichedError['memory_peak_mb'] = $contextData['memory_peak'] ?? null; + $enrichedError['server_load'] = $contextData['server_load'] ?? null; + $enrichedError['php_version'] = $contextData['php_version'] ?? null; + + // Informações de request + $enrichedError['request_summary'] = $this->getRequestSummary($requestData); + $enrichedError['url_short'] = $this->getShortUrl($error['url']); + + // Informações de stack trace + $enrichedError['stack_trace_lines'] = $this->parseStackTrace($error['stack_trace']); + + // Informações de ocorrências + $enrichedError['occurrence_rate'] = $this->calculateOccurrenceRate($error['occurrences'], $error['first_seen'], $error['last_seen']); + + $enrichedErrors[] = $enrichedError; + } + + $this->successResponse($enrichedErrors ?: [], 'Recent errors loaded with enhanced context'); + } catch (Exception $e) { + $this->errorResponse('Erro ao carregar erros recentes: ' . $e->getMessage()); + } + } + + /** + * API: Lista paginada de erros com filtros + */ + public function apiErrors(): void + { + $this->requireAuth(); + + try { + $page = (int)($_GET['page'] ?? 1); + $limit = 20; + $offset = ($page - 1) * $limit; + + // Filtros + $severity = $_GET['severity'] ?? null; + $status = $_GET['status'] ?? null; + $file = $_GET['file'] ?? null; + $project = $_GET['project'] ?? null; + + $db = DatabaseManager::getInstance(); + + // Construir WHERE clause baseado nos filtros + $whereConditions = []; + $params = []; + + if ($severity) { + $whereConditions[] = "severity = ?"; + $params[] = $severity; + } + + if ($status) { + $whereConditions[] = "status = ?"; + $params[] = $status; + } + + if ($file) { + $whereConditions[] = "file_path LIKE ?"; + $params[] = '%' . $file . '%'; + } + + if ($project) { + $whereConditions[] = "project_name = ?"; + $params[] = $project; + } + + $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : ''; + + // Sanitize limit and offset with (string)(int) for maximum MariaDB compatibility + $limitInt = (string)(int)$limit; + $offsetInt = (string)(int)$offset; + + // Query para erros com filtros - usar variáveis sanitizadas inline + $errorsQuery = " + SELECT id, unique_id, project_name, environment, error_type, severity, message, + file_path, line_number, stack_trace, context_data, user_id, session_id, + request_id, ip_address, user_agent, url, http_method, request_data, + server_data, occurrences, first_seen, last_seen, status, assigned_to, + resolution_notes, resolved_at, created_at, updated_at + FROM error_logs + $whereClause + ORDER BY created_at DESC + LIMIT $limitInt OFFSET $offsetInt + "; + + // Query para total com filtros + $totalQuery = " + SELECT COUNT(*) as count + FROM error_logs + $whereClause + "; + + // Use original params for both queries + $errors = $db->fetchAll($errorsQuery, $params); + $totalResult = $db->fetch($totalQuery, $params); + $totalErrors = $totalResult ? (int)$totalResult['count'] : 0; + + $this->successResponse([ + 'errors' => $errors ?: [], + 'filters' => [ + 'severity' => $severity, + 'status' => $status, + 'file' => $file, + 'project' => $project + ], + 'pagination' => [ + 'current_page' => $page, + 'total_pages' => ceil($totalErrors / $limit), + 'total_items' => $totalErrors, + 'per_page' => $limit + ] + ], 'Errors loaded'); + } catch (Exception $e) { + $this->errorResponse('Erro ao carregar erros: ' . $e->getMessage()); + } + } + + /** + * API: Estatísticas em tempo real + */ + public function apiStats(): void + { + $this->requireAuth(); + + try { + // Usar CLI para dados reais + $totalResult = shell_exec('bin/bitreport sql:query "SELECT COUNT(*) as count FROM error_logs" 2>/dev/null'); + $criticalResult = shell_exec('bin/bitreport sql:query "SELECT COUNT(*) as count FROM error_logs WHERE severity = \'critical\'" 2>/dev/null'); + + $totalData = $totalResult ? json_decode($totalResult, true) : null; + $criticalData = $criticalResult ? json_decode($criticalResult, true) : null; + + $stats = [ + 'total_errors' => $totalData['count'] ?? 0, + 'critical_errors' => $criticalData['count'] ?? 0, + 'resolved_errors' => 0, + 'projects_count' => 1, + 'last_updated' => date('Y-m-d H:i:s') + ]; + + $this->successResponse($stats, 'Stats loaded'); + } catch (Exception $e) { + $this->errorResponse('Erro ao obter estatísticas: ' . $e->getMessage()); + } + } + + /** + * API: Informação sobre endpoint JS Error (GET não permitido) + */ + public function apiJsErrorInfo(): void + { + header('Content-Type: application/json'); + http_response_code(405); // Method Not Allowed + + echo json_encode([ + 'success' => false, + 'message' => 'Method Not Allowed', + 'error' => 'This endpoint only accepts POST requests for JavaScript error reporting', + 'usage' => [ + 'method' => 'POST', + 'endpoint' => '/api/error-monitoring/js-error', + 'content_type' => 'application/json', + 'required_fields' => ['message', 'filename', 'lineno'], + 'optional_fields' => ['colno', 'stack', 'url', 'timestamp', 'extra'] + ], + 'example' => [ + 'message' => 'ReferenceError: someVariable is not defined', + 'filename' => null, + 'lineno' => 42, + 'colno' => 15, + 'stack' => 'Error stack trace...', + 'url' => null, + 'timestamp' => date('Y-m-d H:i:s') + ] + ]); + } + + /** + * API: Capturar erro JavaScript + */ + public function apiCaptureJsError(): void + { + try { + $input = json_decode(file_get_contents('php://input'), true); + + if (!$input) { + $this->errorResponse('Invalid JSON data'); + return; + } + + // Validar dados obrigatórios + $requiredFields = ['message', 'filename', 'lineno']; + foreach ($requiredFields as $field) { + if (empty($input[$field])) { + $this->errorResponse("Missing required field: {$field}"); + return; + } + } + + // Usar ErrorCollector para processar o erro JavaScript + $collector = ErrorCollector::getInstance(); + + // Adicionar contexto específico do JavaScript + $collector->setProject($input['project'] ?? 'CRM') + ->setEnvironment($input['environment'] ?? 'production') + ->addContext('javascript_error', true) + ->addContext('error_type', 'JavaScript') + ->addContext('browser_info', [ + 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', + 'url' => $input['url'] ?? '', + 'timestamp' => $input['timestamp'] ?? date('Y-m-d H:i:s'), + 'browser_name' => $this->detectBrowser($_SERVER['HTTP_USER_AGENT'] ?? ''), + 'screen_resolution' => $input['screen'] ?? null, + 'viewport_size' => $input['viewport'] ?? null + ]) + ->addContext('stack_info', [ + 'filename' => $input['filename'], + 'line_number' => $input['lineno'], + 'column_number' => $input['colno'] ?? null, + 'stack_trace' => $input['stack'] ?? null + ]) + ->addContext('page_info', [ + 'page_url' => $input['url'] ?? '', + 'referrer' => $input['referrer'] ?? '', + 'page_title' => $input['title'] ?? '' + ]); + + // Adicionar dados extras se fornecidos + if (!empty($input['extra'])) { + $collector->addContext('extra_data', $input['extra']); + } + + // Criar uma exceção simulada para o JavaScript + $jsException = new Exception( + $input['message'], + $input['error_code'] ?? 0 + ); + + // Não podemos definir propriedades dinâmicas, mas o contexto já tem a informação + + // Capturar o erro + $uniqueId = $collector->capture($jsException); + + $this->successResponse([ + 'unique_id' => $uniqueId, + 'message' => 'JavaScript error captured successfully', + 'timestamp' => date('Y-m-d H:i:s') + ], 'JavaScript error logged'); + + } catch (Exception $e) { + $this->errorResponse('Error capturing JavaScript error: ' . $e->getMessage()); + } + } + + /** + * Calcular idade em horas desde uma data + */ + private function calculateAge(string $dateTime): ?int + { + if (empty($dateTime)) { + return null; + } + + $date = new \DateTime($dateTime); + $now = new \DateTime(); + $diff = $now->diff($date); + + return $diff->h + ($diff->days * 24); + } + + /** + * Obter caminho curto do ficheiro + */ + private function getShortFilePath(string $filePath): string + { + if (empty($filePath)) { + return ''; + } + + $parts = explode('/', $filePath); + if (count($parts) <= 3) { + return $filePath; + } + + // Retornar apenas os últimos 3 segmentos + return '.../' . implode('/', array_slice($parts, -3)); + } + + /** + * Extrair módulo do caminho do ficheiro + */ + private function extractModuleFromPath(string $filePath): string + { + if (empty($filePath)) { + return ''; + } + + if (preg_match('/app\/Modules\/([^\/]+)/', $filePath, $matches)) { + return $matches[1]; + } + + if (preg_match('/app\/Core/', $filePath)) { + return 'Core'; + } + + return 'Unknown'; + } + + /** + * Detectar se é dispositivo móvel + */ + private function isMobileDevice(string $userAgent): bool + { + if (empty($userAgent)) { + return false; + } + + $mobileKeywords = ['Mobile', 'Android', 'iPhone', 'iPad', 'Windows Phone']; + foreach ($mobileKeywords as $keyword) { + if (stripos($userAgent, $keyword) !== false) { + return true; + } + } + + return false; + } + + /** + * Obter resumo do request + */ + private function getRequestSummary(array $requestData): string + { + if (empty($requestData)) { + return 'No request data'; + } + + $summary = []; + + if (!empty($requestData['method'])) { + $summary[] = $requestData['method']; + } + + if (!empty($requestData['url'])) { + $summary[] = parse_url($requestData['url'], PHP_URL_PATH) ?: $requestData['url']; + } + + if (!empty($requestData['params'])) { + $paramCount = count($requestData['params']); + $summary[] = "{$paramCount} params"; + } + + return implode(' | ', $summary) ?: 'Request data available'; + } + + /** + * Obter URL curta + */ + private function getShortUrl(string $url): string + { + if (empty($url)) { + return ''; + } + + $parsed = parse_url($url); + if (!$parsed) { + return $url; + } + + $path = $parsed['path'] ?? ''; + $query = $parsed['query'] ?? ''; + + if (strlen($path) > 50) { + $path = substr($path, 0, 47) . '...'; + } + + if ($query) { + $path .= '?' . $query; + } + + return $path; + } + + /** + * Parse stack trace em linhas + */ + private function parseStackTrace(string $stackTrace): array + { + if (empty($stackTrace)) { + return []; + } + + $lines = explode("\n", $stackTrace); + $parsedLines = []; + + foreach ($lines as $line) { + $line = trim($line); + if (empty($line)) { + continue; + } + + // Extrair informações básicas da linha + if (preg_match('/^#\d+\s+(.+)$/', $line, $matches)) { + $parsedLines[] = [ + 'raw' => $line, + 'function' => $matches[1] ?? $line, + 'short' => $this->getShortStackTraceLine($matches[1] ?? $line) + ]; + } else { + $parsedLines[] = [ + 'raw' => $line, + 'function' => $line, + 'short' => $this->getShortStackTraceLine($line) + ]; + } + } + + return array_slice($parsedLines, 0, 10); // Limitar a 10 linhas + } + + /** + * Obter linha curta do stack trace + */ + private function getShortStackTraceLine(string $line): string + { + if (strlen($line) <= 80) { + return $line; + } + + return substr($line, 0, 77) . '...'; + } + + /** + * Calcular taxa de ocorrência + */ + private function calculateOccurrenceRate(int $occurrences, string $firstSeen, string $lastSeen): ?float + { + if ($occurrences <= 1 || empty($firstSeen) || empty($lastSeen)) { + return null; + } + + $first = new \DateTime($firstSeen); + $last = new \DateTime($lastSeen); + $diff = $last->diff($first); + + $totalHours = $diff->h + ($diff->days * 24); + if ($totalHours === 0) { + return null; + } + + return round($occurrences / $totalHours, 2); + } + + /** + * Detectar browser baseado no User-Agent + */ + private function detectBrowser(string $userAgent): string + { + if (strpos($userAgent, 'Chrome') !== false) { + return 'Chrome'; + } elseif (strpos($userAgent, 'Firefox') !== false) { + return 'Firefox'; + } elseif (strpos($userAgent, 'Safari') !== false) { + return 'Safari'; + } elseif (strpos($userAgent, 'Edge') !== false) { + return 'Edge'; + } elseif (strpos($userAgent, 'Opera') !== false) { + return 'Opera'; + } + + return 'Unknown'; + } + + /** + * API: Marcar erro como resolvido + */ + public function apiResolveError(): void + { + $this->requireAuth(); + + try { + $input = json_decode(file_get_contents('php://input'), true); + $uniqueId = $input['unique_id'] ?? null; + + if (!$uniqueId) { + $this->errorResponse('Unique ID é obrigatório'); + return; + } + + $db = DatabaseManager::getInstance(); + + // Verificar se o erro existe + $error = $db->fetch("SELECT id FROM error_logs WHERE unique_id = ?", [$uniqueId]); + if (!$error) { + $this->errorResponse('Erro não encontrado'); + return; + } + + // Marcar como resolvido + $result = $db->query(" + UPDATE error_logs + SET status = 'resolved', + resolved_at = CURRENT_TIMESTAMP, + resolution_notes = 'Marked as resolved via dashboard' + WHERE unique_id = ? + ", [$uniqueId]); + + if ($result) { + $this->successResponse(['unique_id' => $uniqueId], 'Erro marcado como resolvido'); + } else { + $this->errorResponse('Falha ao marcar erro como resolvido'); + } + + } catch (Exception $e) { + $this->errorResponse('Erro ao resolver: ' . $e->getMessage()); + } + } +} \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Models/ErrorLog.php b/crm/Modules/ErrorMonitoring/Models/ErrorLog.php new file mode 100644 index 0000000..e1df43d --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Models/ErrorLog.php @@ -0,0 +1,320 @@ +db = DatabaseManager::getInstance(); + } + + /** + * Buscar erro por ID + */ + public function findById(int $id): ?array + { + $sql = "SELECT * FROM error_logs WHERE id = ?"; + $result = $this->db->fetch($sql, [$id]); + + return $result ?: null; + } + + /** + * Buscar erro por unique_id + */ + public function findByUniqueId(string $uniqueId): ?array + { + $sql = "SELECT * FROM error_logs WHERE unique_id = ?"; + $result = $this->db->fetch($sql, [$uniqueId]); + + return $result ?: null; + } + + /** + * Listar todos os erros com paginação + */ + public function getAll(int $limit = 50, int $offset = 0, array $filters = []): array + { + $sql = "SELECT * FROM error_logs"; + $params = []; + + // Aplicar filtros + if (!empty($filters)) { + $conditions = []; + + if (isset($filters['severity'])) { + $conditions[] = "severity = ?"; + $params[] = $filters['severity']; + } + + if (isset($filters['status'])) { + $conditions[] = "status = ?"; + $params[] = $filters['status']; + } + + if (isset($filters['project_name'])) { + $conditions[] = "project_name = ?"; + $params[] = $filters['project_name']; + } + + if (isset($filters['environment'])) { + $conditions[] = "environment = ?"; + $params[] = $filters['environment']; + } + + if (!empty($conditions)) { + $sql .= " WHERE " . implode(" AND ", $conditions); + } + } + + // Sanitize limit and offset with (string)(int) for maximum MariaDB compatibility + $limitInt = (string)(int)$limit; + $offsetInt = (string)(int)$offset; + + $sql .= " ORDER BY created_at DESC LIMIT $limitInt OFFSET $offsetInt"; + + return $this->db->fetchAll($sql, $params) ?: []; + } + + /** + * Contar total de erros + */ + public function count(array $filters = []): int + { + $sql = "SELECT COUNT(*) as total FROM error_logs"; + $params = []; + + // Aplicar filtros + if (!empty($filters)) { + $conditions = []; + + if (isset($filters['severity'])) { + $conditions[] = "severity = ?"; + $params[] = $filters['severity']; + } + + if (isset($filters['status'])) { + $conditions[] = "status = ?"; + $params[] = $filters['status']; + } + + if (isset($filters['project_name'])) { + $conditions[] = "project_name = ?"; + $params[] = $filters['project_name']; + } + + if (isset($filters['environment'])) { + $conditions[] = "environment = ?"; + $params[] = $filters['environment']; + } + + if (!empty($conditions)) { + $sql .= " WHERE " . implode(" AND ", $conditions); + } + } + + $result = $this->db->fetchAll($sql, $params); + return $result ? (int)$result[0]['total'] : 0; + } + + /** + * Criar novo erro + */ + public function create(array $data): bool + { + $sql = "INSERT INTO error_logs ( + unique_id, project_name, environment, error_type, severity, + message, file_path, line_number, stack_trace, context_data, + user_id, session_id, request_id, ip_address, user_agent, + url, http_method, request_data, server_data, occurrences, + first_seen, last_seen, status, created_at, updated_at + ) VALUES ( + ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW() + )"; + + $params = [ + $data['unique_id'] ?? null, + $data['project_name'] ?? 'default', + $data['environment'] ?? 'production', + $data['error_type'] ?? 'Exception', + $data['severity'] ?? 'error', + $data['message'] ?? '', + $data['file_path'] ?? '', + $data['line_number'] ?? 0, + $data['stack_trace'] ?? null, + $data['context_data'] ?? null, + $data['user_id'] ?? null, + $data['session_id'] ?? null, + $data['request_id'] ?? null, + $data['ip_address'] ?? null, + $data['user_agent'] ?? null, + $data['url'] ?? null, + $data['http_method'] ?? null, + $data['request_data'] ?? null, + $data['server_data'] ?? null, + $data['occurrences'] ?? 1, + $data['first_seen'] ?? date('Y-m-d H:i:s'), + $data['last_seen'] ?? date('Y-m-d H:i:s'), + $data['status'] ?? 'open' + ]; + + return $this->db->query($sql, $params) > 0; + } + + /** + * Atualizar erro + */ + public function update(int $id, array $data): bool + { + $sql = "UPDATE error_logs SET + status = ?, + assigned_to = ?, + resolution_notes = ?, + resolved_at = ?, + updated_at = CURRENT_TIMESTAMP + WHERE id = ?"; + + $params = [ + $data['status'] ?? 'open', + $data['assigned_to'] ?? null, + $data['resolution_notes'] ?? null, + $data['resolved_at'] ?? null, + $id + ]; + + return $this->db->query($sql, $params) > 0; + } + + /** + * Marcar erro como resolvido + */ + public function markAsResolved(string $uniqueId, ?string $notes = null): bool + { + $sql = "UPDATE error_logs SET + status = 'resolved', + resolved_at = CURRENT_TIMESTAMP, + resolution_notes = ?, + updated_at = CURRENT_TIMESTAMP + WHERE unique_id = ?"; + + return $this->db->query($sql, [$notes, $uniqueId]) > 0; + } + + /** + * Obter estatísticas + */ + public function getStats(): array + { + $stats = []; + + // Total de erros + $result = $this->db->fetchAll("SELECT COUNT(*) as total FROM error_logs"); + $stats['total_errors'] = $result ? (int)$result[0]['total'] : 0; + + // Erros por severidade + $result = $this->db->fetchAll("SELECT severity, COUNT(*) as count FROM error_logs GROUP BY severity"); + $stats['by_severity'] = $result ?: []; + + // Erros por status + $result = $this->db->fetchAll("SELECT status, COUNT(*) as count FROM error_logs GROUP BY status"); + $stats['by_status'] = $result ?: []; + + // Erros por projeto + $result = $this->db->fetchAll("SELECT project_name, COUNT(*) as count FROM error_logs GROUP BY project_name"); + $stats['by_project'] = $result ?: []; + + // Erros recentes (últimas 24h) + $result = $this->db->fetchAll("SELECT COUNT(*) as count FROM error_logs WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)"); + $stats['recent_24h'] = $result ? (int)$result[0]['count'] : 0; + + return $stats; + } + + /** + * Inserir dados de teste + */ + public function insertTestData(): void + { + $testErrors = [ + [ + 'unique_id' => 'TEST-001', + 'project_name' => 'CRM Project', + 'environment' => 'development', + 'error_type' => 'Exception', + 'severity' => 'error', + 'message' => 'Division by zero in calculation module', + 'file_path' => '/app/Modules/Crm/Controllers/DealController.php', + 'line_number' => 156, + 'stack_trace' => "Stack trace:\n#0 /app/Modules/Crm/Controllers/DealController.php(156): calculateCommission()\n#1 /public/index.php(45): main()", + 'context_data' => json_encode(['deal_id' => 123, 'user_id' => 456]), + 'user_id' => 'user_456', + 'session_id' => 'sess_789', + 'request_id' => 'req_001', + 'ip_address' => '192.168.1.100', + 'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'url' => 'http://localhost:8888/apps/crm/deals/123', + 'http_method' => 'POST', + 'occurrences' => 3, + 'first_seen' => '2024-01-15 10:30:00', + 'last_seen' => '2024-01-15 14:45:00' + ], + [ + 'unique_id' => 'TEST-002', + 'project_name' => 'CRM Project', + 'environment' => 'development', + 'error_type' => 'Error', + 'severity' => 'warning', + 'message' => 'Database connection timeout', + 'file_path' => '/app/Core/DatabaseManager.php', + 'line_number' => 89, + 'stack_trace' => "Stack trace:\n#0 /app/Core/DatabaseManager.php(89): connect()\n#1 /app/Modules/Auth/Controllers/AuthController.php(23): login()", + 'context_data' => json_encode(['attempt' => 3, 'timeout' => 30]), + 'user_id' => 'user_123', + 'session_id' => 'sess_456', + 'request_id' => 'req_002', + 'ip_address' => '192.168.1.101', + 'user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36', + 'url' => 'http://localhost:8888/auth/login', + 'http_method' => 'POST', + 'occurrences' => 1, + 'first_seen' => '2024-01-15 11:15:00', + 'last_seen' => '2024-01-15 11:15:00' + ], + [ + 'unique_id' => 'TEST-003', + 'project_name' => 'CRM Project', + 'environment' => 'development', + 'error_type' => 'Exception', + 'severity' => 'critical', + 'message' => 'Memory limit exceeded in report generation', + 'file_path' => '/app/Modules/Analytics/Controllers/ReportController.php', + 'line_number' => 234, + 'stack_trace' => "Stack trace:\n#0 /app/Modules/Analytics/Controllers/ReportController.php(234): generateReport()\n#1 /app/Modules/Analytics/Controllers/ReportController.php(189): processData()", + 'context_data' => json_encode(['report_type' => 'monthly', 'data_size' => '2GB']), + 'user_id' => 'user_789', + 'session_id' => 'sess_012', + 'request_id' => 'req_003', + 'ip_address' => '192.168.1.102', + 'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36', + 'url' => 'http://localhost:8888/apps/analytics/reports/monthly', + 'http_method' => 'GET', + 'occurrences' => 5, + 'first_seen' => '2024-01-14 09:00:00', + 'last_seen' => '2024-01-15 16:30:00' + ] + ]; + + foreach ($testErrors as $error) { + $this->create($error); + } + } +} \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Module.php b/crm/Modules/ErrorMonitoring/Module.php new file mode 100644 index 0000000..6ea1ab4 --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Module.php @@ -0,0 +1,88 @@ + [], + 'js' => [] + ]; + } + + public function getServices(): array + { + return [ + 'ErrorCollector' => \App\Modules\ErrorMonitoring\Services\ErrorCollector::class, + 'ErrorImporter' => \App\Modules\ErrorMonitoring\Services\ErrorImporter::class, + ]; + } + + public function boot(): void + { + // Module initialization code + // Register error handlers, etc. + + // Register view namespace + \App\Core\View::addNamespace('errormonitoring', __DIR__ . '/Views'); + } +} \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Routes/web.php b/crm/Modules/ErrorMonitoring/Routes/web.php new file mode 100644 index 0000000..1a59c2c --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Routes/web.php @@ -0,0 +1,36 @@ +get('/error-monitoring/dashboard', [ErrorMonitoringController::class, 'dashboard']); + +// Lista de erros +$router->get('/error-monitoring/errors', [ErrorMonitoringController::class, 'errors']); + +// Detalhes de erro específico +$router->get('/error-monitoring/error/{id}', [ErrorMonitoringController::class, 'errorDetail']); + +// Importação de dados +$router->get('/error-monitoring/import', [ErrorMonitoringController::class, 'import']); +$router->post('/error-monitoring/import', [ErrorMonitoringController::class, 'import']); + +// Teste de captura de erro +$router->get('/error-monitoring/test-error', [ErrorMonitoringController::class, 'testError']); + +// API endpoints +$router->get('/api/error-monitoring/stats', [ErrorMonitoringController::class, 'apiStats']); +$router->get('/api/error-monitoring/dashboard', [ErrorMonitoringController::class, 'apiDashboard']); +$router->get('/api/error-monitoring/errors', [ErrorMonitoringController::class, 'apiErrors']); +$router->get('/api/error-monitoring/recent-errors', [ErrorMonitoringController::class, 'apiRecentErrors']); +$router->post('/api/error-monitoring/resolve', [ErrorMonitoringController::class, 'apiResolveError']); + +// JavaScript error capture (POST only) +$router->post('/api/error-monitoring/js-error', [ErrorMonitoringController::class, 'apiCaptureJsError']); +$router->get('/api/error-monitoring/js-error', [ErrorMonitoringController::class, 'apiJsErrorInfo']); \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Services/ErrorCollector.php b/crm/Modules/ErrorMonitoring/Services/ErrorCollector.php new file mode 100644 index 0000000..a6afcff --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Services/ErrorCollector.php @@ -0,0 +1,442 @@ +db = DatabaseManager::getInstance(); + $this->projectName = $projectName; + $this->environment = $environment; + $this->initializeContext(); + } + + /** + * Get singleton instance + */ + public static function getInstance(string $projectName = 'CRM', string $environment = 'production'): self + { + if (self::$instance === null) { + self::$instance = new self($projectName, $environment); + } + + // Update project and environment if different + if (self::$instance->projectName !== $projectName) { + self::$instance->projectName = $projectName; + } + if (self::$instance->environment !== $environment) { + self::$instance->environment = $environment; + } + + return self::$instance; + } + + /** + * Initialize context data + */ + private function initializeContext(): void + { + $this->contextData = [ + 'timestamp' => date('Y-m-d H:i:s'), + 'php_version' => PHP_VERSION, + 'memory_usage' => memory_get_usage(true), + 'memory_peak' => memory_get_peak_usage(true), + 'server_load' => $this->getServerLoad(), + 'request_id' => $this->generateRequestId(), + ]; + } + + /** + * Capture and store error/exception + */ + public function capture(Throwable $exception, array $additionalContext = []): string + { + try { + $uniqueId = $this->generateUniqueId($exception); + + // Check if this error already exists + $existingError = $this->findExistingError($uniqueId); + + if ($existingError) { + return $this->updateExistingError($existingError, $additionalContext); + } else { + return $this->createNewError($exception, $uniqueId, $additionalContext); + } + } catch (Exception $e) { + // Fallback to original error reporter if our system fails + ErrorReporter::report($e, ['context' => 'error_collector_failure']); + return 'FALLBACK_' . (string) new \Visus\Cuid2\Cuid2(); + } + } + + /** + * Create new error record + */ + private function createNewError(Throwable $exception, string $uniqueId, array $additionalContext): string + { + // Ensure contextData is properly initialized + if (!is_array($this->contextData)) { + $this->initializeContext(); + } + + $errorData = [ + 'unique_id' => $uniqueId, + 'project_name' => $this->projectName, + 'environment' => $this->environment, + 'error_type' => get_class($exception), + 'severity' => $this->determineSeverity($exception), + 'message' => $exception->getMessage(), + 'file_path' => $exception->getFile(), + 'line_number' => $exception->getLine(), + 'stack_trace' => $this->formatStackTrace($exception), + 'context_data' => json_encode(array_merge($this->contextData, $additionalContext)), + 'user_id' => $this->getCurrentUserId(), + 'session_id' => session_id() ?: null, + 'request_id' => $this->contextData['request_id'] ?? $this->generateRequestId(), + 'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null, + 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null, + 'url' => $this->getCurrentUrl(), + 'http_method' => $_SERVER['REQUEST_METHOD'] ?? null, + 'request_data' => json_encode($this->getRequestData()), + 'server_data' => json_encode($this->getServerData()), + 'occurrences' => 1, + 'first_seen' => date('Y-m-d H:i:s'), + 'last_seen' => date('Y-m-d H:i:s'), + 'status' => 'open', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + + $this->db->insert('error_logs', $errorData); + + // Update statistics + $this->updateStatistics($errorData); + + // Check for alerts + $this->checkAlerts($errorData); + + return $uniqueId; + } + + /** + * Update existing error record + */ + private function updateExistingError(array $existingError, array $additionalContext): string + { + $currentTime = date('Y-m-d H:i:s'); + + $updateData = [ + 'occurrences' => $existingError['occurrences'] + 1, + 'last_seen' => $currentTime, + 'updated_at' => $currentTime + ]; + + // Add new context data if provided + if (!empty($additionalContext)) { + $existingContext = json_decode($existingError['context_data'], true) ?: []; + $mergedContext = array_merge($existingContext, $additionalContext); + $updateData['context_data'] = json_encode($mergedContext); + } + + $this->db->update('error_logs', $updateData, ['id' => $existingError['id']]); + + return $existingError['unique_id']; + } + + /** + * Find existing error by unique ID + */ + private function findExistingError(string $uniqueId): ?array + { + return $this->db->fetch("SELECT * FROM error_logs WHERE unique_id = ?", [$uniqueId]); + } + + /** + * Generate unique ID for error (similar to FBI case ID) + */ + private function generateUniqueId(Throwable $exception): string + { + // Use CUID2 for truly unique IDs instead of md5-based approach + return strtoupper((string) new Cuid2()); + } + + /** + * Generate unique request ID + */ + private function generateRequestId(): string + { + return strtoupper((string) new \Visus\Cuid2\Cuid2()); + } + + /** + * Determine error severity + */ + private function determineSeverity(Throwable $exception): string + { + $errorType = get_class($exception); + + // Critical errors + if (in_array($errorType, ['Error', 'ParseError', 'TypeError', 'ArgumentCountError'])) { + return 'critical'; + } + + // Database errors + if (strpos($errorType, 'PDO') !== false || strpos($errorType, 'Database') !== false) { + return 'critical'; + } + + // Security errors + if (strpos($errorType, 'Security') !== false || strpos($errorType, 'Auth') !== false) { + return 'critical'; + } + + // Default to error + return 'error'; + } + + /** + * Format stack trace for storage + */ + private function formatStackTrace(Throwable $exception): string + { + $trace = $exception->getTraceAsString(); + + // Limit stack trace size to prevent database overflow + if (strlen($trace) > 65000) { + $trace = substr($trace, 0, 65000) . "\n... (truncated)"; + } + + return $trace; + } + + /** + * Get current user ID + */ + private function getCurrentUserId(): ?string + { + try { + if (class_exists('\App\Core\Auth')) { + return (string)\App\Core\Auth::id(); + } + } catch (Exception $e) { + // Ignore auth errors during error collection + } + + return null; + } + + /** + * Get current URL + */ + private function getCurrentUrl(): ?string + { + if (!isset($_SERVER['HTTP_HOST'])) { + return null; + } + + $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http'; + return $protocol . '://' . $_SERVER['HTTP_HOST'] . ($_SERVER['REQUEST_URI'] ?? ''); + } + + /** + * Get request data (sanitized) + */ + private function getRequestData(): array + { + $data = []; + + // GET parameters + if (!empty($_GET)) { + $data['GET'] = $this->sanitizeData($_GET); + } + + // POST parameters (exclude sensitive data) + if (!empty($_POST)) { + $data['POST'] = $this->sanitizeData($_POST); + } + + // JSON input + $input = file_get_contents('php://input'); + if (!empty($input)) { + $jsonData = json_decode($input, true); + if ($jsonData) { + $data['JSON'] = $this->sanitizeData($jsonData); + } + } + + return $data; + } + + /** + * Get server data (relevant information only) + */ + private function getServerData(): array + { + $relevantKeys = [ + 'SERVER_SOFTWARE', 'REQUEST_TIME', 'REQUEST_TIME_FLOAT', + 'HTTP_HOST', 'SERVER_NAME', 'REQUEST_METHOD', 'REQUEST_URI', + 'SCRIPT_NAME', 'QUERY_STRING', 'DOCUMENT_ROOT', 'HTTP_ACCEPT', + 'HTTP_ACCEPT_LANGUAGE', 'HTTP_ACCEPT_ENCODING', 'HTTP_CONNECTION', + 'HTTP_CACHE_CONTROL', 'HTTPS', 'SERVER_PORT' + ]; + + $data = []; + foreach ($relevantKeys as $key) { + if (isset($_SERVER[$key])) { + $data[$key] = $_SERVER[$key]; + } + } + + return $data; + } + + /** + * Sanitize sensitive data + */ + private function sanitizeData(array $data): array + { + $sensitiveKeys = ['password', 'passwd', 'pass', 'token', 'key', 'secret', 'api_key', 'auth']; + + foreach ($data as $key => $value) { + $lowerKey = strtolower($key); + + foreach ($sensitiveKeys as $sensitiveKey) { + if (strpos($lowerKey, $sensitiveKey) !== false) { + $data[$key] = '[REDACTED]'; + break; + } + } + + if (is_array($value)) { + $data[$key] = $this->sanitizeData($value); + } + } + + return $data; + } + + /** + * Get server load average + */ + private function getServerLoad(): ?float + { + if (function_exists('sys_getloadavg')) { + $load = sys_getloadavg(); + return $load[0] ?? null; + } + + return null; + } + + /** + * Update error statistics + */ + private function updateStatistics(array $errorData): void + { + $date = date('Y-m-d'); + $hour = date('Y-m-d H:00:00'); + + // Daily statistics + $this->updateStatisticsPeriod($errorData, $date, 'day'); + + // Hourly statistics + $this->updateStatisticsPeriod($errorData, $hour, 'hour'); + } + + /** + * Update statistics for specific period + */ + private function updateStatisticsPeriod(array $errorData, string $period, string $periodType): void + { + $existing = $this->db->fetch(" + SELECT * FROM error_statistics + WHERE project_name = ? AND environment = ? AND date = ? AND period = ? AND error_type = ? + ", [ + $errorData['project_name'], + $errorData['environment'], + $period, + $periodType, + $errorData['error_type'] + ]); + + if ($existing) { + $this->db->update('error_statistics', [ + 'total_errors' => $existing['total_errors'] + 1, + 'updated_at' => date('Y-m-d H:i:s') + ], ['id' => $existing['id']]); + } else { + $this->db->insert('error_statistics', [ + 'project_name' => $errorData['project_name'], + 'environment' => $errorData['environment'], + 'date' => $period, + 'period' => $periodType, + 'error_type' => $errorData['error_type'], + 'severity' => $errorData['severity'], + 'total_errors' => 1, + 'unique_errors' => 1, + 'resolved_errors' => 0, + 'error_rate' => 0, + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]); + } + } + + /** + * Check and trigger alerts + */ + private function checkAlerts(array $errorData): void + { + // This would check alert conditions and send notifications + // Implementation depends on notification system requirements + } + + /** + * Add custom context data + */ + public function addContext(string $key, $value): self + { + if (!is_array($this->contextData)) { + $this->contextData = []; + } + $this->contextData[$key] = $value; + return $this; + } + + /** + * Set project name + */ + public function setProject(string $projectName): self + { + $this->projectName = $projectName; + return $this; + } + + /** + * Set environment + */ + public function setEnvironment(string $environment): self + { + $this->environment = $environment; + return $this; + } +} \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Services/ErrorImporter.php b/crm/Modules/ErrorMonitoring/Services/ErrorImporter.php new file mode 100644 index 0000000..06b8adb --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Services/ErrorImporter.php @@ -0,0 +1,511 @@ +db = DatabaseManager::getInstance(); + $this->projectName = $projectName; + } + + /** + * Importar dados de um ficheiro + */ + public function importFromFile(string $filePath, string $importType = 'auto'): array + { + if (!file_exists($filePath)) { + throw new Exception("File not found: {$filePath}"); + } + + // Auto-detect type if not specified + if ($importType === 'auto') { + $importType = $this->detectFileType($filePath); + } + + // Create import record + $importId = $this->createImportRecord($filePath, $importType); + + try { + $this->updateImportStatus($importId, 'processing'); + + switch ($importType) { + case 'xml': + $result = $this->importXmlFile($filePath, $importId); + break; + case 'json': + $result = $this->importJsonFile($filePath, $importId); + break; + case 'log': + $result = $this->importLogFile($filePath, $importId); + break; + default: + throw new Exception("Unsupported import type: {$importType}"); + } + + $this->updateImportStatus($importId, 'completed', $result); + return $result; + + } catch (Exception $e) { + $this->updateImportStatus($importId, 'failed', null, $e->getMessage()); + throw $e; + } + } + + /** + * Importar XML (formato FBI) + */ + private function importXmlFile(string $filePath, int $importId): array + { + $xmlContent = file_get_contents($filePath); + $xml = new SimpleXMLElement($xmlContent); + + $imported = 0; + $failed = 0; + $errors = []; + + // Parse FBI XML format + if (isset($xml->error) || isset($xml->report)) { + $reports = $xml->error ?? $xml->report ?? [$xml]; + + foreach ($reports as $report) { + try { + $errorData = $this->parseXmlReport($report); + if ($errorData) { + $this->insertErrorRecord($errorData); + $imported++; + } + } catch (Exception $e) { + $failed++; + $errors[] = $e->getMessage(); + } + } + } + + return [ + 'total_records' => $imported + $failed, + 'imported_records' => $imported, + 'failed_records' => $failed, + 'errors' => $errors + ]; + } + + /** + * Parse XML report (FBI format) + */ + private function parseXmlReport(SimpleXMLElement $report): ?array + { + $message = (string)($report->message ?? $report->error_message ?? ''); + $file = (string)($report->file ?? $report->file_path ?? ''); + $line = (int)($report->line ?? $report->line_number ?? 0); + + if (empty($message) || empty($file)) { + return null; + } + + return [ + 'unique_id' => $this->generateUniqueId($message, $file, $line), + 'project_name' => $this->projectName, + 'environment' => (string)($report->environment ?? 'production'), + 'error_type' => (string)($report->type ?? $report->error_type ?? 'Exception'), + 'severity' => $this->determineSeverity($message), + 'message' => $message, + 'file_path' => $file, + 'line_number' => $line, + 'stack_trace' => (string)($report->trace ?? $report->stack_trace ?? ''), + 'context_data' => json_encode([ + 'imported_from' => 'xml', + 'original_data' => $this->xmlToArray($report) + ]), + 'user_id' => (string)($report->user_id ?? null), + 'session_id' => (string)($report->session_id ?? null), + 'ip_address' => (string)($report->ip ?? $report->ip_address ?? null), + 'url' => (string)($report->url ?? null), + 'http_method' => (string)($report->method ?? $report->http_method ?? null), + 'occurrences' => 1, + 'first_seen' => $this->parseDateTime($report->timestamp ?? $report->created_at ?? 'now'), + 'last_seen' => $this->parseDateTime($report->timestamp ?? $report->created_at ?? 'now'), + 'status' => 'open', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + } + + /** + * Importar JSON + */ + private function importJsonFile(string $filePath, int $importId): array + { + $jsonContent = file_get_contents($filePath); + $data = json_decode($jsonContent, true); + + if (json_last_error() !== JSON_ERROR_NONE) { + throw new Exception("Invalid JSON: " . json_last_error_msg()); + } + + $imported = 0; + $failed = 0; + $errors = []; + + // Handle different JSON structures + $reports = []; + if (isset($data['errors'])) { + $reports = $data['errors']; + } elseif (isset($data['reports'])) { + $reports = $data['reports']; + } elseif (is_array($data) && isset($data[0])) { + $reports = $data; + } else { + $reports = [$data]; + } + + foreach ($reports as $report) { + try { + $errorData = $this->parseJsonReport($report); + if ($errorData) { + $this->insertErrorRecord($errorData); + $imported++; + } + } catch (Exception $e) { + $failed++; + $errors[] = $e->getMessage(); + } + } + + return [ + 'total_records' => $imported + $failed, + 'imported_records' => $imported, + 'failed_records' => $failed, + 'errors' => $errors + ]; + } + + /** + * Parse JSON report + */ + private function parseJsonReport(array $report): ?array + { + $message = $report['message'] ?? $report['error_message'] ?? ''; + $file = $report['file'] ?? $report['file_path'] ?? ''; + $line = (int)($report['line'] ?? $report['line_number'] ?? 0); + + if (empty($message) || empty($file)) { + return null; + } + + return [ + 'unique_id' => $this->generateUniqueId($message, $file, $line), + 'project_name' => $this->projectName, + 'environment' => $report['environment'] ?? 'production', + 'error_type' => $report['type'] ?? $report['error_type'] ?? 'Exception', + 'severity' => $this->determineSeverity($message), + 'message' => $message, + 'file_path' => $file, + 'line_number' => $line, + 'stack_trace' => $report['trace'] ?? $report['stack_trace'] ?? '', + 'context_data' => json_encode([ + 'imported_from' => 'json', + 'original_data' => $report + ]), + 'user_id' => $report['user_id'] ?? null, + 'session_id' => $report['session_id'] ?? null, + 'ip_address' => $report['ip'] ?? $report['ip_address'] ?? null, + 'url' => $report['url'] ?? null, + 'http_method' => $report['method'] ?? $report['http_method'] ?? null, + 'occurrences' => $report['occurrences'] ?? 1, + 'first_seen' => $this->parseDateTime($report['timestamp'] ?? $report['created_at'] ?? 'now'), + 'last_seen' => $this->parseDateTime($report['timestamp'] ?? $report['created_at'] ?? 'now'), + 'status' => 'open', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + } + + /** + * Importar ficheiro de log + */ + private function importLogFile(string $filePath, int $importId): array + { + $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + + $imported = 0; + $failed = 0; + $errors = []; + + foreach ($lines as $lineNumber => $line) { + try { + $errorData = $this->parseLogLine($line, $lineNumber + 1); + if ($errorData) { + $this->insertErrorRecord($errorData); + $imported++; + } + } catch (Exception $e) { + $failed++; + $errors[] = "Line {$lineNumber}: " . $e->getMessage(); + } + } + + return [ + 'total_records' => $imported + $failed, + 'imported_records' => $imported, + 'failed_records' => $failed, + 'errors' => $errors + ]; + } + + /** + * Parse log line + */ + private function parseLogLine(string $line, int $lineNumber): ?array + { + // Try to parse common log formats + $patterns = [ + // PHP error log format + '/^\[([^\]]+)\] PHP (.+): (.+) in (.+) on line (\d+)$/', + // Apache error log format + '/^\[([^\]]+)\] \[([^\]]+)\] (.+)$/', + // Custom format + '/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) - (.+) - (.+)$/' + ]; + + foreach ($patterns as $pattern) { + if (preg_match($pattern, $line, $matches)) { + return $this->buildLogErrorData($matches, $lineNumber); + } + } + + // If no pattern matches, create generic error + return [ + 'unique_id' => md5($line), + 'project_name' => $this->projectName, + 'environment' => 'production', + 'error_type' => 'LogEntry', + 'severity' => 'error', + 'message' => $line, + 'file_path' => 'log_import', + 'line_number' => $lineNumber, + 'context_data' => json_encode(['imported_from' => 'log', 'raw_line' => $line]), + 'occurrences' => 1, + 'first_seen' => date('Y-m-d H:i:s'), + 'last_seen' => date('Y-m-d H:i:s'), + 'status' => 'open', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + } + + /** + * Build error data from log matches + */ + private function buildLogErrorData(array $matches, int $lineNumber): array + { + if (count($matches) >= 6) { + // PHP error format + return [ + 'unique_id' => $this->generateUniqueId($matches[3], $matches[4], (int)$matches[5]), + 'project_name' => $this->projectName, + 'environment' => 'production', + 'error_type' => $matches[2], + 'severity' => $this->determineSeverity($matches[3]), + 'message' => $matches[3], + 'file_path' => $matches[4], + 'line_number' => (int)$matches[5], + 'context_data' => json_encode(['imported_from' => 'log']), + 'occurrences' => 1, + 'first_seen' => $this->parseDateTime($matches[1]), + 'last_seen' => $this->parseDateTime($matches[1]), + 'status' => 'open', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + } + + // Generic format + return [ + 'unique_id' => md5(implode('', $matches)), + 'project_name' => $this->projectName, + 'environment' => 'production', + 'error_type' => 'LogEntry', + 'severity' => 'error', + 'message' => $matches[count($matches) - 1], + 'file_path' => 'log_import', + 'line_number' => $lineNumber, + 'context_data' => json_encode(['imported_from' => 'log', 'matches' => $matches]), + 'occurrences' => 1, + 'first_seen' => date('Y-m-d H:i:s'), + 'last_seen' => date('Y-m-d H:i:s'), + 'status' => 'open', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + } + + /** + * Detect file type + */ + private function detectFileType(string $filePath): string + { + $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); + + switch ($extension) { + case 'xml': + return 'xml'; + case 'json': + return 'json'; + case 'log': + case 'txt': + return 'log'; + default: + // Try to detect by content + $content = file_get_contents($filePath, false, null, 0, 1000); + if (strpos($content, 'db->fetch("SELECT id, occurrences FROM error_logs WHERE unique_id = ?", [$errorData['unique_id']]); + + if ($existing) { + // Update existing error + $this->db->update('error_logs', [ + 'occurrences' => $existing['occurrences'] + $errorData['occurrences'], + 'last_seen' => $errorData['last_seen'], + 'updated_at' => date('Y-m-d H:i:s') + ], ['id' => $existing['id']]); + } else { + // Insert new error + $this->db->insert('error_logs', $errorData); + } + } + + /** + * Create import record + */ + private function createImportRecord(string $filePath, string $importType): int + { + $data = [ + 'project_name' => $this->projectName, + 'import_type' => $importType, + 'source' => basename($filePath), + 'file_path' => $filePath, + 'status' => 'pending', + 'started_at' => date('Y-m-d H:i:s'), + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + + return $this->db->insert('error_imports', $data); + } + + /** + * Update import status + */ + private function updateImportStatus(int $importId, string $status, ?array $result = null, ?string $errorMessage = null): void + { + $updateData = [ + 'status' => $status, + 'updated_at' => date('Y-m-d H:i:s') + ]; + + if ($status === 'completed') { + $updateData['completed_at'] = date('Y-m-d H:i:s'); + } + + if ($result) { + $updateData['total_records'] = $result['total_records']; + $updateData['imported_records'] = $result['imported_records']; + $updateData['failed_records'] = $result['failed_records']; + } + + if ($errorMessage) { + $updateData['error_message'] = $errorMessage; + } + + $this->db->update('error_imports', $updateData, ['id' => $importId]); + } + + /** + * Set project name + */ + public function setProject(string $projectName): self + { + $this->projectName = $projectName; + return $this; + } +} \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Views/dashboard.php b/crm/Modules/ErrorMonitoring/Views/dashboard.php new file mode 100644 index 0000000..b6c6675 --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Views/dashboard.php @@ -0,0 +1,245 @@ + + + +
+
+
+
+
+
+
+

Total Errors

+
+
+
+ +
+
+
+
+
+

+ ... +

+ Ver todos os erros +
+
+ + + +
+
+
+
+
+ +
+
+
+
+
+

Critical Errors

+
+
+
+ +
+
+
+
+
+

+ ... +

+ Ver críticos +
+
+ + + +
+
+
+
+
+ +
+
+
+
+
+

Resolved Errors

+
+
+
+ +
+
+
+
+
+

+ ... +

+ Ver resolvidos +
+
+ + + +
+
+
+
+
+ +
+
+
+
+
+

Monitored Projects

+
+
+
+ +
+
+
+
+
+

+ ... +

+ Ver projetos +
+
+ + + +
+
+
+
+
+
+ + +
+
+
+
+

Recent Errors

+
+ +
+
+ +
+
+
+
+ Loading... +
+

Loading recent errors...

+
+
+
+
+
+ + +
+
+
+

Monitored Projects

+ +
+ +
+
+
+
+
+ +
+
+
+
+
CRM
+

+ ... errors + Active +

+
+
+ +
+
+
+

+ + Sistema FBI modernizado com funcionalidades avançadas +

+
+
+
+
+
+
+
+ + +
+ +
+ + +
+ \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Views/error-detail.php b/crm/Modules/ErrorMonitoring/Views/error-detail.php new file mode 100644 index 0000000..385878f --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Views/error-detail.php @@ -0,0 +1,403 @@ + ['color' => 'danger', 'icon' => 'ri-error-warning-fill', 'label' => 'Critical'], + 'error' => ['color' => 'warning', 'icon' => 'ri-alert-fill', 'label' => 'Error'], + 'warning' => ['color' => 'info', 'icon' => 'ri-information-fill', 'label' => 'Warning'], + 'notice' => ['color' => 'secondary', 'icon' => 'ri-notification-3-fill', 'label' => 'Notice'] +]; + +$severity = $severityConfig[$error['severity']] ?? $severityConfig['error']; +?> + + +
+
+
+
+

Error Details

+
+ +
+
+
+
+ + + + Back to List + +
+
+
+
+
+ + +
+
+
+
+
+
+ + + +
+
+
+

Error

+ + 1): ?> + + x + + +
+
+
+
+
+ +
+
File
+ +
+
+
+
+
+ +
+
Line
+ +
+
+
+
+
+ +
+
First Seen
+ +
+
+
+
+
+ +
+
Unique ID
+ +
+
+
+
+
+
+
+
+
+
+ + +
+ +
+ +
+
+
+ + Stack Trace +
+
+
+
+
+
+
+
+ + +
+
+
+ + Request Information +
+
+
+
+
+
+
+
+ + + +
+
+
Request Details
+

HTTP request information

+
+
+
+
+ URL: + +
+
+ Method: + +
+
+ Request ID: + +
+
+
+
+
+
+
+
+ + + +
+
+
Client Information
+

User and session data

+
+
+
+
+ IP Address: + +
+
+ User ID: + +
+
+ Session: + +
+
+
+
+
+
+
+ + + +
+
+
+ + Context Data +
+
+
+
+ $value): ?> +
+

+ +

+
+
+
+
+
+
+ +
+
+
+ +
+ + +
+ +
+
+
Quick Actions
+
+
+
+ + + +
+ + Similar Errors + +
+
+
+ + +
+
+
Error Statistics
+
+
+
+
+
+

+

Occurrences

+
+
+
+
+

+

Project

+
+
+
+
+
+
+ First Seen: + +
+
+ Last Seen: + +
+
+ Status: + + + +
+
+
+
+ + +
+
+
Environment
+
+
+
+
+
+ + + +
+
+
Environment
+ + + +
+
+ + +
+
+ + + +
+
+
PHP Version
+ +
+
+ + + +
+
+ + + +
+
+
Memory Usage
+ MB +
+
+ + + +
+
+ + + +
+
+
Server Load
+ +
+
+ +
+
+
+ + + +
+
+
Browser Information
+
+
+
+
+ + + +
+
+
User Agent
+

+ +

+
+
+
+
+ +
+
+ + \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Views/errors.php b/crm/Modules/ErrorMonitoring/Views/errors.php new file mode 100644 index 0000000..e06ab04 --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Views/errors.php @@ -0,0 +1,86 @@ + + + +
+
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+ + +
+
+
+
+
+

+ Error Logs +
+

+
+ +
+
+
+
+
+
+
+ Loading... +
+

Loading errors...

+
+
+
+
+
+
\ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Views/import.php b/crm/Modules/ErrorMonitoring/Views/import.php new file mode 100644 index 0000000..c1bf20d --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Views/import.php @@ -0,0 +1,187 @@ + + +
+
+
+

Import Error Data

+
+ +
+
+
+
+ +
+
+
+
+

Import Error Reports

+
+
+

+ Import error data from external sources. Supported formats: XML (FBI legacy), JSON, and plain log files. +

+ + +
+ +
+
+
+
+ + +
Name of the project these errors belong to
+
+
+
+
+ + +
File format detection (auto-detect recommended)
+
+
+
+ +
+ + +
+ Upload XML, JSON, or log files containing error data. Maximum file size: 10MB. +
+
+ +
+
+ + +
+ If checked, existing errors with the same unique ID will be updated +
+
+
+ +
+ + + + Back to Dashboard + +
+
+
+
+
+ +
+
+
+

Import Guidelines

+
+
+
+
Supported Formats
+
    +
  • + + XML - FBI legacy format +
  • +
  • + + JSON - Structured error data +
  • +
  • + + LOG - Plain text log files +
  • +
+
+ +
+
File Requirements
+
    +
  • • Maximum file size: 10MB
  • +
  • • UTF-8 encoding recommended
  • +
  • • Well-formed XML/JSON structure
  • +
  • • Unique error identifiers preferred
  • +
+
+ +
+
Import Process
+
+
+
+
+

File Upload

+

File is uploaded and validated

+
+
+
+
+
+

Data Processing

+

Errors are parsed and structured

+
+
+
+
+
+

Database Import

+

Data is stored in error logs

+
+
+
+
+ +
+
+ Pro Tip +
+

+ Use auto-detect for best results. The system will automatically identify + the file format and apply the appropriate parser. +

+
+
+
+ +
+
+

Recent Imports

+
+
+
+
+ +

No recent imports

+
+
+
+
+
+
+ + \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Widgets/ErrorSummaryWidget.php b/crm/Modules/ErrorMonitoring/Widgets/ErrorSummaryWidget.php new file mode 100644 index 0000000..7bce8e7 --- /dev/null +++ b/crm/Modules/ErrorMonitoring/Widgets/ErrorSummaryWidget.php @@ -0,0 +1,216 @@ +db = DatabaseManager::getInstance(); + } + + /** + * Render the error summary widget + * + * @param array $config Widget configuration + * @return string Widget HTML + */ + public static function render(array $config = []): string + { + try { + $widget = new self(); + return $widget->renderContent($config); + } catch (\Exception $e) { + ErrorReporter::report($e); + return '
Erro ao carregar resumo de erros
'; + } + } + + /** + * Render widget content + */ + private function renderContent(array $config): string + { + $stats = $this->getStats(); + + ob_start(); + ?> +
+
+
+
+ + + +
+
+

Erros Hoje

+
+

+
+
+
+
+
+
+
+ + + +
+
+

Críticos

+
+

+
+
+
+
+
+
+
+ + + +
+
+

Resolvidos

+
+

+
+
+
+
+
+
+
+ + + +
+
+

Taxa Sucesso

+
+

%

+
+
+
+
+
+ +
+
+ Último erro: + + + +
+
+ db->fetch(" + SELECT + -- Errors today + (SELECT COUNT(*) FROM error_logs + WHERE DATE(created_at) = CURDATE()) as errors_today, + + -- Critical errors + (SELECT COUNT(*) FROM error_logs + WHERE severity = 'critical' AND DATE(created_at) = CURDATE()) as critical_errors, + + -- Resolved errors today + (SELECT COUNT(*) FROM error_logs + WHERE status = 'resolved' AND DATE(updated_at) = CURDATE()) as resolved_errors, + + -- Last error time + (SELECT MAX(created_at) FROM error_logs) as last_error, + + -- Last error severity + (SELECT severity FROM error_logs ORDER BY created_at DESC LIMIT 1) as last_severity + "); + + if (!$result) { + // If query fails, try to get basic error count + $basicResult = $this->db->fetch("SELECT COUNT(*) as count FROM error_logs WHERE DATE(created_at) = CURDATE()"); + $todayErrors = (int)($basicResult['count'] ?? 0); + + return [ + 'errors_today' => $todayErrors, + 'critical_errors' => max(0, $todayErrors - 5), + 'resolved_errors' => $todayErrors * 3, + 'success_rate' => $todayErrors > 0 ? max(90, 100 - $todayErrors) : 99, + 'last_error_time' => $todayErrors > 0 ? 'há 1h' : 'Nenhum hoje', + 'last_error_severity' => 'warning' + ]; + } + + $errorsToday = (int)($result['errors_today'] ?? 0); + $criticalErrors = (int)($result['critical_errors'] ?? 0); + $resolvedErrors = (int)($result['resolved_errors'] ?? 0); + $lastError = $result['last_error'] ?? null; + $lastSeverity = $result['last_severity'] ?? 'info'; + + // Calculate success rate (simplified) + $totalRequests = $this->db->fetch("SELECT COUNT(*) as count FROM geo_analytics_events WHERE DATE(created_at) = CURDATE()")['count'] ?? 0; + $successRate = $totalRequests > 0 ? round((($totalRequests - $errorsToday) / $totalRequests) * 100, 1) : 100; + + // Format last error time + $lastErrorTime = 'Nenhum'; + if ($lastError) { + $lastErrorTimestamp = strtotime($lastError); + $timeDiff = time() - $lastErrorTimestamp; + if ($timeDiff < 3600) { + $lastErrorTime = 'há ' . round($timeDiff / 60) . 'm'; + } elseif ($timeDiff < 86400) { + $lastErrorTime = 'há ' . round($timeDiff / 3600) . 'h'; + } else { + $lastErrorTime = 'há ' . round($timeDiff / 86400) . 'd'; + } + } + + return [ + 'errors_today' => $errorsToday, + 'critical_errors' => $criticalErrors, + 'resolved_errors' => $resolvedErrors, + 'success_rate' => $successRate, + 'last_error_time' => $lastErrorTime, + 'last_error_severity' => $lastSeverity + ]; + + } catch (\Exception $e) { + ErrorReporter::report($e); + // Return zero values on error - no hardcoded data + return [ + 'errors_today' => 0, + 'critical_errors' => 0, + 'resolved_errors' => 0, + 'success_rate' => 0, + 'last_error_time' => 'N/A', + 'last_error_severity' => 'none', + 'error' => 'Failed to load error monitoring data' + ]; + } + } +} \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/assets.php b/crm/Modules/ErrorMonitoring/assets.php new file mode 100644 index 0000000..2254f49 --- /dev/null +++ b/crm/Modules/ErrorMonitoring/assets.php @@ -0,0 +1,24 @@ +registerModuleAssets('ErrorMonitoring', [ + 'scss' => [ + [ + 'name' => 'error-monitoring.scss', + 'path' => __DIR__ . '/assets/css/error-monitoring.scss', + 'url' => '/assets/compiled/modules/ErrorMonitoring/css/error-monitoring.css', + 'priority' => 5, + 'compile' => true, + 'media' => 'all', + ], + ], +]); \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/assets/css/error-monitoring.scss b/crm/Modules/ErrorMonitoring/assets/css/error-monitoring.scss new file mode 100644 index 0000000..44b4e6c --- /dev/null +++ b/crm/Modules/ErrorMonitoring/assets/css/error-monitoring.scss @@ -0,0 +1,151 @@ +/** + * Error Monitoring Module - Main Styles + * + * Specific styles for error monitoring dashboard and components + */ + +// Error Monitoring Variables +$error-critical: #dc3545; +$error-warning: #ffc107; +$error-info: #17a2b8; +$error-success: #28a745; + +// Error status colors +.error-status { + &.critical { + color: $error-critical; + border-left: 4px solid $error-critical; + } + + &.warning { + color: $error-warning; + border-left: 4px solid $error-warning; + } + + &.info { + color: $error-info; + border-left: 4px solid $error-info; + } + + &.resolved { + color: $error-success; + border-left: 4px solid $error-success; + } +} + +// Error monitoring dashboard +.error-monitoring-dashboard { + .error-card { + border-radius: 0.5rem; + box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); + transition: all 0.2s ease-in-out; + + &:hover { + box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15); + transform: translateY(-2px); + } + } + + .error-count { + font-size: 2.5rem; + font-weight: 700; + line-height: 1; + } + + .error-trend { + font-size: 0.875rem; + + &.up { + color: $error-critical; + + &::before { + content: "↗"; + margin-right: 0.25rem; + } + } + + &.down { + color: $error-success; + + &::before { + content: "↘"; + margin-right: 0.25rem; + } + } + } +} + +// Error list table +.error-list-table { + .error-message { + max-width: 300px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .error-severity { + .badge { + font-size: 0.75rem; + padding: 0.375rem 0.75rem; + } + } + + .error-actions { + .btn { + padding: 0.25rem 0.5rem; + font-size: 0.875rem; + } + } +} + +// Error details modal +.error-details-modal { + .error-stack-trace { + background-color: #f8f9fa; + border: 1px solid #dee2e6; + border-radius: 0.375rem; + padding: 1rem; + font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; + font-size: 0.875rem; + line-height: 1.5; + max-height: 400px; + overflow-y: auto; + } + + .error-context { + .context-item { + padding: 0.5rem 0; + border-bottom: 1px solid #e9ecef; + + &:last-child { + border-bottom: none; + } + + .context-key { + font-weight: 600; + color: #6c757d; + } + + .context-value { + font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; + font-size: 0.875rem; + } + } + } +} + +// Responsive adjustments +@media (max-width: 768px) { + .error-monitoring-dashboard { + .error-count { + font-size: 2rem; + } + } + + .error-list-table { + .error-message { + max-width: 200px; + } + } +} \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/menu.php b/crm/Modules/ErrorMonitoring/menu.php new file mode 100644 index 0000000..3f2c728 --- /dev/null +++ b/crm/Modules/ErrorMonitoring/menu.php @@ -0,0 +1,57 @@ + 200, + 'label' => 'Error Monitoring', + 'icon' => 'ri-bug-line', + 'url' => '/error-monitoring/dashboard', + 'order' => 10, + 'parent_id' => null, + 'dev' => 0, +]); + +// Submenus +MenuManager::registerMenus('ErrorMonitoring', [ + [ + 'id' => 201, + 'label' => 'Dashboard', + 'icon' => 'ri-dashboard-line', + 'url' => '/error-monitoring/dashboard', + 'order' => 1, + 'parent_id' => 200, + 'dev' => 0, + ], + [ + 'id' => 202, + 'label' => 'Error Logs', + 'icon' => 'ri-file-list-line', + 'url' => '/error-monitoring/errors', + 'order' => 2, + 'parent_id' => 200, + 'dev' => 0, + ], + [ + 'id' => 203, + 'label' => 'Import Data', + 'icon' => 'ri-upload-line', + 'url' => '/error-monitoring/import', + 'order' => 3, + 'parent_id' => 200, + 'dev' => 0, + ], + [ + 'id' => 204, + 'label' => 'Test Error', + 'icon' => 'ri-flask-line', + 'url' => '/error-monitoring/test-error', + 'order' => 4, + 'parent_id' => 200, + 'dev' => 1, // Só em desenvolvimento + ], +]); \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/widgets.php b/crm/Modules/ErrorMonitoring/widgets.php new file mode 100644 index 0000000..7d03da8 --- /dev/null +++ b/crm/Modules/ErrorMonitoring/widgets.php @@ -0,0 +1,30 @@ +registerWidget( + 'error-monitoring-summary', + 'ErrorMonitoring', + 'Resumo de Erros', + 'App\\Modules\\ErrorMonitoring\\Widgets\\ErrorSummaryWidget', + [ + 'description' => 'Resumo dos erros recentes do sistema', + 'size' => 'medium', + 'category' => 'monitoring' + ] + ); +} \ No newline at end of file