Init Commit
This commit is contained in:
239
frontend/src/components/Configuracion/ConfiguracionAccesos.tsx
Normal file
239
frontend/src/components/Configuracion/ConfiguracionAccesos.tsx
Normal file
@@ -0,0 +1,239 @@
|
||||
import { useState } from 'react';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { Database, FolderOpen, Loader2, Info, AlertTriangle } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { configuracionApi } from '../../services/api';
|
||||
import type { Configuracion } from '../../types';
|
||||
import { Save } from 'lucide-react';
|
||||
|
||||
interface ConfiguracionAccesosProps {
|
||||
configuracion: Configuracion;
|
||||
onChange: (updates: Partial<Configuracion>) => void;
|
||||
onSave: () => void; // Nuevo prop
|
||||
isSaving: boolean; // Nuevo prop
|
||||
}
|
||||
|
||||
export default function ConfiguracionAccesos({ configuracion, onChange, onSave, isSaving }: ConfiguracionAccesosProps) {
|
||||
const [probandoSQL, setProbandoSQL] = useState(false);
|
||||
|
||||
const probarSQLMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
configuracionApi.probarConexionSQL({
|
||||
servidor: configuracion.dbServidor,
|
||||
nombreDB: configuracion.dbNombre,
|
||||
usuario: configuracion.dbUsuario,
|
||||
clave: configuracion.dbClave,
|
||||
trustedConnection: configuracion.dbTrusted,
|
||||
}),
|
||||
onSuccess: (data) => {
|
||||
if (data.exito) {
|
||||
toast.success('✓ ' + data.mensaje);
|
||||
} else {
|
||||
toast.error('✗ ' + data.mensaje);
|
||||
}
|
||||
setProbandoSQL(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Error: ${error.message}`);
|
||||
setProbandoSQL(false);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* ==============================================
|
||||
SECCIÓN 1: BASE DE DATOS EXTERNA
|
||||
============================================== */}
|
||||
<div className="bg-white rounded-lg">
|
||||
<div className="flex items-center gap-2 text-primary-600 mb-4 border-b border-gray-100 pb-2">
|
||||
<Database className="w-5 h-5" />
|
||||
<h3 className="text-lg font-semibold">Conexión a Base de Datos (DB del Tercero)</h3>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="label-text">Servidor SQL Server:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={configuracion.dbServidor}
|
||||
onChange={(e) => onChange({ dbServidor: e.target.value })}
|
||||
className="input-field"
|
||||
placeholder="Ej: FEBO o 192.168.1.X"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label-text">Nombre de Base de Datos:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={configuracion.dbNombre}
|
||||
onChange={(e) => onChange({ dbNombre: e.target.value })}
|
||||
className="input-field"
|
||||
placeholder="Nombre de la BD Externa"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tipo de autenticación */}
|
||||
<div className="bg-gray-50 p-3 rounded-md border border-gray-200">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={configuracion.dbTrusted}
|
||||
onChange={(e) => onChange({ dbTrusted: e.target.checked })}
|
||||
className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
|
||||
/>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
Usar Autenticación de Windows
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{configuracion.dbTrusted && (
|
||||
<div className="mt-2 flex items-start gap-2 text-xs text-amber-700 bg-amber-50 p-2 rounded">
|
||||
<AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
|
||||
<p>
|
||||
<strong>Atención:</strong> La autenticación de Windows no suele funcionar en contenedores Docker Linux.
|
||||
Se recomienda usar <strong>Autenticación de SQL Server</strong> (Usuario/Clave).
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Credenciales SQL (Mostrar si NO es Trusted o para forzar edición) */}
|
||||
<div className={`grid grid-cols-1 md:grid-cols-2 gap-4 transition-all duration-300 ${configuracion.dbTrusted ? 'opacity-50 grayscale pointer-events-none' : 'opacity-100'}`}>
|
||||
<div>
|
||||
<label className="label-text">Usuario SQL:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={configuracion.dbUsuario || ''}
|
||||
onChange={(e) => onChange({ dbUsuario: e.target.value })}
|
||||
className="input-field"
|
||||
placeholder="Ej: sa"
|
||||
disabled={configuracion.dbTrusted}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label-text">Contraseña SQL:</label>
|
||||
<input
|
||||
type="password"
|
||||
value={configuracion.dbClave || ''}
|
||||
onChange={(e) => onChange({ dbClave: e.target.value })}
|
||||
className="input-field"
|
||||
placeholder="••••••••"
|
||||
disabled={configuracion.dbTrusted}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Botón probar conexión */}
|
||||
<div className="flex justify-end pt-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
setProbandoSQL(true);
|
||||
probarSQLMutation.mutate();
|
||||
}}
|
||||
disabled={probandoSQL || !configuracion.dbNombre}
|
||||
className="btn-secondary flex items-center gap-2 disabled:opacity-50 text-sm"
|
||||
>
|
||||
{probandoSQL ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Conectando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Database className="w-4 h-4" />
|
||||
Probar Conexión
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ==============================================
|
||||
SECCIÓN 2: RUTAS DE ARCHIVOS (DOCKER VOLUMES)
|
||||
============================================== */}
|
||||
<div className="bg-white rounded-lg">
|
||||
<div className="flex items-center gap-2 text-primary-600 mb-4 border-b border-gray-100 pb-2">
|
||||
<FolderOpen className="w-5 h-5" />
|
||||
<h3 className="text-lg font-semibold">Rutas de Archivos (Volúmenes Docker)</h3>
|
||||
</div>
|
||||
|
||||
{/* Info Box para Docker */}
|
||||
<div className="mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3">
|
||||
<Info className="w-5 h-5 text-blue-600 mt-0.5 shrink-0" />
|
||||
<div className="text-sm text-blue-800">
|
||||
<p className="font-semibold mb-1">Configuración para Docker/Linux:</p>
|
||||
<p>
|
||||
No uses rutas de Windows (<code>\\servidor\...</code>).
|
||||
Usa las rutas internas donde montaste los volúmenes en el contenedor.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* Ruta Origen */}
|
||||
<div>
|
||||
<label className="label-text">Ruta Origen (Interna del Contenedor):</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
value={configuracion.rutaFacturas}
|
||||
onChange={(e) => onChange({ rutaFacturas: e.target.value })}
|
||||
className={`input-field font-mono text-sm pl-9 ${configuracion.rutaFacturas.includes('\\') ? 'border-yellow-400 focus:ring-yellow-400' : ''
|
||||
}`}
|
||||
placeholder="/app/data/origen"
|
||||
/>
|
||||
<div className="absolute left-3 top-2.5 text-gray-400">
|
||||
<FolderOpen className="w-4 h-4" />
|
||||
</div>
|
||||
</div>
|
||||
{configuracion.rutaFacturas.includes('\\') && (
|
||||
<p className="text-xs text-yellow-600 mt-1 flex items-center gap-1">
|
||||
<AlertTriangle className="w-3 h-3" />
|
||||
Advertencia: Estás usando barras invertidas (\). Si usas Docker en Linux, usa barras normales (/).
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-gray-500 mt-1 ml-1">
|
||||
Debe coincidir con el volumen montado en <code>docker-compose.yml</code>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Ruta Destino */}
|
||||
<div>
|
||||
<label className="label-text">Ruta Destino (Interna del Contenedor):</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
value={configuracion.rutaDestino}
|
||||
onChange={(e) => onChange({ rutaDestino: e.target.value })}
|
||||
className="input-field font-mono text-sm pl-9"
|
||||
placeholder="/app/data/destino"
|
||||
/>
|
||||
<div className="absolute left-3 top-2.5 text-gray-400">
|
||||
<FolderOpen className="w-4 h-4" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1 ml-1">
|
||||
Donde el sistema guardará los archivos procesados
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* BOTÓN GUARDAR SECCIÓN (Al final de todo) */}
|
||||
<div className="flex justify-end pt-6 border-t border-gray-100">
|
||||
<button
|
||||
onClick={onSave}
|
||||
disabled={isSaving}
|
||||
className="btn-primary flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
Guardar Configuración de Accesos
|
||||
</button>
|
||||
</div>
|
||||
</div >
|
||||
);
|
||||
}
|
||||
200
frontend/src/components/Configuracion/ConfiguracionAlertas.tsx
Normal file
200
frontend/src/components/Configuracion/ConfiguracionAlertas.tsx
Normal file
@@ -0,0 +1,200 @@
|
||||
import { useState } from 'react';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { Mail, Send, Loader2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { configuracionApi } from '../../services/api';
|
||||
import type { Configuracion } from '../../types';
|
||||
import { Save } from 'lucide-react';
|
||||
|
||||
interface ConfiguracionAlertasProps {
|
||||
configuracion: Configuracion;
|
||||
onChange: (updates: Partial<Configuracion>) => void;
|
||||
onSave: () => void; // Nuevo prop
|
||||
isSaving: boolean; // Nuevo prop
|
||||
}
|
||||
|
||||
export default function ConfiguracionAlertas({ configuracion, onChange, onSave, isSaving }: ConfiguracionAlertasProps) {
|
||||
const [probandoSMTP, setProbandoSMTP] = useState(false);
|
||||
|
||||
const probarSMTPMutation = useMutation({
|
||||
mutationFn: () => {
|
||||
if (!configuracion.smtpServidor || !configuracion.smtpUsuario || !configuracion.smtpDestinatario) {
|
||||
throw new Error('Completa todos los campos SMTP antes de probar');
|
||||
}
|
||||
|
||||
return configuracionApi.probarSMTP({
|
||||
servidor: configuracion.smtpServidor,
|
||||
puerto: configuracion.smtpPuerto,
|
||||
usuario: configuracion.smtpUsuario,
|
||||
clave: configuracion.smtpClave || '',
|
||||
ssl: configuracion.smtpSSL,
|
||||
destinatario: configuracion.smtpDestinatario,
|
||||
});
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (data.exito) {
|
||||
toast.success('✓ ' + data.mensaje);
|
||||
} else {
|
||||
toast.error('✗ ' + data.mensaje);
|
||||
}
|
||||
setProbandoSMTP(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Error: ${error.message}`);
|
||||
setProbandoSMTP(false);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2 text-primary-600 mb-4">
|
||||
<Mail className="w-5 h-5" />
|
||||
<h3 className="text-lg font-semibold">Configuración de Alertas por Correo</h3>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-gray-600 mb-6">
|
||||
Configura el envío de notificaciones por email cuando ocurran errores en el procesamiento.
|
||||
</p>
|
||||
|
||||
{/* Switch para activar/desactivar */}
|
||||
<div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
|
||||
<label className="flex items-center justify-between cursor-pointer">
|
||||
<div>
|
||||
<span className="text-sm font-medium text-gray-900">Activar Alertas por Correo</span>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Enviar email cuando haya errores en el procesamiento
|
||||
</p>
|
||||
</div>
|
||||
<div className="relative inline-block w-12 h-6">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={configuracion.avisoMail}
|
||||
onChange={(e) => onChange({ avisoMail: e.target.checked })}
|
||||
className="sr-only peer"
|
||||
/>
|
||||
<div className="w-12 h-6 bg-gray-300 rounded-full peer peer-checked:bg-green-500 transition-colors"></div>
|
||||
<div className="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform peer-checked:translate-x-6"></div>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Configuración SMTP */}
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="label-text">Servidor SMTP:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={configuracion.smtpServidor || ''}
|
||||
onChange={(e) => onChange({ smtpServidor: e.target.value })}
|
||||
className="input-field"
|
||||
placeholder="smtp.ejemplo.com"
|
||||
disabled={!configuracion.avisoMail}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label-text">Puerto:</label>
|
||||
<input
|
||||
type="number"
|
||||
value={configuracion.smtpPuerto}
|
||||
onChange={(e) => onChange({ smtpPuerto: parseInt(e.target.value) || 587 })}
|
||||
className="input-field"
|
||||
placeholder="587"
|
||||
disabled={!configuracion.avisoMail}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="label-text">Usuario SMTP:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={configuracion.smtpUsuario || ''}
|
||||
onChange={(e) => onChange({ smtpUsuario: e.target.value })}
|
||||
className="input-field"
|
||||
placeholder="usuario@ejemplo.com"
|
||||
disabled={!configuracion.avisoMail}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label-text">Contraseña SMTP:</label>
|
||||
<input
|
||||
type="password"
|
||||
value={configuracion.smtpClave || ''}
|
||||
onChange={(e) => onChange({ smtpClave: e.target.value })}
|
||||
className="input-field"
|
||||
placeholder="••••••••"
|
||||
disabled={!configuracion.avisoMail}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label-text">Email Destinatario:</label>
|
||||
<input
|
||||
type="email"
|
||||
value={configuracion.smtpDestinatario || ''}
|
||||
onChange={(e) => onChange({ smtpDestinatario: e.target.value })}
|
||||
className="input-field"
|
||||
placeholder="admin@empresa.com"
|
||||
disabled={!configuracion.avisoMail}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Dirección que recibirá las alertas de errores
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={configuracion.smtpSSL}
|
||||
onChange={(e) => onChange({ smtpSSL: e.target.checked })}
|
||||
className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
|
||||
disabled={!configuracion.avisoMail}
|
||||
/>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
Usar SSL/TLS (Recomendado)
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Botón probar SMTP */}
|
||||
<button
|
||||
onClick={() => {
|
||||
setProbandoSMTP(true);
|
||||
probarSMTPMutation.mutate();
|
||||
}}
|
||||
disabled={probandoSMTP || !configuracion.avisoMail || !configuracion.smtpServidor}
|
||||
className="btn-secondary flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{probandoSMTP ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Enviando correo de prueba...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Send className="w-4 h-4" />
|
||||
Enviar Correo de Prueba
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
{/* BOTÓN GUARDAR SECCIÓN */}
|
||||
<div className="flex justify-end pt-6 border-t border-gray-100 mt-6">
|
||||
<button
|
||||
onClick={onSave}
|
||||
disabled={isSaving}
|
||||
className="btn-primary flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
Guardar Configuración de Alertas
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
209
frontend/src/components/Configuracion/ConfiguracionPanel.tsx
Normal file
209
frontend/src/components/Configuracion/ConfiguracionPanel.tsx
Normal file
@@ -0,0 +1,209 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useQuery, useMutation } from '@tanstack/react-query';
|
||||
import { Loader2, Trash2 } from 'lucide-react'; // Agregado Trash2
|
||||
import { toast } from 'sonner';
|
||||
import { configuracionApi, operacionesApi } from '../../services/api'; // Agregado operacionesApi
|
||||
import ConfiguracionTiempos from './ConfiguracionTiempos';
|
||||
import ConfiguracionAccesos from './ConfiguracionAccesos';
|
||||
import ConfiguracionAlertas from './ConfiguracionAlertas';
|
||||
import type { Configuracion } from '../../types';
|
||||
|
||||
interface ConfiguracionPanelProps {
|
||||
onGuardar: () => void;
|
||||
}
|
||||
|
||||
export default function ConfiguracionPanel({ onGuardar }: ConfiguracionPanelProps) {
|
||||
const [seccionActiva, setSeccionActiva] = useState<'tiempos' | 'accesos' | 'alertas'>('tiempos');
|
||||
const [showConfirm, setShowConfirm] = useState(false);
|
||||
|
||||
const { data: configuracion, isLoading, refetch } = useQuery({
|
||||
queryKey: ['configuracion'],
|
||||
queryFn: configuracionApi.obtener,
|
||||
});
|
||||
|
||||
const [formData, setFormData] = useState<Configuracion | null>(null);
|
||||
|
||||
// Sincronizar estado local cuando llega la data del servidor
|
||||
useEffect(() => {
|
||||
if (configuracion && !formData) {
|
||||
setFormData(configuracion);
|
||||
}
|
||||
}, [configuracion, formData]);
|
||||
|
||||
// Mutación para guardar configuración
|
||||
const guardarMutation = useMutation({
|
||||
mutationFn: (data: Configuracion) => configuracionApi.actualizar(data),
|
||||
onSuccess: (data) => {
|
||||
toast.success('✓ Configuración guardada correctamente');
|
||||
setFormData(data);
|
||||
refetch();
|
||||
onGuardar();
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Error al guardar: ${error.message}`);
|
||||
},
|
||||
});
|
||||
|
||||
// --- NUEVO: Mutación para limpiar logs ---
|
||||
const limpiarLogsMutation = useMutation({
|
||||
mutationFn: () => operacionesApi.limpiarLogs(30), // Borra logs de +30 días
|
||||
onSuccess: (data) => {
|
||||
toast.success(data.mensaje || 'Logs eliminados correctamente');
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Error al limpiar logs: ${error.message}`);
|
||||
},
|
||||
});
|
||||
|
||||
// Función genérica que pasaremos a los hijos para guardar
|
||||
const handleGuardar = () => {
|
||||
if (!formData) return;
|
||||
guardarMutation.mutate(formData);
|
||||
};
|
||||
|
||||
// --- NUEVO: Función que faltaba ---
|
||||
const handleLimpiar = () => {
|
||||
limpiarLogsMutation.mutate();
|
||||
};
|
||||
|
||||
const secciones = [
|
||||
{ id: 'tiempos' as const, nombre: 'Tiempos y Periodicidad' },
|
||||
{ id: 'accesos' as const, nombre: 'Accesos y Rutas' },
|
||||
{ id: 'alertas' as const, nombre: 'Alertas por Correo' },
|
||||
];
|
||||
|
||||
if (isLoading || !configuracion) {
|
||||
return (
|
||||
<div className="card flex items-center justify-center py-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary-500" />
|
||||
<span className="ml-3 text-gray-600">Cargando configuración...</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const currentData = formData || configuracion;
|
||||
const isSaving = guardarMutation.isPending;
|
||||
const hayCambios = JSON.stringify(formData) !== JSON.stringify(configuracion);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="card min-h-[500px]">
|
||||
{/* Header con Título y Botón de Limpieza */}
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<h2 className="text-2xl font-bold text-gray-900">
|
||||
Configuración del Sistema
|
||||
</h2>
|
||||
{/* Indicador Global de Cambios */}
|
||||
{hayCambios && (
|
||||
<span className="text-xs font-medium text-amber-600 bg-amber-50 px-2 py-1 rounded-full border border-amber-200 animate-pulse">
|
||||
Cambios sin guardar
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Botón para abrir el modal de limpieza */}
|
||||
<button
|
||||
onClick={() => setShowConfirm(true)}
|
||||
className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-red-600 bg-red-50 hover:bg-red-100 rounded-lg transition-colors border border-red-200"
|
||||
title="Limpiar logs antiguos"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">Limpiar Logs</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Pestañas */}
|
||||
<div className="border-b border-gray-200 mb-6">
|
||||
<nav className="flex space-x-8 overflow-x-auto">
|
||||
{secciones.map((seccion) => (
|
||||
<button
|
||||
key={seccion.id}
|
||||
onClick={() => setSeccionActiva(seccion.id)}
|
||||
className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors whitespace-nowrap flex items-center gap-2 ${seccionActiva === seccion.id
|
||||
? 'border-primary-500 text-primary-600'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
|
||||
}`}
|
||||
>
|
||||
{seccion.nombre}
|
||||
{seccionActiva === seccion.id && hayCambios && (
|
||||
<span className="w-2 h-2 bg-amber-500 rounded-full" title="Hay cambios sin guardar" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Contenido */}
|
||||
<div className="mt-6 pb-6">
|
||||
{seccionActiva === 'tiempos' && (
|
||||
<ConfiguracionTiempos
|
||||
configuracion={currentData}
|
||||
onChange={(updates) => setFormData((prev) => ({ ...(prev || configuracion), ...updates }))}
|
||||
onSave={handleGuardar}
|
||||
isSaving={isSaving}
|
||||
/>
|
||||
)}
|
||||
|
||||
{seccionActiva === 'accesos' && (
|
||||
<ConfiguracionAccesos
|
||||
configuracion={currentData}
|
||||
onChange={(updates) => setFormData((prev) => ({ ...(prev || configuracion), ...updates }))}
|
||||
onSave={handleGuardar}
|
||||
isSaving={isSaving}
|
||||
/>
|
||||
)}
|
||||
|
||||
{seccionActiva === 'alertas' && (
|
||||
<ConfiguracionAlertas
|
||||
configuracion={currentData}
|
||||
onChange={(updates) => setFormData((prev) => ({ ...(prev || configuracion), ...updates }))}
|
||||
onSave={handleGuardar}
|
||||
isSaving={isSaving}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal de Confirmación */}
|
||||
{showConfirm && (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 backdrop-blur-sm">
|
||||
<div className="bg-white rounded-lg p-6 max-w-sm w-full shadow-2xl transform transition-all scale-100 animate-in fade-in zoom-in duration-200">
|
||||
<div className="flex items-center gap-3 mb-4 text-red-600">
|
||||
<Trash2 className="w-6 h-6" />
|
||||
<h3 className="text-lg font-bold text-gray-900">¿Estás seguro?</h3>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-600 mb-6 text-sm">
|
||||
Esta acción eliminará todos los logs con más de <strong>30 días de antigüedad</strong>.
|
||||
<br /><br />
|
||||
Esta acción no se puede deshacer.
|
||||
</p>
|
||||
|
||||
<div className="flex justify-end gap-3">
|
||||
<button
|
||||
onClick={() => setShowConfirm(false)}
|
||||
className="px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg font-medium transition-colors"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
handleLimpiar();
|
||||
setShowConfirm(false);
|
||||
}}
|
||||
className="px-4 py-2 bg-red-600 text-white hover:bg-red-700 rounded-lg font-medium transition-colors flex items-center gap-2"
|
||||
>
|
||||
{limpiarLogsMutation.isPending ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
'Sí, eliminar'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
158
frontend/src/components/Configuracion/ConfiguracionTiempos.tsx
Normal file
158
frontend/src/components/Configuracion/ConfiguracionTiempos.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
import { Clock, Save, Loader2, Info } from 'lucide-react';
|
||||
import type { Configuracion } from '../../types';
|
||||
import { addMinutes, addDays, addMonths, format } from 'date-fns';
|
||||
|
||||
interface ConfiguracionTiemposProps {
|
||||
configuracion: Configuracion;
|
||||
onChange: (updates: Partial<Configuracion>) => void;
|
||||
onSave: () => void;
|
||||
isSaving: boolean;
|
||||
}
|
||||
|
||||
export default function ConfiguracionTiempos({ configuracion, onChange, onSave, isSaving }: ConfiguracionTiemposProps) {
|
||||
|
||||
// Determinamos el valor mínimo según el tipo seleccionado
|
||||
const minimoPermitido = configuracion.periodicidad === 'Minutos' ? 15 : 1;
|
||||
|
||||
const calcularProyeccion = () => {
|
||||
if (!configuracion.valorPeriodicidad) return null;
|
||||
|
||||
const ahora = new Date();
|
||||
let proxima = ahora;
|
||||
const tipo = configuracion.periodicidad;
|
||||
const valor = configuracion.valorPeriodicidad;
|
||||
|
||||
if (tipo === 'Minutos') {
|
||||
proxima = addMinutes(ahora, valor);
|
||||
} else if (tipo === 'Dias') {
|
||||
proxima = addDays(ahora, valor);
|
||||
} else if (tipo === 'Meses') {
|
||||
proxima = addMonths(ahora, valor);
|
||||
}
|
||||
|
||||
return format(proxima, 'dd/MM/yyyy HH:mm:ss');
|
||||
};
|
||||
|
||||
const proximaEstimada = calcularProyeccion();
|
||||
|
||||
// Manejador inteligente para el cambio de tipo
|
||||
const handleTipoChange = (nuevoTipo: string) => {
|
||||
let nuevoValor = configuracion.valorPeriodicidad;
|
||||
|
||||
// Si cambia a Minutos y el valor es menor a 15, lo corregimos a 15
|
||||
if (nuevoTipo === 'Minutos' && nuevoValor < 15) {
|
||||
nuevoValor = 15;
|
||||
}
|
||||
// Si cambia a Días/Meses y el valor es 0 o negativo, lo corregimos a 1
|
||||
else if (nuevoTipo !== 'Minutos' && nuevoValor < 1) {
|
||||
nuevoValor = 1;
|
||||
}
|
||||
|
||||
onChange({
|
||||
periodicidad: nuevoTipo,
|
||||
valorPeriodicidad: nuevoValor
|
||||
});
|
||||
};
|
||||
|
||||
// Manejador para el cambio de valor numérico
|
||||
const handleValorChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const val = parseInt(e.target.value) || 0;
|
||||
// Permitimos escribir, la validación estricta ocurre al cambiar tipo o guardar en backend,
|
||||
// pero aquí respetamos el min del input HTML para las flechas.
|
||||
onChange({ valorPeriodicidad: val });
|
||||
};
|
||||
|
||||
// Validación para deshabilitar el botón si no cumple la regla
|
||||
const esValido = !(configuracion.periodicidad === 'Minutos' && configuracion.valorPeriodicidad < 15) && configuracion.valorPeriodicidad > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2 text-primary-600 mb-4">
|
||||
<Clock className="w-5 h-5" />
|
||||
<h3 className="text-lg font-semibold">Configuración de Periodicidad</h3>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-gray-600 mb-6">
|
||||
Define cada cuánto tiempo debe ejecutarse el proceso de organización de facturas.
|
||||
</p>
|
||||
|
||||
{/* inputs */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<label className="label-text">Tipo de Periodicidad:</label>
|
||||
<select
|
||||
value={configuracion.periodicidad}
|
||||
onChange={(e) => handleTipoChange(e.target.value)}
|
||||
className="input-field"
|
||||
>
|
||||
<option value="Minutos">Minutos</option>
|
||||
<option value="Dias">Días</option>
|
||||
<option value="Meses">Meses</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label-text">Cada cuánto:</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="number"
|
||||
min={minimoPermitido}
|
||||
value={configuracion.valorPeriodicidad}
|
||||
onChange={handleValorChange}
|
||||
className={`input-field ${!esValido ? 'border-red-300 focus:ring-red-200' : ''}`}
|
||||
/>
|
||||
{!esValido && (
|
||||
<span className="absolute right-3 top-2.5 text-xs text-red-500 font-medium">
|
||||
Mínimo {minimoPermitido}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{configuracion.periodicidad === 'Minutos' && (
|
||||
<p className="text-xs text-gray-500 mt-1 flex items-center gap-1">
|
||||
<Info className="w-3 h-3" /> Mínimo permitido: 15 minutos
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(configuracion.periodicidad === 'Dias' || configuracion.periodicidad === 'Meses') && (
|
||||
<div>
|
||||
<label className="label-text">Hora de Ejecución:</label>
|
||||
<input
|
||||
type="time"
|
||||
step="1"
|
||||
value={configuracion.horaEjecucion}
|
||||
onChange={(e) => onChange({ horaEjecucion: e.target.value })}
|
||||
className="input-field"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-blue-50 border-l-4 border-blue-400 p-4 rounded-r-lg mt-4">
|
||||
<div className="flex">
|
||||
<div className="ml-3">
|
||||
<p className="text-sm text-blue-700">
|
||||
<span className="font-bold">Proyección:</span> Si guardas esta configuración,
|
||||
la próxima ejecución estimada sería alrededor del:
|
||||
</p>
|
||||
<p className="text-lg font-bold text-blue-900 mt-1">
|
||||
{proximaEstimada}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* BOTÓN GUARDAR SECCIÓN */}
|
||||
<div className="flex justify-end pt-6 border-t border-gray-100 mt-6">
|
||||
<button
|
||||
onClick={onSave}
|
||||
disabled={isSaving || !esValido}
|
||||
className="btn-primary flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
Guardar Cambios
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
124
frontend/src/components/Dashboard/ControlServicio.tsx
Normal file
124
frontend/src/components/Dashboard/ControlServicio.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import { useState } from 'react';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { Play, Square, Loader2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { configuracionApi } from '../../services/api';
|
||||
import type { Configuracion } from '../../types';
|
||||
|
||||
interface ControlServicioProps {
|
||||
configuracion?: Configuracion;
|
||||
onUpdate: () => void;
|
||||
onExecute: () => void;
|
||||
}
|
||||
|
||||
export default function ControlServicio({ configuracion, onUpdate, onExecute }: ControlServicioProps) {
|
||||
const [isToggling, setIsToggling] = useState(false);
|
||||
|
||||
const toggleMutation = useMutation({
|
||||
mutationFn: async (nuevoEstado: boolean) => {
|
||||
if (!configuracion) throw new Error('No hay configuración');
|
||||
|
||||
const updated = { ...configuracion, enEjecucion: nuevoEstado };
|
||||
return configuracionApi.actualizar(updated);
|
||||
},
|
||||
onSuccess: (_, nuevoEstado) => {
|
||||
toast.success(
|
||||
nuevoEstado ? '✓ Servicio iniciado correctamente' : '⏸️ Servicio detenido'
|
||||
);
|
||||
onUpdate();
|
||||
onExecute();
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Error al cambiar estado del servicio: ${error.message}`);
|
||||
},
|
||||
onSettled: () => {
|
||||
setIsToggling(false);
|
||||
},
|
||||
});
|
||||
|
||||
const handleToggle = () => {
|
||||
if (!configuracion) {
|
||||
toast.error('No se ha cargado la configuración');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validar configuración antes de iniciar
|
||||
if (!configuracion.enEjecucion) {
|
||||
if (!configuracion.dbNombre || !configuracion.rutaFacturas || !configuracion.rutaDestino) {
|
||||
toast.error('Debes configurar la base de datos y las rutas antes de iniciar el servicio');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setIsToggling(true);
|
||||
toggleMutation.mutate(!configuracion.enEjecucion);
|
||||
};
|
||||
|
||||
const estaActivo = configuracion?.enEjecucion || false;
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<h3 className="text-xl font-bold text-gray-900 mb-4">Control del Servicio</h3>
|
||||
|
||||
<div className="flex flex-col items-center justify-center py-8 space-y-6">
|
||||
{/* Indicador visual */}
|
||||
<div
|
||||
className={`w-32 h-32 rounded-full flex items-center justify-center transition-all duration-300 ${estaActivo
|
||||
? 'bg-green-100 shadow-lg shadow-green-200'
|
||||
: 'bg-gray-100 shadow-md'
|
||||
}`}
|
||||
>
|
||||
{estaActivo ? (
|
||||
<div className="relative">
|
||||
<div className="w-16 h-16 bg-green-500 rounded-full animate-pulse" />
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Play className="w-8 h-8 text-white fill-white" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Square className="w-18 h-18 text-red-700" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Estado textual */}
|
||||
<div className="text-center">
|
||||
<p className="text-2xl font-bold text-gray-900">
|
||||
{estaActivo ? 'Servicio en Ejecución' : 'Servicio Detenido'}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
{estaActivo
|
||||
? 'El proceso se ejecutará según la periodicidad configurada'
|
||||
: 'El servicio está pausado y no procesará facturas'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Botón de control */}
|
||||
<button
|
||||
onClick={handleToggle}
|
||||
disabled={isToggling || !configuracion}
|
||||
className={`flex items-center gap-2 px-8 py-4 rounded-lg font-bold text-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed ${estaActivo
|
||||
? 'bg-red-500 hover:bg-red-600 text-white shadow-lg hover:shadow-xl'
|
||||
: 'bg-green-500 hover:bg-green-600 text-white shadow-lg hover:shadow-xl'
|
||||
}`}
|
||||
>
|
||||
{isToggling ? (
|
||||
<>
|
||||
<Loader2 className="w-6 h-6 animate-spin" />
|
||||
Procesando...
|
||||
</>
|
||||
) : estaActivo ? (
|
||||
<>
|
||||
<Square className="w-6 h-6" />
|
||||
Detener Servicio
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="w-6 h-6" />
|
||||
Iniciar Servicio
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
88
frontend/src/components/Dashboard/Dashboard.tsx
Normal file
88
frontend/src/components/Dashboard/Dashboard.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { operacionesApi, configuracionApi } from '../../services/api';
|
||||
import Header from '../Layout/Header';
|
||||
import ControlServicio from './ControlServicio';
|
||||
import EstadisticasCards from './EstadisticasCards';
|
||||
import EjecucionManual from './EjecucionManual';
|
||||
import TablaEventos from '../Eventos/TablaEventos';
|
||||
import ConfiguracionPanel from '../Configuracion/ConfiguracionPanel';
|
||||
|
||||
// CONFIGURACIÓN CENTRALIZADA DEL TIEMPO DE REFRESCO
|
||||
const REFRESH_INTERVAL = 5000; // Sugiero bajarlo a 5s para pruebas, luego subirlo a 10s
|
||||
|
||||
export default function Dashboard() {
|
||||
const [vistaActual, setVistaActual] = useState<'dashboard' | 'configuracion'>('dashboard');
|
||||
|
||||
// 1. Obtener estadísticas
|
||||
const { data: estadisticas, refetch: refetchEstadisticas } = useQuery({
|
||||
queryKey: ['estadisticas'],
|
||||
queryFn: operacionesApi.obtenerEstadisticas,
|
||||
refetchInterval: REFRESH_INTERVAL,
|
||||
// IMPORTANTE: Esto permite que siga actualizando aunque minimices la ventana
|
||||
refetchIntervalInBackground: true,
|
||||
// IMPORTANTE: Anulamos el global de 30s para que siempre acepte datos frescos
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
// 2. Obtener configuración
|
||||
const { data: configuracion, refetch: refetchConfig } = useQuery({
|
||||
queryKey: ['configuracion'],
|
||||
queryFn: configuracionApi.obtener,
|
||||
refetchInterval: REFRESH_INTERVAL,
|
||||
refetchIntervalInBackground: true, // Permitir actualización en segundo plano
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
|
||||
<Header
|
||||
vistaActual={vistaActual}
|
||||
setVistaActual={setVistaActual}
|
||||
estadisticas={estadisticas}
|
||||
/>
|
||||
|
||||
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||
{vistaActual === 'dashboard' ? (
|
||||
<div className="space-y-8">
|
||||
{/* Estadísticas */}
|
||||
<EstadisticasCards
|
||||
estadisticas={estadisticas}
|
||||
configuracion={configuracion}
|
||||
/>
|
||||
|
||||
{/* Control del servicio */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<ControlServicio
|
||||
configuracion={configuracion}
|
||||
onUpdate={refetchConfig}
|
||||
onExecute={refetchEstadisticas}
|
||||
/>
|
||||
<EjecucionManual onExecute={refetchEstadisticas} />
|
||||
</div>
|
||||
|
||||
{/* Tabla de eventos */}
|
||||
<div className="card">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900">
|
||||
Registro de Eventos
|
||||
</h2>
|
||||
<span className="flex items-center gap-2 text-xs font-medium text-green-600 bg-green-50 px-2 py-1 rounded-full border border-green-100 animate-pulse">
|
||||
<span className="relative flex h-2 w-2">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
|
||||
<span className="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
|
||||
</span>
|
||||
En Vivo
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<TablaEventos refreshInterval={REFRESH_INTERVAL} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<ConfiguracionPanel onGuardar={refetchConfig} />
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
101
frontend/src/components/Dashboard/EjecucionManual.tsx
Normal file
101
frontend/src/components/Dashboard/EjecucionManual.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import { useState } from 'react';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { Calendar, PlayCircle, Loader2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { operacionesApi } from '../../services/api';
|
||||
|
||||
interface EjecucionManualProps {
|
||||
onExecute: () => void;
|
||||
}
|
||||
|
||||
export default function EjecucionManual({ onExecute }: EjecucionManualProps) {
|
||||
const [fechaDesde, setFechaDesde] = useState<string>(
|
||||
new Date().toISOString().split('T')[0]
|
||||
);
|
||||
|
||||
const ejecutarMutation = useMutation({
|
||||
mutationFn: () => operacionesApi.ejecutarManual({ fechaDesde }),
|
||||
onSuccess: () => {
|
||||
toast.success('✓ Proceso iniciado correctamente');
|
||||
toast.info('Revisa los eventos para ver el progreso');
|
||||
onExecute();
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Error al ejecutar: ${error.message}`);
|
||||
},
|
||||
});
|
||||
|
||||
const handleEjecutar = () => {
|
||||
if (!fechaDesde) {
|
||||
toast.error('Debes seleccionar una fecha');
|
||||
return;
|
||||
}
|
||||
|
||||
ejecutarMutation.mutate();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<h3 className="text-xl font-bold text-gray-900 mb-4">
|
||||
Ejecución Manual
|
||||
</h3>
|
||||
|
||||
<p className="text-sm text-gray-600 mb-6">
|
||||
Ejecuta el proceso inmediatamente sin esperar al cronograma programado.
|
||||
Selecciona la fecha desde la cual buscar facturas.
|
||||
</p>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Selector de fecha */}
|
||||
<div>
|
||||
<label htmlFor="fechaDesde" className="label-text">
|
||||
Fecha desde:
|
||||
</label>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<Calendar className="w-5 h-5 text-gray-400" />
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
id="fechaDesde"
|
||||
value={fechaDesde}
|
||||
onChange={(e) => setFechaDesde(e.target.value)}
|
||||
max={new Date().toISOString().split('T')[0]}
|
||||
className="input-field pl-10"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Se procesarán todas las facturas desde esta fecha hasta hoy
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Botón de ejecución */}
|
||||
<button
|
||||
onClick={handleEjecutar}
|
||||
disabled={ejecutarMutation.isPending || !fechaDesde}
|
||||
className="w-full btn-primary flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{ejecutarMutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
Ejecutando proceso...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<PlayCircle className="w-5 h-5" />
|
||||
Ejecutar Ahora
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Información adicional */}
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
|
||||
<p className="text-sm text-blue-800">
|
||||
<strong>Nota:</strong> El proceso se ejecutará en segundo plano. Los resultados
|
||||
aparecerán en la tabla de eventos más abajo.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
114
frontend/src/components/Dashboard/EstadisticasCards.tsx
Normal file
114
frontend/src/components/Dashboard/EstadisticasCards.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import { Activity, AlertCircle, CheckCircle2, Info } from 'lucide-react';
|
||||
import type { Estadisticas, Configuracion } from '../../types';
|
||||
import ExecutionCard from './ExecutionCard';
|
||||
|
||||
interface EstadisticasCardsProps {
|
||||
estadisticas?: Estadisticas;
|
||||
configuracion?: Configuracion;
|
||||
}
|
||||
|
||||
export default function EstadisticasCards({ estadisticas, configuracion }: EstadisticasCardsProps) {
|
||||
// Extraemos los valores para usarlos más fácilmente
|
||||
const errores = estadisticas?.eventosHoy?.errores || 0;
|
||||
const advertencias = estadisticas?.eventosHoy?.advertencias || 0;
|
||||
|
||||
const standardCards = [
|
||||
{
|
||||
titulo: 'Estado Último Proceso',
|
||||
valor: estadisticas?.ultimaEjecucion
|
||||
? estadisticas.estado
|
||||
? 'Exitoso'
|
||||
: 'Con Fallas'
|
||||
: 'Sin datos',
|
||||
icono: estadisticas?.estado ? CheckCircle2 : AlertCircle,
|
||||
color: estadisticas?.estado ? 'text-green-600 bg-green-50' : 'text-red-600 bg-red-50',
|
||||
borde: estadisticas?.estado ? 'border-green-100' : 'border-red-100',
|
||||
},
|
||||
{
|
||||
titulo: 'Eventos de Hoy',
|
||||
valor: estadisticas?.eventosHoy?.total?.toString() || '0',
|
||||
subtext: 'Registros totales',
|
||||
extraInfo: (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{errores > 0 && (
|
||||
<span className="text-xs font-bold text-red-600 bg-red-50 px-2 py-0.5 rounded-full border border-red-100">
|
||||
{errores} errores
|
||||
</span>
|
||||
)}
|
||||
{advertencias > 0 && (
|
||||
<span className="text-xs font-bold text-amber-600 bg-amber-50 px-2 py-0.5 rounded-full border border-amber-100">
|
||||
{advertencias} advert.
|
||||
</span>
|
||||
)}
|
||||
{errores === 0 && advertencias === 0 && (
|
||||
<span className="text-xs text-gray-400">Sin incidentes</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
icono: Activity,
|
||||
color: 'text-purple-600 bg-purple-50',
|
||||
// Lógica de color del borde basada directamente en los valores
|
||||
borde: errores > 0 ? 'border-red-200' : (advertencias > 0 ? 'border-amber-200' : 'border-purple-100'),
|
||||
},
|
||||
{
|
||||
titulo: 'Informativos de Hoy',
|
||||
valor: estadisticas?.eventosHoy?.info?.toString() || '0',
|
||||
subtext: 'Logs informativos',
|
||||
icono: Info,
|
||||
color: 'text-blue-600 bg-blue-50',
|
||||
borde: 'border-blue-100',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
|
||||
{/* 1. Tarjeta Timeline */}
|
||||
<div className="h-full">
|
||||
<ExecutionCard
|
||||
ultimaEjecucion={configuracion?.ultimaEjecucion}
|
||||
proximaEjecucion={configuracion?.proximaEjecucion}
|
||||
enEjecucion={configuracion?.enEjecucion ?? false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 2, 3, 4. Tarjetas Estándar */}
|
||||
{standardCards.map((card, index) => {
|
||||
const Icono = card.icono;
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={`bg-white rounded-lg shadow-sm border p-4 h-full flex flex-col justify-between hover:shadow-md transition-shadow ${card.borde || 'border-gray-200'}`}
|
||||
>
|
||||
{/* Parte Superior: Título e Icono */}
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
|
||||
{card.titulo}
|
||||
</span>
|
||||
<div className={`p-2 rounded-lg ${card.color}`}>
|
||||
<Icono className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Parte Inferior: Valor Grande y Detalles */}
|
||||
<div className="mt-2">
|
||||
<p className="text-3xl font-bold text-gray-900 tracking-tight">
|
||||
{card.valor}
|
||||
</p>
|
||||
|
||||
<div className="flex items-center gap-2 mt-1 min-h-[24px]">
|
||||
{card.extraInfo ? (
|
||||
card.extraInfo
|
||||
) : (
|
||||
<p className="text-xs text-gray-400 font-medium">
|
||||
{card.subtext || '\u00A0'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
106
frontend/src/components/Dashboard/ExecutionCard.tsx
Normal file
106
frontend/src/components/Dashboard/ExecutionCard.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import { Clock, PauseCircle, Hourglass } from 'lucide-react';
|
||||
import { format, formatDistanceToNow, isPast, addSeconds } from 'date-fns';
|
||||
import { es } from 'date-fns/locale';
|
||||
|
||||
interface ExecutionCardProps {
|
||||
ultimaEjecucion: string | null | undefined;
|
||||
proximaEjecucion: string | null | undefined;
|
||||
enEjecucion: boolean;
|
||||
}
|
||||
|
||||
export default function ExecutionCard({ ultimaEjecucion, proximaEjecucion, enEjecucion }: ExecutionCardProps) {
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return format(new Date(dateString), "dd/MM, HH:mm", { locale: es }); // Formato más corto
|
||||
};
|
||||
|
||||
const formatRelative = (dateString: string) => {
|
||||
return formatDistanceToNow(new Date(dateString), { addSuffix: true, locale: es });
|
||||
};
|
||||
|
||||
const isOverdue = proximaEjecucion ? isPast(addSeconds(new Date(proximaEjecucion), -10)) : false;
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow-sm border border-gray-200 relative overflow-hidden flex flex-col h-full hover:shadow-md transition-shadow">
|
||||
{/* Barra de estado */}
|
||||
<div className={`h-1 w-full ${enEjecucion ? 'bg-green-500' : 'bg-gray-300'}`} />
|
||||
|
||||
<div className="p-4 flex-1 flex flex-col"> {/* Padding reducido a p-4 */}
|
||||
|
||||
{/* Encabezado Compacto */}
|
||||
<div className="flex justify-between items-center mb-3"> {/* Margin reducido */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="w-4 h-4 text-gray-400" />
|
||||
<span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
|
||||
Sincronización
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<span className={`text-[10px] font-bold px-1.5 py-0.5 rounded border ${enEjecucion
|
||||
? 'bg-green-50 text-green-700 border-green-200'
|
||||
: 'bg-gray-50 text-gray-600 border-gray-200'
|
||||
}`}>
|
||||
{enEjecucion ? 'AUTO' : 'MANUAL'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 pl-1 flex-1 flex flex-col justify-center"> {/* Espaciado reducido a space-y-4 */}
|
||||
|
||||
{/* ÚLTIMA EJECUCIÓN */}
|
||||
<div className="relative pl-5 border-l-2 border-gray-100">
|
||||
<div className="absolute -left-[5px] top-1.5 w-2 h-2 rounded-full bg-gray-300 ring-2 ring-white" />
|
||||
|
||||
<p className="text-[10px] text-gray-400 font-medium uppercase mb-0.5">Última</p>
|
||||
{ultimaEjecucion ? (
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-800">
|
||||
{formatRelative(ultimaEjecucion)}
|
||||
</p>
|
||||
<p className="text-[10px] text-gray-400">
|
||||
{formatDate(ultimaEjecucion)}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-gray-400 italic">--</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* PRÓXIMA EJECUCIÓN */}
|
||||
<div className="relative pl-5 border-l-2 border-transparent">
|
||||
<div className={`absolute -left-[5px] top-1.5 w-2 h-2 rounded-full ring-2 ring-white transition-colors duration-500 ${enEjecucion ? (isOverdue ? 'bg-amber-500' : 'bg-green-500') : 'bg-gray-300'
|
||||
}`} />
|
||||
|
||||
<p className="text-[10px] text-gray-400 font-medium uppercase mb-0.5">Próxima</p>
|
||||
|
||||
{enEjecucion && proximaEjecucion ? (
|
||||
<div className="animate-in fade-in duration-500">
|
||||
{isOverdue ? (
|
||||
<div>
|
||||
<p className="text-sm font-bold text-amber-600 flex items-center gap-1.5">
|
||||
En cola...
|
||||
<Hourglass className="w-3 h-3 animate-spin-slow" />
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<p className="text-sm font-bold text-primary-700">
|
||||
{formatDate(proximaEjecucion)} hs
|
||||
</p>
|
||||
<p className="text-[10px] text-primary-600/70">
|
||||
aprox. {formatRelative(proximaEjecucion)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-xs text-gray-400 font-medium flex items-center gap-1">
|
||||
<PauseCircle className="w-3 h-3" /> Detenido
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
223
frontend/src/components/Eventos/TablaEventos.tsx
Normal file
223
frontend/src/components/Eventos/TablaEventos.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { AlertCircle, Info, AlertTriangle, ChevronLeft, ChevronRight, RefreshCw, Search, Copy, Check } from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
import { es } from 'date-fns/locale';
|
||||
import { operacionesApi } from '../../services/api';
|
||||
import type { Evento } from '../../types';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
// Definimos las props para recibir el intervalo desde el padre
|
||||
interface TablaEventosProps {
|
||||
refreshInterval?: number;
|
||||
}
|
||||
|
||||
export default function TablaEventos({ refreshInterval = 30000 }: TablaEventosProps) {
|
||||
const [pageNumber, setPageNumber] = useState(1);
|
||||
const [tipoFiltro, setTipoFiltro] = useState<string>('');
|
||||
const [busqueda, setBusqueda] = useState('');
|
||||
const pageSize = 15;
|
||||
|
||||
const CopyButton = ({ text }: { text: string }) => {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = () => {
|
||||
navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
toast.success("Mensaje copiado");
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className="text-gray-400 hover:text-primary-600 p-1 rounded transition-colors"
|
||||
title="Copiar mensaje"
|
||||
>
|
||||
{copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
const { data, isLoading, refetch, isFetching } = useQuery({
|
||||
queryKey: ['eventos', pageNumber, tipoFiltro],
|
||||
queryFn: () => operacionesApi.obtenerLogs(pageNumber, pageSize, tipoFiltro || undefined),
|
||||
|
||||
refetchInterval: refreshInterval,
|
||||
refetchIntervalInBackground: true, // Clave para que no se detenga al cambiar de pestaña
|
||||
staleTime: 0, // Asegura que React Query sepa que los datos "caducan" inmediatamente
|
||||
|
||||
placeholderData: (previousData) => previousData,
|
||||
});
|
||||
|
||||
const getTipoIcon = (tipo: string) => {
|
||||
switch (tipo) {
|
||||
case 'Error': return <AlertCircle className="w-5 h-5 text-red-500" />;
|
||||
case 'Warning': return <AlertTriangle className="w-5 h-5 text-yellow-500" />;
|
||||
default: return <Info className="w-5 h-5 text-blue-500" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getTipoClass = (tipo: string) => {
|
||||
switch (tipo) {
|
||||
case 'Error': return 'bg-red-50 text-red-700 border-red-200';
|
||||
case 'Warning': return 'bg-yellow-50 text-yellow-700 border-yellow-200';
|
||||
default: return 'bg-blue-50 text-blue-700 border-blue-200';
|
||||
}
|
||||
};
|
||||
|
||||
const renderMensaje = (msg: string) => {
|
||||
const parts = msg.split(/(\S+\.pdf)/g);
|
||||
return (
|
||||
<span>
|
||||
{parts.map((part, i) =>
|
||||
part.endsWith('.pdf') ? (
|
||||
<span key={i} className="font-mono text-xs bg-gray-100 px-1 py-0.5 rounded border border-gray-300 font-semibold text-gray-800">
|
||||
{part}
|
||||
</span>
|
||||
) : part
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
// Filtrado simple en cliente para la búsqueda (si la API no tiene endpoint de búsqueda textual)
|
||||
// Si la API soporta búsqueda, deberías añadir 'busqueda' al queryKey y a la llamada API.
|
||||
const itemsFiltrados = data?.items?.filter(item =>
|
||||
item.mensaje.toLowerCase().includes(busqueda.toLowerCase())
|
||||
) ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Filtros y acciones */}
|
||||
<div className="flex flex-wrap justify-between items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-sm font-medium text-gray-700">Filtrar por tipo:</label>
|
||||
<select
|
||||
value={tipoFiltro}
|
||||
onChange={(e) => {
|
||||
setTipoFiltro(e.target.value);
|
||||
setPageNumber(1);
|
||||
}}
|
||||
className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="Info">Información</option>
|
||||
<option value="Warning">Advertencia</option>
|
||||
<option value="Error">Error</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="relative flex-1 min-w-[200px]">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<Search className="h-4 w-4 text-gray-400" />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Buscar en esta página..."
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
className="input-field pl-9 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => refetch()}
|
||||
disabled={isFetching}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${isFetching ? 'animate-spin' : ''}`} />
|
||||
{/* Ocultar texto en móvil para ahorrar espacio */}
|
||||
<span className="hidden sm:inline">Actualizar</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Tabla */}
|
||||
<div className="overflow-x-auto border border-gray-200 rounded-lg">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-48">Fecha</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-32">Tipo</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Mensaje</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{isLoading ? (
|
||||
<tr>
|
||||
<td colSpan={3} className="px-6 py-12 text-center">
|
||||
<div className="flex items-center justify-center">
|
||||
<RefreshCw className="w-6 h-6 animate-spin text-primary-500" />
|
||||
<span className="ml-2 text-gray-600">Cargando eventos...</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : itemsFiltrados.length > 0 ? (
|
||||
itemsFiltrados.map((evento: Evento) => (
|
||||
<tr key={evento.id} className="hover:bg-gray-50 transition-colors">
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-mono">
|
||||
{format(new Date(evento.fecha), 'dd/MM/yyyy HH:mm:ss', { locale: es })}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium border ${getTipoClass(evento.tipo)}`}>
|
||||
{getTipoIcon(evento.tipo)}
|
||||
{evento.tipo}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-700">
|
||||
<div className="flex justify-between items-start gap-2 group">
|
||||
<span className="break-all">{renderMensaje(evento.mensaje)}</span>
|
||||
<div className="opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<CopyButton text={evento.mensaje} />
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={3} className="px-6 py-16 text-center">
|
||||
<div className="flex flex-col items-center justify-center text-gray-400">
|
||||
<div className="bg-gray-50 p-4 rounded-full mb-3">
|
||||
<AlertCircle className="w-8 h-8 text-gray-300" />
|
||||
</div>
|
||||
<p className="text-lg font-medium text-gray-900">Sin eventos</p>
|
||||
<p className="text-sm">No hay registros para mostrar.</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Paginación */}
|
||||
{data && data.totalPages > 1 && (
|
||||
<div className="flex items-center justify-between border-t border-gray-200 pt-4">
|
||||
<div className="text-sm text-gray-700 hidden sm:block">
|
||||
Página <span className="font-medium">{pageNumber}</span> de <span className="font-medium">{data.totalPages}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 w-full sm:w-auto justify-between sm:justify-end">
|
||||
<button
|
||||
onClick={() => setPageNumber((p) => Math.max(1, p - 1))}
|
||||
disabled={pageNumber === 1}
|
||||
className="flex items-center gap-1 px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
Anterior
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setPageNumber((p) => Math.min(data.totalPages, p + 1))}
|
||||
disabled={pageNumber === data.totalPages}
|
||||
className="flex items-center gap-1 px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm"
|
||||
>
|
||||
Siguiente
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
130
frontend/src/components/Layout/Header.tsx
Normal file
130
frontend/src/components/Layout/Header.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
import { FileText, Settings, LogOut, User } from 'lucide-react';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { authApi } from '../../services/api';
|
||||
import { getRefreshToken } from '../../utils/storage';
|
||||
import { toast } from 'sonner';
|
||||
import type { Estadisticas } from '../../types';
|
||||
|
||||
interface HeaderProps {
|
||||
vistaActual: 'dashboard' | 'configuracion';
|
||||
setVistaActual: (vista: 'dashboard' | 'configuracion') => void;
|
||||
estadisticas?: Estadisticas;
|
||||
}
|
||||
|
||||
export default function Header({ vistaActual, setVistaActual, estadisticas }: HeaderProps) {
|
||||
const { usuario, logout } = useAuth();
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
// 1. Intentar invalidar en el servidor (Seguridad)
|
||||
const token = getRefreshToken();
|
||||
if (token) {
|
||||
await authApi.logout(token);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error al notificar cierre de sesión al servidor', error);
|
||||
// No bloqueamos el logout visual si falla el servidor
|
||||
} finally {
|
||||
// 2. Limpiar cliente y redirigir (UX)
|
||||
logout();
|
||||
toast.success('Sesión cerrada correctamente');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="bg-white shadow-sm border-b border-gray-200">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex justify-between items-center py-4">
|
||||
|
||||
{/* Logo y Título */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center space-y-2 sm:space-y-0 sm:space-x-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="bg-primary-600 rounded-lg p-2.5 shadow-lg shadow-primary-500/30">
|
||||
<FileText className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
|
||||
Gestor de Facturas
|
||||
{/* Indicador visible en móvil (punto simple) */}
|
||||
<span className={`flex md:hidden h-3 w-3 rounded-full ${estadisticas?.enEjecucion ? 'bg-green-500 animate-pulse' : 'bg-gray-400'}`} />
|
||||
</h1>
|
||||
<div className="flex items-center gap-1 text-xs text-gray-500 font-medium">
|
||||
<User className="w-3 h-3" />
|
||||
<span>{usuario}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Estado del servicio y Navegación */}
|
||||
<div className="flex items-center gap-6">
|
||||
|
||||
{/* Indicador de Estado (Solo visible en desktop) */}
|
||||
<div className="hidden md:flex items-center gap-2 bg-gray-50 px-3 py-1.5 rounded-full border border-gray-100 group cursor-help relative">
|
||||
|
||||
{/* Tooltip nativo simple */}
|
||||
<div className="absolute top-full mt-2 left-1/2 -translate-x-1/2 w-48 bg-gray-800 text-white text-xs rounded py-1 px-2 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 text-center">
|
||||
{estadisticas?.enEjecucion
|
||||
? "El worker está activo buscando facturas nuevas automáticamente."
|
||||
: "El servicio está detenido. No se procesarán facturas."}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<div
|
||||
className={`w-2.5 h-2.5 rounded-full transition-colors ${estadisticas?.enEjecucion ? 'bg-green-500' : 'bg-gray-400'
|
||||
}`}
|
||||
/>
|
||||
{/* Anillo de pulso animado solo si está activo */}
|
||||
{estadisticas?.enEjecucion && (
|
||||
<div className="absolute inset-0 rounded-full bg-green-500 animate-ping opacity-75"></div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<span className="text-xs font-medium text-gray-600">
|
||||
{estadisticas?.enEjecucion ? 'Monitor Activo' : 'Servicio Detenido'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Separador vertical */}
|
||||
<div className="h-8 w-px bg-gray-200 hidden md:block"></div>
|
||||
|
||||
{/* Botones de acción */}
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setVistaActual('dashboard')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${vistaActual === 'dashboard'
|
||||
? 'bg-primary-50 text-primary-700 ring-1 ring-primary-200'
|
||||
: 'text-gray-600 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<FileText className="w-4 h-4" />
|
||||
Dashboard
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setVistaActual('configuracion')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${vistaActual === 'configuracion'
|
||||
? 'bg-primary-50 text-primary-700 ring-1 ring-primary-200'
|
||||
: 'text-gray-600 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<Settings className="w-4 h-4" />
|
||||
Configuración
|
||||
</button>
|
||||
|
||||
{/* Botón Cerrar Sesión */}
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="flex items-center gap-2 px-3 py-2 ml-2 rounded-lg text-sm font-medium text-red-600 hover:bg-red-50 hover:text-red-700 transition-colors border border-transparent hover:border-red-100"
|
||||
title="Cerrar Sesión"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
<span className="hidden md:inline">Salir</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
123
frontend/src/components/Login.tsx
Normal file
123
frontend/src/components/Login.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
import React, { useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import { toast } from 'sonner';
|
||||
import { Lock, User, Building2, Eye, EyeOff } from 'lucide-react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function Login() {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [rememberMe, setRememberMe] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const { login } = useAuth();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
try {
|
||||
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000/api';
|
||||
|
||||
const { data } = await axios.post(`${API_URL}/auth/login`, {
|
||||
username,
|
||||
password,
|
||||
rememberMe // true o false
|
||||
});
|
||||
|
||||
// Pasamos rememberMe al contexto para que decida el storage
|
||||
login(data.token, data.refreshToken, data.usuario, rememberMe);
|
||||
|
||||
toast.success(rememberMe ? 'Sesión segura por 30 días' : 'Bienvenido');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
toast.error('Credenciales inválidas');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200">
|
||||
<div className="bg-white p-8 rounded-xl shadow-xl w-full max-w-md border border-gray-100">
|
||||
<div className="flex justify-center mb-6">
|
||||
<div className="bg-primary-600 p-3 rounded-xl">
|
||||
<Building2 className="w-10 h-10 text-white" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center mb-8">
|
||||
<h2 className="text-2xl font-bold text-gray-900">Iniciar Sesión</h2>
|
||||
<p className="text-gray-500 mt-2">Gestor de Facturas El Día</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">Usuario</label>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<User className="h-5 w-5 text-gray-400" />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="input-field pl-10"
|
||||
placeholder="admin"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">Contraseña</label>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<Lock className="h-5 w-5 text-gray-400" />
|
||||
</div>
|
||||
<input
|
||||
type={showPassword ? "text" : "password"} // Toggle tipo
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="input-field pl-10 pr-10" // Padding derecho extra para el ojo
|
||||
placeholder="••••••"
|
||||
required
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer text-gray-400 hover:text-gray-600"
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* CHECKBOX REMEMBER ME */}
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
id="remember-me"
|
||||
type="checkbox"
|
||||
checked={rememberMe}
|
||||
onChange={(e) => setRememberMe(e.target.checked)}
|
||||
className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded cursor-pointer"
|
||||
/>
|
||||
<label htmlFor="remember-me" className="ml-2 block text-sm text-gray-900 cursor-pointer select-none">
|
||||
Mantener sesión iniciada por 30 días
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full btn-primary flex justify-center py-3"
|
||||
>
|
||||
{loading ? 'Ingresando...' : 'Ingresar'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="mt-6 text-center text-xs text-gray-400">
|
||||
Versión 1.0.0 © 2025 El Día
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user