'use client'; import React, { useState, useEffect } from 'react'; import { useRouter } from 'next/navigation'; import Header from '@/components/Header'; import { useLocale } from '@/lib/i18n/LocaleContext'; import { useUser } from '@/lib/auth/UserContext'; import styles from './page.module.css'; interface AuditLog { id: number; userId: number; action: 'CREATE' | 'UPDATE' | 'DELETE' | 'APPROVE' | 'REJECT' | 'LOGIN'; targetTable: string; targetId: number; previousValue: any; newValue: any; ipAddress: string | null; createdAt: string; user: { username: string; email: string; role: string; }; } export default function AuditLogsPage() { const router = useRouter(); const { t, locale } = useLocale(); const { role, isLoading: authLoading } = useUser(); const [logs, setLogs] = useState([]); const [isLoading, setIsLoading] = useState(true); const [selectedLog, setSelectedLog] = useState(null); const fetchLogs = async () => { setIsLoading(true); try { const res = await fetch('/api/audit-logs'); if (res.ok) { const data = await res.json(); setLogs(data.logs || []); } } catch (err) { console.error('Failed to fetch audit logs', err); } finally { setIsLoading(false); } }; useEffect(() => { if (!authLoading && role !== 'admin') { router.push('/unauthorized'); } }, [role, authLoading, router]); useEffect(() => { if (role === 'admin') { fetchLogs(); } }, [role]); const handleRowClick = (log: AuditLog) => { setSelectedLog(log); }; if (authLoading || (role !== 'admin' && role !== null)) { return
Verificando credenciales...
; } if (role !== 'admin') { return null; // Redirecting... } return (

{t('audit.title')}

{/* Audit Logs Table */}
{isLoading ? (
Cargando registros...
) : logs.length === 0 ? (
{t('audit.empty')}
) : ( {logs.map((log) => ( handleRowClick(log)} className={`${styles.tr} ${selectedLog?.id === log.id ? styles.trSelected : ''}`} data-audit-id={log.id} > ))}
{t('audit.timestamp')} {t('audit.actor')} {t('audit.action')} {t('audit.target_table')} ID {t('audit.ip_address')}
{new Date(log.createdAt).toLocaleString(locale === 'es' ? 'es-CO' : 'en-US')}
{log.user.username}
{log.user.role}
{log.action} {log.targetTable} {log.targetId} {log.ipAddress || '-'}
)}
{/* Details Side Panel */}

{t('audit.details')}

{selectedLog ? (
ID: {selectedLog.id}
Actor: {selectedLog.user.username} ({selectedLog.user.email})
Acción: {selectedLog.action}
Tabla: {selectedLog.targetTable} (ID: {selectedLog.targetId})
Fecha: {new Date(selectedLog.createdAt).toLocaleString()}
IP: {selectedLog.ipAddress || '-'}

{t('audit.diff_panel')}

{t('audit.previous')} {selectedLog.previousValue ? (
                        {JSON.stringify(selectedLog.previousValue, null, 2)}
                      
) : (
{t('audit.no_diff')}
)}
{t('audit.new')} {selectedLog.newValue ? (
                        {JSON.stringify(selectedLog.newValue, null, 2)}
                      
) : (
{t('audit.no_diff')}
)}
) : (
Seleccione una fila para ver el JSON Diff
)}
); }