import React, { useState, useEffect } from 'react'; import { useAuth } from '../../contexts/AuthContext'; import { Activity, Clock, CheckCircle, XCircle, AlertTriangle, Users, BarChart3, TrendingUp } from 'lucide-react'; import PageLoader from '../../components/common/PageLoader'; import { logger } from '../../utils/logger'; import { useTranslation } from 'react-i18next'; interface TenantMonitoringStats { tenantId: string; tenantName: string; totalSchedules: number; activeSchedules: number; inactiveSchedules: number; totalExecutions: number; successfulExecutions: number; failedExecutions: number; lastExecution?: string; nextExecution?: string; averageExecutionsPerSchedule: number; schedulesByFrequency: { minute: number; daily: number; weekly: number; monthly: number; }; } interface GlobalStats { totalTenants: number; totalSchedules: number; totalActiveSchedules: number; totalExecutions: number; averageSchedulesPerTenant: number; } interface MonitoringStatistics { tenantStats: TenantMonitoringStats[]; globalStats: GlobalStats; } const TenantMonitoringStatusPage: React.FC = () => { const { token, user } = useAuth(); const { t, i18n } = useTranslation(); const locale = i18n.language || 'es-ES'; const [statistics, setStatistics] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const fetchStatistics = async () => { try { setLoading(true); setError(null); if (!token) { throw new Error(t('superAdminMonitoring.errors.authMissing')); } if (!user || user.role !== 'superuser') { throw new Error(t('superAdminMonitoring.errors.accessDenied')); } logger.log('Fetching monitoring statistics with token:', token?.substring(0, 10) + '...'); const response = await fetch('/api/monitoring/statistics', { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' } }); logger.log('Response status:', response.status, response.statusText); if (!response.ok) { const errorText = await response.text(); logger.error('Error response:', errorText); throw new Error(t('superAdminMonitoring.errors.fetchFailed', { status: response.status, statusText: response.statusText })); } const data = await response.json(); logger.log('Received data:', data); setStatistics(data); } catch (err) { logger.error('Error fetching monitoring statistics:', err); setError(err instanceof Error ? err.message : t('superAdminMonitoring.errors.loadStats')); } finally { setLoading(false); } }; useEffect(() => { fetchStatistics(); }, [token]); const getStatusColor = (activeSchedules: number, totalSchedules: number) => { if (totalSchedules === 0) return 'text-gray-500'; const percentage = (activeSchedules / totalSchedules) * 100; if (percentage >= 80) return 'text-green-500'; if (percentage >= 50) return 'text-yellow-500'; return 'text-red-500'; }; const getStatusIcon = (activeSchedules: number, totalSchedules: number) => { if (totalSchedules === 0) return ; const percentage = (activeSchedules / totalSchedules) * 100; if (percentage >= 80) return ; if (percentage >= 50) return ; return ; }; const formatDate = (dateString?: string) => { if (!dateString) return t('superAdminMonitoring.date.never'); return new Date(dateString).toLocaleDateString(locale, { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); }; const getFrequencyBadge = (frequency: string, count: number) => { if (count === 0) return null; const colors = { minute: 'bg-red-100 text-red-800', daily: 'bg-blue-100 text-blue-800', weekly: 'bg-green-100 text-green-800', monthly: 'bg-purple-100 text-purple-800' }; const labels = { minute: t('superAdminMonitoring.frequency.min'), daily: t('superAdminMonitoring.frequency.daily'), weekly: t('superAdminMonitoring.frequency.weekly'), monthly: t('superAdminMonitoring.frequency.monthly') }; return ( {labels[frequency as keyof typeof labels]}: {count} ); }; if (loading) { return ; } if (error) { return (
{error}
); } if (!statistics) { return (
{t('superAdminMonitoring.messages.noData')}
); } return (
{/* Header */}

{t('superAdminMonitoring.title')}

{t('superAdminMonitoring.subtitle')}

{/* Global Statistics Cards */}

{t('superAdminMonitoring.stats.totalTenants')}

{statistics.globalStats.totalTenants}

{t('superAdminMonitoring.stats.totalSchedules')}

{statistics.globalStats.totalSchedules}

{t('superAdminMonitoring.stats.activeSchedules')}

{statistics.globalStats.totalActiveSchedules}

{t('superAdminMonitoring.stats.totalExecutions')}

{statistics.globalStats.totalExecutions}

{t('superAdminMonitoring.stats.averagePerTenant')}

{statistics.globalStats.averageSchedulesPerTenant}

{/* Tenant Statistics Table */}

{t('superAdminMonitoring.sections.tenantDetail')}

{statistics.tenantStats.length === 0 ? ( ) : ( statistics.tenantStats.map((tenant) => ( )) )}
{t('superAdminMonitoring.table.columns.tenant')} {t('superAdminMonitoring.table.columns.status')} {t('superAdminMonitoring.table.columns.schedules')} {t('superAdminMonitoring.table.columns.executions')} {t('superAdminMonitoring.table.columns.frequencies')} {t('superAdminMonitoring.table.columns.lastExecution')} {t('superAdminMonitoring.table.columns.nextExecution')}

{t('superAdminMonitoring.messages.noMonitoringConfigured')}

{t('superAdminMonitoring.messages.noMonitoringFound')}

{tenant.tenantName}
{t('superAdminMonitoring.labels.id')}: {tenant.tenantId.substring(0, 8)}...
{getStatusIcon(tenant.activeSchedules, tenant.totalSchedules)} {tenant.totalSchedules === 0 ? t('superAdminMonitoring.status.noSchedules') : tenant.activeSchedules === tenant.totalSchedules ? t('superAdminMonitoring.status.allActive') : tenant.activeSchedules === 0 ? t('superAdminMonitoring.status.allInactive') : t('superAdminMonitoring.status.activeCount', { active: tenant.activeSchedules, total: tenant.totalSchedules })}
{t('superAdminMonitoring.labels.totals')}: {tenant.totalSchedules}
{t('superAdminMonitoring.labels.active')}: {tenant.activeSchedules} | {t('superAdminMonitoring.labels.inactive')}: {tenant.inactiveSchedules}
{t('superAdminMonitoring.labels.totals')}: {tenant.totalExecutions}
✓ {tenant.successfulExecutions} | ✗ {tenant.failedExecutions}
{t('superAdminMonitoring.labels.average')}: {tenant.averageExecutionsPerSchedule}{t('superAdminMonitoring.labels.perSchedule')}
{getFrequencyBadge('minute', tenant.schedulesByFrequency.minute)} {getFrequencyBadge('daily', tenant.schedulesByFrequency.daily)} {getFrequencyBadge('weekly', tenant.schedulesByFrequency.weekly)} {getFrequencyBadge('monthly', tenant.schedulesByFrequency.monthly)} {tenant.totalSchedules === 0 && ( - )}
{formatDate(tenant.lastExecution)}
{formatDate(tenant.nextExecution)}
{/* Refresh Button */}
); }; export default TenantMonitoringStatusPage;