Files
MoneyFlix/crm/Core/AlertManager.php
1sonhador 9d43854277 feat: Initial MoneyFlix project setup
- Created separate MoneyFlix project directory
- Copied Node.js redirector from production server
- Added CRM PHP code (Redirects module, Core classes, Config, Routes, Views)
- Created comprehensive documentation (README_MONEYFLIX.md)
- Added sync script to keep CRM code updated (sync-from-crm.sh)
- Configured .gitignore for Node.js and PHP
- Set up proper project structure for multi-client isolation

This separates MoneyFlix from the main CRM to avoid confusion
between different client systems and provides a dedicated
environment for MoneyFlix-specific development and maintenance.
2025-10-03 12:09:41 +01:00

487 lines
14 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Core;
use Exception;
use Visus\Cuid2\Cuid2;
/**
* Sistema de Alertas Proativo
*
* Monitoriza a aplicação e envia alertas quando detecta problemas
* ou condições que requerem atenção imediata.
*/
class AlertManager
{
private Logger $logger;
private array $config;
private array $thresholds;
private array $alertHistory;
public function __construct()
{
$this->logger = new Logger();
$this->config = $this->loadConfig();
$this->thresholds = $this->config['thresholds'] ?? [];
$this->alertHistory = [];
}
/**
* Carregar configuração de alertas
*/
private function loadConfig(): array
{
$configFile = __DIR__ . '/../../config/alerts.php';
if (file_exists($configFile)) {
return require $configFile;
}
// Configuração padrão
return [
'enabled' => true,
'email' => [
'enabled' => false,
'to' => '[email protected]',
'from' => '[email protected]'
],
'thresholds' => [
'performance' => [
'response_time' => 2.0, // segundos
'memory_usage' => 80, // percentagem
'disk_usage' => 85 // percentagem
],
'security' => [
'failed_logins' => 5, // tentativas
'suspicious_ips' => 3 // IPs diferentes
],
'errors' => [
'critical_errors' => 3, // erros por hora
'database_errors' => 2 // erros por hora
]
],
'cooldown' => [
'performance' => 300, // 5 minutos
'security' => 600, // 10 minutos
'errors' => 1800 // 30 minutos
]
];
}
/**
* Verificar performance da aplicação
*/
public function checkPerformance(float $responseTime, ?float $memoryUsage = null): void
{
if (!$this->config['enabled']) return;
$threshold = $this->thresholds['performance']['response_time'] ?? 2.0;
if ($responseTime > $threshold) {
$this->triggerAlert('performance', 'response_time', [
'current' => $responseTime,
'threshold' => $threshold,
'message' => "Tempo de resposta lento: {$responseTime}s (limite: {$threshold}s)"
]);
}
// Verificar uso de memória se fornecido
if ($memoryUsage !== null) {
$memoryThreshold = $this->thresholds['performance']['memory_usage'] ?? 80;
if ($memoryUsage > $memoryThreshold) {
$this->triggerAlert('performance', 'memory_usage', [
'current' => $memoryUsage,
'threshold' => $memoryThreshold,
'message' => "Uso de memória alto: {$memoryUsage}% (limite: {$memoryThreshold}%)"
]);
}
}
}
/**
* Verificar segurança
*/
public function checkSecurity(string $event, array $context = []): void
{
if (!$this->config['enabled']) return;
switch ($event) {
case 'failed_login':
$this->checkFailedLogins($context);
break;
case 'suspicious_activity':
$this->checkSuspiciousActivity($context);
break;
case 'unauthorized_access':
$this->triggerAlert('security', 'unauthorized_access', [
'ip' => $context['ip'] ?? 'unknown',
'endpoint' => $context['endpoint'] ?? 'unknown',
'message' => 'Tentativa de acesso não autorizado'
]);
break;
}
}
/**
* Verificar tentativas de login falhadas
*/
private function checkFailedLogins(array $context): void
{
$ip = $context['ip'] ?? 'unknown';
$threshold = $this->thresholds['security']['failed_logins'] ?? 5;
// Contar tentativas falhadas por IP (simplificado)
$failedLogins = $this->getFailedLoginsCount($ip);
if ($failedLogins >= $threshold) {
$this->triggerAlert('security', 'failed_logins', [
'ip' => $ip,
'count' => $failedLogins,
'threshold' => $threshold,
'message' => "Múltiplas tentativas de login falhadas do IP {$ip}: {$failedLogins} tentativas"
]);
}
}
/**
* Verificar atividade suspeita
*/
private function checkSuspiciousActivity(array $context): void
{
$ip = $context['ip'] ?? 'unknown';
$threshold = $this->thresholds['security']['suspicious_ips'] ?? 3;
// Verificar se o IP está na lista de suspeitos
$suspiciousCount = $this->getSuspiciousIPCount($ip);
if ($suspiciousCount >= $threshold) {
$this->triggerAlert('security', 'suspicious_activity', [
'ip' => $ip,
'count' => $suspiciousCount,
'threshold' => $threshold,
'message' => "Atividade suspeita detectada do IP {$ip}"
]);
}
}
/**
* Verificar erros críticos
*/
public function checkErrors(string $errorType, array $context = []): void
{
if (!$this->config['enabled']) return;
$threshold = $this->thresholds['errors'][$errorType] ?? 3;
$errorCount = $this->getErrorCount($errorType);
if ($errorCount >= $threshold) {
$this->triggerAlert('errors', $errorType, [
'count' => $errorCount,
'threshold' => $threshold,
'message' => "Múltiplos erros {$errorType}: {$errorCount} erros (limite: {$threshold})",
'context' => $context
]);
}
}
/**
* Verificar saúde do sistema
*/
public function checkSystemHealth(): void
{
if (!$this->config['enabled']) return;
// Verificar espaço em disco
$diskUsage = $this->getDiskUsage();
$diskThreshold = $this->thresholds['performance']['disk_usage'] ?? 85;
if ($diskUsage > $diskThreshold) {
$this->triggerAlert('performance', 'disk_usage', [
'current' => $diskUsage,
'threshold' => $diskThreshold,
'message' => "Espaço em disco crítico: {$diskUsage}% (limite: {$diskThreshold}%)"
]);
}
// Verificar conectividade da base de dados
$this->checkDatabaseConnection();
}
/**
* Verificar conectividade da base de dados
*/
private function checkDatabaseConnection(): void
{
try {
$pdo = \App\Core\DatabaseManager::getConnection();
$stmt = $pdo->query('SELECT 1');
$stmt->fetch();
} catch (\Exception $e) {
$this->triggerAlert('errors', 'database_connection', [
'error' => $e->getMessage(),
'message' => 'Falha na conectividade da base de dados'
]);
}
}
/**
* Obter uso de disco
*/
private function getDiskUsage(): float
{
$path = __DIR__ . '/../../';
$total = disk_total_space($path);
$free = disk_free_space($path);
return round((($total - $free) / $total) * 100, 2);
}
/**
* Obter contagem de tentativas de login falhadas
*/
private function getFailedLoginsCount(string $ip): int
{
// Implementação simplificada - em produção usar Redis ou base de dados
$cacheFile = __DIR__ . '/../../storage/cache/failed_logins.json';
if (file_exists($cacheFile)) {
$data = json_decode(file_get_contents($cacheFile), true);
return $data[$ip] ?? 0;
}
return 0;
}
/**
* Obter contagem de IPs suspeitos
*/
private function getSuspiciousIPCount(string $ip): int
{
// Implementação simplificada
$cacheFile = __DIR__ . '/../../storage/cache/suspicious_ips.json';
if (file_exists($cacheFile)) {
$data = json_decode(file_get_contents($cacheFile), true);
return $data[$ip] ?? 0;
}
return 0;
}
/**
* Obter contagem de erros
*/
private function getErrorCount(string $errorType): int
{
// Implementação simplificada
$cacheFile = __DIR__ . '/../../storage/cache/error_counts.json';
if (file_exists($cacheFile)) {
$data = json_decode(file_get_contents($cacheFile), true);
return $data[$errorType] ?? 0;
}
return 0;
}
/**
* Criar alerta manual
*/
public function createAlert(string $type, string $title, string $message, string $priority = 'medium', array $context = []): void
{
$alert = [
'id' => (string) new \Visus\Cuid2\Cuid2(),
'category' => 'manual',
'type' => $type,
'title' => $title,
'message' => $message,
'priority' => $priority,
'timestamp' => time(),
'data' => $context,
'context' => $context
];
// Log do alerta
$this->logger->alert($message, $alert);
// Guardar no histórico
$alertKey = "manual_{$type}";
$this->alertHistory[$alertKey] = $alert;
// Enviar notificação se configurado
if ($this->config['email']['enabled']) {
$this->sendEmailAlert($alert);
}
// Guardar alerta em ficheiro
$this->saveAlert($alert);
}
/**
* Disparar alerta
*/
private function triggerAlert(string $category, string $type, array $data): void
{
$alertKey = "{$category}_{$type}";
$cooldown = $this->config['cooldown'][$category] ?? 300;
// Verificar cooldown
if ($this->isInCooldown($alertKey, $cooldown)) {
return;
}
$alert = [
'id' => (string) new \Visus\Cuid2\Cuid2(),
'category' => $category,
'type' => $type,
'timestamp' => time(),
'data' => $data,
'message' => $data['message'] ?? 'Alerta disparado'
];
// Log do alerta
$this->logger->alert($alert['message'], $alert);
// Guardar no histórico
$this->alertHistory[$alertKey] = $alert;
// Enviar notificação se configurado
if ($this->config['email']['enabled']) {
$this->sendEmailAlert($alert);
}
// Guardar alerta em ficheiro
$this->saveAlert($alert);
}
/**
* Verificar se está em cooldown
*/
private function isInCooldown(string $alertKey, int $cooldown): bool
{
if (!isset($this->alertHistory[$alertKey])) {
return false;
}
$lastAlert = $this->alertHistory[$alertKey];
return (time() - $lastAlert['timestamp']) < $cooldown;
}
/**
* Enviar alerta por email
*/
private function sendEmailAlert(array $alert): void
{
$to = $this->config['email']['to'];
$from = $this->config['email']['from'];
$subject = "🚨 Alerta BitReport CRM - {$alert['category']}";
$message = "
<h2>🚨 Alerta do Sistema BitReport CRM</h2>
<p><strong>Categoria:</strong> {$alert['category']}</p>
<p><strong>Tipo:</strong> {$alert['type']}</p>
<p><strong>Mensagem:</strong> {$alert['message']}</p>
<p><strong>Data/Hora:</strong> " . date('Y-m-d H:i:s', $alert['timestamp']) . "</p>
<h3>Detalhes:</h3>
<pre>" . json_encode($alert['data'], JSON_PRETTY_PRINT) . "</pre>
<hr>
<p><em>Este é um alerta automático do sistema BitReport CRM.</em></p>
";
$headers = [
'MIME-Version: 1.0',
'Content-type: text/html; charset=utf-8',
'From: ' . $from,
'Reply-To: ' . $from,
'X-Mailer: PHP/' . phpversion()
];
mail($to, $subject, $message, implode("\r\n", $headers));
}
/**
* Guardar alerta em ficheiro
*/
private function saveAlert(array $alert): void
{
$alertsFile = __DIR__ . '/../../storage/logs/alerts.json';
$alerts = [];
if (file_exists($alertsFile)) {
$alerts = json_decode(file_get_contents($alertsFile), true) ?? [];
}
$alerts[] = $alert;
// Manter apenas últimos 100 alertas
if (count($alerts) > 100) {
$alerts = array_slice($alerts, -100);
}
file_put_contents($alertsFile, json_encode($alerts, JSON_PRETTY_PRINT));
}
/**
* Obter histórico de alertas
*/
public function getAlertHistory(): array
{
$alertsFile = __DIR__ . '/../../storage/logs/alerts.json';
if (file_exists($alertsFile)) {
return json_decode(file_get_contents($alertsFile), true) ?? [];
}
return [];
}
/**
* Obter estatísticas de alertas
*/
public function getAlertStats(): array
{
$alerts = $this->getAlertHistory();
$stats = [
'total' => count($alerts),
'by_category' => [],
'by_type' => [],
'recent' => []
];
foreach ($alerts as $alert) {
$category = $alert['category'];
$type = $alert['type'];
$stats['by_category'][$category] = ($stats['by_category'][$category] ?? 0) + 1;
$stats['by_type'][$type] = ($stats['by_type'][$type] ?? 0) + 1;
}
// Últimos 10 alertas
$stats['recent'] = array_slice($alerts, -10);
return $stats;
}
/**
* Limpar alertas antigos
*/
public function cleanupAlerts(int $daysToKeep = 30): int
{
$alerts = $this->getAlertHistory();
$cutoff = time() - ($daysToKeep * 24 * 60 * 60);
$originalCount = count($alerts);
$alerts = array_filter($alerts, function($alert) use ($cutoff) {
return $alert['timestamp'] > $cutoff;
});
$alertsFile = __DIR__ . '/../../storage/logs/alerts.json';
file_put_contents($alertsFile, json_encode(array_values($alerts), JSON_PRETTY_PRINT));
return $originalCount - count($alerts);
}
}