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
This commit is contained in:
1 parent
2cab67b1ab
commit
968e7b3451
15 files changed
+3645
No files matched your search
@@ -0,0 +1,849 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\ErrorMonitoring\Controllers;
|
||||
|
||||
use App\Core\BaseController;
|
||||
use App\Core\DatabaseManager;
|
||||
use App\Core\View;
|
||||
use App\Core\Cache\RedisManager;
|
||||
use App\Modules\ErrorMonitoring\Services\ErrorCollector;
|
||||
use App\Modules\ErrorMonitoring\Services\ErrorImporter;
|
||||
use App\Modules\ErrorMonitoring\Models\ErrorLog;
|
||||
use App\Core\InputSanitizer;
|
||||
use Exception;
|
||||
use PDO;
|
||||
use Visus\Cuid2\Cuid2;
|
||||
|
||||
/**
|
||||
* ErrorMonitoringController - Dashboard de monitorização de erros
|
||||
*/
|
||||
class ErrorMonitoringController extends BaseController
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('ErrorMonitoring');
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard principal
|
||||
*/
|
||||
public function dashboard(): void
|
||||
{
|
||||
$this->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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\ErrorMonitoring\Models;
|
||||
|
||||
use App\Core\DatabaseManager;
|
||||
|
||||
/**
|
||||
* ErrorLog Model - Modelo para a tabela error_logs
|
||||
*/
|
||||
class ErrorLog
|
||||
{
|
||||
private DatabaseManager $db;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\ErrorMonitoring;
|
||||
|
||||
/**
|
||||
* Error Monitoring Module
|
||||
* Sistema moderno de monitorização de erros equivalente ao FBI
|
||||
*/
|
||||
class Module
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'ErrorMonitoring';
|
||||
}
|
||||
|
||||
public function getDisplayName(): string
|
||||
{
|
||||
return 'Error Monitoring';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Sistema moderno de monitorização e análise de erros com dashboard centralizado, importação de dados externos e alertas automáticos. Equivalente moderno ao sistema FBI.';
|
||||
}
|
||||
|
||||
public function getVersion(): string
|
||||
{
|
||||
return '1.0.0';
|
||||
}
|
||||
|
||||
public function getDependencies(): array
|
||||
{
|
||||
return ['Core'];
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function install(): bool
|
||||
{
|
||||
// Installation is handled by migrations
|
||||
return true;
|
||||
}
|
||||
|
||||
public function uninstall(): bool
|
||||
{
|
||||
// Uninstallation is handled by migration rollbacks
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getRoutes(): array
|
||||
{
|
||||
return include __DIR__ . '/Routes/web.php';
|
||||
}
|
||||
|
||||
public function getMenu(): array
|
||||
{
|
||||
return include __DIR__ . '/menu.php';
|
||||
}
|
||||
|
||||
public function getAssets(): array
|
||||
{
|
||||
return [
|
||||
'css' => [],
|
||||
'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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
/**
|
||||
* Rotas do Módulo Error Monitoring
|
||||
*/
|
||||
|
||||
use App\Core\Router;
|
||||
use App\Modules\ErrorMonitoring\Controllers\ErrorMonitoringController;
|
||||
|
||||
$router = Router::getInstance();
|
||||
|
||||
// Dashboard principal
|
||||
$router->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']);
|
||||
@@ -0,0 +1,442 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\ErrorMonitoring\Services;
|
||||
|
||||
use App\Core\DatabaseManager;
|
||||
use App\Core\ErrorReporter;
|
||||
use Exception;
|
||||
use Throwable;
|
||||
use PDOException;
|
||||
use Visus\Cuid2\Cuid2;
|
||||
|
||||
/**
|
||||
* ErrorCollector - Sistema moderno de captura e análise de erros
|
||||
* Equivalente moderno ao sistema FBI, mas com funcionalidades avançadas
|
||||
*/
|
||||
class ErrorCollector
|
||||
{
|
||||
private DatabaseManager $db;
|
||||
private string $projectName;
|
||||
private string $environment;
|
||||
private array $contextData = [];
|
||||
private static ?self $instance = null;
|
||||
|
||||
public function __construct(string $projectName = 'CRM', string $environment = 'production')
|
||||
{
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\ErrorMonitoring\Services;
|
||||
|
||||
use App\Core\DatabaseManager;
|
||||
use App\Core\ErrorReporter;
|
||||
use Exception;
|
||||
use SimpleXMLElement;
|
||||
use Visus\Cuid2\Cuid2;
|
||||
|
||||
/**
|
||||
* ErrorImporter - Sistema de importação de dados de erros externos
|
||||
* Suporta múltiplos formatos: XML (FBI), JSON, Log files
|
||||
*/
|
||||
class ErrorImporter
|
||||
{
|
||||
private DatabaseManager $db;
|
||||
private string $projectName;
|
||||
private array $importStats = [];
|
||||
|
||||
public function __construct(string $projectName = 'External')
|
||||
{
|
||||
$this->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, '<?xml') === 0) {
|
||||
return 'xml';
|
||||
}
|
||||
if (json_decode($content) !== null) {
|
||||
return 'json';
|
||||
}
|
||||
return 'log';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate unique ID
|
||||
*/
|
||||
private function generateUniqueId(string $message, string $file, int $line): string
|
||||
{
|
||||
// Use CUID2 for truly unique IDs instead of md5-based approach
|
||||
return strtoupper((string) new Cuid2());
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine severity
|
||||
*/
|
||||
private function determineSeverity(string $message): string
|
||||
{
|
||||
$message = strtolower($message);
|
||||
|
||||
if (strpos($message, 'fatal') !== false || strpos($message, 'critical') !== false) {
|
||||
return 'critical';
|
||||
}
|
||||
if (strpos($message, 'warning') !== false) {
|
||||
return 'warning';
|
||||
}
|
||||
if (strpos($message, 'notice') !== false || strpos($message, 'info') !== false) {
|
||||
return 'info';
|
||||
}
|
||||
|
||||
return 'error';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse datetime
|
||||
*/
|
||||
private function parseDateTime(string $datetime): string
|
||||
{
|
||||
try {
|
||||
return date('Y-m-d H:i:s', strtotime($datetime));
|
||||
} catch (Exception $e) {
|
||||
return date('Y-m-d H:i:s');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert XML to array
|
||||
*/
|
||||
private function xmlToArray(SimpleXMLElement $xml): array
|
||||
{
|
||||
return json_decode(json_encode($xml), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert error record
|
||||
*/
|
||||
private function insertErrorRecord(array $errorData): void
|
||||
{
|
||||
// Check if error already exists
|
||||
$existing = $this->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
<?php
|
||||
/**
|
||||
* Error Monitoring Dashboard - API-driven
|
||||
*/
|
||||
|
||||
use App\Core\View;
|
||||
?>
|
||||
|
||||
<!-- Estatísticas -->
|
||||
<div x-data="errorMonitoringDashboard()">
|
||||
<div class="row" id="stats-cards">
|
||||
<div class="col-xl-3 col-md-6">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1 overflow-hidden">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Total Errors</p>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<h5 class="text-success fs-14 mb-0">
|
||||
<i class="ri-arrow-right-up-line fs-13 align-middle"></i>
|
||||
</h5>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex align-items-end justify-content-between mt-4">
|
||||
<div>
|
||||
<h4 class="fs-22 fw-semibold ff-secondary mb-4">
|
||||
<span class="counter-value" id="total-errors">...</span>
|
||||
</h4>
|
||||
<a href="/error-monitoring/errors" class="text-decoration-underline">Ver todos os erros</a>
|
||||
</div>
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-danger-subtle rounded fs-3">
|
||||
<i class="bx bx-error text-danger"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-3 col-md-6">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1 overflow-hidden">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Critical Errors</p>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<h5 class="text-danger fs-14 mb-0">
|
||||
<i class="ri-arrow-right-up-line fs-13 align-middle"></i>
|
||||
</h5>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex align-items-end justify-content-between mt-4">
|
||||
<div>
|
||||
<h4 class="fs-22 fw-semibold ff-secondary mb-4">
|
||||
<span class="counter-value" id="critical-errors">...</span>
|
||||
</h4>
|
||||
<a href="/error-monitoring/errors?severity=critical" class="text-decoration-underline">Ver críticos</a>
|
||||
</div>
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-danger-subtle rounded fs-3">
|
||||
<i class="bx bx-bug text-danger"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-3 col-md-6">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1 overflow-hidden">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Resolved Errors</p>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<h5 class="text-success fs-14 mb-0">
|
||||
<i class="ri-arrow-right-up-line fs-13 align-middle"></i>
|
||||
</h5>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex align-items-end justify-content-between mt-4">
|
||||
<div>
|
||||
<h4 class="fs-22 fw-semibold ff-secondary mb-4">
|
||||
<span class="counter-value" id="resolved-errors">...</span>
|
||||
</h4>
|
||||
<a href="/error-monitoring/errors?status=resolved" class="text-decoration-underline">Ver resolvidos</a>
|
||||
</div>
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-success-subtle rounded fs-3">
|
||||
<i class="bx bx-check-circle text-success"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-3 col-md-6">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1 overflow-hidden">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Monitored Projects</p>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<h5 class="text-info fs-14 mb-0">
|
||||
<i class="ri-arrow-right-up-line fs-13 align-middle"></i>
|
||||
</h5>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex align-items-end justify-content-between mt-4">
|
||||
<div>
|
||||
<h4 class="fs-22 fw-semibold ff-secondary mb-4">
|
||||
<span class="counter-value" id="projects-count">...</span>
|
||||
</h4>
|
||||
<a href="#projects-section" class="text-decoration-underline">Ver projetos</a>
|
||||
</div>
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-info-subtle rounded fs-3">
|
||||
<i class="bx bx-folder text-info"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Erros Recentes -->
|
||||
<div class="row">
|
||||
<div class="col-xl-8">
|
||||
<div class="card">
|
||||
<div class="card-header align-items-center d-flex">
|
||||
<h4 class="card-title mb-0 flex-grow-1">Recent Errors</h4>
|
||||
<div class="flex-shrink-0">
|
||||
<button type="button" class="btn btn-primary btn-sm" @click="refreshRecentErrors()">
|
||||
<i class="ri-refresh-line me-1"></i> Refresh
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-body">
|
||||
<div id="recent-errors-container">
|
||||
<div class="text-center py-4">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Loading...</span>
|
||||
</div>
|
||||
<p class="mt-2">Loading recent errors...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Projetos Monitorizados -->
|
||||
<div class="col-xl-4">
|
||||
<div class="card" id="projects-section">
|
||||
<div class="card-header align-items-center d-flex">
|
||||
<h4 class="card-title mb-0 flex-grow-1">Monitored Projects</h4>
|
||||
<div class="flex-shrink-0">
|
||||
<a href="/error-monitoring/import" class="btn btn-soft-primary btn-sm">
|
||||
<i class="ri-download-line me-1"></i> Import Data
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm">
|
||||
<div class="avatar-title bg-success-subtle text-success rounded fs-16">
|
||||
<i class="ri-folder-line"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="fs-14 mb-1">CRM</h6>
|
||||
<p class="text-muted mb-0 fs-12">
|
||||
<span id="project-errors">...</span> errors
|
||||
<span class="badge bg-success-subtle text-success ms-1">Active</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 pt-2 border-top border-top-dashed">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-muted mb-0 fs-13">
|
||||
<i class="ri-information-line me-1"></i>
|
||||
Sistema FBI modernizado com funcionalidades avançadas
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações Rápidas -->
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Quick Actions</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-3">
|
||||
<a href="/error-monitoring/test-error" class="btn btn-outline-primary w-100">
|
||||
<i class="ri-flask-line me-2"></i>
|
||||
Test Error Capture
|
||||
</a>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<a href="/error-monitoring/import" class="btn btn-outline-info w-100">
|
||||
<i class="ri-download-line me-2"></i>
|
||||
Import External Data
|
||||
</a>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<a href="/error-monitoring/errors" class="btn btn-outline-secondary w-100">
|
||||
<i class="ri-file-list-3-line me-2"></i>
|
||||
View All Errors
|
||||
</a>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<a href="/api/error-monitoring/stats" class="btn btn-outline-success w-100" target="_blank">
|
||||
<i class="ri-bar-chart-line me-2"></i>
|
||||
API Stats
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Close Alpine.js component wrapper -->
|
||||
</div>
|
||||
<!-- All JavaScript functionality moved to bundle: error-monitoring-dashboard.js -->
|
||||
@@ -0,0 +1,403 @@
|
||||
<?php
|
||||
use App\Core\View;
|
||||
|
||||
// Parse context and server data
|
||||
$contextData = json_decode($error['context_data'] ?? '{}', true) ?: [];
|
||||
$serverData = json_decode($error['server_data'] ?? '{}', true) ?: [];
|
||||
|
||||
// Determine severity styling
|
||||
$severityConfig = [
|
||||
'critical' => ['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'];
|
||||
?>
|
||||
|
||||
<!-- Page Title -->
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="page-title-box d-sm-flex align-items-center justify-content-between">
|
||||
<div>
|
||||
<h4 class="mb-sm-0">Error Details</h4>
|
||||
<div class="mt-2">
|
||||
<nav aria-label="breadcrumb">
|
||||
<ol class="breadcrumb mb-0">
|
||||
<li class="breadcrumb-item"><a href="/dashboard">Dashboard</a></li>
|
||||
<li class="breadcrumb-item"><a href="/error-monitoring/dashboard">Error Monitoring</a></li>
|
||||
<li class="breadcrumb-item"><a href="/error-monitoring/errors">Errors</a></li>
|
||||
<li class="breadcrumb-item active">#<?= $error['id'] ?></li>
|
||||
</ol>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
<div class="page-title-right">
|
||||
<div class="d-flex gap-2">
|
||||
<button class="btn btn-outline-success btn-sm" @click="resolveError()" x-ref="resolveButton">
|
||||
<i class="ri-check-line me-1"></i> Mark as Resolved
|
||||
</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" @click="copyToClipboard('<?= $error['unique_id'] ?>')">
|
||||
<i class="ri-file-copy-line me-1"></i> Copy ID
|
||||
</button>
|
||||
<a href="/error-monitoring/errors" class="btn btn-outline-primary btn-sm">
|
||||
<i class="ri-arrow-left-line me-1"></i> Back to List
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error Overview Card -->
|
||||
<div class="row" x-data="errorMonitoringDetail()" data-error-id="<?= $error['id'] ?>" data-unique-id="<?= $error['unique_id'] ?>">
|
||||
<div class="col-12">
|
||||
<div class="card bg-<?= $severity['color'] ?>-subtle border-<?= $severity['color'] ?>">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-start">
|
||||
<div class="avatar-lg bg-<?= $severity['color'] ?> text-white rounded me-4">
|
||||
<span class="avatar-title fs-24">
|
||||
<i class="<?= $severity['icon'] ?>"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-grow-1">
|
||||
<div class="d-flex align-items-center mb-2">
|
||||
<h4 class="mb-0 me-3"><?= $severity['label'] ?> Error</h4>
|
||||
<span class="badge bg-<?= $severity['color'] ?> fs-12"><?= strtoupper($error['severity']) ?></span>
|
||||
<?php if ($error['occurrences'] > 1): ?>
|
||||
<span class="badge bg-danger ms-2 fs-12">
|
||||
<i class="ri-repeat-line me-1"></i><?= $error['occurrences'] ?>x
|
||||
</span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<h5 class="text-<?= $severity['color'] ?> mb-3"><?= htmlspecialchars($error['message']) ?></h5>
|
||||
<div class="row g-3">
|
||||
<div class="col-md-3">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="ri-file-code-line text-muted me-2"></i>
|
||||
<div>
|
||||
<div class="fs-13 text-muted">File</div>
|
||||
<code class="fs-12"><?= basename($error['file_path']) ?></code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="ri-hashtag text-muted me-2"></i>
|
||||
<div>
|
||||
<div class="fs-13 text-muted">Line</div>
|
||||
<span class="fw-medium"><?= $error['line_number'] ?></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="ri-time-line text-muted me-2"></i>
|
||||
<div>
|
||||
<div class="fs-13 text-muted">First Seen</div>
|
||||
<span class="fw-medium"><?= date('M j, Y H:i', strtotime($error['first_seen'])) ?></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="ri-fingerprint-line text-muted me-2"></i>
|
||||
<div>
|
||||
<div class="fs-13 text-muted">Unique ID</div>
|
||||
<code class="fs-12"><?= $error['unique_id'] ?></code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Content -->
|
||||
<div class="row">
|
||||
<!-- Left Column - Main Info -->
|
||||
<div class="col-xl-8">
|
||||
<!-- Stack Trace -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">
|
||||
<i class="ri-stack-line text-primary me-2"></i>
|
||||
Stack Trace
|
||||
</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="bg-light rounded p-3">
|
||||
<pre class="mb-0 fs-13 text-dark" style="max-height: 400px; overflow-y: auto;"><code><?= htmlspecialchars($error['stack_trace']) ?></code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Request Information -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">
|
||||
<i class="ri-global-line text-success me-2"></i>
|
||||
Request Information
|
||||
</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-4">
|
||||
<div class="col-md-6">
|
||||
<div class="border rounded p-3 h-100">
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="avatar-sm bg-primary-subtle rounded me-3">
|
||||
<span class="avatar-title text-primary">
|
||||
<i class="ri-links-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<h6 class="mb-1">Request Details</h6>
|
||||
<p class="text-muted mb-0 fs-13">HTTP request information</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="vstack gap-2">
|
||||
<div class="d-flex justify-content-between">
|
||||
<span class="text-muted fs-13">URL:</span>
|
||||
<span class="fw-medium fs-13"><?= $error['url'] ?? 'N/A' ?></span>
|
||||
</div>
|
||||
<div class="d-flex justify-content-between">
|
||||
<span class="text-muted fs-13">Method:</span>
|
||||
<span class="badge bg-secondary-subtle text-secondary"><?= $error['http_method'] ?? 'N/A' ?></span>
|
||||
</div>
|
||||
<div class="d-flex justify-content-between">
|
||||
<span class="text-muted fs-13">Request ID:</span>
|
||||
<code class="fs-12"><?= $error['request_id'] ?? 'N/A' ?></code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="border rounded p-3 h-100">
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="avatar-sm bg-info-subtle rounded me-3">
|
||||
<span class="avatar-title text-info">
|
||||
<i class="ri-user-location-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<h6 class="mb-1">Client Information</h6>
|
||||
<p class="text-muted mb-0 fs-13">User and session data</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="vstack gap-2">
|
||||
<div class="d-flex justify-content-between">
|
||||
<span class="text-muted fs-13">IP Address:</span>
|
||||
<span class="fw-medium fs-13"><?= $error['ip_address'] ?? 'N/A' ?></span>
|
||||
</div>
|
||||
<div class="d-flex justify-content-between">
|
||||
<span class="text-muted fs-13">User ID:</span>
|
||||
<span class="fw-medium fs-13"><?= $error['user_id'] ?: 'Guest' ?></span>
|
||||
</div>
|
||||
<div class="d-flex justify-content-between">
|
||||
<span class="text-muted fs-13">Session:</span>
|
||||
<code class="fs-12"><?= $error['session_id'] ? substr($error['session_id'], 0, 12) . '...' : 'N/A' ?></code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Context Data -->
|
||||
<?php if (!empty($contextData)): ?>
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">
|
||||
<i class="ri-database-2-line text-warning me-2"></i>
|
||||
Context Data
|
||||
</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="accordion" id="contextAccordion">
|
||||
<?php foreach ($contextData as $key => $value): ?>
|
||||
<div class="accordion-item">
|
||||
<h2 class="accordion-header" id="context<?= md5($key) ?>">
|
||||
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
|
||||
data-bs-target="#collapse<?= md5($key) ?>" aria-expanded="false">
|
||||
<i class="ri-braces-line me-2"></i>
|
||||
<?= htmlspecialchars($key) ?>
|
||||
</button>
|
||||
</h2>
|
||||
<div id="collapse<?= md5($key) ?>" class="accordion-collapse collapse"
|
||||
data-bs-parent="#contextAccordion">
|
||||
<div class="accordion-body">
|
||||
<pre class="bg-light rounded p-3 mb-0"><code><?= htmlspecialchars(is_array($value) ? json_encode($value, JSON_PRETTY_PRINT) : $value) ?></code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<!-- Right Column - Sidebar Info -->
|
||||
<div class="col-xl-4">
|
||||
<!-- Quick Actions -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">Quick Actions</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="d-grid gap-2">
|
||||
<button class="btn btn-success" @click="resolveError()" :disabled="resolving">
|
||||
<i class="ri-check-line me-2"></i>Mark as Resolved
|
||||
</button>
|
||||
<button class="btn btn-outline-secondary" @click="copyToClipboard('<?= $error['unique_id'] ?>')">
|
||||
<i class="ri-file-copy-line me-2"></i>Copy Error ID
|
||||
</button>
|
||||
<button class="btn btn-outline-warning" @click="showError('Ignore functionality will be implemented soon')">
|
||||
<i class="ri-eye-off-line me-2"></i>Ignore Error
|
||||
</button>
|
||||
<hr>
|
||||
<a href="/error-monitoring/errors?file=<?= urlencode(basename($error['file_path'])) ?>" class="btn btn-outline-info">
|
||||
<i class="ri-search-line me-2"></i>Similar Errors
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error Statistics -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">Error Statistics</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-6">
|
||||
<div class="text-center p-3 bg-primary-subtle rounded">
|
||||
<h4 class="mb-1 text-primary"><?= $error['occurrences'] ?></h4>
|
||||
<p class="text-muted mb-0 fs-13">Occurrences</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<div class="text-center p-3 bg-info-subtle rounded">
|
||||
<h4 class="mb-1 text-info"><?= $error['project_name'] ?></h4>
|
||||
<p class="text-muted mb-0 fs-13">Project</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<hr>
|
||||
<div class="vstack gap-3">
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted fs-13">First Seen:</span>
|
||||
<span class="fw-medium fs-13"><?= date('M j, H:i', strtotime($error['first_seen'])) ?></span>
|
||||
</div>
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted fs-13">Last Seen:</span>
|
||||
<span class="fw-medium fs-13"><?= date('M j, H:i', strtotime($error['last_seen'])) ?></span>
|
||||
</div>
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted fs-13">Status:</span>
|
||||
<span class="badge bg-<?= $error['status'] === 'resolved' ? 'success' : 'warning' ?>-subtle text-<?= $error['status'] === 'resolved' ? 'success' : 'warning' ?>">
|
||||
<?= ucfirst($error['status']) ?>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Environment Info -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">Environment</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="vstack gap-3">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-xs bg-success-subtle rounded me-3">
|
||||
<span class="avatar-title text-success fs-16">
|
||||
<i class="ri-settings-2-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<div class="fs-13 text-muted">Environment</div>
|
||||
<span class="badge bg-<?= $error['environment'] === 'production' ? 'danger' : 'warning' ?>-subtle text-<?= $error['environment'] === 'production' ? 'danger' : 'warning' ?>">
|
||||
<?= strtoupper($error['environment']) ?>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($contextData['php_version'])): ?>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-xs bg-primary-subtle rounded me-3">
|
||||
<span class="avatar-title text-primary fs-16">
|
||||
<i class="ri-code-s-slash-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<div class="fs-13 text-muted">PHP Version</div>
|
||||
<span class="fw-medium"><?= $contextData['php_version'] ?></span>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (!empty($contextData['memory_usage'])): ?>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-xs bg-warning-subtle rounded me-3">
|
||||
<span class="avatar-title text-warning fs-16">
|
||||
<i class="ri-dashboard-3-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<div class="fs-13 text-muted">Memory Usage</div>
|
||||
<span class="fw-medium"><?= number_format($contextData['memory_usage'] / 1024 / 1024, 2) ?> MB</span>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (!empty($contextData['server_load'])): ?>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-xs bg-info-subtle rounded me-3">
|
||||
<span class="avatar-title text-info fs-16">
|
||||
<i class="ri-cpu-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<div class="fs-13 text-muted">Server Load</div>
|
||||
<span class="fw-medium"><?= number_format($contextData['server_load'], 2) ?></span>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- User Agent -->
|
||||
<?php if ($error['user_agent']): ?>
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">Browser Information</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-start">
|
||||
<div class="avatar-sm bg-secondary-subtle rounded me-3">
|
||||
<span class="avatar-title text-secondary">
|
||||
<i class="ri-computer-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-grow-1">
|
||||
<h6 class="mb-2">User Agent</h6>
|
||||
<p class="text-muted mb-0 fs-13" style="word-break: break-all;">
|
||||
<?= htmlspecialchars($error['user_agent']) ?>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- All JavaScript functionality moved to bundle: error-monitoring-detail.js -->
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
use App\Core\View;
|
||||
?>
|
||||
|
||||
<!-- Filtros -->
|
||||
<div class="row mb-3">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<form id="filters-form" class="row g-3">
|
||||
<div class="col-md-3">
|
||||
<label for="severity-filter" class="form-label">Severity</label>
|
||||
<select class="form-select" id="severity-filter" name="severity">
|
||||
<option value="">All Severities</option>
|
||||
<option value="critical">Critical</option>
|
||||
<option value="error">Error</option>
|
||||
<option value="warning">Warning</option>
|
||||
<option value="info">Info</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="status-filter" class="form-label">Status</label>
|
||||
<select class="form-select" id="status-filter" name="status">
|
||||
<option value="">All Status</option>
|
||||
<option value="open">Open</option>
|
||||
<option value="resolved">Resolved</option>
|
||||
<option value="ignored">Ignored</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="file-filter" class="form-label">File</label>
|
||||
<input type="text" class="form-control" id="file-filter" name="file" placeholder="Enter file name...">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="project-filter" class="form-label">Project</label>
|
||||
<select class="form-select" id="project-filter" name="project">
|
||||
<option value="">All Projects</option>
|
||||
<option value="CRM">CRM</option>
|
||||
<option value="Betzoo">Betzoo</option>
|
||||
<option value="Dashboard">Dashboard</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<button type="submit" class="btn btn-primary">
|
||||
<i class="ri-filter-line me-1"></i> Apply Filters
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline-secondary ms-2" onclick="clearFilters()">
|
||||
<i class="ri-filter-off-line me-1"></i> Clear All
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Lista de Erros -->
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<div class="d-flex align-items-center">
|
||||
<h4 class="card-title mb-0 flex-grow-1">
|
||||
Error Logs
|
||||
<div id="active-filters" class="mt-1"></div>
|
||||
</h4>
|
||||
<div class="flex-shrink-0">
|
||||
<button type="button" class="btn btn-primary btn-sm" onclick="refreshErrors()">
|
||||
<i class="ri-refresh-line align-bottom me-1"></i> Refresh
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div id="errors-container">
|
||||
<div class="text-center py-4">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Loading...</span>
|
||||
</div>
|
||||
<p class="mt-2">Loading errors...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
use App\Core\View;
|
||||
?>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="page-title-box d-sm-flex align-items-center justify-content-between">
|
||||
<h4 class="mb-sm-0">Import Error Data</h4>
|
||||
<div class="page-title-right">
|
||||
<ol class="breadcrumb m-0">
|
||||
<li class="breadcrumb-item"><a href="/dashboard">Dashboard</a></li>
|
||||
<li class="breadcrumb-item"><a href="/error-monitoring/dashboard">Error Monitoring</a></li>
|
||||
<li class="breadcrumb-item active">Import</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row" x-data="errorMonitoringImport()">
|
||||
<div class="col-xl-8">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Import Error Reports</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<p class="text-muted">
|
||||
Import error data from external sources. Supported formats: XML (FBI legacy), JSON, and plain log files.
|
||||
</p>
|
||||
|
||||
<!-- Status Message -->
|
||||
<div x-show="message" class="alert alert-info" x-text="message"></div>
|
||||
|
||||
<form id="import-form" method="POST" enctype="multipart/form-data" @submit.prevent="importFile()">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="project-name" class="form-label">Project Name</label>
|
||||
<input type="text" class="form-control" id="project-name" name="project_name"
|
||||
value="CRM" placeholder="Enter project name" required>
|
||||
<div class="form-text">Name of the project these errors belong to</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="import-type" class="form-label">Import Type</label>
|
||||
<select class="form-select" id="import-type" name="import_type">
|
||||
<option value="auto">Auto-detect</option>
|
||||
<option value="xml">XML (FBI Legacy)</option>
|
||||
<option value="json">JSON</option>
|
||||
<option value="log">Log File</option>
|
||||
</select>
|
||||
<div class="form-text">File format detection (auto-detect recommended)</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="error-file" class="form-label">Error Data File</label>
|
||||
<input type="file" class="form-control" id="error-file" name="error_file"
|
||||
accept=".xml,.json,.log,.txt" required @change="onFileSelect()">
|
||||
<div class="form-text">
|
||||
Upload XML, JSON, or log files containing error data. Maximum file size: 10MB.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="overwrite-duplicates"
|
||||
name="overwrite_duplicates" value="1">
|
||||
<label class="form-check-label" for="overwrite-duplicates">
|
||||
Overwrite duplicate errors
|
||||
</label>
|
||||
<div class="form-text">
|
||||
If checked, existing errors with the same unique ID will be updated
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex gap-2">
|
||||
<button type="submit" class="btn btn-primary" :disabled="importing">
|
||||
<i class="ri-upload-line me-1" x-show="!importing"></i>
|
||||
<i class="ri-loader-2-line me-1 spinner-border spinner-border-sm" x-show="importing"></i>
|
||||
<span x-text="importing ? 'Importing...' : 'Import Data'"></span>
|
||||
</button>
|
||||
<button type="reset" class="btn btn-outline-secondary">
|
||||
<i class="ri-refresh-line me-1"></i> Reset Form
|
||||
</button>
|
||||
<a href="/error-monitoring/dashboard" class="btn btn-outline-primary">
|
||||
<i class="ri-arrow-left-line me-1"></i> Back to Dashboard
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-4">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Import Guidelines</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-4">
|
||||
<h6 class="fs-14 mb-2">Supported Formats</h6>
|
||||
<ul class="list-unstyled mb-0">
|
||||
<li class="py-1">
|
||||
<i class="ri-file-code-line text-primary me-2"></i>
|
||||
<strong>XML</strong> - FBI legacy format
|
||||
</li>
|
||||
<li class="py-1">
|
||||
<i class="ri-braces-line text-success me-2"></i>
|
||||
<strong>JSON</strong> - Structured error data
|
||||
</li>
|
||||
<li class="py-1">
|
||||
<i class="ri-file-text-line text-info me-2"></i>
|
||||
<strong>LOG</strong> - Plain text log files
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<h6 class="fs-14 mb-2">File Requirements</h6>
|
||||
<ul class="list-unstyled mb-0 text-muted fs-13">
|
||||
<li class="py-1">• Maximum file size: 10MB</li>
|
||||
<li class="py-1">• UTF-8 encoding recommended</li>
|
||||
<li class="py-1">• Well-formed XML/JSON structure</li>
|
||||
<li class="py-1">• Unique error identifiers preferred</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<h6 class="fs-14 mb-2">Import Process</h6>
|
||||
<div class="timeline-sm">
|
||||
<div class="timeline-sm-item">
|
||||
<div class="timeline-sm-marker"></div>
|
||||
<div class="timeline-sm-content">
|
||||
<p class="timeline-sm-title fs-13">File Upload</p>
|
||||
<p class="text-muted fs-12 mb-0">File is uploaded and validated</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="timeline-sm-item">
|
||||
<div class="timeline-sm-marker"></div>
|
||||
<div class="timeline-sm-content">
|
||||
<p class="timeline-sm-title fs-13">Data Processing</p>
|
||||
<p class="text-muted fs-12 mb-0">Errors are parsed and structured</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="timeline-sm-item">
|
||||
<div class="timeline-sm-marker"></div>
|
||||
<div class="timeline-sm-content">
|
||||
<p class="timeline-sm-title fs-13">Database Import</p>
|
||||
<p class="text-muted fs-12 mb-0">Data is stored in error logs</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-info">
|
||||
<h6 class="alert-heading fs-14">
|
||||
<i class="ri-information-line me-1"></i> Pro Tip
|
||||
</h6>
|
||||
<p class="mb-0 fs-13">
|
||||
Use auto-detect for best results. The system will automatically identify
|
||||
the file format and apply the appropriate parser.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Recent Imports</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div id="recent-imports-container">
|
||||
<div class="text-center py-3 text-muted">
|
||||
<i class="ri-file-upload-line fs-24 mb-2"></i>
|
||||
<p class="mb-0 fs-13">No recent imports</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- All JavaScript functionality moved to bundle: error-monitoring-import.js -->
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\ErrorMonitoring\Widgets;
|
||||
|
||||
use App\Core\DatabaseManager;
|
||||
use App\Core\ErrorReporter;
|
||||
|
||||
/**
|
||||
* Error Summary Widget
|
||||
*
|
||||
* Displays error monitoring summary including recent errors, error rates
|
||||
* for the modular dashboard system.
|
||||
*/
|
||||
class ErrorSummaryWidget
|
||||
{
|
||||
private DatabaseManager $db;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->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 '<div class="alert alert-danger">Erro ao carregar resumo de erros</div>';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render widget content
|
||||
*/
|
||||
private function renderContent(array $config): string
|
||||
{
|
||||
$stats = $this->getStats();
|
||||
|
||||
ob_start();
|
||||
?>
|
||||
<div class="row g-3">
|
||||
<div class="col-6">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-danger-subtle text-danger rounded-circle fs-3">
|
||||
<i class="ri-error-warning-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Erros Hoje</p>
|
||||
<div class="d-flex align-items-center mb-0">
|
||||
<h4 class="fs-4 flex-grow-1 mb-0"><?php echo number_format($stats['errors_today']); ?></h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-warning-subtle text-warning rounded-circle fs-3">
|
||||
<i class="ri-alert-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Críticos</p>
|
||||
<div class="d-flex align-items-center mb-0">
|
||||
<h4 class="fs-4 flex-grow-1 mb-0"><?php echo number_format($stats['critical_errors']); ?></h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-success-subtle text-success rounded-circle fs-3">
|
||||
<i class="ri-check-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Resolvidos</p>
|
||||
<div class="d-flex align-items-center mb-0">
|
||||
<h4 class="fs-4 flex-grow-1 mb-0"><?php echo number_format($stats['resolved_errors']); ?></h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-info-subtle text-info rounded-circle fs-3">
|
||||
<i class="ri-percent-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Taxa Sucesso</p>
|
||||
<div class="d-flex align-items-center mb-0">
|
||||
<h4 class="fs-4 flex-grow-1 mb-0"><?php echo $stats['success_rate']; ?>%</h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted">Último erro:</span>
|
||||
<span class="fw-bold text-<?php echo $stats['last_error_severity'] === 'critical' ? 'danger' : 'warning'; ?>">
|
||||
<?php echo $stats['last_error_time']; ?>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get error monitoring statistics
|
||||
*/
|
||||
private function getStats(): array
|
||||
{
|
||||
try {
|
||||
// Get error stats from error_logs table if exists
|
||||
$result = $this->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'
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
/**
|
||||
* ErrorMonitoring Module - Asset Registration
|
||||
*
|
||||
* Register CSS and JS assets specific to the Error Monitoring module
|
||||
*/
|
||||
|
||||
use App\Core\AssetManager;
|
||||
|
||||
$assetManager = AssetManager::getInstance();
|
||||
|
||||
// Register module-specific assets
|
||||
$assetManager->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',
|
||||
],
|
||||
],
|
||||
]);
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
/**
|
||||
* Menu do Módulo Error Monitoring
|
||||
*/
|
||||
|
||||
use App\Core\MenuManager;
|
||||
|
||||
// Menu principal
|
||||
MenuManager::registerMenu('ErrorMonitoring', [
|
||||
'id' => 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
|
||||
],
|
||||
]);
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Error Monitoring Module - Widget Registration
|
||||
*
|
||||
* This file is automatically loaded when the ErrorMonitoring module is detected.
|
||||
* It registers all widgets that this module provides to the dashboard system.
|
||||
*/
|
||||
|
||||
use App\Core\DashboardWidgetManager;
|
||||
|
||||
// Only register widgets if the widget manager is available
|
||||
if (class_exists('App\Core\DashboardWidgetManager')) {
|
||||
$widgetManager = DashboardWidgetManager::getInstance();
|
||||
|
||||
// Register Error Summary Widget
|
||||
$widgetManager->registerWidget(
|
||||
'error-monitoring-summary',
|
||||
'ErrorMonitoring',
|
||||
'Resumo de Erros',
|
||||
'App\\Modules\\ErrorMonitoring\\Widgets\\ErrorSummaryWidget',
|
||||
[
|
||||
'description' => 'Resumo dos erros recentes do sistema',
|
||||
'size' => 'medium',
|
||||
'category' => 'monitoring'
|
||||
]
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user