Init Commit
This commit is contained in:
2
frontend/.env.example
Normal file
2
frontend/.env.example
Normal file
@@ -0,0 +1,2 @@
|
||||
# Backend API URL
|
||||
VITE_API_URL=http://localhost:5036/api
|
||||
24
frontend/.gitignore
vendored
Normal file
24
frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
29
frontend/Dockerfile
Normal file
29
frontend/Dockerfile
Normal file
@@ -0,0 +1,29 @@
|
||||
# Etapa 1: Construcción
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /app
|
||||
|
||||
# Argumento para la URL de la API (se pasa desde el docker-compose al construir)
|
||||
ARG VITE_API_URL
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# Etapa 2: Servidor Web Nginx
|
||||
FROM nginx:alpine
|
||||
WORKDIR /usr/share/nginx/html
|
||||
|
||||
# Limpiar default
|
||||
RUN rm -rf ./*
|
||||
|
||||
# Copiar build de React
|
||||
COPY --from=build /app/dist .
|
||||
|
||||
# Copiar configuración de Nginx
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 80
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
73
frontend/README.md
Normal file
73
frontend/README.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
23
frontend/eslint.config.js
Normal file
23
frontend/eslint.config.js
Normal file
@@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
13
frontend/index.html
Normal file
13
frontend/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/png" href="/folder.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
23
frontend/nginx.conf
Normal file
23
frontend/nginx.conf
Normal file
@@ -0,0 +1,23 @@
|
||||
server {
|
||||
listen 80;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# 1. Configuración para React Router
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# 2. PROXY INVERSO
|
||||
location /api/ {
|
||||
proxy_pass http://backend:8080;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection keep-alive;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
}
|
||||
4299
frontend/package-lock.json
generated
Normal file
4299
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
40
frontend/package.json
Normal file
40
frontend/package.json
Normal file
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.90.12",
|
||||
"axios": "^1.13.2",
|
||||
"date-fns": "^4.1.0",
|
||||
"lucide-react": "^0.559.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-router-dom": "^7.10.1",
|
||||
"sonner": "^2.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@tailwindcss/postcss": "^4.1.17",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/react": "^19.2.5",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
"autoprefixer": "^10.4.22",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.24",
|
||||
"globals": "^16.5.0",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^4.1.17",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.46.4",
|
||||
"vite": "^7.2.4"
|
||||
}
|
||||
}
|
||||
6
frontend/postcss.config.js
Normal file
6
frontend/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
BIN
frontend/public/folder.png
Normal file
BIN
frontend/public/folder.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
42
frontend/src/App.css
Normal file
42
frontend/src/App.css
Normal file
@@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
34
frontend/src/App.tsx
Normal file
34
frontend/src/App.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { Toaster } from 'sonner';
|
||||
import { AuthProvider, useAuth } from './context/AuthContext';
|
||||
import Login from './components/Login';
|
||||
import Dashboard from './components/Dashboard/Dashboard';
|
||||
import './index.css';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
refetchOnWindowFocus: false,
|
||||
retry: 1,
|
||||
staleTime: 30000,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Componente para manejar la lógica de rutas protegidas
|
||||
function AppContent() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
return isAuthenticated ? <Dashboard /> : <Login />;
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AuthProvider>
|
||||
<AppContent />
|
||||
<Toaster position="top-right" richColors closeButton />
|
||||
</AuthProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
export default App;
|
||||
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>
|
||||
);
|
||||
}
|
||||
44
frontend/src/context/AuthContext.tsx
Normal file
44
frontend/src/context/AuthContext.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { createContext, useContext, useState, type ReactNode } from 'react';
|
||||
import { getToken, getUsuario, setAuthData, clearAuthData } from '../utils/storage';
|
||||
|
||||
interface AuthContextType {
|
||||
usuario: string | null;
|
||||
login: (token: string, refreshToken: string, usuario: string, rememberMe: boolean) => void;
|
||||
logout: () => void;
|
||||
isAuthenticated: boolean;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null);
|
||||
|
||||
export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
||||
// Inicializamos leyendo de cualquiera de los dos storages
|
||||
const [token, setToken] = useState<string | null>(getToken());
|
||||
const [usuario, setUsuario] = useState<string | null>(getUsuario());
|
||||
|
||||
const login = (newToken: string, newRefreshToken: string, newUser: string, rememberMe: boolean) => {
|
||||
// Usamos la utilidad para guardar en el lugar correcto
|
||||
setAuthData(newToken, newRefreshToken, newUser, rememberMe);
|
||||
|
||||
setToken(newToken);
|
||||
setUsuario(newUser);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
clearAuthData();
|
||||
setToken(null);
|
||||
setUsuario(null);
|
||||
window.location.href = '/';
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ usuario, login, logout, isAuthenticated: !!token }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) throw new Error('useAuth must be used within an AuthProvider');
|
||||
return context;
|
||||
};
|
||||
85
frontend/src/index.css
Normal file
85
frontend/src/index.css
Normal file
@@ -0,0 +1,85 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--color-primary-50: #f0f9ff;
|
||||
--color-primary-100: #e0f2fe;
|
||||
--color-primary-200: #bae6fd;
|
||||
--color-primary-300: #7dd3fc;
|
||||
--color-primary-400: #38bdf8;
|
||||
--color-primary-500: #0ea5e9;
|
||||
--color-primary-600: #0284c7;
|
||||
--color-primary-700: #0369a1;
|
||||
--color-primary-800: #075985;
|
||||
--color-primary-900: #0c4a6e;
|
||||
}
|
||||
|
||||
:root {
|
||||
font-family: 'Inter', system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
|
||||
color-scheme: light;
|
||||
color: #1f2937;
|
||||
/* text-gray-800 - oscuro para fondos claros */
|
||||
background-color: #f5f5f5;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
#root {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.card {
|
||||
@apply bg-white rounded-lg shadow-md p-6;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
@apply bg-primary-600 hover:bg-primary-700 text-white font-semibold py-2 px-4 rounded-lg transition-colors duration-200;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
@apply bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 px-4 rounded-lg transition-colors duration-200;
|
||||
}
|
||||
|
||||
.input-field {
|
||||
@apply w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent text-gray-900 bg-white;
|
||||
}
|
||||
|
||||
.label-text {
|
||||
@apply block text-sm font-medium text-gray-700 mb-1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Estilos adicionales para inputs, selects y textareas */
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
color: #111827 !important;
|
||||
/* text-gray-900 - texto oscuro */
|
||||
background-color: white !important;
|
||||
}
|
||||
|
||||
input::placeholder,
|
||||
textarea::placeholder {
|
||||
color: #9ca3af;
|
||||
/* text-gray-400 - placeholder gris claro */
|
||||
}
|
||||
|
||||
/* Asegurar que los options en select sean legibles */
|
||||
select option {
|
||||
color: #111827;
|
||||
background-color: white;
|
||||
}
|
||||
10
frontend/src/main.tsx
Normal file
10
frontend/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
129
frontend/src/services/api.ts
Normal file
129
frontend/src/services/api.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
import axios from 'axios';
|
||||
import type {
|
||||
Configuracion,
|
||||
Evento,
|
||||
PagedResult,
|
||||
Estadisticas,
|
||||
ProbarConexionDto,
|
||||
ProbarSMTPDto,
|
||||
EjecucionManualDto,
|
||||
ApiResponse,
|
||||
} from '../types';
|
||||
import { clearAuthData, getRefreshToken, getToken, updateTokens } from '../utils/storage';
|
||||
|
||||
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000/api';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// Interceptor Request
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = getToken(); // Usa la utilidad que busca en ambos
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// Interceptor Response
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
const originalRequest = error.config;
|
||||
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
const refreshToken = getRefreshToken(); // Usa la utilidad
|
||||
|
||||
if (!refreshToken) throw new Error('No refresh token');
|
||||
|
||||
const { data } = await axios.post(`${API_BASE_URL}/auth/refresh-token`, {
|
||||
token: refreshToken
|
||||
});
|
||||
|
||||
// IMPORTANTE: Actualizamos en el storage correspondiente
|
||||
updateTokens(data.token, data.refreshToken);
|
||||
|
||||
originalRequest.headers.Authorization = `Bearer ${data.token}`;
|
||||
return api(originalRequest);
|
||||
|
||||
} catch (refreshError) {
|
||||
console.error('Sesión expirada', refreshError);
|
||||
clearAuthData();
|
||||
window.location.href = '/';
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// ===== CONFIGURACIÓN =====
|
||||
export const configuracionApi = {
|
||||
obtener: async (): Promise<Configuracion> => {
|
||||
const { data } = await api.get<Configuracion>('/configuracion');
|
||||
return data;
|
||||
},
|
||||
|
||||
actualizar: async (config: Configuracion): Promise<Configuracion> => {
|
||||
const { data } = await api.put<Configuracion>('/configuracion', config);
|
||||
return data;
|
||||
},
|
||||
|
||||
probarConexionSQL: async (dto: ProbarConexionDto): Promise<ApiResponse> => {
|
||||
const { data } = await api.post<ApiResponse>('/configuracion/probar-conexion-sql', dto);
|
||||
return data;
|
||||
},
|
||||
|
||||
probarSMTP: async (dto: ProbarSMTPDto): Promise<ApiResponse> => {
|
||||
const { data } = await api.post<ApiResponse>('/configuracion/probar-smtp', dto);
|
||||
return data;
|
||||
},
|
||||
};
|
||||
|
||||
// ===== OPERACIONES =====
|
||||
export const operacionesApi = {
|
||||
ejecutarManual: async (dto: EjecucionManualDto): Promise<ApiResponse> => {
|
||||
const { data } = await api.post<ApiResponse>('/operaciones/ejecutar-manual', dto);
|
||||
return data;
|
||||
},
|
||||
|
||||
obtenerLogs: async (
|
||||
pageNumber: number = 1,
|
||||
pageSize: number = 20,
|
||||
tipo?: string
|
||||
): Promise<PagedResult<Evento>> => {
|
||||
const params: any = { pageNumber, pageSize };
|
||||
if (tipo) params.tipo = tipo;
|
||||
|
||||
const { data } = await api.get<PagedResult<Evento>>('/operaciones/logs', { params });
|
||||
return data;
|
||||
},
|
||||
|
||||
obtenerEstadisticas: async (): Promise<Estadisticas> => {
|
||||
const { data } = await api.get<Estadisticas>('/operaciones/estadisticas');
|
||||
return data;
|
||||
},
|
||||
|
||||
limpiarLogs: async (diasAntiguedad: number = 30): Promise<ApiResponse> => {
|
||||
const { data } = await api.delete<ApiResponse>('/operaciones/logs/limpiar', {
|
||||
params: { diasAntiguedad },
|
||||
});
|
||||
return data;
|
||||
},
|
||||
};
|
||||
|
||||
export const authApi = {
|
||||
logout: async (refreshToken: string) => {
|
||||
// No esperamos respuesta, es un "fire and forget" para el usuario
|
||||
return api.post('/auth/revoke', { token: refreshToken });
|
||||
}
|
||||
};
|
||||
|
||||
export default api;
|
||||
81
frontend/src/types/index.ts
Normal file
81
frontend/src/types/index.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
// Tipos y interfaces para el sistema de gestión de facturas
|
||||
|
||||
export interface Configuracion {
|
||||
id: number;
|
||||
periodicidad: string;
|
||||
valorPeriodicidad: number;
|
||||
horaEjecucion: string;
|
||||
ultimaEjecucion: string | null;
|
||||
proximaEjecucion?: string | null;
|
||||
estado: boolean;
|
||||
enEjecucion: boolean;
|
||||
dbServidor: string;
|
||||
dbNombre: string;
|
||||
dbUsuario: string | null;
|
||||
dbClave: string | null;
|
||||
dbTrusted: boolean;
|
||||
rutaFacturas: string;
|
||||
rutaDestino: string;
|
||||
smtpServidor: string | null;
|
||||
smtpPuerto: number;
|
||||
smtpUsuario: string | null;
|
||||
smtpClave: string | null;
|
||||
smtpSSL: boolean;
|
||||
smtpDestinatario: string | null;
|
||||
avisoMail: boolean;
|
||||
}
|
||||
|
||||
export interface Evento {
|
||||
id: number;
|
||||
fecha: string;
|
||||
mensaje: string;
|
||||
tipo: 'Info' | 'Error' | 'Warning';
|
||||
enviado: boolean;
|
||||
}
|
||||
|
||||
export interface PagedResult<T> {
|
||||
items: T[];
|
||||
totalCount: number;
|
||||
pageNumber: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export interface Estadisticas {
|
||||
ultimaEjecucion: string | null;
|
||||
estado: boolean;
|
||||
enEjecucion: boolean;
|
||||
eventosHoy: {
|
||||
total: number;
|
||||
errores: number;
|
||||
advertencias: number;
|
||||
info: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ProbarConexionDto {
|
||||
servidor: string;
|
||||
nombreDB: string;
|
||||
usuario: string | null;
|
||||
clave: string | null;
|
||||
trustedConnection: boolean;
|
||||
}
|
||||
|
||||
export interface ProbarSMTPDto {
|
||||
servidor: string;
|
||||
puerto: number;
|
||||
usuario: string;
|
||||
clave: string;
|
||||
ssl: boolean;
|
||||
destinatario: string;
|
||||
}
|
||||
|
||||
export interface EjecucionManualDto {
|
||||
fechaDesde: string;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T = any> {
|
||||
exito?: boolean;
|
||||
mensaje?: string;
|
||||
data?: T;
|
||||
}
|
||||
44
frontend/src/utils/storage.ts
Normal file
44
frontend/src/utils/storage.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// Detecta dónde están guardados los tokens actualmente
|
||||
export const getStorageType = (): 'local' | 'session' | null => {
|
||||
if (localStorage.getItem('token')) return 'local';
|
||||
if (sessionStorage.getItem('token')) return 'session';
|
||||
return null;
|
||||
};
|
||||
|
||||
export const getToken = () => {
|
||||
return localStorage.getItem('token') || sessionStorage.getItem('token');
|
||||
};
|
||||
|
||||
export const getRefreshToken = () => {
|
||||
return localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken');
|
||||
};
|
||||
|
||||
export const getUsuario = () => {
|
||||
return localStorage.getItem('usuario') || sessionStorage.getItem('usuario');
|
||||
};
|
||||
|
||||
export const setAuthData = (token: string, refreshToken: string, usuario: string, rememberMe: boolean) => {
|
||||
const storage = rememberMe ? localStorage : sessionStorage;
|
||||
|
||||
// Limpiamos el otro storage por si acaso había residuos
|
||||
if (rememberMe) sessionStorage.clear();
|
||||
else localStorage.clear();
|
||||
|
||||
storage.setItem('token', token);
|
||||
storage.setItem('refreshToken', refreshToken);
|
||||
storage.setItem('usuario', usuario);
|
||||
};
|
||||
|
||||
export const updateTokens = (token: string, refreshToken: string) => {
|
||||
// Detectamos dónde están guardados para actualizarlos en el mismo lugar
|
||||
const type = getStorageType();
|
||||
const storage = type === 'local' ? localStorage : sessionStorage;
|
||||
|
||||
storage.setItem('token', token);
|
||||
storage.setItem('refreshToken', refreshToken);
|
||||
};
|
||||
|
||||
export const clearAuthData = () => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
};
|
||||
26
frontend/tailwind.config.js
Normal file
26
frontend/tailwind.config.js
Normal file
@@ -0,0 +1,26 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: [
|
||||
"./index.html",
|
||||
"./src/**/*.{js,ts,jsx,tsx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
primary: {
|
||||
50: '#f0f9ff',
|
||||
100: '#e0f2fe',
|
||||
200: '#bae6fd',
|
||||
300: '#7dd3fc',
|
||||
400: '#38bdf8',
|
||||
500: '#0ea5e9',
|
||||
600: '#0284c7',
|
||||
700: '#0369a1',
|
||||
800: '#075985',
|
||||
900: '#0c4a6e',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
28
frontend/tsconfig.app.json
Normal file
28
frontend/tsconfig.app.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
frontend/tsconfig.json
Normal file
7
frontend/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
26
frontend/tsconfig.node.json
Normal file
26
frontend/tsconfig.node.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
17
frontend/vite.config.ts
Normal file
17
frontend/vite.config.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: {
|
||||
// Cuando el frontend pida "/api", Vite lo redirigirá al backend
|
||||
'/api': {
|
||||
target: 'http://localhost:5036',
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user